You are here

public static function EntityAutocomplete::validateEntityAutocomplete in YAML Form 8

Form API callback. Remove target id property and create an array of entity ids.

File

src/Plugin/YamlFormElement/EntityAutocomplete.php, line 93

Class

EntityAutocomplete
Provides a 'entity_autocomplete' element.

Namespace

Drupal\yamlform\Plugin\YamlFormElement

Code

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'])) {

        // If #auto_create is set then we need to save the entity and get
        // the new entity's id.
        // @todo Decide what level of access controls are needed to allow
        // users to create entities.
        $entity = $item['entity'];
        $entity
          ->save();
        $entity_ids[] = $entity
          ->id();
      }
    }
    $form_state
      ->setValueForElement($element, $entity_ids);
  }
}