getViewBuilder example

if ($referenced_entity === NULL) {
      return [];
    }

    $query = $this->entityTypeManager()->getStorage('entity_test')->getQuery()
      ->accessCheck(TRUE)
      ->condition($entity_reference_field_name . '.target_id', $referenced_entity_id);
    $entities = $this->entityTypeManager()
      ->getStorage('entity_test')
      ->loadMultiple($query->execute());
    return $this->entityTypeManager()
      ->getViewBuilder('entity_test')
      ->viewMultiple($entities, 'full');
  }

  /** * List entities of the given entity type labels, sorted alphabetically. * * @param string $entity_type_id * The type of the entity being listed. * * @return array * A renderable array. */
else {
      // Explicitly unset the property in $this->values if a non-defined       // property is unset, such that its key is removed from $this->values.       unset($this->values[$name]);
    }
  }

  /** * {@inheritdoc} */
  public function view($display_options = []) {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($this->getEntity()->getEntityTypeId());
    return $view_builder->viewFieldItem($this$display_options);
  }

  /** * {@inheritdoc} */
  public function preSave() {}

  /** * {@inheritdoc} */
  


  /** * Asserts that the rendered entity has the correct fields. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity to render. * @param array $attributes * An array of field attributes to assert. */
  protected function assertFieldAttributes(EntityInterface $entity, array $attributes) {
    $view_builder = $this->container->get('entity_type.manager')->getViewBuilder($entity->getEntityTypeId());
    $build = $view_builder->view($entity);
    $this->render($build);

    $actual = array_map(function D\SimpleXMLElement $element) {
      return (string) $element->attributes();
    }$this->cssSelect('.field'));
    $this->assertSame($attributes$actual);
  }

}
public function testTermPreview() {
    $entity_manager = \Drupal::entityTypeManager();
    $vocabulary = $this->createVocabulary();

    // Create a unsaved term.     $term = $entity_manager->getStorage('taxonomy_term')->create([
      'vid' => $vocabulary->id(),
      'name' => 'Foo',
    ]);

    // Confirm we can get the view of unsaved term.     $render_array = $entity_manager->getViewBuilder('taxonomy_term')
      ->view($term);
    $this->assertNotEmpty($render_array, 'Term view builder is built.');

    // Confirm we can render said view.     $rendered = \Drupal::service('renderer')->renderPlain($render_array);
    $this->assertNotEmpty(trim($rendered), 'Term is able to be rendered.');
  }

  /** * @covers \Drupal\taxonomy\TermStorage::deleteTermHierarchy * @group legacy */

  public function __construct(EntityTypeManagerInterface $entity_type_manager, MediaLibraryUiBuilder $library_ui_builder, OpenerResolverInterface $opener_resolver) {
    $this->entityTypeManager = $entity_type_manager;
    $this->libraryUiBuilder = $library_ui_builder;
    $this->viewBuilder = $this->entityTypeManager->getViewBuilder('media');
    $this->openerResolver = $opener_resolver;
  }

  /** * {@inheritdoc} */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('media_library.ui_builder'),
      $container->get('media_library.opener_resolver')
    );
protected $defaultTheme = 'stark';

  /** * Tests if template_preprocess_node() generates the correct suggestions. */
  public function testNodeThemeHookSuggestions() {
    // Create node to be rendered.     $node = $this->drupalCreateNode();
    $view_mode = 'full';

    // Simulate theming of the node.     $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node$view_mode);

    $variables['elements'] = $build;
    $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_node', [$variables]);

    $this->assertEquals(['node__full', 'node__page', 'node__page__full', 'node__' . $node->id(), 'node__' . $node->id() . '__full']$suggestions, 'Found expected node suggestions.');

    // Change the view mode.     $view_mode = 'node.my_custom_view_mode';
    $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node$view_mode);

    $variables['elements'] = $build;
    

class UnpublishByKeywordNode extends ConfigurableActionBase {

  /** * {@inheritdoc} */
  public function execute($node = NULL) {
    $elements = \Drupal::entityTypeManager()
      ->getViewBuilder('node')
      ->view(clone $node);
    $render = \Drupal::service('renderer')->render($elements);
    foreach ($this->configuration['keywords'] as $keyword) {
      if (str_contains($render$keyword) || str_contains($node->label()$keyword)) {
        $node->setUnpublished();
        $node->save();
        break;
      }
    }
  }

  
'value' => $comment->getAuthorName(),
      ],
      [
        'key' => 'guid',
        'value' => 'comment ' . $comment->id() . ' at ' . $base_url,
        'attributes' => ['isPermaLink' => 'false'],
      ],
    ];

    // The comment gets built and modules add to or modify     // $comment->rss_elements and $comment->rss_namespaces.     $build = $this->entityTypeManager->getViewBuilder('comment')->view($comment, 'rss');
    unset($build['#theme']);

    if (!empty($comment->rss_namespaces)) {
      $this->view->style_plugin->namespaces = array_merge($this->view->style_plugin->namespaces, $comment->rss_namespaces);
    }

    $item = new \stdClass();
    if ($view_mode != 'title') {
      // We render comment contents.       $item->description = $build;
    }
    
$this->setContainerParameter('twig.config', $parameters);
    $this->rebuildContainer();
    $this->resetAll();

    $cache = $this->container->get('theme.registry')->get();
    // Create array of Twig templates.     $templates = drupal_find_theme_templates($cache$extension$this->getThemePath('test_theme'));
    $templates += drupal_find_theme_templates($cache$extension$this->getModulePath('node'));

    // Create a node and test different features of the debug markup.     $node = $this->drupalCreateNode();
    $builder = \Drupal::entityTypeManager()->getViewBuilder('node');
    $build = $builder->view($node);
    $output = $renderer->renderRoot($build);
    $this->assertStringContainsString('<!-- THEME DEBUG -->', $output, 'Twig debug markup found in theme output when debug is enabled.');
    $this->assertStringContainsString("THEME HOOK: 'node'", $output, 'Theme call information found.');
    $this->assertStringContainsString('* node--1--full' . $extension . PHP_EOL . ' x node--1' . $extension . PHP_EOL . ' * node--page--full' . $extension . PHP_EOL . ' * node--page' . $extension . PHP_EOL . ' * node--full' . $extension . PHP_EOL . ' * node' . $extension$output, 'Suggested template files found in order and node ID specific template shown as current template.');
    $this->assertStringContainsString(Html::escape('node--<script type="text/javascript">alert(\'yo\');</script>')(string) $output);
    $this->assertStringContainsString('<!-- INVALID FILE NAME SUGGESTIONS:' . PHP_EOL . ' See https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!theme.api.php/function/hook_theme_suggestions_alter' . PHP_EOL . ' invalid_theme_suggestions' . PHP_EOL . '-->', $output, 'Twig debug markup found invalid suggestions.');
    $template_filename = $templates['node__1']['path'] . '/' . $templates['node__1']['template'] . $extension;
    $this->assertStringContainsString("BEGIN OUTPUT from '$template_filename'", $output, 'Full path to current template file found.');

    // Create another node and make sure the template suggestions shown in the

  public function __construct(EntityTypeManagerInterface $entity_type_manager, BookManagerInterface $book_manager, EntityRepositoryInterface $entity_repository) {
    $this->nodeStorage = $entity_type_manager->getStorage('node');
    $this->viewBuilder = $entity_type_manager->getViewBuilder('node');
    $this->bookManager = $book_manager;
    $this->entityRepository = $entity_repository;
  }

  /** * Generates HTML for export when invoked by book_export(). * * The given node is embedded to its absolute depth in a top level section. For * example, a child node with depth 2 in the hierarchy is contained in * (otherwise empty) <div> elements corresponding to depth 0 and depth 1. * This is intended to support WYSIWYG output; for instance, level 3 sections * always look like level 3 sections, no matter their depth relative to the * node selected to be exported as printer-friendly HTML. * * @param \Drupal\node\NodeInterface $node * The node to export. * * @return array * A render array representing the HTML for a node and its children in the * book hierarchy. * * @throws \Exception * Thrown when the node was not attached to a book. */

  protected function setUp(): void {
    parent::setUp();

    $this->controller = $this->container
      ->get('entity_type.manager')
      ->getStorage('block');

    $this->blockViewBuilder = $this->container
      ->get('entity_type.manager')
      ->getViewBuilder('block');
  }

  /** * Tests template suggestions from big_pipe_theme_suggestions_big_pipe_interface_preview(). */
  public function testBigPipeThemeHookSuggestions() {
    $entity = $this->controller->create([
      'id' => 'test_block1',
      'theme' => 'stark',
      'plugin' => 'test_html',
    ]);
    


  /** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    if ($update) {
      // Invalidate the render cache for all affected entities.       $entity_type_manager = \Drupal::entityTypeManager();
      $entity_type = $this->getTargetEntityTypeId();
      if ($entity_type_manager->hasHandler($entity_type, 'view_builder')) {
        $entity_type_manager->getViewBuilder($entity_type)->resetCache();
      }
    }
  }

  /** * {@inheritdoc} */
  public static function preDelete(EntityStorageInterface $storage, array $field_storages) {
    /** @var \Drupal\Core\Field\DeletedFieldsRepositoryInterface $deleted_fields_repository */
    $deleted_fields_repository = \Drupal::service('entity_field.deleted_fields_repository');

    
/** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    // Clear the cache.     \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();

    // Invalidate the render cache for all affected entities.     $entity_type = $this->getFieldStorageDefinition()->getTargetEntityTypeId();
    if ($this->entityTypeManager()->hasHandler($entity_type, 'view_builder')) {
      $this->entityTypeManager()->getViewBuilder($entity_type)->resetCache();
    }
  }

  /** * {@inheritdoc} */
  public function getLabel() {
    return $this->label();
  }

  /** * {@inheritdoc} */
$field_state = static::getWidgetState($form['#parents']$field_name$form_state);
    $field_state['items'] = $items->getValue();
    static::setWidgetState($form['#parents']$field_name$form_state$field_state);
  }

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    /** @var \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items */
    $referenced_entities = $items->referencedEntities();
    $view_builder = $this->entityTypeManager->getViewBuilder('media');
    $field_name = $this->fieldDefinition->getName();
    $parents = $form['#parents'];
    // Create an ID suffix from the parents to make sure each widget is unique.     $id_suffix = $parents ? '-' . implode('-', $parents) : '';
    $field_widget_id = implode(':', array_filter([$field_name$id_suffix]));
    $wrapper_id = $field_name . '-media-library-wrapper' . $id_suffix;
    $limit_validation_errors = [array_merge($parents[$field_name])];

    $settings = $this->getFieldSetting('handler_settings');
    $element += [
      '#type' => 'fieldset',
      
parent::__construct($values$entity_type);
  }

  /** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    // Reset the render cache for the target entity type.     parent::postSave($storage$update);
    if (\Drupal::entityTypeManager()->hasHandler($this->targetEntityType, 'view_builder')) {
      \Drupal::entityTypeManager()->getViewBuilder($this->targetEntityType)->resetCache();
    }
  }

  /** * {@inheritdoc} */
  public function getRenderer($field_name) {
    if (isset($this->plugins[$field_name])) {
      return $this->plugins[$field_name];
    }

    
Home | Imprint | This part of the site doesn't use cookies.