You are here

public function ParagraphsTableFormatter::viewElements in Paragraphs table 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/ParagraphsTableFormatter.php, line 270

Class

ParagraphsTableFormatter
Plugin implementation of the 'paragraphs_table_formatter' formatter.

Namespace

Drupal\paragraphs_table\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $setting = $this
    ->getSettings();
  $targetType = $this
    ->getFieldSetting('target_type');
  $field_definition = $items
    ->getFieldDefinition();
  $entity = $items
    ->getEntity();
  $entityId = $entity
    ->id();

  // In edit Mode if entity have multiple paragraphs table
  // we will have 1st paragraphs field.
  $field_name_current = $field_definition
    ->getName();
  $request = \Drupal::request()->request;
  if ($field_name_current != ($trigger_name = $request
    ->get('_triggering_add_paragraphs'))) {
    if ($entity
      ->hasField($trigger_name) && empty($request
      ->get('edit_' . $trigger_name))) {
      $items = $entity
        ->get($trigger_name);
      $field_definition = $items
        ->getFieldDefinition();
    }
  }
  $targetBundle = array_key_first($field_definition
    ->getSetting("handler_settings")["target_bundles"]);

  /** @var \Drupal\paragraphs\ParagraphInterface $paragraphs_entity */
  $paragraphs_entity = \Drupal::entityTypeManager()
    ->getStorage($targetType)
    ->create([
    'type' => $targetBundle,
  ]);
  $field_definitions = $paragraphs_entity
    ->getFieldDefinitions();
  $view_mode = $setting['view_mode'];
  $viewDisplay = \Drupal::service('entity_display.repository')
    ->getViewDisplay($targetType, $targetBundle, $view_mode);
  $components = $viewDisplay
    ->getComponents();
  uasort($components, 'Drupal\\Component\\Utility\\SortArray::sortByWeightElement');
  $table = $table_header = $fields = [];
  foreach ($components as $field_name => $component) {
    if (!empty($field_definitions[$field_name]) && $field_definitions[$field_name] instanceof FieldConfigInterface) {
      $fields[$field_name] = $field_definitions[$field_name];
      $table_header[$field_name] = $this
        ->t((string) $field_definitions[$field_name]
        ->getLabel());
    }
  }
  $fieldName = $field_definition
    ->getName();
  $hasPermission = $this
    ->checkPermissionOperation($entity, $fieldName);
  if (!empty($setting['hide_line_operations'])) {
    $hasPermission = FALSE;
  }
  if ($hasPermission) {
    $table_header['operation'] = '';
  }
  $entities = $this
    ->getEntitiesToView($items, $langcode);
  $table_rows = $notEmptyColumn = [];
  if (in_array($setting['mode'], [
    'datatables',
    'bootstrapTable',
  ]) || empty($setting['mode'])) {
    if (empty($setting["ajax"]) && !empty($entities)) {
      $table_rows = $this
        ->getPreparedRenderedEntities($targetType, $targetBundle, $entities, $fields, $notEmptyColumn, $view_mode, $hasPermission);

      // Remove empty columns.
      if (!empty($setting["empty"]) && !empty($notEmptyColumn)) {
        foreach ($table_header as $field_name => $label_column) {
          if (empty($notEmptyColumn[$field_name])) {
            unset($table_header[$field_name]);
            foreach ($table_rows as $delta => &$row) {
              unset($row[$field_name]);
            }
          }
        }
      }
    }
    if (!empty($setting["vertical"])) {
      $table = $this
        ->getTableVertical($table_header, $table_rows, $entities);
    }
    else {
      $table = $this
        ->getTable($table_header, $table_rows, $entities);
      if (empty($table_rows) && $setting['empty']) {
        unset($table["#header"]);
      }
    }
  }
  $table_id = implode('-', [
    $targetType,
    $targetBundle,
  ]);
  $table['#attributes']['id'] = $table_id;
  $table['#attributes']['class'][] = 'paragraphs-table';
  if (!empty($setting['caption'])) {
    $table['#caption'] = $this
      ->t((string) $setting['caption']);
  }
  if (!empty($setting['custom_class'])) {
    $table['#attributes']['class'][] = $setting['custom_class'];
  }
  switch ($setting['mode']) {
    case 'datatables':
      $datatable_options = $this
        ->datatablesOption($table_header, $components, $langcode);
      if (!empty($setting["ajax"]) && $entityId) {
        $url = Url::fromRoute('paragraphs_item.json', [
          'field_name' => $fieldName,
          'host_type' => $field_definition
            ->getTargetEntityTypeId(),
          'host_id' => $entityId,
        ]);
        $datatable_options["ajax"] = $url
          ->toString();
      }
      $table['#attributes']['width'] = '100%';
      $table['#attached']['library'][] = 'paragraphs_table/datatables_core';
      $table['#attached']['drupalSettings']['datatables']['#' . $table_id] = $datatable_options;
      $table['#attached']['library'][] = 'paragraphs_table/datatables';
      break;
    case 'bootstrapTable':
      $bootstrapTable_options = $this
        ->bootstrapTableOption($table_header, $components, $langcode);
      foreach ($bootstrapTable_options as $dataTable => $valueData) {
        $table['#attributes']["data-{$dataTable}"] = $valueData;
      }
      if (!empty($setting["ajax"]) && $entityId) {
        $url = Url::fromRoute('paragraphs_item.json', [
          'field_name' => $fieldName,
          'host_type' => $field_definition
            ->getTargetEntityTypeId(),
          'host_id' => $entityId,
        ], [
          'query' => [
            'type' => 'rows',
          ],
        ]);
        $table['#attributes']["data-url"] = $url
          ->toString();
      }
      foreach ($table_header as $field_name => $field_label) {
        $table_header[$field_name] = [
          'data' => $field_label,
          'data-field' => $field_name,
          'data-sortable' => "true",
        ];
      }
      $table['#header'] = $table_header;
      $table['#attached']['library'][] = 'paragraphs_table/bootstrapTable';
      if (!\Drupal::moduleHandler()
        ->moduleExists('fontawesome')) {
        $table['#attached']['library'][] = 'paragraphs_table/bootstrapTable_fontawesome';
      }
      break;
    case 'googleCharts':
      $options = $this
        ->googleChartsOption($setting['chart_type']);
      $options['url'] = FALSE;
      if (!empty($setting['caption'])) {
        $options['title'] = $setting['caption'];
      }
      if (is_numeric($setting['chart_width'])) {
        $setting['chart_width'] .= 'px';
      }
      if (is_numeric($setting['chart_height'])) {
        $setting['chart_height'] .= 'px';
      }
      if (empty($setting['chart_width'])) {
        $setting['chart_width'] = '100%';
      }
      $table = [
        '#theme' => 'paragraphs_table_chart',
        '#settings' => $setting,
        '#id_field_name' => $table_id,
      ];
      $table['#attached']['drupalSettings']['googleCharts']['#' . $table_id] = [
        'id' => $table_id,
        'type' => !empty($setting['chart_type']) ? $setting['chart_type'] : 'BarChart',
        'options' => $options,
      ];
      if (empty($setting["ajax"])) {
        $data = $this
          ->getData($targetType, $targetBundle, $entities, $fields, $notEmptyColumn, $view_mode);
        if (isset($table_header["operation"])) {
          unset($table_header["operation"]);
        }
        if (empty($options['notHeader'])) {
          $data = array_merge([
            array_values($table_header),
          ], $data);
        }
        $table['#attached']['drupalSettings']['googleCharts']['#' . $table_id]['data'] = $data;
      }
      else {
        $url = Url::fromRoute('paragraphs_item.jsonData', [
          'field_name' => $fieldName,
          'host_type' => $field_definition
            ->getTargetEntityTypeId(),
          'host_id' => $entityId,
        ]);
        $table['#attached']['drupalSettings']['googleCharts']['#' . $table_id]['options']['url'] = $url
          ->toString();
      }
      $table['#attached']['library'][] = 'paragraphs_table/googleCharts';
      break;
    default:
      if (!empty($setting["ajax"])) {
        $url = Url::fromRoute('paragraphs_item.ajax', [
          'field_name' => $fieldName,
          'host_type' => $field_definition
            ->getTargetEntityTypeId(),
          'host_id' => $entityId,
        ]);
        $table['#attached']['drupalSettings']['paragraphsTable']['#' . $table_id] = [
          'id' => $table_id,
          'view_mode' => $view_mode,
          'url' => $url
            ->toString(),
        ];
        $table['#attached']['library'][] = 'paragraphs_table/paragraphsTable';
      }
      break;
  }

  // Alter table results.
  \Drupal::moduleHandler()
    ->alter('paragraphs_table_formatter', $table, $table_id);
  $form = NULL;
  if ($hasPermission) {
    $arrInfo = [
      $entity,
      $field_definition
        ->getName(),
      $targetBundle,
    ];
    $form_state = (new FormState())
      ->set('langcode', $langcode)
      ->disableRedirect()
      ->addBuildInfo('args', $arrInfo);
    $edit_btn = 'edit_' . $fieldName;
    if ($fieldName == $field_name_current) {
      $load_form = 'Drupal\\paragraphs_table\\Form\\ActionButtonForm';
      $is_edit_mode = FALSE;
      if (!empty($_POST[$edit_btn])) {
        $load_form = 'Drupal\\paragraphs_table\\Form\\ActionEditFieldForm';
        $table['#access'] = FALSE;
        $is_edit_mode = TRUE;
      }
      $form = \Drupal::formBuilder()
        ->buildForm($load_form, $form_state);
      if ($is_edit_mode) {
        $form[$edit_btn] = [
          '#type' => 'hidden',
          '#value' => $fieldName,
          '#name' => $edit_btn,
        ];
      }
    }
    if (!empty($redirect = $form_state
      ->getRedirect())) {
      return new RedirectResponse($redirect
        ->toString());
    }
    $triggering_input = $form_state
      ->getUserInput();
    if (!empty($triggering_input)) {
      $triggering_element = $form_state
        ->getTriggeringElement();
      $temp = !empty($triggering_element["#name"]) ? explode("_", $triggering_element["#name"]) : [];
      $trigger_mode = end($temp);
      if (!empty($triggering_input[$edit_btn]) || in_array($trigger_mode, [
        'remove',
        'duplicate',
      ])) {
        $table['#attributes']['class'][] = 'hidden';
        $table['#access'] = FALSE;
      }
    }
  }
  return [
    $table,
    $form,
  ];
}