You are here

public function ViewsReferenceTrait::fieldElement in Views Reference Field 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/Field/FieldWidget/ViewsReferenceTrait.php \Drupal\viewsreference\Plugin\Field\FieldWidget\ViewsReferenceTrait::fieldElement()

Build a field element for a viewsreference field.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: Array of default values for this field.

int $delta: The order of this item in the array of sub-elements (0, 1, 2, etc.).

array $element: The field item element.

array $form: The overall form array.

\Drupal\Core\Form\FormStateInterface $form_state: Array of default values for this field.

Return value

array The changed field element.

2 calls to ViewsReferenceTrait::fieldElement()
ViewsReferenceSelectWidget::formElement in src/Plugin/Field/FieldWidget/ViewsReferenceSelectWidget.php
Returns the form for a single field widget.
ViewsReferenceWidget::formElement in src/Plugin/Field/FieldWidget/ViewsReferenceWidget.php
Returns the form for a single field widget.

File

src/Plugin/Field/FieldWidget/ViewsReferenceTrait.php, line 33

Class

ViewsReferenceTrait
Trait for shared code in Viewsreference Field Widgets.

Namespace

Drupal\viewsreference\Plugin\Field\FieldWidget

Code

public function fieldElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $field_name = $this->fieldDefinition
    ->getName();

  // Determine the element parents.
  $field_parents = [];
  if (isset($element['#field_parents'])) {
    $field_parents = $element['#field_parents'];
  }
  elseif (isset($element['target_id']['#field_parents'])) {
    $field_parents = $element['target_id']['#field_parents'];
  }
  $field_path = array_merge($field_parents, [
    $field_name,
    $delta,
  ]);
  $target_id_field_path = array_merge($field_path, [
    'target_id',
  ]);

  // Get the current values.
  $field_value = $this
    ->itemCurrentValues($items, $delta, $element, $form, $form_state);

  // Setup JavaScript states.
  switch ($element['target_id']['#type']) {
    case 'select':
      $view_selected_js_state = [
        '!value' => '_none',
      ];
      $ajax_event = 'change';
      $element['target_id']['#default_value'] = isset($field_value['target_id']) ? $field_value['target_id'] : '';
      break;
    default:
      $view_selected_js_state = [
        'filled' => TRUE,
      ];
      $ajax_event = 'viewsreference-select';
      break;
  }

  // Build our target_id field name attribute from the parent elements.
  $target_id_names = $target_id_field_path;
  $target_id_name_string = array_shift($target_id_names);
  foreach ($target_id_names as $target_id_name) {
    $target_id_name_string .= '[' . $target_id_name . ']';
  }

  // We build a unique class name from field elements and any parent elements
  // that might exist which will be used to render the display id options in
  // our ajax function.
  $html_wrapper_id = Html::getUniqueId(implode('-', $field_path));
  $class = get_class($this);
  $element['target_id']['#target_type'] = 'view';
  $element['target_id']['#limit_validation_errors'] = [];
  $element['target_id']['#ajax'] = [
    'callback' => [
      $class,
      'itemAjaxRefresh',
    ],
    'event' => $ajax_event,
    'wrapper' => $html_wrapper_id,
    'progress' => [
      'type' => 'throbber',
      'message' => $this
        ->t('Getting display IDs...'),
    ],
  ];
  $display_id = $field_value['display_id'] ?? NULL;
  $view_name = $field_value['target_id'] ?? NULL;
  $options = [];
  if ($view_name) {

    // Extract the view id from the text.
    preg_match('#\\((.*?)\\)#', $view_name, $match);
    if (!empty($match)) {
      $view_name = $match[1];
    }
    $options = $this
      ->getViewDisplays($view_name);
  }
  $element['display_id'] = [
    '#title' => $this
      ->t('Display'),
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => $display_id,
    '#empty_option' => $this
      ->t('- Select -'),
    '#empty_value' => '',
    '#weight' => 10,
    '#attributes' => [
      'class' => [
        'viewsreference-display-id',
      ],
    ],
    '#states' => [
      'visible' => [
        ':input[name="' . $target_id_name_string . '"]' => $view_selected_js_state,
      ],
      'required' => [
        ':input[name="' . $target_id_name_string . '"]' => $view_selected_js_state,
      ],
    ],
    '#ajax' => [
      'callback' => [
        $class,
        'itemAjaxRefresh',
      ],
      'event' => $ajax_event,
      'wrapper' => $html_wrapper_id,
      'progress' => [
        'type' => 'throbber',
        'message' => $this
          ->t('Getting options...'),
      ],
    ],
  ];
  $field_data = [];
  if (isset($field_value['data'])) {
    $field_data = unserialize($field_value['data'], [
      'allowed_classes' => FALSE,
    ]);
  }
  $element['options'] = [
    '#type' => 'details',
    '#title' => $this
      ->t('Options'),
    '#weight' => 10,
    '#states' => [
      'visible' => [
        ':input[name="' . $target_id_name_string . '"]' => $view_selected_js_state,
      ],
    ],
  ];
  $viewsreference_plugin_manager = \Drupal::service('plugin.manager.viewsreference.setting');
  $plugin_definitions = $viewsreference_plugin_manager
    ->getDefinitions();
  $enabled_settings = array_filter($this
    ->getFieldSetting('enabled_settings') ?? []);
  foreach ($enabled_settings as $enabled_setting) {
    if (!empty($plugin_definitions[$enabled_setting])) {
      $plugin_definition = $plugin_definitions[$enabled_setting];

      /** @var \Drupal\viewsreference\Plugin\ViewsReferenceSettingInterface $plugin_instance */
      $plugin_instance = $viewsreference_plugin_manager
        ->createInstance($plugin_definition['id'], [
        'view_name' => $view_name,
        'display_id' => $display_id,
      ]);
      $element['options'][$plugin_definition['id']] = [
        '#title' => $plugin_definition['label'],
        '#type' => 'textfield',
        '#default_value' => $field_data[$plugin_definition['id']] ?? $plugin_definition['default_value'],
        '#states' => [
          'visible' => [
            ':input[name="' . $target_id_name_string . '"]' => $view_selected_js_state,
          ],
        ],
      ];
      $plugin_instance
        ->alterFormField($element['options'][$plugin_definition['id']]);
    }
  }
  if (empty($enabled_settings)) {
    unset($element['options']);
  }
  $element['#attached']['library'][] = 'viewsreference/viewsreference';
  $element['#after_build'][] = [
    $class,
    'itemResetValues',
  ];

  // Wrap element for AJAX replacement.
  $element = [
    '#prefix' => '<div id="' . $html_wrapper_id . '">',
    '#suffix' => '</div>',
    // Pass the id along to other methods.
    '#wrapper_id' => $html_wrapper_id,
  ] + $element;
  return $element;
}