setValue(array($items[$delta]->getValue())); } else { $items->setValue(array()); } return parent::formElement($items, $delta, $element, $langcode, $form, $form_state); } /** * {@inheritdoc} */ public function elementValidate($element, &$form_state, $form) { $auto_create = $this->getSelectionHandlerSetting('auto_create'); // If a value was entered into the autocomplete. $value = ''; if (!empty($element['#value'])) { // Take "label (entity id)', match the id from parenthesis. if (preg_match("/.+\((\d+)\)/", $element['#value'], $matches)) { $value = $matches[1]; } else { // Try to get a match from the input string when the user didn't use the // autocomplete but filled in a value manually. $handler = \Drupal::service('plugin.manager.entity_reference.selection')->getSelectionHandler($this->fieldDefinition); $value = $handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form, !$auto_create); } if (!$value && $auto_create && (count($this->getSelectionHandlerSetting('target_bundles')) == 1)) { // Auto-create item. see entity_reference_field_presave(). $value = array( 'target_id' => 0, 'entity' => $this->createNewEntity($element['#value'], $element['#autocreate_uid']), // Keep the weight property. '_weight' => $element['#weight'], ); // Change the element['#parents'], so in form_set_value() we // populate the correct key. array_pop($element['#parents']); } } form_set_value($element, $value, $form_state); } }