You are here

public function SelectOtherAllowedValuesConstraintValidator::validate in CCK Select Other 8

File

src/Validation/Plugin/Validation/Constraint/SelectOtherAllowedValuesConstraintValidator.php, line 69

Class

SelectOtherAllowedValuesConstraintValidator
Bypass AllowedValuesConstraintValidator by rewriting it.

Namespace

Drupal\cck_select_other\Validation\Plugin\Validation\Constraint

Code

public function validate($value, Constraint $constraint) {
  $typed_data = $this
    ->getTypedData();

  // Only bypass validation for ListItemBase.
  if ($typed_data instanceof ListItemBase) {

    // Get the field instance definition.
    $constraint->choices = [];

    /** @var \Drupal\Core\Field\FieldDefinitionInterface $instance */
    $instance = $typed_data
      ->getFieldDefinition();
    $value = $typed_data
      ->getValue();
    if ($this
      ->hasSelectOtherWidget($instance) && !in_array($value, $constraint->choices)) {

      // Add the other value to the constraint choices.
      $constraint->choices[] = $value;
    }
  }
  elseif ($typed_data instanceof EntityReferenceItem) {

    // Entity reference fields remove their allowed values constraint in the
    // getConstraint method, but those fields will have their constraints
    // altered already, and so those fields must be ignored.
    return;
  }
  if (empty($constraint->choices)) {
    $this
      ->validateFallback($value, $constraint);
    return;
  }

  // The parent implementation ignores values that are not set, but makes
  // sure some choices are available firstly. However, we want to support
  // empty choices for undefined values, e.g. if a term reference field
  // points to an empty vocabulary.
  if (!isset($value)) {
    return;
  }
  parent::validate($value, $constraint);
}