3 namespace Drupal\Core\Entity\Element;
5 use Drupal\Component\Utility\Crypt;
6 use Drupal\Component\Utility\Tags;
7 use Drupal\Core\Entity\EntityInterface;
8 use Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface;
9 use Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element\Textfield;
12 use Drupal\Core\Site\Settings;
15 * Provides an entity autocomplete form element.
17 * The #default_value accepted by this element is either an entity object or an
18 * array of entity objects.
20 * @FormElement("entity_autocomplete")
22 class EntityAutocomplete extends Textfield {
27 public function getInfo() {
28 $info = parent::getInfo();
29 $class = get_class($this);
31 // Apply default form element properties.
32 $info['#target_type'] = NULL;
33 $info['#selection_handler'] = 'default';
34 $info['#selection_settings'] = [];
35 $info['#tags'] = FALSE;
36 $info['#autocreate'] = NULL;
37 // This should only be set to FALSE if proper validation by the selection
38 // handler is performed at another level on the extracted form values.
39 $info['#validate_reference'] = TRUE;
40 // IMPORTANT! This should only be set to FALSE if the #default_value
41 // property is processed at another level (e.g. by a Field API widget) and
42 // it's value is properly checked for access.
43 $info['#process_default_value'] = TRUE;
45 $info['#element_validate'] = [[$class, 'validateEntityAutocomplete']];
46 array_unshift($info['#process'], [$class, 'processEntityAutocomplete']);
54 public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
55 // Process the #default_value property.
56 if ($input === FALSE && isset($element['#default_value']) && $element['#process_default_value']) {
57 if (is_array($element['#default_value']) && $element['#tags'] !== TRUE) {
58 throw new \InvalidArgumentException('The #default_value property is an array but the form element does not allow multiple values.');
60 elseif (!empty($element['#default_value']) && !is_array($element['#default_value'])) {
61 // Convert the default value into an array for easier processing in
62 // static::getEntityLabels().
63 $element['#default_value'] = [$element['#default_value']];
66 if ($element['#default_value']) {
67 if (!(reset($element['#default_value']) instanceof EntityInterface)) {
68 throw new \InvalidArgumentException('The #default_value property has to be an entity object or an array of entity objects.');
71 // Extract the labels from the passed-in entity objects, taking access
72 // checks into account.
73 return static::getEntityLabels($element['#default_value']);
77 // Potentially the #value is set directly, so it contains the 'target_id'
78 // array structure instead of a string.
79 if ($input !== FALSE && is_array($input)) {
80 $entity_ids = array_map(function(array $item) {
81 return $item['target_id'];
84 $entities = \Drupal::entityTypeManager()->getStorage($element['#target_type'])->loadMultiple($entity_ids);
86 return static::getEntityLabels($entities);
91 * Adds entity autocomplete functionality to a form element.
93 * @param array $element
94 * The form element to process. Properties used:
95 * - #target_type: The ID of the target entity type.
96 * - #selection_handler: The plugin ID of the entity reference selection
98 * - #selection_settings: An array of settings that will be passed to the
100 * @param \Drupal\Core\Form\FormStateInterface $form_state
101 * The current state of the form.
102 * @param array $complete_form
103 * The complete form structure.
108 * @throws \InvalidArgumentException
109 * Exception thrown when the #target_type or #autocreate['bundle'] are
112 public static function processEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
113 // Nothing to do if there is no target entity type.
114 if (empty($element['#target_type'])) {
115 throw new \InvalidArgumentException('Missing required #target_type parameter.');
118 // Provide default values and sanity checks for the #autocreate parameter.
119 if ($element['#autocreate']) {
120 if (!isset($element['#autocreate']['bundle'])) {
121 throw new \InvalidArgumentException("Missing required #autocreate['bundle'] parameter.");
123 // Default the autocreate user ID to the current user.
124 $element['#autocreate']['uid'] = isset($element['#autocreate']['uid']) ? $element['#autocreate']['uid'] : \Drupal::currentUser()->id();
127 // Store the selection settings in the key/value store and pass a hashed key
128 // in the route parameters.
129 $selection_settings = isset($element['#selection_settings']) ? $element['#selection_settings'] : [];
130 $data = serialize($selection_settings) . $element['#target_type'] . $element['#selection_handler'];
131 $selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());
133 $key_value_storage = \Drupal::keyValue('entity_autocomplete');
134 if (!$key_value_storage->has($selection_settings_key)) {
135 $key_value_storage->set($selection_settings_key, $selection_settings);
138 $element['#autocomplete_route_name'] = 'system.entity_autocomplete';
139 $element['#autocomplete_route_parameters'] = [
140 'target_type' => $element['#target_type'],
141 'selection_handler' => $element['#selection_handler'],
142 'selection_settings_key' => $selection_settings_key,
149 * Form element validation handler for entity_autocomplete elements.
151 public static function validateEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
154 if (!empty($element['#value'])) {
156 'target_type' => $element['#target_type'],
157 'handler' => $element['#selection_handler'],
158 'handler_settings' => $element['#selection_settings'],
160 /** @var /Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler */
161 $handler = \Drupal::service('plugin.manager.entity_reference_selection')->getInstance($options);
162 $autocreate = (bool) $element['#autocreate'] && $handler instanceof SelectionWithAutocreateInterface;
164 // GET forms might pass the validated data around on the next request, in
165 // which case it will already be in the expected format.
166 if (is_array($element['#value'])) {
167 $value = $element['#value'];
170 $input_values = $element['#tags'] ? Tags::explode($element['#value']) : [$element['#value']];
172 foreach ($input_values as $input) {
173 $match = static::extractEntityIdFromAutocompleteInput($input);
174 if ($match === NULL) {
175 // Try to get a match from the input string when the user didn't use
176 // the autocomplete but filled in a value manually.
177 $match = static::matchEntityByTitle($handler, $input, $element, $form_state, !$autocreate);
180 if ($match !== NULL) {
182 'target_id' => $match,
185 elseif ($autocreate) {
186 /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface $handler */
187 // Auto-create item. See an example of how this is handled in
188 // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::presave().
190 'entity' => $handler->createNewEntity($element['#target_type'], $element['#autocreate']['bundle'], $input, $element['#autocreate']['uid']),
196 // Check that the referenced entities are valid, if needed.
197 if ($element['#validate_reference'] && !empty($value)) {
198 // Validate existing entities.
199 $ids = array_reduce($value, function ($return, $item) {
200 if (isset($item['target_id'])) {
201 $return[] = $item['target_id'];
207 $valid_ids = $handler->validateReferenceableEntities($ids);
208 if ($invalid_ids = array_diff($ids, $valid_ids)) {
209 foreach ($invalid_ids as $invalid_id) {
210 $form_state->setError($element, t('The referenced entity (%type: %id) does not exist.', ['%type' => $element['#target_type'], '%id' => $invalid_id]));
215 // Validate newly created entities.
216 $new_entities = array_reduce($value, function ($return, $item) {
217 if (isset($item['entity'])) {
218 $return[] = $item['entity'];
225 $valid_new_entities = $handler->validateReferenceableNewEntities($new_entities);
226 $invalid_new_entities = array_diff_key($new_entities, $valid_new_entities);
229 // If the selection handler does not support referencing newly
230 // created entities, all of them should be invalidated.
231 $invalid_new_entities = $new_entities;
234 foreach ($invalid_new_entities as $entity) {
235 /** @var \Drupal\Core\Entity\EntityInterface $entity */
236 $form_state->setError($element, t('This entity (%type: %label) cannot be referenced.', ['%type' => $element['#target_type'], '%label' => $entity->label()]));
241 // Use only the last value if the form element does not support multiple
243 if (!$element['#tags'] && !empty($value)) {
244 $last_value = $value[count($value) - 1];
245 $value = isset($last_value['target_id']) ? $last_value['target_id'] : $last_value;
249 $form_state->setValueForElement($element, $value);
253 * Finds an entity from an autocomplete input without an explicit ID.
255 * The method will return an entity ID if one single entity unambuguously
256 * matches the incoming input, and sill assign form errors otherwise.
258 * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler
259 * Entity reference selection plugin.
260 * @param string $input
261 * Single string from autocomplete element.
262 * @param array $element
263 * The form element to set a form error.
264 * @param \Drupal\Core\Form\FormStateInterface $form_state
265 * The current form state.
266 * @param bool $strict
267 * Whether to trigger a form error if an element from $input (eg. an entity)
271 * Value of a matching entity ID, or NULL if none.
273 protected static function matchEntityByTitle(SelectionInterface $handler, $input, array &$element, FormStateInterface $form_state, $strict) {
274 $entities_by_bundle = $handler->getReferenceableEntities($input, '=', 6);
275 $entities = array_reduce($entities_by_bundle, function ($flattened, $bundle_entities) {
276 return $flattened + $bundle_entities;
282 if (empty($entities)) {
284 // Error if there are no entities available for a required field.
285 $form_state->setError($element, t('There are no entities matching "%value".', $params));
288 elseif (count($entities) > 5) {
289 $params['@id'] = key($entities);
290 // Error if there are more than 5 matching entities.
291 $form_state->setError($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)".', $params));
293 elseif (count($entities) > 1) {
294 // More helpful error if there are only a few matching entities.
296 foreach ($entities as $id => $name) {
297 $multiples[] = $name . ' (' . $id . ')';
299 $params['@id'] = $id;
300 $form_state->setError($element, t('Multiple entities match this reference; "%multiple". Specify the one you want by appending the id in parentheses, like "@value (@id)".', ['%multiple' => implode('", "', $multiples)] + $params));
303 // Take the one and only matching entity.
304 return key($entities);
309 * Converts an array of entity objects into a string of entity labels.
311 * This method is also responsible for checking the 'view label' access on the
312 * passed-in entities.
314 * @param \Drupal\Core\Entity\EntityInterface[] $entities
315 * An array of entity objects.
318 * A string of entity labels separated by commas.
320 public static function getEntityLabels(array $entities) {
321 /** @var \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository */
322 $entity_repository = \Drupal::service('entity.repository');
325 foreach ($entities as $entity) {
326 // Set the entity in the correct language for display.
327 $entity = $entity_repository->getTranslationFromContext($entity);
329 // Use the special view label, since some entities allow the label to be
330 // viewed, even if the entity is not allowed to be viewed.
331 $label = ($entity->access('view label')) ? $entity->label() : t('- Restricted access -');
333 // Take into account "autocreated" entities.
334 if (!$entity->isNew()) {
335 $label .= ' (' . $entity->id() . ')';
338 // Labels containing commas or quotes must be wrapped in quotes.
339 $entity_labels[] = Tags::encode($label);
342 return implode(', ', $entity_labels);
346 * Extracts the entity ID from the autocompletion result.
348 * @param string $input
349 * The input coming from the autocompletion result.
352 * An entity ID or NULL if the input does not contain one.
354 public static function extractEntityIdFromAutocompleteInput($input) {
357 // Take "label (entity id)', match the ID from inside the parentheses.
358 // @todo Add support for entities containing parentheses in their ID.
359 // @see https://www.drupal.org/node/2520416
360 if (preg_match("/.+\s\(([^\)]+)\)/", $input, $matches)) {
361 $match = $matches[1];