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
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\Core\Render\Element\RenderElement implements ElementInterface
- class \Drupal\Core\Render\Element\FormElement implements FormElementInterface
- class \Drupal\commerce\Element\EntitySelect
- class \Drupal\Core\Render\Element\FormElement implements FormElementInterface
- class \Drupal\Core\Render\Element\RenderElement implements ElementInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
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.
File
- src/
Element/ EntitySelect.php, line 41
Namespace
Drupal\commerce\ElementView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntitySelect:: |
public | function |
Returns the element properties for this element. Overrides ElementInterface:: |
|
EntitySelect:: |
public static | function | Process callback. | |
EntitySelect:: |
public static | function | Validation callback. | |
FormElement:: |
public static | function | Adds autocomplete functionality to elements. | |
FormElement:: |
public static | function | #process callback for #pattern form element property. | |
FormElement:: |
public static | function | #element_validate callback for #pattern form element property. | |
FormElement:: |
public static | function |
Determines how user input is mapped to an element's #value property. Overrides FormElementInterface:: |
15 |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
PluginBase:: |
protected | property | Configuration information passed into the plugin. | 1 |
PluginBase:: |
protected | property | The plugin implementation definition. | 1 |
PluginBase:: |
protected | property | The plugin_id. | |
PluginBase:: |
constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
PluginBase:: |
public | function |
Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: |
|
PluginBase:: |
public | function |
Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: |
3 |
PluginBase:: |
public | function |
Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: |
|
PluginBase:: |
public | function | Determines if the plugin is configurable. | |
PluginBase:: |
public | function | Constructs a \Drupal\Component\Plugin\PluginBase object. | 92 |
RenderElement:: |
public static | function | Adds Ajax information about an element to communicate with JavaScript. | |
RenderElement:: |
public static | function | Adds members of this group as actual elements for rendering. | |
RenderElement:: |
public static | function | Form element processing handler for the #ajax form property. | 1 |
RenderElement:: |
public static | function | Arranges elements into groups. | |
RenderElement:: |
public static | function |
Sets a form element's class attribute. Overrides ElementInterface:: |
|
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. |