You are here

function bat_event_field_widget_form_alter in Booking and Availability Management Tools for Drupal 8

Implements hook_field_widget_WIDGET_TYPE_form_alter().

Limit BAT state reference fields to valid states.

File

modules/bat_event/bat_event.module, line 242
Manage Events - Events store the EventValue of a Unit over a period of time.

Code

function bat_event_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  // See if this form is editing a BAT event.
  $form_object = $form_state
    ->getFormObject();
  if ($form_object instanceof EntityFormInterface) {
    $entity = $form_object
      ->getEntity();
    if ($entity
      ->getEntityTypeId() == 'bat_event') {
      $entity_type_bundle = $entity
        ->bundle();

      // Limit options for select widgets.
      if (isset($element['#key_column']) && $element['#key_column'] == 'target_id' && $element['#type'] == 'select') {
        $valid_state_ids = array_keys(bat_event_get_states($entity_type_bundle));
        foreach ($element['#options'] as $key => $val) {
          if (!in_array($key, $valid_state_ids)) {
            unset($element['#options'][$key]);
          }
        }
      }
      elseif (isset($element['target_id']) && $element['target_id']['#type'] == 'entity_autocomplete' && $element['target_id']['#target_type'] == 'state') {

        // Use our custom selection handler.
        $element['target_id']['#selection_handler'] = 'bat_event:state';

        // Pass the bundle id to the handler.
        $element['target_id']['#selection_settings']['event_type_bundle'] = $entity_type_bundle;
      }
    }
  }
}