Szymon Nowak
Szymon Nowak

Reputation: 23

Symfony 2 form conditional required field with fields not mapped to entity

I have a form that requires field conditionalRequiredField only if requireField is selected.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add(
            'requireField', 'choice', array
            (
                'label' => ' ',
                'mapped' => false,
                'choices' => array
                (
                    'require' => 'Should I require that field?'
                ),
                'multiple' => true,
                'expanded' => true
            )
        )
        ->add(
            'conditionalRequiredField', 'text', array
            (
                'label' => 'I am required because the field above was selected',
                'class' => 'AppBundle\Entity\SomeEntity',
            )
        )

...and some other fields, some of them mapped to entities.

The first field is not mapped to the entity. So in controller it's not available when I access $form->getData(), it's only available through Request object. Now the question is, how and where should I add the validation to do it properly? To just validate whole form with use of isValid() method, without any additional logic in other places? I could probably put the validation in service somewhere, but it feels wrong. I've read a lot about constraints and validators, but they all seem to be connected with an entity field.

Thank you for your help :-).

Upvotes: 2

Views: 3908

Answers (1)

Vincent Barrault
Vincent Barrault

Reputation: 2916

Imagine your entity linked to this FormType is call MyEntity

you probably should have somthing like that:

/**
 * @My\CustomValidation
 */
class MyEntity
{
    private $requiredField;

    /**
     * @ORM\Column(type="string")
     */
    private $conditionalRequiredField;
}

In order to create your custom validation, you can take a look at http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#class-constraint-validator to create a class contraint validator

you validate method will looks like:

public function validate($entity, Constraint $constraint)
{
    if(!$entity instanceof MyEntity){
        return;
    }

    if($entity->getRequiredField() && $entity->getConditionalRequiredField() == null) {
        $this->context->addViolationAt('conditionalRequiredField', 'you.error.flag', array(), null);
    }
}

Upvotes: 1

Related Questions