Symfony2 form builder without class check if multiple fields are empty

1.2k views Asked by At

I am using form builder without class and have two fields with each having constraints :

$form = $this->createFormBuilder()
        ->add('name', 'text', array(
            'required'=>false,
            'constraints'=> new Length(array('min'=>3)
        ))
        ->add('dob', 'date', array(
            'required'=>false,
            'constraints'=> new Date()
        ))
        ->getForm()
        ->handleRequest($request);

This works great but I want to check if both fields are emtpy, and display error. Just can't seem to get a handle on this. Could someone provide help???

2

There are 2 answers

1
john Smith On BEST ANSWER

the easiest solution is to just set both as required ...

but.. on post you could check as simple as

if( empty($form->get('name')->getData()) && empty($form->get('dob')->getData())){
   $form->addError(new FormError("fill out both yo"));
   // ... return your view
}else {

  // ... do your persisting stuff
}
... 

the symfony way would possibly be adding a custom validator I suggest you to look at custom validator especially this part

pseudo :

namespace My\Bundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class CheckBothValidator extends ConstraintValidator
{
    public function validate($foo, Constraint $constraint)
    {
            if (!($foo->getName() && $foo->getDob()) {
                $this->context->addViolationAt('both', $constraint->message, array(), null);
            }
    }
}
1
Shairyar On

Inside your Bundle->Resources->Config folder create a file name validation.yml and then

namespace\YourBundle\Entity\EntityName:
    properties:
        dob://field that you want to put validation on 
            - NotBlank: { message: "Message that you want to display"}
        gender:
            - NotBlank: { message: "Message that you want to display" }

The validation will come into play as soon as you check if the form data submitted isValid()

$entity = new Programs();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add(
                'notice',
                'Success'
            );
            //  your return here
            return ...;

        }