You are here

class EntitySelect in Commerce Core 8.2

Provides a form input element for selecting one or multiple entities.

The element is transformed based on the number of available entities: 1..#autocomplete_threshold: Checkboxes/radios element, based on #multiple. >#autocomplete_threshold: entity autocomplete element. If the element is required, and there's only one available entity, a hidden form element can be used instead of checkboxes/radios.

Properties:

  • #target_type: The entity type being selected.
  • #multiple: Whether the user may select more than one item.
  • #default_value: An entity ID or an array of entity IDs.
  • #hide_single_entity: Whether to use a hidden element when there's only one available entity and the element is required.
  • #autocomplete_threshold: Determines when to use the autocomplete.
  • #autocomplete_size: The size of the autocomplete element in characters.
  • #autocomplete_placeholder: The placeholder for the autocomplete element.

Example usage:


$form['entities'] = [
  '#type' => 'commerce_entity_select',
  '#title' => t('Stores'),
  '#target_type' => 'commerce_store',
  '#multiple' => TRUE,
];

@end

<h3>Plugin annotation</h3>
@code
@FormElement("commerce_entity_select")

Hierarchy

Expanded class hierarchy of EntitySelect

8 #type uses of EntitySelect
EntityBundleBase::buildConfigurationForm in src/Plugin/Commerce/Condition/EntityBundleBase.php
Form constructor.
EntitySelectWidget::formElement in src/Plugin/Field/FieldWidget/EntitySelectWidget.php
Returns the form for a single field widget.
OrderAddForm::buildForm in modules/order/src/Form/OrderAddForm.php
Form constructor.
OrderCurrency::buildConfigurationForm in modules/order/src/Plugin/Commerce/Condition/OrderCurrency.php
Form constructor.
OrderPaymentGateway::buildConfigurationForm in modules/payment/src/Plugin/Commerce/Condition/OrderPaymentGateway.php
Form constructor.

... See full list

File

src/Element/EntitySelect.php, line 41

Namespace

Drupal\commerce\Element
View source
class EntitySelect extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#target_type' => '',
      '#multiple' => FALSE,
      '#hide_single_entity' => TRUE,
      '#autocomplete_threshold' => 7,
      '#autocomplete_size' => 60,
      '#autocomplete_placeholder' => '',
      '#process' => [
        [
          $class,
          'processEntitySelect',
        ],
        [
          $class,
          'processAjaxForm',
        ],
      ],
      '#element_validate' => [
        [
          $class,
          'validateEntitySelect',
        ],
      ],
    ];
  }

  /**
   * Process callback.
   */
  public static function processEntitySelect(&$element, FormStateInterface $form_state, &$complete_form) {

    // Nothing to do if there is no target entity type.
    if (empty($element['#target_type'])) {
      throw new \InvalidArgumentException('Missing required #target_type parameter.');
    }

    /** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
    $storage = \Drupal::service('entity_type.manager')
      ->getStorage($element['#target_type']);
    $entity_count = $storage
      ->getQuery()
      ->accessCheck(TRUE)
      ->count()
      ->execute();
    $element['#tree'] = TRUE;

    // No need to show anything, there's only one possible value.
    if ($element['#required'] && $entity_count == 1 && $element['#hide_single_entity']) {
      $entity_ids = $storage
        ->getQuery()
        ->accessCheck(TRUE)
        ->execute();
      $element['value'] = [
        '#type' => 'hidden',
        '#value' => reset($entity_ids),
      ];
      return $element;
    }
    if ($entity_count <= $element['#autocomplete_threshold']) {

      // Start with a query to get only access-filtered results.
      $entity_ids = $storage
        ->getQuery()
        ->accessCheck(TRUE)
        ->execute();
      $entities = $storage
        ->loadMultiple($entity_ids);
      $entity_labels = EntityHelper::extractLabels($entities);

      // Radio buttons don't have a None option by default.
      if (!$element['#multiple'] && !$element['#required']) {
        $entity_labels = [
          '' => t('None'),
        ] + $entity_labels;
      }
      $element['value'] = [
        '#type' => $element['#multiple'] ? 'checkboxes' : 'radios',
        '#required' => $element['#required'],
        '#options' => $entity_labels,
      ];
      if (!empty($element['#default_value'])) {
        $element['value']['#default_value'] = $element['#default_value'];
      }
    }
    else {
      $default_value = NULL;
      if (!empty($element['#default_value'])) {

        // Upcast ids into entities, as expected by entity_autocomplete.
        if ($element['#multiple']) {
          $default_value = $storage
            ->loadMultiple($element['#default_value']);
        }
        else {
          $default_value = $storage
            ->load($element['#default_value']);
        }
      }
      $element['value'] = [
        '#type' => 'entity_autocomplete',
        '#target_type' => $element['#target_type'],
        '#tags' => $element['#multiple'],
        '#required' => $element['#required'],
        '#default_value' => $default_value,
        '#size' => $element['#autocomplete_size'],
        '#placeholder' => $element['#autocomplete_placeholder'],
        '#maxlength' => NULL,
      ];
    }

    // These keys only make sense on the actual input element.
    foreach ([
      '#title',
      '#title_display',
      '#description',
      '#ajax',
    ] as $key) {
      if (isset($element[$key])) {
        $element['value'][$key] = $element[$key];
        unset($element[$key]);
      }
    }
    return $element;
  }

  /**
   * Validation callback.
   *
   * Transforms the subelement value into a consistent format and set it on the
   * main element.
   */
  public static function validateEntitySelect(&$element, FormStateInterface $form_state, &$complete_form) {
    $value_element = $element['value'];
    $value = $form_state
      ->getValue($value_element['#parents']);
    if (is_array($value)) {
      if ($value_element['#type'] == 'checkboxes') {

        // Remove unselected checkboxes.
        $value = array_filter($value);

        // Non-numeric keys can cause issues when passing values to TypedData.
        $value = array_values($value);
      }
      elseif (!empty($value_element['#tags'])) {

        // Extract the entity ids from a multivalue autocomplete.
        $value = array_column($value, 'target_id');
      }
    }
    $form_state
      ->setValueForElement($element, $value);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntitySelect::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
EntitySelect::processEntitySelect public static function Process callback.
EntitySelect::validateEntitySelect public static function Validation callback.
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
FormElement::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElementInterface::valueCallback 15
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.