1

I'm building a form for array data that embeds an entity type like this:

$data = array('message' => '', 'book' => new Book());
$formBld = $this->createFormBuilder($data);
$formBld->add('book', new BookType(), array(
        'label' => false,
        'constraints' => new Symfony\Component\Validator\Constraints\Valid()
     ))
     ->add('message', 'textarea')
     ->add('send', 'submit')
;

The Book entity contains validation constraints, but they are never called. What is missing/wrong?

2
  • 1
    Do you use validation groups for Book entity constraints? Commented Jun 23, 2014 at 9:48
  • That's it, @pazulx ! I had a validation group there. Can you write a short answer so I can choose that answer as the correct one? Commented Jun 23, 2014 at 19:21

2 Answers 2

1

Valid constraint do not support validation groups. Only constraints without group will be used.

For example:

Acme\BlogBundle\Entity\User:
    properties:
        email:
            - Email: { groups: [registration] }
        password:
            - NotBlank: { groups: [registration] }
            - Length: { min: 7, groups: [registration] }
        city:
            - Length:
                min: 2

If you use Valid constraint on UserType then only the city Length will be validated.

Sign up to request clarification or add additional context in comments.

Comments

0

As you can read here, if you have added validation to the Book entity the form will automatically use these validations of the specified class.

For this to work you should pass the object Book to the form or use the data_class option in the BookType to set the Book entity.

To use the data_class option you would do the following:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'YourName\YourBundle\Entity\Book',
    ));
}

However you can specify different validations with the constraints key.

When you specified this Valid class constraint you override the constraints which are defined in the Book entity.

Source: http://symfony.com/doc/current/book/forms.html#form-option-constraints

1 Comment

Thanks! While this did not solve my problem in this case (I already had the correct data_class in my default options, my error was caused by wrong validation groups in the form initialization), it's generally a good approach to do it like you do.

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.