You are here

public function StarsFormatter::viewElements in Fivestar 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/StarsFormatter.php, line 105

Class

StarsFormatter
Plugin implementation of the 'fivestar_stars' formatter.

Namespace

Drupal\fivestar\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $entity = $items
    ->getEntity();
  $form_builder = \Drupal::formBuilder();
  $widget_active_key = $this
    ->getSelectedWidgetKey();
  $display_settings = [
    'name' => $this->widgetManager
      ->getWidgetInfo($widget_active_key) ? $widget_active_key : 'default',
  ] + $this
    ->getSettings();
  if (!$items
    ->isEmpty()) {

    /** @var \Drupal\fivestar\Plugin\Field\FieldType\FivestarItem $item */
    foreach ($items as $delta => $item) {
      $context = [
        'entity' => $entity,
        'field_definition' => $item
          ->getFieldDefinition(),
        'display_settings' => $display_settings,
      ];
      $elements[$delta] = $form_builder
        ->getForm('\\Drupal\\fivestar\\Form\\FivestarForm', $context);
    }
  }
  else {
    $bundle_fields = \Drupal::getContainer()
      ->get('entity_field.manager')
      ->getFieldDefinitions($entity
      ->getEntityType()
      ->id(), $entity
      ->bundle());
    $field_definition = $bundle_fields[$items
      ->getName()];
    $context = [
      'entity' => $entity,
      'field_definition' => $field_definition,
      'display_settings' => $display_settings,
    ];
    $elements[] = $form_builder
      ->getForm('\\Drupal\\fivestar\\Form\\FivestarForm', $context);
  }
  return $elements;
}