EntityAutocomplete.php in YAML Form 8
File
src/Plugin/YamlFormElement/EntityAutocomplete.php
View source
<?php
namespace Drupal\yamlform\Plugin\YamlFormElement;
use Drupal\Core\Form\FormStateInterface;
use Drupal\yamlform\YamlFormElementBase;
use Drupal\yamlform\YamlFormSubmissionInterface;
class EntityAutocomplete extends YamlFormElementBase implements YamlFormEntityReferenceInterface {
use YamlFormEntityReferenceTrait;
public function getDefaultProperties() {
return parent::getDefaultProperties() + [
'target_type' => '',
'selection_handler' => 'default',
'selection_settings' => [],
'tags' => FALSE,
];
}
public function setDefaultValue(array &$element) {
if (isset($element['#default_value']) && (!empty($element['#default_value']) || $element['#default_value'] === 0)) {
$target_storage = $this->entityTypeManager
->getStorage($element['#target_type']);
if ($this
->hasMultipleValues($element)) {
$entity_ids = $this
->getTargetEntityIds($element['#default_value']);
$element['#default_value'] = $entity_ids ? $target_storage
->loadMultiple($entity_ids) : [];
}
else {
$element['#default_value'] = $target_storage
->load($element['#default_value']) ?: NULL;
}
}
else {
$element['#default_value'] = NULL;
}
}
public function hasMultipleValues(array $element) {
return !empty($element['#tags']) ? TRUE : parent::hasMultipleValues($element);
}
public function prepare(array &$element, YamlFormSubmissionInterface $yamlform_submission) {
parent::prepare($element, $yamlform_submission);
if ($this
->hasMultipleValues($element)) {
$element['#after_build'][] = [
get_class($this),
'afterBuildEntityAutocomplete',
];
}
if (!empty($element['#selection_settings']['auto_create_bundle'])) {
$element['#autocreate']['bundle'] = $element['#selection_settings']['auto_create_bundle'];
}
}
public static function afterBuildEntityAutocomplete(array $element, FormStateInterface $form_state) {
$element['#element_validate'][] = [
'\\Drupal\\yamlform\\Plugin\\YamlFormElement\\EntityAutocomplete',
'validateEntityAutocomplete',
];
return $element;
}
public static function validateEntityAutocomplete(array &$element, FormStateInterface $form_state) {
$name = $element['#name'];
$value = $form_state
->getValue($name);
if (is_array($value) && !empty($value)) {
$entity_ids = [];
foreach ($value as $item) {
if (isset($item['target_id'])) {
$entity_ids[] = $item['target_id'];
}
elseif (isset($item['entity'])) {
$entity = $item['entity'];
$entity
->save();
$entity_ids[] = $entity
->id();
}
}
$form_state
->setValueForElement($element, $entity_ids);
}
}
}