/** * Callback for preg_replace in process() */ public static function processCallback($matches = array()) { $content = ''; $entity_type = $entity_id = $view_mode = ''; foreach ($matches as $key => $match) { switch ($key) { case 1: $entity_type = $match; break; case 2: $entity_id = $match; break; case 3: $view_mode = $match; break; } } $entities = entity_load($entity_type, array($entity_id)); if (!empty($entities)) { $render_array = entity_view($entity_type, $entities, $view_mode, NULL, TRUE); // Remove contextual links. if (isset($render_array[$entity_type][$entity_id]['#contextual_links'])) { unset($render_array[$entity_type][$entity_id]['#contextual_links']); } $content = render($render_array); } return $content; }
/** * Lists all instances of fields on any views. * * @return array * The Views fields report page. */ public function nodeMarkup($node, $key = 'default') { $node = Node::load($node); $builded_entity = entity_view($node, $key); $markup = drupal_render($builded_entity); $links = array(); $links['default'] = array( 'title' => 'Default', 'url' => Url::fromRoute('ds_devel.markup', array('node' => $node->id())), ); $view_modes = \Drupal::entityManager()->getViewModes('node'); foreach ($view_modes as $id => $info) { if (!empty($info['status'])) { $links[] = array( 'title' => $info['label'], 'url' => Url::fromRoute('ds_devel.markup_view_mode', array('node' => $node->id(), 'key' => $id)), ); } } $build['links'] = array( '#theme' => 'links', '#links' => $links, '#prefix' => '<div>', '#suffix' => '</div><hr />', ); $build['markup'] = [ '#markup' => '<code><pre>' . Html::escape($markup) . '</pre></code>', '#allowed_tags' => ['code', 'pre'], ]; return $build; }
/** * Test the Who's Online block. */ function testWhosOnlineBlock() { $block = $this->drupalPlaceBlock('views_block:who_s_online-who_s_online_block'); // Generate users. $user1 = $this->drupalCreateUser(array('access user profiles')); $user2 = $this->drupalCreateUser(array()); $user3 = $this->drupalCreateUser(array()); // Update access of two users to be within the active timespan. $this->updateAccess($user1->id()); $this->updateAccess($user2->id(), REQUEST_TIME + 1); // Insert an inactive user who should not be seen in the block, and ensure // that the admin user used in setUp() does not appear. $inactive_time = REQUEST_TIME - 15 * 60 - 1; $this->updateAccess($user3->id(), $inactive_time); $this->updateAccess($this->adminUser->id(), $inactive_time); // Test block output. \Drupal::currentUser()->setAccount($user1); $content = entity_view($block, 'block'); $this->drupalSetContent(render($content)); $this->assertRaw(t('2 users'), 'Correct number of online users (2 users).'); $this->assertText($user1->getUsername(), 'Active user 1 found in online list.'); $this->assertText($user2->getUsername(), 'Active user 2 found in online list.'); $this->assertNoText($user3->getUsername(), 'Inactive user not found in online list.'); $this->assertTrue(strpos($this->drupalGetContent(), $user1->getUsername()) > strpos($this->drupalGetContent(), $user2->getUsername()), 'Online users are ordered correctly.'); }
function gitp_preprocess_node__blog(&$variables) { $author_uid = $variables['uid']; $author = profile2_load_by_user($author_uid); $variables['author_thumbnail_profile'] = entity_view('profile2', $author, 'thumbnail_profile'); $variables['author_profile'] = entity_view('profile2', $author, 'author_profile'); }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $view_mode = $this->getSetting('view_mode'); $elements = array(); foreach ($this->getEntitiesToView($items) as $delta => $entity) { // Protect ourselves from recursive rendering. static $depth = 0; $depth++; if ($depth > 20) { throw new RecursiveRenderingException(format_string('Recursive rendering detected when rendering entity @entity_type(@entity_id). Aborting rendering.', array('@entity_type' => $entity->getEntityTypeId(), '@entity_id' => $entity->id()))); } if ($entity->id()) { $elements[$delta] = entity_view($entity, $view_mode, $entity->language()->getId()); // Add a resource attribute to set the mapping property's value to the // entity's url. Since we don't know what the markup of the entity will // be, we shouldn't rely on it for structured data such as RDFa. if (!empty($items[$delta]->_attributes)) { $items[$delta]->_attributes += array('resource' => $entity->url()); } } else { // This is an "auto_create" item. $elements[$delta] = array('#markup' => $entity->label()); } $depth = 0; } return $elements; }
/** * Tests the rendering of blocks. */ public function testBasicRendering() { \Drupal::state()->set('block_test.content', ''); $entity = $this->controller->create(array('id' => 'test_block1', 'theme' => 'stark', 'plugin' => 'test_html')); $entity->save(); // Test the rendering of a block. $entity = Block::load('test_block1'); $output = entity_view($entity, 'block'); $expected = array(); $expected[] = '<div id="block-test-block1">'; $expected[] = ' '; $expected[] = ' '; $expected[] = ' '; $expected[] = ' </div>'; $expected[] = ''; $expected_output = implode("\n", $expected); $this->assertEqual($this->renderer->renderRoot($output), $expected_output); // Reset the HTML IDs so that the next render is not affected. Html::resetSeenIds(); // Test the rendering of a block with a given title. $entity = $this->controller->create(array('id' => 'test_block2', 'theme' => 'stark', 'plugin' => 'test_html', 'settings' => array('label' => 'Powered by Bananas'))); $entity->save(); $output = entity_view($entity, 'block'); $expected = array(); $expected[] = '<div id="block-test-block2">'; $expected[] = ' '; $expected[] = ' <h2>Powered by Bananas</h2>'; $expected[] = ' '; $expected[] = ' '; $expected[] = ' </div>'; $expected[] = ''; $expected_output = implode("\n", $expected); $this->assertEqual($this->renderer->renderRoot($output), $expected_output); }
/** * Returns text for a product to be indexed as search keywords. * * @param $product stdClass The commerce_product to be indexed. * * @return String|Array The keywords to be indexed. */ function hook_commerce_search_index_product($product) { $keywords = explode('-', $product->sku); $renderable = entity_view('commerce_product', array($product), 'node_search_index'); $keywords[] = drupal_render($renderable); return $keywords; }
private function content_ajax_page_fc($fcid) { $fcitem = \Drupal\field_collection\Entity\FieldCollectionItem::load($fcid); $target = WG::entity_get_field_value($fcitem, 'field_target'); preg_match('%^([^:]+)://([0-9]+)$%', $target, $m); $itemtype = $m[1]; $id = $m[2]; switch ($itemtype) { case 'public318': $identifier = $id; $text = WG::entity_get_field_formatted_text($fcitem, 'field_annotation'); $stylename = 'large'; $icon_uri = _expo_public318_get_icon_uri($identifier); $icontag = WG::render_styled_image($icon_uri, $stylename); $output = '<div class="sticky-fc-public318">' . '<div class="collicon">' . _expo_coll_url($identifier, $icontag) . '</div>' . '<div class="colltext">' . $text . '</div>' . '</div>'; break; case 'storynode': $nid = $id; $story = node_load($nid); $v = entity_view($story, 'ajaxpage'); $output = render($v); break; default: $tag = "<div class=\"sticky\" id=\"sticky_{$pos}\">" . $itemtype . $pos . "</div>"; } $build = ['#markup' => $output]; return $build; }
/** * {@inheritdoc} */ public function build() { $nid = self::_gen_random_nid(); $node = node_load($nid); $v = entity_view($node, 'full'); $build = ['#markup' => render($v), '#cache' => ['max-age' => 0]]; return $build; }
/** * @Route("/{entity_type}/{entity}", name="entity_view", defaults={"view_mode" = "full", "langcode" = null, "page" = null}) * @Method("GET") * @ParamConverter("entity", converter="drupal.entity") * @Template */ public function viewAction(Request $request, $entity_type, $entity) { $view_mode = $request->get('view_mode'); $langcode = $request->get('langcode'); $page = $request->get('page'); list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity); $entities = entity_view($entity_type, array($id => $entity), $view_mode, $langcode, $page); return array('label' => entity_label($entity_type, $entity), 'uri' => entity_uri($entity_type, $entity), 'entity_type' => $entity_type, 'id' => $id, 'vid' => $vid, 'bundle' => $bundle, 'entity' => $entity, 'content' => reset($entities[$entity_type])); }
/** * {@inheritdoc} */ public function build() { $view_mode = $this->getEntityViewMode(); /** @var $comment CommentInterface */ $comment = $this->entity(); $uid = $comment->getOwnerId(); $user = entity_load('user', $uid); $build = entity_view($user, $view_mode); return $build; }
/** * {@inheritdoc} */ public function entityView() { $configuration = $this->getConfiguration(); if ($node = $this->entityLoad()) { if ($this->entityAccess()) { return entity_view($this->getType(), array($this->getEntity()), $configuration['view mode']); } } return FALSE; }
/** * {@inheritdoc} */ public function render($empty = FALSE) { if (!$empty || !empty($this->options['empty'])) { $entity_id = $this->tokenizeValue($this->options['entity_id']); $entity = entity_load($this->entityType, $entity_id); if ($entity && (!empty($this->options['bypass_access']) || $entity->access('view'))) { return entity_view($entity, $this->options['view_mode']); } } return array(); }
/** * Returns an node through JSON. * * @param Request $request * The global request object. * @param string $entityType * The type of the requested entity. * @param string $entityId * The id of the requested entity. * @param string $viewMode * The view mode you wish to render for the requested entity. * * @return array * The Views fields report page. */ public function switchViewMode(Request $request, $entityType, $entityId, $viewMode) { $response = new AjaxResponse(); $entity = entity_load($entityType, $entityId); if ($entity->access('view')) { $element = entity_view($entity, $viewMode); $content = \Drupal::service('renderer')->render($element, FALSE); $response->addCommand(new ReplaceCommand('.' . $request->get('selector'), $content)); } return $response; }
/** * Displays the bean. */ public function view($bean, $content, $view_mode = 'default', $langcode = NULL) { // Retrieve the terms from the loaded entity. $active_entity = bean_tax_active_entity_array(); // Check for cached content on this block. $cache_name = 'bean_tax:listing:' . $bean->delta . ':' . $active_entity['type'] . ':' . $active_entity['ids'][0]; if ($cache = cache_get($cache_name)) { $content = $cache->data; } else { // We need to make sure that the bean is configured correctly. if ($active_entity['type'] != 'bean' && !empty($bean->filters['vocabulary']) && (isset($active_entity['terms']) && count($active_entity['terms']))) { // Reformat vocabulary list from machine names to vocabulary vids. $vids = array(); foreach ($bean->filters['vocabulary'] as $vm) { $query = new EntityFieldQuery(); $result = $query->entityCondition('entity_type', 'taxonomy_vocabulary'); $query->propertyCondition('machine_name', $vm); global $language; if ($language->language != NULL && db_field_exists('taxonomy_vocabulary', 'language')) { $query->propertyCondition('language', $language->language); } $result = $query->execute(); foreach ($result['taxonomy_vocabulary'] as $vocabulary) { $vids[$vocabulary->vid] = $vocabulary->vid; } } $i = 0; $content['terms'] = array(); // Parse terms from correct vocabularies, limit list to X results. foreach ($active_entity['terms'] as $term) { $term = entity_load_single('taxonomy_term', $term->tid); if (in_array($term->vid, $vids) && $i < $bean->settings['records_shown']) { $content['terms'][$term->tid] = entity_view('taxonomy_term', array($term->tid => $term), $bean->settings['term_view_mode']); $i++; } } cache_set($cache_name, $content, 'cache', time() + 60 * $bean->settings['cache_duration']); } elseif (isset($active_entity['type']) && $active_entity['type'] == 'bean' && $bean->bid === $active_entity['object']->bid) { $content['#markup'] = ''; } elseif ($bean->settings['hide_empty'] || !$active_entity['object']) { return; } else { $content['#markup'] = t('No terms.'); } } return $content; }
/** * Helper function to test the formatter's RDFa. * * @param array $formatter * An associative array describing the formatter to test and its settings * containing: * - type: The machine name of the field formatter to test. * - settings: The settings of the field formatter to test. * @param string $property * The property that should be found. * @param array $expected_rdf_value * An associative array describing the expected value of the property * containing: * - value: The actual value of the string or URI. * - type: The type of RDF value, e.g. 'literal' for a string, or 'uri'. * Defaults to 'literal'. * - datatype: (optional) The datatype of the value (e.g. xsd:dateTime). */ protected function assertFormatterRdfa($formatter, $property, $expected_rdf_value) { $expected_rdf_value += array('type' => 'literal'); // The field formatter will be rendered inside the entity. Set the field // formatter in the entity display options before rendering the entity. entity_get_display('entity_test', 'entity_test', 'default')->setComponent($this->fieldName, $formatter)->save(); $build = entity_view($this->entity, 'default'); $output = drupal_render($build); $graph = new \EasyRdf_Graph($this->uri, $output, 'rdfa'); // If verbose debugging is turned on, display the HTML and parsed RDF // in the results. if ($this->debug) { debug($output); debug($graph->toRdfPhp()); } $this->assertTrue($graph->hasProperty($this->uri, $property, $expected_rdf_value), "Formatter {$formatter['type']} exposes data correctly for {$this->fieldType} fields."); }
/** * Lists all instances of fields on any views. * * @param \Drupal\Core\Routing\RouteMatchInterface $route_match * A RouteMatch object. * * @return array * The Views fields report page. */ public function entityMarkup(RouteMatchInterface $route_match) { $parameter_name = $route_match->getRouteObject()->getOption('_devel_entity_type_id'); $entity = $route_match->getParameter($parameter_name); $entity_type_id = $entity->getEntityTypeId(); $key = \Drupal::request()->get('key', 'default'); $builded_entity = entity_view($entity, $key); $markup = \Drupal::service('renderer')->render($builded_entity); $links = array(); $active_view_modes = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle($entity_type_id, $entity->bundle()); foreach ($active_view_modes as $id => $label) { $links[] = array('title' => $label, 'url' => Url::fromRoute("entity.{$entity_type_id}.devel_markup", array($entity_type_id => $entity->id(), 'key' => $id))); } $build['links'] = array('#theme' => 'links', '#links' => $links, '#prefix' => '<hr/><div>', '#suffix' => '</div><hr />'); $build['markup'] = ['#markup' => '<code><pre>' . Html::escape($markup) . '</pre></code>', '#cache' => array('max-age' => 0), '#allowed_tags' => ['code', 'pre']]; return $build; }
/** * Assert unaccessible items don't change the data of the fields. */ public function testAccess() { $field_name = $this->fieldName; $referencing_entity = entity_create($this->entityType, array('name' => $this->randomMachineName())); $referencing_entity->save(); $referencing_entity->{$field_name}->entity = $this->referencedEntity; // Assert user doesn't have access to the entity. $this->assertFalse($this->referencedEntity->access('view'), 'Current user does not have access to view the referenced entity.'); $formatter_manager = $this->container->get('plugin.manager.field.formatter'); // Get all the existing formatters. foreach ($formatter_manager->getOptions('entity_reference') as $formatter => $name) { // Set formatter type for the 'full' view mode. entity_get_display($this->entityType, $this->bundle, 'default')->setComponent($field_name, array('type' => $formatter))->save(); // Invoke entity view. entity_view($referencing_entity, 'default'); // Verify the un-accessible item still exists. $this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', array('@name' => $name))); } }
/** * {@inheritdoc} */ public function build() { $config = $this->getConfiguration(); $nr_items = isset($config['slideshow_items']) ? $config['slideshow_items'] : 3; // $order = isset($config['slideshow_order']) ? $config['slideshow_order'] : 'created'; // Fetches the slideshow nodes. $query = \Drupal::entityQuery('node')->condition('status', 1)->condition('type', 'object')->range(0, $nr_items); $nids = $query->execute(); $items = array(); foreach ($nids as $nid) { $node = entity_load('node', $nid); $node_view = entity_view($node, 'hero_teaser'); $items[] = array('#markup' => drupal_render($node_view), '#wrapper_attributes' => array('class' => array('slide'))); } $build['show'] = array('#theme' => 'item_list', '#items' => $items, '#attributes' => array('class' => array('slideshow', 'rslides'))); $build['#attributes']['class'][] = 'slideshow-block'; $build['#attached']['library'][] = 'dd8_tools/slideshow'; $build['#attached']['library'][] = 'dd8_tools/responsiveslides'; // $build['asfasf']['#markup'] = 'efkjqekjfkjah aekjkjwevkj HSHAJHDJAH'; return $build; }
function casabienestar_preprocess_search_api_page_results(array &$variables) { $results = $variables['results']; if (!empty($variables['results']['results'])) { $variables['items'] = $variables['index']->loadItems(array_keys($variables['results']['results'])); } $variables['result_count'] = $results['result count']; $variables['sec'] = 0; if (isset($results['performance']['complete'])) { $variables['sec'] = round($results['performance']['complete'], 3); } $variables['search_performance'] = array('#theme' => 'search_api_page_search_performance', '#markup' => format_plural($results['result count'], 'The search found 1 result in @sec seconds.', 'The search found @count results in @sec seconds.', array('@sec' => $variables['sec'])), '#prefix' => '<p class="search-performance">', '#suffix' => '</p>'); // Make the help text depend on the parse mode used. switch ($variables['page']->options['mode']) { case 'direct': if ($variables['index']->server()->class == 'search_api_solr') { $variables['no_results_help'] = t('<ul> <li>Check if your spelling is correct.</li> <li>Remove quotes around phrases to search for each word individually. <em>bike shed</em> will often show more results than <em>"bike shed"</em>.</li> <li>Consider loosening your query with <em>OR</em>. <em>bike OR shed</em> will often show more results than <em>bike shed</em>.</li> </ul>'); } else { $variables['no_results_help'] = t('<ul> <li>Check if your spelling is correct.</li> <li>Use fewer keywords to increase the number of results.</li> </ul>'); } break; case 'single': $variables['no_results_help'] = t('<ul> <li>Check if your spelling is correct.</li> <li>Use fewer keywords to increase the number of results.</li> </ul>'); break; case 'terms': $variables['no_results_help'] = t('<ul> <li>Check if your spelling is correct.</li> <li>Remove quotes around phrases to search for each word individually. <em>bike shed</em> will often show more results than <em>"bike shed"</em>.</li> <li>Use fewer keywords to increase the number of results.</li> </ul>'); break; } // Prepare CSS classes. $classes_array = array('search-api-page', 'search-api-page-' . drupal_clean_css_identifier($variables['page']->machine_name), 'view-mode-' . drupal_clean_css_identifier($variables['view_mode'])); $variables['classes'] = implode(' ', $classes_array); // Distinguish between the native search_api_page_result "view mode" and // proper entity view modes (e.g., Teaser, Full content, RSS and so forth). $variables['search_results'] = array(); if ($variables['view_mode'] != 'search_api_page_result') { // Check if we have any entities to show and, if yes, show them. if (!empty($variables['items'])) { $variables['search_results'] = entity_view($variables['index']->getEntityType(), $variables['items'], $variables['view_mode']); } } else { foreach ($results['results'] as $item) { if (!empty($variables['items'][$item['id']])) { $variables['search_results'][] = array('#theme' => 'search_api_page_result', '#index' => $variables['index'], '#result' => $item, '#item' => $variables['items'][$item['id']]); } } } // Load CSS. $base_path = drupal_get_path('module', 'search_api_page') . '/'; drupal_add_css($base_path . 'search_api_page.css'); }
/** * Displays the bean. */ public function view($bean, $content, $view_mode = 'default', $langcode = NULL) { // We need to make sure that the bean is configured correctly. if (!empty($bean->filters['vocabulary']) && !empty($bean->settings['bundle_types'])) { // Define an array of all taxonomy terms in the defined vocabularies. $possible_tid = array(); foreach ($bean->filters['vocabulary'] as $vm) { $query = new EntityFieldQuery(); $result = $query->entityCondition('entity_type', 'taxonomy_vocabulary')->propertyCondition('machine_name', $vm)->execute(); foreach ($result['taxonomy_vocabulary'] as $vocabulary) { $vid = $vocabulary->vid; } $tree = taxonomy_get_tree($vid); foreach ($tree as $term) { $possible_tid[$term->tid] = $term->tid; } } // Compare possible terms to those attached to the menu object or current // user depending on 'related' settings. $active_entity = bean_tax_active_entity_array($bean->settings['related']); if (isset($active_entity['terms'])) { $valid_tid = array(); foreach ($active_entity['terms'] as $term) { if (isset($possible_tid[$term->tid])) { $valid_tid[$term->tid] = $term->tid; } } // Store Entity type. $type = $bean->settings['entity_type']; // Entity field query for entities of the defined bundle. $aggregate = array(); foreach ($bean->settings['bundle_types'] as $bundle) { $query = new EntityFieldQuery(); $query->entityCondition('entity_type', $type); $query->entityCondition('bundle', $bundle); $query->propertyOrderBy('created', 'DESC'); if ($type == 'node') { $query->propertyCondition('status', 1); } // Additional conditions for node based translations. global $language; if ($language->language != NULL && $type == 'node') { $query->propertyCondition('language', $language->language); $query->propertyCondition('tnid', 0, "<>"); } $results[$bundle] = $query->execute(); // For nodes using field based translation. if ($language->language != NULL && $type == 'node') { $query = new EntityFieldQuery(); $query->entityCondition('entity_type', $type); $query->entityCondition('bundle', $bundle); $query->propertyOrderBy('created', 'DESC'); $query->propertyCondition('tnid', 0); $query->propertyCondition('status', 1); $field_translated = $query->execute(); // Reassign the result array or merge arrays if necessary if (empty($results[$bundle][$type]) && !empty($field_translated[$type])) { $results[$bundle][$type] = $field_translated[$type]; } elseif (!empty($results[$bundle][$type]) && !empty($field_translated[$type])) { $combined = $results[$bundle][$type] + $field_translated[$type]; ksort($combined); $results[$bundle][$type] = $combined; } } // Store the results in an aggregated array of entities. if (isset($results[$bundle][$bean->settings['entity_type']])) { foreach ($results[$bundle][$bean->settings['entity_type']] as $id => $result) { $aggregate[$bean->settings['entity_type']][$id] = $result; } } } // Create a taxonomy related "score" for each result's matching terms. $result = array(); $unmatching = array(); if (isset($aggregate[$bean->settings['entity_type']])) { foreach ($aggregate[$bean->settings['entity_type']] as $key => $value) { $entity_terms = bean_tax_get_entity_terms($bean->settings['entity_type'], $key); $score = 0; // The actual scoring to determine valid taxonomy term matching. foreach ($entity_terms as $term) { if (isset($valid_tid[$term->tid])) { $score++; } } $item['id'] = $key; $item['score'] = $score; // A score of 1 or greater adds to the array of matching entities. if ($score != 0) { $result[] = $item; } elseif ($score == 0 && $bean->settings['unmatch_add']) { $result[] = $item; } } } // Calculate an overall score. $all = 0; foreach ($result as $item) { $all = $item['score'] + $all; } // If overall score is none, do sort. if ($all != 0) { // Invoke comparison function to determine highest ranked results. usort($result, "bean_tax_cmp"); } } // Remove active page from results. if (!empty($result)) { foreach ($result as $key => $entity) { $active_page = bean_tax_active_entity_array('page'); if (isset($active_page['ids']) && $active_page['ids'][0] == $entity['id'] && $active_page['type'] == $bean->settings['entity_type']) { unset($result[$key]); } } } // Related entities initially set to none. if (empty($result)) { // Hide block when result is empty and 'hide_empty' option is checked. if ($bean->settings['hide_empty'] || !$active_entity['object']) { return; } // There are no related nodes. Set Empty array for theme output. $content['#markup'] = t('No Results'); } elseif (isset($active_entity['type']) && $active_entity['type'] == 'bean' && $bean->bid === $active_entity['object']->bid) { $content['#markup'] = ''; } else { // Start counting results at index of 0. $i = 0; // Set and index for actual results shown. $shown = 0; // Set markup index as empty. $content['#markup'] = ''; // Load and render the related entities. foreach ($result as $entity) { if (isset($entity['id']) && $shown < $bean->filters['records_shown'] && $i >= $bean->filters['offset_results']) { $entity = entity_load_single($bean->settings['entity_type'], $entity['id']); $entity_view = entity_view($bean->settings['entity_type'], array($entity), $bean->settings['entity_view_mode']); $content['#markup'] .= drupal_render($entity_view); $shown++; } // Count continues along... $i++; } } } if (!empty($bean->more_link['text']) && !empty($bean->more_link['path'])) { // Invoke the theme function to show the additional information "more link" $content['#markup'] .= theme('bean_tax_more_link', array('text' => $bean->more_link['text'], 'path' => $bean->more_link['path'])); } return $content; }
/** * Return the related entities as rendered HTML markup. */ private function returnMarkup($bean, $result) { // Start counting results at index of 0. $i = 0; // Set and index for actual results shown. $shown = 0; // Set markup array as empty. $markup = ''; // Load and render the related entities. foreach ($result as $entity) { if (isset($entity['id']) && $shown < $bean->filters['records_shown'] && $i >= $bean->filters['offset_results']) { $entity = entity_load_single($bean->settings['entity_type'], $entity['id']); $entity_view = entity_view($bean->settings['entity_type'], array($entity), $bean->settings['entity_view_mode']); $markup .= drupal_render($entity_view); $shown++; } // Count continues along... $i++; } return $markup; }
/** * Theme an entity through an advanced function coming from the views entity plugin. * * @param $entity * The entity * @param $view_mode * The name of the view mode. */ function hook_ds_views_row_render_entity($entity, $view_mode) { $entity = entity_load('node', 1); return entity_view($entity, $view_mode); }
foreach ($chat_log as $openid => $chat_info) { ?> <?php //$chat_info = (object) $chat_info; ?> <div class="chat_log_item <?php echo $chat_info->who_to_who; ?> "> <?php //dpm($chat_info); $massage = ''; $view = ''; if ($chat_info->who_to_who == 'user_to_kf') { $massage = wechat_kf_received_load($chat_info->received_id); $view = $massage->view(); } elseif ($chat_info->who_to_who == 'kf_to_user') { $massage = wechat_kf_send_load($chat_info->send_id); $view = entity_view('wechat_kf_send', array($massage)); } ?> <?php echo render($view); ?> </div> <?php } ?> </ul>
/** * {@inheritdoc} */ public function build() { $uuid = $this->getDerivativeId(); if ($block = entity_load_by_uuid('block_content', $uuid)) { return entity_view($block, $this->configuration['view_mode']); } else { return array('#markup' => t('Block with uuid %uuid does not exist. <a href="!url">Add custom block</a>.', array('%uuid' => $uuid, '!url' => url('block/add'))), '#access' => $this->account->hasPermission('administer blocks')); } }
/** * Tests using entity fields of the file field type. */ public function testFileItem() { // Check that the selection handler was automatically assigned to // 'default:file'. $field_definition = FieldConfig::load('entity_test.entity_test.file_test'); $handler_id = $field_definition->getSetting('handler'); $this->assertEqual($handler_id, 'default:file'); // Create a test entity with the $entity = EntityTest::create(); $entity->file_test->target_id = $this->file->id(); $entity->file_test->display = 1; $entity->file_test->description = $description = $this->randomMachineName(); $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = EntityTest::load($entity->id()); $this->assertTrue($entity->file_test instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->file_test[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->file_test->target_id, $this->file->id()); $this->assertEqual($entity->file_test->display, 1); $this->assertEqual($entity->file_test->description, $description); $this->assertEqual($entity->file_test->entity->getFileUri(), $this->file->getFileUri()); $this->assertEqual($entity->file_test->entity->url(), $url = file_create_url($this->file->getFileUri())); $this->assertEqual($entity->file_test->entity->id(), $this->file->id()); $this->assertEqual($entity->file_test->entity->uuid(), $this->file->uuid()); // Make sure the computed files reflects updates to the file. file_put_contents('public://example-2.txt', $this->randomMachineName()); $file2 = File::create(['uri' => 'public://example-2.txt']); $file2->save(); $entity->file_test->target_id = $file2->id(); $this->assertEqual($entity->file_test->entity->id(), $file2->id()); $this->assertEqual($entity->file_test->entity->getFileUri(), $file2->getFileUri()); // Test the deletion of an entity having an entity reference field targeting // a non-existing entity. $file2->delete(); $entity->delete(); // Test the generateSampleValue() method. $entity = EntityTest::create(); $entity->file_test->generateSampleItems(); $this->entityValidateAndSave($entity); // Verify that the sample file was stored in the correct directory. $uri = $entity->file_test->entity->getFileUri(); $this->assertEqual($this->directory, dirname(file_uri_target($uri))); // Make sure the computed files reflects updates to the file. file_put_contents('public://example-3.txt', $this->randomMachineName()); // Test unsaved file entity. $file3 = File::create(['uri' => 'public://example-3.txt']); $display = entity_get_display('entity_test', 'entity_test', 'default'); $display->setComponent('file_test', ['label' => 'above', 'type' => 'file_default', 'weight' => 1])->save(); $entity = EntityTest::create(); $entity->file_test = array('entity' => $file3); $uri = $file3->getFileUri(); $output = entity_view($entity, 'default'); \Drupal::service('renderer')->renderRoot($output); $this->assertTrue(!empty($entity->file_test->entity)); $this->assertEqual($entity->file_test->entity->getFileUri(), $uri); }
/** * {@inheritdoc} * * @see \Drupal\content_translation\Controller\ContentTranslationController::prepareTranslation() * Uses a similar approach to populate a new translation. */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $field_name = $this->fieldDefinition->getName(); $parents = $element['#field_parents']; $paragraphs_entity = NULL; $widget_state = static::getWidgetState($parents, $field_name, $form_state); $entity_manager = \Drupal::entityManager(); $target_type = $this->getFieldSetting('target_type'); $item_mode = isset($widget_state['paragraphs'][$delta]['mode']) ? $widget_state['paragraphs'][$delta]['mode'] : 'edit'; $default_edit_mode = $this->getSetting('edit_mode'); $show_must_be_saved_warning = FALSE; if (isset($widget_state['paragraphs'][$delta]['entity'])) { $paragraphs_entity = $widget_state['paragraphs'][$delta]['entity']; } elseif (isset($items[$delta]->entity)) { $paragraphs_entity = $items[$delta]->entity; // We don't have a widget state yet, get from selector settings. if (!isset($widget_state['paragraphs'][$delta]['mode'])) { if ($default_edit_mode == 'open') { $item_mode = 'edit'; } elseif ($default_edit_mode == 'closed') { $item_mode = 'closed'; } elseif ($default_edit_mode == 'preview') { $item_mode = 'preview'; } } } elseif (isset($widget_state['selected_bundle'])) { $entity_type = $entity_manager->getDefinition($target_type); $bundle_key = $entity_type->getKey('bundle'); $paragraphs_entity = $entity_manager->getStorage($target_type)->create(array($bundle_key => $widget_state['selected_bundle'])); $item_mode = 'edit'; } if ($item_mode == 'collapsed') { $item_mode = $default_edit_mode; $show_must_be_saved_warning = TRUE; } if ($paragraphs_entity) { // If target translation is not yet available, populate it with data from the original paragraph. $target_langcode = $this->getCurrentLangcode($form_state, $items); if ($paragraphs_entity->language()->getId() != $target_langcode && !$paragraphs_entity->hasTranslation($target_langcode)) { $paragraphs_entity->addTranslation($target_langcode, $paragraphs_entity->toArray()); } // Initiate the paragraph with the correct translation. if ($paragraphs_entity->hasTranslation($this->getCurrentLangcode($form_state, $items))) { $paragraphs_entity = $paragraphs_entity->getTranslation($this->getCurrentLangcode($form_state, $items)); } else { $paragraphs_entity = $paragraphs_entity->addTranslation($this->getCurrentLangcode($form_state, $items)); } $element_parents = $parents; $element_parents[] = $field_name; $element_parents[] = $delta; $element_parents[] = 'subform'; $id_prefix = implode('-', array_merge($parents, array($field_name, $delta))); $wrapper_id = Html::getUniqueId($id_prefix . '-item-wrapper'); $element += array('#type' => 'container', '#element_validate' => array(array($this, 'elementValidate')), 'subform' => array('#type' => 'container', '#parents' => $element_parents)); $element['#prefix'] = '<div id="' . $wrapper_id . '">'; $element['#suffix'] = '</div>'; $item_bundles = $entity_manager->getBundleInfo($target_type); if (isset($item_bundles[$paragraphs_entity->bundle()])) { $bundle_info = $item_bundles[$paragraphs_entity->bundle()]; $element['top'] = array('#type' => 'container', '#weight' => -1000, '#attributes' => array('class' => array('paragraph-type-top'))); $element['top']['paragraph_type_title'] = array('#type' => 'container', '#weight' => 0, '#attributes' => array('class' => array('paragraph-type-title'))); $element['top']['paragraph_type_title']['info'] = array('#markup' => t('@title type: %type', array('@title' => $this->getSetting('title'), '%type' => $bundle_info['label']))); $actions = array(); $links = array(); $info = array(); if ($item_mode == 'edit') { if (isset($items[$delta]->entity) && ($default_edit_mode == 'preview' || $default_edit_mode == 'closed')) { $links['collapse_button'] = array('#type' => 'submit', '#value' => t('Collapse'), '#name' => strtr($id_prefix, '-', '_') . '_collapse', '#weight' => 499, '#submit' => array(array(get_class($this), 'collapseItemSubmit')), '#limit_validation_errors' => array(array_merge($parents, array($field_name, 'add_more'))), '#delta' => $delta, '#ajax' => array('callback' => array(get_class($this), 'itemAjax'), 'wrapper' => $widget_state['ajax_wrapper_id'], 'effect' => 'fade'), '#access' => $paragraphs_entity->access('update'), '#prefix' => '<li class="collapse">', '#suffix' => '</li>'); } // Hide the button when translating. $button_access = $paragraphs_entity->access('delete') && $paragraphs_entity->language()->getId() == $paragraphs_entity->getUntranslated()->language()->getId(); $links['remove_button'] = array('#type' => 'submit', '#value' => t('Remove'), '#name' => strtr($id_prefix, '-', '_') . '_remove', '#weight' => 500, '#submit' => array(array(get_class($this), 'removeItemSubmit')), '#limit_validation_errors' => array(array_merge($parents, array($field_name, 'add_more'))), '#delta' => $delta, '#ajax' => array('callback' => array(get_class($this), 'itemAjax'), 'wrapper' => $widget_state['ajax_wrapper_id'], 'effect' => 'fade'), '#access' => $button_access, '#prefix' => '<li class="remove">', '#suffix' => '</li>'); $info['edit_button_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('You are not allowed to edit this @title.', array('@title' => $this->getSetting('title'))) . '</em>', '#access' => !$paragraphs_entity->access('update') && $paragraphs_entity->access('delete')); $info['remove_button_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('You are not allowed to remove this @title.', array('@title' => $this->getSetting('title'))) . '</em>', '#access' => !$paragraphs_entity->access('delete') && $paragraphs_entity->access('update')); $info['edit_remove_button_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('You are not allowed to edit or remove this @title.', array('@title' => $this->getSetting('title'))) . '</em>', '#access' => !$paragraphs_entity->access('update') && !$paragraphs_entity->access('delete')); } elseif ($item_mode == 'preview' || $item_mode == 'closed') { $links['edit_button'] = array('#type' => 'submit', '#value' => t('Edit'), '#name' => strtr($id_prefix, '-', '_') . '_edit', '#weight' => 501, '#submit' => array(array(get_class($this), 'editItemSubmit')), '#limit_validation_errors' => array(array_merge($parents, array($field_name, 'add_more'))), '#delta' => $delta, '#ajax' => array('callback' => array(get_class($this), 'itemAjax'), 'wrapper' => $widget_state['ajax_wrapper_id'], 'effect' => 'fade'), '#access' => $paragraphs_entity->access('update'), '#prefix' => '<li class="edit">', '#suffix' => '</li>'); $links['remove_button'] = array('#type' => 'submit', '#value' => t('Remove'), '#name' => strtr($id_prefix, '-', '_') . '_remove', '#weight' => 502, '#submit' => array(array(get_class($this), 'removeItemSubmit')), '#limit_validation_errors' => array(array_merge($parents, array($field_name, 'add_more'))), '#delta' => $delta, '#ajax' => array('callback' => array(get_class($this), 'itemAjax'), 'wrapper' => $widget_state['ajax_wrapper_id'], 'effect' => 'fade'), '#access' => $paragraphs_entity->access('delete'), '#prefix' => '<li class="remove">', '#suffix' => '</li>'); if ($show_must_be_saved_warning) { $info['must_be_saved_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('Warning: this content must be saved to reflect changes on this @title item.', array('@title' => $this->getSetting('title'))) . '</em>'); } $info['preview_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('You are not allowed to view this @title.', array('@title' => $this->getSetting('title'))) . '</em>', '#access' => !$paragraphs_entity->access('view')); $info['edit_button_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('You are not allowed to edit this @title.', array('@title' => $this->getSetting('title'))) . '</em>', '#access' => !$paragraphs_entity->access('update') && $paragraphs_entity->access('delete')); $info['remove_button_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('You are not allowed to remove this @title.', array('@title' => $this->getSetting('title'))) . '</em>', '#access' => !$paragraphs_entity->access('delete') && $paragraphs_entity->access('update')); $info['edit_remove_button_info'] = array('#type' => 'markup', '#markup' => '<em>' . t('You are not allowed to edit or remove this @title.', array('@title' => $this->getSetting('title'))) . '</em>', '#access' => !$paragraphs_entity->access('update') && !$paragraphs_entity->access('delete')); } elseif ($item_mode == 'remove') { $element['top']['paragraph_type_title']['info'] = array('#markup' => t('Deleted @title type: %type', array('@title' => $this->getSetting('title'), '%type' => $bundle_info['label']))); $links['confirm_remove_button'] = array('#type' => 'submit', '#value' => t('Confirm removal'), '#name' => strtr($id_prefix, '-', '_') . '_confirm_remove', '#weight' => 503, '#submit' => array(array(get_class($this), 'confirmRemoveItemSubmit')), '#limit_validation_errors' => array(array_merge($parents, array($field_name, 'add_more'))), '#delta' => $delta, '#ajax' => array('callback' => array(get_class($this), 'itemAjax'), 'wrapper' => $widget_state['ajax_wrapper_id'], 'effect' => 'fade'), '#prefix' => '<li class="confirm-remove">', '#suffix' => '</li>'); $links['restore_button'] = array('#type' => 'submit', '#value' => t('Restore'), '#name' => strtr($id_prefix, '-', '_') . '_restore', '#weight' => 504, '#submit' => array(array(get_class($this), 'restoreItemSubmit')), '#limit_validation_errors' => array(array_merge($parents, array($field_name, 'add_more'))), '#delta' => $delta, '#ajax' => array('callback' => array(get_class($this), 'itemAjax'), 'wrapper' => $widget_state['ajax_wrapper_id'], 'effect' => 'fade'), '#prefix' => '<li class="restore">', '#suffix' => '</li>'); } if (count($links)) { $show_links = 0; foreach ($links as $link_item) { if (!isset($link_item['#access']) || $link_item['#access']) { $show_links++; } } if ($show_links > 0) { $element['top']['links'] = $links; if ($show_links > 1) { $element['top']['links']['#theme_wrappers'] = array('dropbutton_wrapper', 'paragraphs_dropbutton_wrapper'); $element['top']['links']['prefix'] = array('#markup' => '<ul class="dropbutton">', '#weight' => -999); $element['top']['links']['suffix'] = array('#markup' => '</li>', '#weight' => 999); } else { $element['top']['links']['#theme_wrappers'] = array('paragraphs_dropbutton_wrapper'); foreach ($links as $key => $link_item) { unset($element['top']['links'][$key]['#prefix']); unset($element['top']['links'][$key]['#suffix']); } } $element['top']['links']['#weight'] = 1; } } if (count($info)) { $show_info = FALSE; foreach ($info as $info_item) { if (!isset($info_item['#access']) || $info_item['#access']) { $show_info = TRUE; break; } } if ($show_info) { $element['info'] = $info; $element['info']['#weight'] = 998; } } if (count($actions)) { $show_actions = FALSE; foreach ($actions as $action_item) { if (!isset($action_item['#access']) || $action_item['#access']) { $show_actions = TRUE; break; } } if ($show_actions) { $element['actions'] = $actions; $element['actions']['#type'] = 'actions'; $element['actions']['#weight'] = 999; } } } $display = EntityFormDisplay::collectRenderDisplay($paragraphs_entity, $this->getSetting('form_display_mode')); if ($item_mode == 'edit') { $display->buildForm($paragraphs_entity, $element['subform'], $form_state); } elseif ($item_mode == 'preview') { $element['subform'] = array(); $element['preview'] = entity_view($paragraphs_entity, 'preview', $paragraphs_entity->language()->getId()); $element['preview']['#access'] = $paragraphs_entity->access('view'); } elseif ($item_mode == 'closed') { $element['subform'] = array(); } else { $element['subform'] = array(); } $element['subform']['#attributes']['class'][] = 'paragraphs-subform'; $element['subform']['#access'] = $paragraphs_entity->access('update'); if ($item_mode == 'removed') { $element['#access'] = FALSE; } $widget_state['paragraphs'][$delta] = array('entity' => $paragraphs_entity, 'display' => $display, 'mode' => $item_mode); static::setWidgetState($parents, $field_name, $form_state, $widget_state); } else { $element['#access'] = FALSE; } return $element; }
/** * Tests using entity fields of the file field type. */ public function testFileItem() { // Create a test entity with the $entity = entity_create('entity_test'); $entity->file_test->target_id = $this->file->id(); $entity->file_test->display = 1; $entity->file_test->description = $description = $this->randomMachineName(); $entity->name->value = $this->randomMachineName(); $entity->save(); $entity = entity_load('entity_test', $entity->id()); $this->assertTrue($entity->file_test instanceof FieldItemListInterface, 'Field implements interface.'); $this->assertTrue($entity->file_test[0] instanceof FieldItemInterface, 'Field item implements interface.'); $this->assertEqual($entity->file_test->target_id, $this->file->id()); $this->assertEqual($entity->file_test->display, 1); $this->assertEqual($entity->file_test->description, $description); $this->assertEqual($entity->file_test->entity->getFileUri(), $this->file->getFileUri()); $this->assertEqual($entity->file_test->entity->url(), $url = file_create_url($this->file->getFileUri())); $this->assertEqual($entity->file_test->entity->id(), $this->file->id()); $this->assertEqual($entity->file_test->entity->uuid(), $this->file->uuid()); // Make sure the computed files reflects updates to the file. file_put_contents('public://example-2.txt', $this->randomMachineName()); $file2 = entity_create('file', array('uri' => 'public://example-2.txt')); $file2->save(); $entity->file_test->target_id = $file2->id(); $this->assertEqual($entity->file_test->entity->id(), $file2->id()); $this->assertEqual($entity->file_test->entity->getFileUri(), $file2->getFileUri()); // Test the deletion of an entity having an entity reference field targeting // a non-existing entity. $file2->delete(); $entity->delete(); // Test the generateSampleValue() method. $entity = entity_create('entity_test'); $entity->file_test->generateSampleItems(); $this->entityValidateAndSave($entity); // Make sure the computed files reflects updates to the file. file_put_contents('public://example-3.txt', $this->randomMachineName()); // Test unsaved file entity. $file3 = entity_create('file', array('uri' => 'public://example-3.txt')); $display = entity_get_display('entity_test', 'entity_test', 'default'); $display->setComponent('file_test', ['label' => 'above', 'type' => 'file_default', 'weight' => 1])->save(); $entity = entity_create('entity_test'); $entity->file_test = array('entity' => $file3); $uri = $file3->getFileUri(); $output = entity_view($entity, 'default'); \Drupal::service('renderer')->renderRoot($output); $this->assertTrue(!empty($entity->file_test->entity)); $this->assertEqual($entity->file_test->entity->getFileUri(), $uri); }
/** * Returns a list of entities as a render array using the given view mode and theme wrapper. * * @param $ids * Array of entity IDs to show in the list. * @param $view_mode * What view mode to use for showing the entities. * @param $theme_wrapper * An optional theme wrapper. * @param $entity_type * The entity type for the given IDs. * @return Render array. */ protected function getList($ids, $view_mode = 'teaser', $theme_wrapper = NULL, $entity_type = 'node') { if (!$ids) { return FALSE; } $entities = entity_load($entity_type, $ids); $ret = array('#total' => count($entities)); $info = entity_get_info($entity_type); foreach ($entities as $entity) { $ret[$entity->{$info['entity keys']['id']}] = entity_view($entity_type, array($entity), $view_mode); } if ($theme_wrapper) { $ret['#theme_wrappers'] = array($theme_wrapper); } return $ret; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $view_mode = $this->getSetting('view_mode'); $links = $this->getSetting('links'); $target_type = $this->getFieldSetting('target_type'); $elements = array(); foreach ($items as $delta => $item) { if (!$item->access) { // User doesn't have access to the referenced entity. continue; } // Protect ourselves from recursive rendering. static $depth = 0; $depth++; if ($depth > 20) { throw new RecursiveRenderingException(format_string('Recursive rendering detected when rendering entity @entity_type(@entity_id). Aborting rendering.', array('@entity_type' => $item->entity->getEntityTypeId(), '@entity_id' => $item->target_id))); } if (!empty($item->target_id)) { // The viewElements() method of entity field formatters is run // during the #pre_render phase of rendering an entity. A formatter // builds the content of the field in preparation for theming. // All entity cache tags must be available after the #pre_render phase. // This field formatter is highly exceptional: it renders *another* // entity and this referenced entity has its own #pre_render // callbacks. In order collect the cache tags associated with the // referenced entity it must be passed to drupal_render() so that its // #pre_render callbacks are invoked and its full build array is // assembled. Rendering the referenced entity in place here will allow // its cache tags to be bubbled up and included with those of the // main entity when cache tags are collected for a renderable array // in drupal_render(). // @todo remove this work-around, see https://drupal.org/node/2273277 $referenced_entity_build = entity_view($item->entity, $view_mode, $item->getLangcode()); drupal_render($referenced_entity_build, TRUE); $elements[$delta] = $referenced_entity_build; if (empty($links) && isset($result[$delta][$target_type][$item->target_id]['links'])) { // Hide the element links. $elements[$delta][$target_type][$item->target_id]['links']['#access'] = FALSE; } // Add a resource attribute to set the mapping property's value to the // entity's url. Since we don't know what the markup of the entity will // be, we shouldn't rely on it for structured data such as RDFa. if (!empty($item->_attributes)) { $item->_attributes += array('resource' => $item->entity->url()); } } else { // This is an "auto_create" item. $elements[$delta] = array('#markup' => $item->entity->label()); } $depth = 0; } return $elements; }