You are here

protected function EntityFormDisplay::movePropertyPathViolationsRelativeToField in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php \Drupal\Core\Entity\Entity\EntityFormDisplay::movePropertyPathViolationsRelativeToField()
  2. 9 core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php \Drupal\Core\Entity\Entity\EntityFormDisplay::movePropertyPathViolationsRelativeToField()

Moves the property path to be relative to field level.

Parameters

string $field_name: The field name.

\Symfony\Component\Validator\ConstraintViolationListInterface $violations: The violations.

Return value

\Symfony\Component\Validator\ConstraintViolationList A new constraint violation list with the changed property path.

1 call to EntityFormDisplay::movePropertyPathViolationsRelativeToField()
EntityFormDisplay::flagWidgetsErrorsFromViolations in core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php
Flags entity validation violations as form errors.

File

core/lib/Drupal/Core/Entity/Entity/EntityFormDisplay.php, line 284

Class

EntityFormDisplay
Configuration entity that contains widget options for all components of an entity form in a given form mode.

Namespace

Drupal\Core\Entity\Entity

Code

protected function movePropertyPathViolationsRelativeToField($field_name, ConstraintViolationListInterface $violations) {
  $new_violations = new ConstraintViolationList();
  foreach ($violations as $violation) {

    // All the logic below is necessary to change the property path of the
    // violations to be relative to the item list, so like title.0.value gets
    // changed to 0.value. Sadly constraints in Symfony don't have setters so
    // we have to create new objects.

    /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */

    // Create a new violation object with just a different property path.
    $violation_path = $violation
      ->getPropertyPath();
    $path_parts = explode('.', $violation_path);
    if ($path_parts[0] === $field_name) {
      unset($path_parts[0]);
    }
    $new_path = implode('.', $path_parts);
    $constraint = NULL;
    $cause = NULL;
    $parameters = [];
    $plural = NULL;
    if ($violation instanceof ConstraintViolation) {
      $constraint = $violation
        ->getConstraint();
      $cause = $violation
        ->getCause();
      $parameters = $violation
        ->getParameters();
      $plural = $violation
        ->getPlural();
    }
    $new_violation = new ConstraintViolation($violation
      ->getMessage(), $violation
      ->getMessageTemplate(), $parameters, $violation
      ->getRoot(), $new_path, $violation
      ->getInvalidValue(), $plural, $violation
      ->getCode(), $constraint, $cause);
    $new_violations
      ->add($new_violation);
  }
  return $new_violations;
}