You are here

public static function AutoCreationProcessTrait::processAutoCreation in Select2 Boxes 8

Process the auto-creations and then normalise the input.

Parameters

array $element: The element.

mixed $input: The submitted data for the element.

Return value

mixed The processed input.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityStorageException

File

src/AutoCreationProcessTrait.php, line 30

Class

AutoCreationProcessTrait
Trait AutoCreationProcessTrait.

Namespace

Drupal\select2boxes

Code

public static function processAutoCreation(array &$element, $input) {

  // If '_none' is being sent as input then we bail out early.
  if ($input === '_none') {
    return $element['#multiple'] ? [] : NULL;
  }
  $data = $element['#select2'];
  if (!(isset($data['handler_settings']['auto_create']) && $data['handler_settings']['auto_create']) || !$input) {

    // Don't return false even though we were given it... That is bad somehow.
    return $input !== FALSE ? $input : ($element['#multiple'] ? [] : NULL);
  }

  // Prepare the data.
  $output = NULL;
  $options = $element['#options'];
  $target_type = $data['target_type'];
  $definition = \Drupal::entityTypeManager()
    ->getDefinition($target_type);
  $target_bundle = !empty($data['handler_settings']['auto_create_bundle']) ? $data['handler_settings']['auto_create_bundle'] : reset($data['handler_settings']['target_bundles']);

  // Prepare entity metadata array.
  $entity_metadata = [
    $target_type,
    $target_bundle,
    $definition,
  ];

  // Handle multi-value widget.
  if ($element['#multiple']) {

    // Process each item.
    foreach ($input as $item) {
      $output[] = self::processValueItem($entity_metadata, $item, $options);
    }
  }
  else {

    // Handle single-value widget.
    $output = self::processValueItem($entity_metadata, $input, $options);
  }
  $element['#options'] = $options;
  return $output;
}