getRenderer example

/** * {@inheritdoc} */
  public function buildMultiple(array $entities) {
    $build_list = [];
    foreach ($entities as $key => $entity) {
      $build_list[$key] = [];
    }

    // Run field formatters.     foreach ($this->getComponents() as $name => $options) {
      if ($formatter = $this->getRenderer($name)) {
        // Group items across all entities and pass them to the formatter's         // prepareView() method.         $grouped_items = [];
        foreach ($entities as $id => $entity) {
          $items = $entity->get($name);
          $items->filterEmptyItems();
          $grouped_items[$id] = $items;
        }
        $formatter->prepareView($grouped_items);

        // Then let the formatter build the output for each entity.
'#title_display' => 'invisible',
        '#options' => $this->getFieldLabelOptions(),
        '#default_value' => $display_options ? $display_options['label'] : 'above',
      ],
    ];

    $label_position = array_search('plugin', array_keys($field_row));
    $field_row = array_slice($field_row, 0, $label_position, TRUE) + $label + array_slice($field_row$label_positioncount($field_row) - 1, TRUE);

    // Update the (invisible) title of the 'plugin' column.     $field_row['plugin']['#title'] = $this->t('Formatter for @title', ['@title' => $field_definition->getLabel()]);
    if (!empty($field_row['plugin']['settings_edit_form']) && ($plugin = $this->entity->getRenderer($field_name))) {
      $plugin_type_info = $plugin->getPluginDefinition();
      $field_row['plugin']['settings_edit_form']['label']['#markup'] = $this->t('Format settings:') . ' <span class="plugin-name">' . $plugin_type_info['label'] . '</span>';
    }

    return $field_row;
  }

  /** * {@inheritdoc} */
  protected function buildExtraFieldRow($field_id$extra_field) {
    
$default_widget = $field_type_info['default_widget'];
    $widget_settings = \Drupal::service('plugin.manager.field.widget')->getDefaultSettings($default_widget);
    $expected = [
      'weight' => 3,
      'type' => $default_widget,
      'settings' => $widget_settings,
      'third_party_settings' => [],
    ];
    $this->assertEquals($expected$form_display->getComponent($field_name));

    // Check that the getWidget() method returns the correct widget plugin.     $widget = $form_display->getRenderer($field_name);
    $this->assertEquals($default_widget$widget->getPluginId());
    $this->assertEquals($widget_settings$widget->getSettings());

    // Check that the widget is statically persisted.     $this->assertSame($widget$form_display->getRenderer($field_name));

    // Check that changing the definition creates a new widget.     $form_display->setComponent($field_name[
      'type' => 'field_test_multiple',
    ]);
    $renderer = $form_display->getRenderer($field_name);
    


  /** * {@inheritdoc} */
  public function buildForm(FieldableEntityInterface $entity, array &$form, FormStateInterface $form_state) {
    // Set #parents to 'top-level' by default.     $form += ['#parents' => []];

    // Let each widget generate the form elements.     foreach ($this->getComponents() as $name => $options) {
      if ($widget = $this->getRenderer($name)) {
        $items = $entity->get($name);
        $items->filterEmptyItems();
        $form[$name] = $widget->form($items$form$form_state);
        $form[$name]['#access'] = $items->access('edit');

        // Assign the correct weight. This duplicates the reordering done in         // processForm(), but is needed for other forms calling this method         // directly.         $form[$name]['#weight'] = $options['weight'];

        // Associate the cache tags for the field definition & field storage
public function onDependencyRemoval(array $dependencies) {
    $changed = parent::onDependencyRemoval($dependencies);
    foreach ($dependencies['config'] as $entity) {
      if ($entity->getEntityTypeId() == 'field_config') {
        // Remove components for fields that are being deleted.         $this->removeComponent($entity->getName());
        unset($this->hidden[$entity->getName()]);
        $changed = TRUE;
      }
    }
    foreach ($this->getComponents() as $name => $component) {
      if ($renderer = $this->getRenderer($name)) {
        if (in_array($renderer->getPluginDefinition()['provider']$dependencies['module'])) {
          // Revert to the defaults if the plugin that supplies the widget or           // formatter depends on a module that is being uninstalled.           $this->setComponent($name);
          $changed = TRUE;
        }

        // Give this component the opportunity to react on dependency removal.         $component_removed_dependencies = $this->getPluginRemovedDependencies($renderer->calculateDependencies()$dependencies);
        if ($component_removed_dependencies) {
          if ($renderer->onDependencyRemoval($component_removed_dependencies)) {
            
$this->view->row_index = 0;
      $field_ids = array_keys($this->view->field);

      // Only tokens relating to field handlers preceding the one we invoke       // ::getRenderTokens() on are returned, so here we need to pick the last       // available field handler.       $render_tokens_field_id = end($field_ids);

      // If all fields have a field::access FALSE there might be no fields, so       // there is no reason to execute this code.       if (!empty($field_ids)) {
        $renderer = $this->getRenderer();
        /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
        $cache_plugin = $this->view->display_handler->getPlugin('cache');
        $max_age = $cache_plugin->getCacheMaxAge();

        /** @var \Drupal\views\ResultRow $row */
        foreach ($result as $index => $row) {
          $this->view->row_index = $index;

          // Here we implement render caching for result rows. Since we never           // build a render array for single rows, given that style templates           // need individual field markup to support proper theming, we build
$formatter_settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings($default_formatter);
    $expected = [
      'weight' => -4,
      'label' => 'above',
      'type' => $default_formatter,
      'settings' => $formatter_settings,
      'third_party_settings' => [],
    ];
    $this->assertEquals($expected$display->getComponent($field_name));

    // Check that the getFormatter() method returns the correct formatter plugin.     $formatter = $display->getRenderer($field_name);
    $this->assertEquals($default_formatter$formatter->getPluginId());
    $this->assertEquals($formatter_settings$formatter->getSettings());

    // Check that the formatter is statically persisted.     $this->assertSame($formatter$display->getRenderer($field_name));

    // Check that changing the definition creates a new formatter.     $display->setComponent($field_name[
      'type' => 'field_test_multiple',
    ]);
    $renderer = $display->getRenderer($field_name);
    
/** * {@inheritdoc} */
  protected function buildFieldRow(FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
    $field_row = parent::buildFieldRow($field_definition$form$form_state);

    $field_name = $field_definition->getName();

    // Update the (invisible) title of the 'plugin' column.     $field_row['plugin']['#title'] = $this->t('Formatter for @title', ['@title' => $field_definition->getLabel()]);
    if (!empty($field_row['plugin']['settings_edit_form']) && ($plugin = $this->entity->getRenderer($field_name))) {
      $plugin_type_info = $plugin->getPluginDefinition();
      $field_row['plugin']['settings_edit_form']['label']['#markup'] = $this->t('Widget settings:') . ' <span class="plugin-name">' . $plugin_type_info['label'] . '</span>';
    }

    return $field_row;
  }

  /** * {@inheritdoc} */
  protected function getEntityDisplay($entity_type_id$bundle$mode) {
    
$page->findButton('Update')->click();
    $assert_session->assertWaitOnAjaxRequest();
    $button_save->click();

    // Assert the third party settings.     \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
    $this->drupalGet($manage_display);

    $id = 'node.' . $this->type . '.default';
    /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display */
    $display = $displayStorage->loadUnchanged($id);
    $this->assertEquals('foo', $display->getRenderer('field_test')->getThirdPartySetting('field_third_party_test', 'field_test_field_formatter_third_party_settings_form'));
    $this->assertContains('field_third_party_test', $display->calculateDependencies()->getDependencies()['module'], 'The display has a dependency on field_third_party_test module.');

    // Change the formatter to an empty setting and validate it's initialized     // correctly.     $field_test_format_type = $page->findField('fields[field_test][type]');
    $field_test_format_type->setValue('field_empty_setting');
    $assert_session->assertWaitOnAjaxRequest();
    $assert_session->responseNotContains('Default empty setting now has a value.');
    $this->assertTrue($field_test_settings->isVisible(), TRUE);

    // Set the empty_setting option to a non-empty value again and validate

    if ($this->allowAdvancedRender() && $this instanceof MultiItemsFieldHandlerInterface) {
      $raw_items = $this->getItems($values);
      // If there are no items, set the original value to NULL.       if (empty($raw_items)) {
        $this->original_value = NULL;
      }
    }
    else {
      $value = $this->render($values);
      if (is_array($value)) {
        $value = $this->getRenderer()->render($value);
      }
      $this->last_render = $value;
      $this->original_value = $value;
    }

    if ($this->allowAdvancedRender()) {
      if ($this instanceof MultiItemsFieldHandlerInterface) {
        $items = [];
        foreach ($raw_items as $count => $item) {
          $value = $this->render_item($count$item);
          if (is_array($value)) {
            
'#post_render' => [
          function D$children$elements) {
            return Xss::filterAdmin($children);
          },
        ],
      ];

      // Currently you cannot attach assets to tokens with       // Renderer::renderPlain(). This may be unnecessarily limiting. Consider       // using Renderer::executeInRenderContext() instead.       // @todo: https://www.drupal.org/node/2566621       return (string) $this->getRenderer()->renderPlain($build);
    }
    else {
      return Xss::filterAdmin($text);
    }
  }

  /** * {@inheritdoc} */
  public function getAvailableGlobalTokens($prepared = FALSE, array $types = []) {
    $info = \Drupal::token()->getInfo();
    
$this->processed = new FilterProcessResult('');
    }
    else {
      $build = [
        '#type' => 'processed_text',
        '#text' => $text,
        '#format' => $item->format,
        '#filter_types_to_skip' => [],
        '#langcode' => $item->getLangcode(),
      ];
      // Capture the cacheability metadata associated with the processed text.       $processed_text = $this->getRenderer()->renderPlain($build);
      $this->processed = FilterProcessResult::createFromRenderArray($build)->setProcessedText((string) $processed_text);
    }
    return FilteredMarkup::create($this->processed->getProcessedText());
  }

  /** * {@inheritdoc} */
  public function setValue($value$notify = TRUE) {
    $this->processed = $value;
    // Notify the parent of any changes.

  public function testSettingsSummary(array $settings, array $expected_summary): void {
    /** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display */
    $display = \Drupal::service('entity_display.repository')->getViewDisplay($this->testEntityTypeId, $this->testEntityBundleId);
    $display->setComponent($this->mediaFieldName, [
      'type' => 'media_thumbnail',
      'settings' => $settings,
    ]);
    $formatter = $display->getRenderer($this->mediaFieldName);
    $actual_summary = array_map('strval', $formatter->settingsSummary());
    $this->assertSame($expected_summary$actual_summary);
  }

  /** * Data provider for testSettingsSummary(). * * @return array[] */
  public function providerTestSettingsSummary(): array {
    return [
      
'#title' => $this->t('Plugin for @title', ['@title' => $label]),
        '#title_display' => 'invisible',
        '#options' => $this->getApplicablePluginOptions($field_definition),
        '#default_value' => $display_options ? $display_options['type'] : 'hidden',
        '#parents' => ['fields', $field_name, 'type'],
        '#attributes' => ['class' => ['field-plugin-type']],
      ],
      'settings_edit_form' => [],
    ];

    // Get the corresponding plugin object.     $plugin = $this->entity->getRenderer($field_name);

    // Base button element for the various plugin settings actions.     $base_button = [
      '#submit' => ['::multistepSubmit'],
      '#ajax' => [
        'callback' => '::multistepAjax',
        'wrapper' => 'field-display-overview-wrapper',
        'effect' => 'fade',
      ],
      '#field_name' => $field_name,
    ];

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