Thursday, May 16, 2013

Symfony 2 Forms - validate at least one field is non empty

Say you have a form that allows you to add a post to an existing list or a new list. The form will have a dropdown box with existing lists and an input box asking the user to input the name of the new list. When the user clicks on submit, the post will be added to that list.

In earlier version of Symfony 2, you can use the CallbackValidator to do that, but it's deprecated. You will need to use event listener now.

In the following example, the dropdown box has the element name 'listId' while the input box has the element name 'listName'.

In your form's buildForm function, add the following EventListener.

public function buildForm(FormBuilderInterface $builder, array $options)
{
        $builder->addEventListener(FormEvents::POST_BIND, function (DataEvent $event) {
            $form = $event->getForm();

            $listName = $form['listName']->getData();
            $originalListId = $form['listId']->getData();

            if( ($listName == null || $listName == '') && ($listId == null || $listId == '') ) {
                $form['listId']->addError(new FormError("Please select a list or create a new list."));
            }
        });
}

No comments:

Post a Comment