3 namespace Drupal\entity_browser\Element;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Render\Element\FormElement;
8 use Drupal\entity_browser\Entity\EntityBrowser;
9 use Drupal\Core\Entity\EntityInterface;
12 * Provides an Entity Browser form element.
15 * - #entity_browser: Entity browser or ID of the Entity browser to be used.
16 * - #cardinality: (optional) Maximum number of items that are expected from
17 * the entity browser. Unlimited by default.
18 * - #default_value: (optional) Array of entities that Entity browser should be
19 * initialized with. It's only applicable when edit selection mode is used.
20 * - #entity_browser_validators: (optional) Array of validators that are to be
21 * passed to the entity browser. Array keys are plugin IDs and array values
22 * are plugin configuration values. Cardinality validator will be set
24 * - #selection_mode: (optional) Determines how selection in entity browser will
25 * be handled. Will selection be appended/prepended or it will be replaced
26 * in case of editing. Defaults to append.
28 * Return value will be an array of selected entities, which will appear under
29 * 'entities' key on the root level of the element's values in the form state.
31 * @FormElement("entity_browser")
33 class EntityBrowserElement extends FormElement {
36 * Indicating an entity browser can return an unlimited number of values.
38 * Note: When entity browser is used in Fields, cardinality is directly
39 * propagated from Field settings, that's why this constant should be equal to
40 * FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED.
42 const CARDINALITY_UNLIMITED = -1;
45 * Selection from entity browser will be appended to existing list.
47 * When this selection mode is used, then entity browser will not be
48 * populated with existing selection. Preselected list will be empty.
50 * Note: This option is also used by "js/entity_browser.common.js".
52 const SELECTION_MODE_APPEND = 'selection_append';
55 * Selection from entity browser will be prepended to existing list.
57 * When this selection mode is used, then entity browser will not be
58 * populated with existing selection. Preselected list will be empty.
60 * Note: This option is also used by "js/entity_browser.common.js".
62 const SELECTION_MODE_PREPEND = 'selection_prepend';
65 * Selection from entity browser will replace existing.
67 * When this selection mode is used, then entity browser will be populated
68 * with existing selection and returned selected list will replace existing
69 * selection. This option requires entity browser selection display with
70 * preselection support.
72 * Note: This option is also used by "js/entity_browser.common.js".
74 const SELECTION_MODE_EDIT = 'selection_edit';
79 public function getInfo() {
80 $class = get_class($this);
84 '#cardinality' => static::CARDINALITY_UNLIMITED,
85 '#selection_mode' => static::SELECTION_MODE_APPEND,
86 '#process' => [[$class, 'processEntityBrowser']],
87 '#default_value' => [],
88 '#entity_browser_validators' => [],
89 '#attached' => ['library' => ['entity_browser/common']],
94 * Get selection mode options.
97 * Selection mode options.
99 public static function getSelectionModeOptions() {
101 static::SELECTION_MODE_APPEND => t('Append to selection'),
102 static::SELECTION_MODE_PREPEND => t('Prepend selection'),
103 static::SELECTION_MODE_EDIT => t('Edit selection'),
108 * Check whether entity browser should be available for selection of entities.
110 * @param string $selection_mode
111 * Used selection mode.
112 * @param int $cardinality
114 * @param int $preselection_size
115 * Preseletion size, if it's available.
118 * Returns positive if entity browser can be used.
120 public static function isEntityBrowserAvailable($selection_mode, $cardinality, $preselection_size) {
121 if ($selection_mode == static::SELECTION_MODE_EDIT) {
125 $cardinality_exceeded =
126 $cardinality != static::CARDINALITY_UNLIMITED
127 && $preselection_size >= $cardinality;
129 return !$cardinality_exceeded;
133 * Render API callback: Processes the entity browser element.
135 public static function processEntityBrowser(&$element, FormStateInterface $form_state, &$complete_form) {
136 /** @var \Drupal\entity_browser\EntityBrowserInterface $entity_browser */
137 if (is_string($element['#entity_browser'])) {
138 $entity_browser = EntityBrowser::load($element['#entity_browser']);
141 $entity_browser = $element['#entity_browser'];
144 // Propagate selection if edit selection mode is used.
145 $entity_browser_preselected_entities = [];
146 if ($element['#selection_mode'] === static::SELECTION_MODE_EDIT) {
147 $entity_browser->getSelectionDisplay()->checkPreselectionSupport();
149 $entity_browser_preselected_entities = $element['#default_value'];
152 $default_value = implode(' ', array_map(
153 function (EntityInterface $item) {
154 return $item->getEntityTypeId() . ':' . $item->id();
156 $entity_browser_preselected_entities
158 $validators = array_merge(
159 $element['#entity_browser_validators'],
160 ['cardinality' => ['cardinality' => $element['#cardinality']]]
163 $display = $entity_browser->getDisplay();
164 $display->setUuid(sha1(implode('-', array_merge([$complete_form['#build_id']], $element['#parents']))));
165 $element['entity_browser'] = [
166 '#eb_parents' => array_merge($element['#parents'], ['entity_browser']),
168 $element['entity_browser'] = $display->displayEntityBrowser(
169 $element['entity_browser'],
173 'validators' => $validators,
174 'selected_entities' => $entity_browser_preselected_entities,
178 $hidden_id = Html::getUniqueId($element['#id'] . '-target');
179 $element['entity_ids'] = [
182 // We need to repeat ID here as it is otherwise skipped when rendering.
183 '#attributes' => ['id' => $hidden_id, 'class' => ['eb-target']],
184 '#default_value' => $default_value,
187 $element['#attached']['drupalSettings']['entity_browser'] = [
188 $entity_browser->getDisplay()->getUuid() => [
189 'cardinality' => $element['#cardinality'],
190 'selection_mode' => $element['#selection_mode'],
191 'selector' => '#' . $hidden_id,
201 public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
202 if ($input === FALSE) {
203 return $element['#default_value'] ?: [];
207 if ($input['entity_ids']) {
208 $entities = static::processEntityIds($input['entity_ids']);
211 return ['entities' => $entities];
215 * Processes entity IDs and gets array of loaded entities.
217 * @param array|string $ids
218 * Processes entity IDs as they are returned from the entity browser. They
219 * are in [entity_type_id]:[entity_id] form. Array of IDs or a
220 * space-delimited string is supported.
222 * @return \Drupal\Core\Entity\EntityInterface[]
223 * Array of entity objects.
225 public static function processEntityIds($ids) {
226 if (!is_array($ids)) {
227 $ids = array_filter(explode(' ', $ids));
232 list($entity_type, $entity_id) = explode(':', $item);
233 return \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id);
240 * Processes entity IDs and gets array of loaded entities.
243 * Processes entity ID as it is returned from the entity browser. ID should
244 * be in [entity_type_id]:[entity_id] form.
246 * @return \Drupal\Core\Entity\EntityInterface
249 public static function processEntityId($id) {
250 $return = static::processEntityIds([$id]);
251 return current($return);