1

I am trying to add error to form using FormError. Error must be displayed when user tries to create collection with existing name. But this code doesn't work, and I can't understand why

  public function submitInObjectAction(Request $request)
{
    $collection = new Collection();
    $user = $this->getUser();
    $form = $this->createForm(
        new CollectionType(),
        $collection
    );


    $form->handleRequest($request);
    if ($form->isValid() && $form->isSubmitted()) {

        $colname = $form["name"]->getData();
        $existing = $this->getDoctrine()->getRepository('CollectionBundle:Collection')
                         ->findBy(['name' => $colname, 'user' => $user]);
        if ($existing != NULL) {
            $error = new FormError("You already have collection with such name");
            $form->get('name')->addError($error);
        }

        $em = $this->getDoctrine()->getManager();
        $collection->setUser($user);
        $em->persist($collection);
        $em->flush();

        return new JsonResponse([
            'id' => $collection->getId(),
            'name' => $collection->getName()
        ]);
    }
}

I cannot use annotation on name field in Collection entity, because names must be unique only for particular user

1 Answer 1

1

I think it is too late in the chain. Form validation happens when you call $form->handleRequest() and by the time $form->isValid() is called your validation should be complete. It is better to add validation constraints further up the chain. See the Symfony guide on form validation and if necessary the validation component, for more info.

I would use annotations to set a unique constraint on the name field of the Collection entity in the CollectionBundle.

This not only validates this user input form, but any other form or component or bundle which uses CollectionBundle - and Doctrine will even prevent storage depending on the constraint leaving your database tidy!

EDIT: Another option for more advanced validation is writing a custom form event listener. Three events are dispatched when Form::handleRequest() or Form::submit() are called: FormEvents::PRE_SUBMIT, FormEvents::SUBMIT, FormEvents::POST_SUBMIT. This example also shows how to access the form itself.

$form = $formFactory->createBuilder()
    ->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $user = $event->getData();
        $form = $event->getForm();
        // .. validation here
    })
    ->getForm();
Sign up to request clarification or add additional context in comments.

1 Comment

the problem with annotations is that names must be unique only for particular user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.