You are here

public function IngredientItem::processDefaultUnit in Recipe 8.2

Sets the options of the default_unit form element.

File

modules/ingredient/src/Plugin/Field/FieldType/IngredientItem.php, line 141

Class

IngredientItem
Plugin implementation of the 'ingredient' field type.

Namespace

Drupal\ingredient\Plugin\Field\FieldType

Code

public function processDefaultUnit($element, FormStateInterface $form_state, $form) {
  $unit_sets = $form_state
    ->getValue([
    'settings',
    'unit_sets',
  ]);
  $ingredient_unit_utility = \Drupal::service('ingredient.unit');
  $units = $ingredient_unit_utility
    ->getConfiguredUnits($unit_sets);
  $units = $ingredient_unit_utility
    ->sortUnitsByName($units);
  $element['#options'] = $ingredient_unit_utility
    ->createUnitSelectOptions($units);

  // If the #default_value is not in the current list of units due to an AJAX
  // reload, unset it to prevent a validation error when reloading.
  if (!isset($element['#options'][$element['#default_value']])) {
    unset($element['#default_value']);
    unset($element['#value']);
  }
  return $element;
}