View source
<?php
namespace Drupal\Core\Entity\Element;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Tags;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionWithAutocreateInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Textfield;
use Drupal\Core\Site\Settings;
class EntityAutocomplete extends Textfield {
public function getInfo() {
$info = parent::getInfo();
$class = get_class($this);
$info['#target_type'] = NULL;
$info['#selection_handler'] = 'default';
$info['#selection_settings'] = array();
$info['#tags'] = FALSE;
$info['#autocreate'] = NULL;
$info['#validate_reference'] = TRUE;
$info['#process_default_value'] = TRUE;
$info['#element_validate'] = array(
array(
$class,
'validateEntityAutocomplete',
),
);
array_unshift($info['#process'], array(
$class,
'processEntityAutocomplete',
));
return $info;
}
public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
if ($input === FALSE && isset($element['#default_value']) && $element['#process_default_value']) {
if (is_array($element['#default_value']) && $element['#tags'] !== TRUE) {
throw new \InvalidArgumentException('The #default_value property is an array but the form element does not allow multiple values.');
}
elseif (!is_array($element['#default_value'])) {
$element['#default_value'] = array(
$element['#default_value'],
);
}
if ($element['#default_value'] && !reset($element['#default_value']) instanceof EntityInterface) {
throw new \InvalidArgumentException('The #default_value property has to be an entity object or an array of entity objects.');
}
return static::getEntityLabels($element['#default_value']);
}
}
public static function processEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
if (empty($element['#target_type'])) {
throw new \InvalidArgumentException('Missing required #target_type parameter.');
}
if ($element['#autocreate']) {
if (!isset($element['#autocreate']['bundle'])) {
throw new \InvalidArgumentException("Missing required #autocreate['bundle'] parameter.");
}
$element['#autocreate']['uid'] = isset($element['#autocreate']['uid']) ? $element['#autocreate']['uid'] : \Drupal::currentUser()
->id();
}
$selection_settings = isset($element['#selection_settings']) ? $element['#selection_settings'] : [];
$data = serialize($selection_settings) . $element['#target_type'] . $element['#selection_handler'];
$selection_settings_key = Crypt::hmacBase64($data, Settings::getHashSalt());
$key_value_storage = \Drupal::keyValue('entity_autocomplete');
if (!$key_value_storage
->has($selection_settings_key)) {
$key_value_storage
->set($selection_settings_key, $selection_settings);
}
$element['#autocomplete_route_name'] = 'system.entity_autocomplete';
$element['#autocomplete_route_parameters'] = array(
'target_type' => $element['#target_type'],
'selection_handler' => $element['#selection_handler'],
'selection_settings_key' => $selection_settings_key,
);
return $element;
}
public static function validateEntityAutocomplete(array &$element, FormStateInterface $form_state, array &$complete_form) {
$value = NULL;
if (!empty($element['#value'])) {
$options = array(
'target_type' => $element['#target_type'],
'handler' => $element['#selection_handler'],
'handler_settings' => $element['#selection_settings'],
);
$handler = \Drupal::service('plugin.manager.entity_reference_selection')
->getInstance($options);
$autocreate = (bool) $element['#autocreate'] && $handler instanceof SelectionWithAutocreateInterface;
$input_values = $element['#tags'] ? Tags::explode($element['#value']) : array(
$element['#value'],
);
foreach ($input_values as $input) {
$match = static::extractEntityIdFromAutocompleteInput($input);
if ($match === NULL) {
$match = static::matchEntityByTitle($handler, $input, $element, $form_state, !$autocreate);
}
if ($match !== NULL) {
$value[] = array(
'target_id' => $match,
);
}
elseif ($autocreate) {
$value[] = array(
'entity' => $handler
->createNewEntity($element['#target_type'], $element['#autocreate']['bundle'], $input, $element['#autocreate']['uid']),
);
}
}
if ($element['#validate_reference'] && !empty($value)) {
$ids = array_reduce($value, function ($return, $item) {
if (isset($item['target_id'])) {
$return[] = $item['target_id'];
}
return $return;
});
if ($ids) {
$valid_ids = $handler
->validateReferenceableEntities($ids);
if ($invalid_ids = array_diff($ids, $valid_ids)) {
foreach ($invalid_ids as $invalid_id) {
$form_state
->setError($element, t('The referenced entity (%type: %id) does not exist.', array(
'%type' => $element['#target_type'],
'%id' => $invalid_id,
)));
}
}
}
$new_entities = array_reduce($value, function ($return, $item) {
if (isset($item['entity'])) {
$return[] = $item['entity'];
}
return $return;
});
if ($new_entities) {
if ($autocreate) {
$valid_new_entities = $handler
->validateReferenceableNewEntities($new_entities);
$invalid_new_entities = array_diff_key($new_entities, $valid_new_entities);
}
else {
$invalid_new_entities = $new_entities;
}
foreach ($invalid_new_entities as $entity) {
$form_state
->setError($element, t('This entity (%type: %label) cannot be referenced.', array(
'%type' => $element['#target_type'],
'%label' => $entity
->label(),
)));
}
}
}
if (!$element['#tags'] && !empty($value)) {
$last_value = $value[count($value) - 1];
$value = isset($last_value['target_id']) ? $last_value['target_id'] : $last_value;
}
}
$form_state
->setValueForElement($element, $value);
}
protected static function matchEntityByTitle($handler, $input, &$element, FormStateInterface $form_state, $strict) {
$entities_by_bundle = $handler
->getReferenceableEntities($input, '=', 6);
$entities = array_reduce($entities_by_bundle, function ($flattened, $bundle_entities) {
return $flattened + $bundle_entities;
}, []);
$params = array(
'%value' => $input,
'@value' => $input,
);
if (empty($entities)) {
if ($strict) {
$form_state
->setError($element, t('There are no entities matching "%value".', $params));
}
}
elseif (count($entities) > 5) {
$params['@id'] = key($entities);
$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));
}
elseif (count($entities) > 1) {
$multiples = array();
foreach ($entities as $id => $name) {
$multiples[] = $name . ' (' . $id . ')';
}
$params['@id'] = $id;
$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)".', array(
'%multiple' => implode('", "', $multiples),
)));
}
else {
return key($entities);
}
}
public static function getEntityLabels(array $entities) {
$entity_labels = array();
foreach ($entities as $entity) {
$label = $entity
->access('view') ? $entity
->label() : t('- Restricted access -');
if (!$entity
->isNew()) {
$label .= ' (' . $entity
->id() . ')';
}
$entity_labels[] = Tags::encode($label);
}
return implode(', ', $entity_labels);
}
public static function extractEntityIdFromAutocompleteInput($input) {
$match = NULL;
if (preg_match("/.+\\((\\d+)\\)/", $input, $matches)) {
$match = $matches[1];
}
elseif (preg_match("/.+\\(([\\w.]+)\\)/", $input, $matches)) {
$match = $matches[1];
}
return $match;
}
}