You are here

public function ViewfieldWidgetSelect::formElement in Viewfield 8.3

Returns the form for a single field widget.

Field widget form elements should be based on the passed-in $element, which contains the base form element properties derived from the field configuration.

The BaseWidget methods will set the weight, field name and delta values for each form element. If there are multiple values for this field, the formElement() method will be called as many times as needed.

Other modules may alter the form element provided by this function using hook_field_widget_form_alter() or hook_field_widget_WIDGET_TYPE_form_alter().

The FAPI element callbacks (such as #process, #element_validate, #value_callback, etc.) used by the widget do not have access to the original $field_definition passed to the widget's constructor. Therefore, if any information is needed from that definition by those callbacks, the widget implementing this method, or a hook_field_widget[_WIDGET_TYPE]_form_alter() implementation, must extract the needed properties from the field definition and set them as ad-hoc $element['#custom'] properties, for later use by its element callbacks.

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: A form element array containing basic properties for the widget:

  • #field_parents: The 'parents' space for the field in the form. Most widgets can simply overlook this property. This identifies the location where the field values are placed within $form_state->getValues(), and is used to access processing information for the field through the getWidgetState() and setWidgetState() methods.
  • #title: The sanitized element label for the field, ready for output.
  • #description: The sanitized element description for the field, ready for output.
  • #required: A Boolean indicating whether the element value is required; for required multiple value fields, only the first widget's values are required.
  • #delta: The order of this item in the array of sub-elements; see $delta above.

array $form: The form structure where widgets are being attached to. This might be a full form structure, or a sub-element of a larger form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form elements for a single widget for this field.

Overrides OptionsSelectWidget::formElement

See also

hook_field_widget_form_alter()

hook_field_widget_WIDGET_TYPE_form_alter()

File

src/Plugin/Field/FieldWidget/ViewfieldWidgetSelect.php, line 27

Class

ViewfieldWidgetSelect
Plugin implementation of the 'viewfield_select' widget.

Namespace

Drupal\viewfield\Plugin\Field\FieldWidget

Code

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $field_type = $this->fieldDefinition
    ->getType();
  $item = $items[$delta];
  $element['target_id'] = parent::formElement($items, $delta, $element, $form, $form_state);
  $element['target_id']['#field_type'] = $field_type;
  $element['target_id']['#field_item'] = $item;
  $element['target_id']['#description'] = $this
    ->t('View name.');
  $element['target_id']['#ajax'] = [
    'callback' => [
      $this,
      'ajaxGetDisplayOptions',
    ],
    'event' => 'change',
    'progress' => [
      'type' => 'throbber',
      'message' => $this
        ->t('Retrieving view displays.'),
    ],
  ];

  // Set up options for allowed views.
  $empty_label = $this
    ->getEmptyLabel() ?: $this
    ->t('- None -');

  // Always allow '_none' for non-required fields or second and greater delta.
  $none_option = !$this->fieldDefinition
    ->isRequired() || $delta > 0 ? [
    '_none' => $empty_label,
  ] : [];
  $element['target_id']['#options'] = array_merge($none_option, $item
    ->getViewOptions());
  $element['target_id']['#multiple'] = FALSE;

  // Build an array of keys to retrieve values from $form_state.
  $form_state_keys = [
    $this->fieldDefinition
      ->getName(),
    $delta,
  ];
  if (!empty($form['#parents'])) {
    $form_state_keys = array_merge($form['#parents'], $form_state_keys);
  }

  // Assign default values.
  $default_target_id = NULL;
  $display_id_options = NULL;
  $default_display_id = NULL;
  $default_arguments = NULL;
  $default_items_to_display = NULL;
  $item_value = $item
    ->getValue();

  // Set initial default values from the item if they exist.
  if (isset($item_value['target_id'])) {
    $default_target_id = $item_value['target_id'];
    $display_id_options = $item
      ->getDisplayOptions($item_value['target_id']);
    $default_display_id = $item_value['display_id'];
    $default_arguments = $item_value['arguments'];
    $default_items_to_display = $item_value['items_to_display'];
  }

  // Set default values based on values from form_state, if they exist.
  $values = $form_state
    ->getValue($this->fieldDefinition
    ->getName());
  if (!empty($values[$delta])) {
    $default_target_id = $values[$delta]['target_id'];
    $default_display_id = $values[$delta]['display_id'];
    $default_arguments = $values[$delta]['arguments'];
    $display_id_options = $item
      ->getDisplayOptions($default_target_id);
    $default_items_to_display = $values[$delta]['items_to_display'];
  }

  // #default_value needs special handling, otherwise it consists of an array
  // of values corresponding to field items, one for each #delta.
  $element['target_id']['#default_value'] = $default_target_id;

  // Construct CSS class to target ajax callback.
  $display_id_class = $this
    ->createDisplayClass($form_state_keys);

  // Use primary target_id field to control visibility of secondary ones.
  $field_key = $form_state_keys[0] . '[' . implode('][', array_slice($form_state_keys, 1)) . ']';
  $primary_field_name = $field_key . '[target_id]';
  $primary_field_visible_test = [
    ':input[name="' . $primary_field_name . '"]' => [
      '!value' => '_none',
    ],
  ];
  $element['display_id'] = [
    '#title' => $this
      ->t('Display'),
    '#type' => 'select',
    '#options' => $display_id_options,
    '#default_value' => $default_display_id,
    '#description' => $this
      ->t('View display to be used.'),
    '#attributes' => [
      'class' => [
        $display_id_class,
      ],
    ],
    '#weight' => 10,
    '#states' => [
      'visible' => $primary_field_visible_test,
    ],
  ];
  $element['view_options'] = [
    '#type' => 'details',
    '#title' => $this
      ->t('Advanced options'),
    '#weight' => 20,
    '#open' => false,
    '#parents' => $form_state_keys,
    '#states' => [
      'open' => [
        [
          ':input[name="' . $field_key . '[arguments]"]' => [
            'filled' => TRUE,
          ],
        ],
        [
          ':input[name="' . $field_key . '[items_to_display]"]' => [
            'filled' => TRUE,
          ],
        ],
      ],
      'visible' => $primary_field_visible_test,
    ],
  ];
  $element['view_options']['arguments'] = [
    '#title' => $this
      ->t('Arguments'),
    '#type' => 'textfield',
    '#default_value' => $default_arguments,
    '#description' => $this
      ->t('Separate contextual filters with a "/". Each filter may use "+" or "," for multi-value arguments.<br>This field supports tokens.'),
    '#weight' => 20,
    '#states' => [
      'visible' => $primary_field_visible_test,
    ],
    '#maxlength' => 255,
  ];

  // Get entity types from the $items.
  $entity_type = $items
    ->getEntity()
    ->getEntityTypeId();

  // Token expects the value "term" for taxonomy_term entities.
  if ($entity_type == 'taxonomy_term') {
    $entity_type = 'term';
  }
  $element['view_options']['token_help'] = [
    '#type' => 'item',
    '#weight' => 30,
    '#states' => [
      'visible' => $primary_field_visible_test,
    ],
    'tokens' => [
      '#theme' => 'token_tree_link',
      '#token_types' => [
        $entity_type,
      ],
    ],
  ];
  $element['view_options']['items_to_display'] = [
    '#title' => $this
      ->t('Items to display'),
    '#type' => 'textfield',
    '#default_value' => $default_items_to_display,
    '#description' => $this
      ->t('Override the number of items to display. This also disables the pager if one is configured. Leave empty for default limit.'),
    '#weight' => 40,
    '#states' => [
      'visible' => $primary_field_visible_test,
    ],
  ];
  $element['#attached']['library'][] = 'viewfield/viewfield';
  return $element;
}