Skip to content

Commit

Permalink
Try another approach
Browse files Browse the repository at this point in the history
  • Loading branch information
jordisala1991 committed Sep 19, 2022
1 parent ede85b0 commit dee070b
Showing 1 changed file with 26 additions and 20 deletions.
46 changes: 26 additions & 20 deletions src/Controller/CRUDController.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationInterface;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Environment;

Expand Down Expand Up @@ -1359,34 +1362,37 @@ protected function handleXmlHttpRequestErrorResponse(Request $request, FormInter
return $this->renderJson([], Response::HTTP_NOT_ACCEPTABLE);
}

$errors = [];
$formName = $form->getName();
return $this->json(
$this->buildConstraintViolationList($form),
Response::HTTP_BAD_REQUEST
);
}

foreach ($form->getErrors(true) as $formError) {
$origin = $formError->getOrigin();
private function buildConstraintViolationList(FormInterface $form): ConstraintViolationList
{
$errors = new ConstraintViolationList();

$fieldName = $origin->getName();
$name = '';
foreach ($form->getErrors(true) as $formError) {
$formName = $this->buildName($formError->getOrigin());
$closure = \Closure::bind(function (ConstraintViolationInterface $violation) use ($formName): ConstraintViolationInterface {
$violation->propertyPath = $formName;

while ($origin = $origin->getParent()) {
if ($formName !== $origin->getName()) {
$name = $origin->getName() . '_' . $name;
}
}
return $violation;
}, null, ConstraintViolation::class);

$fieldName = $formName . '_' . $name . $fieldName;
$errors->add($closure($formError->getCause()));
}

if (!isset($errors[$fieldName])) {
$errors[$fieldName] = [];
}
return $errors;
}

$errors[$fieldName][] = $formError->getMessage();
private function buildName(FormInterface $form): string
{
if (!$form->getParent()) {
return $form->getName();
}

return $this->renderJson([
'result' => 'error',
'errors' => $errors,
], Response::HTTP_BAD_REQUEST);
return $this->buildName($form->getParent()).'['.$form->getName().']';
}

/**
Expand Down

0 comments on commit dee070b

Please sign in to comment.