Andreas Schmidt
Andreas Schmidt

Reputation: 3

Symfony 2 Form validation with dependencies

I have an entity with 2 fields (of course some more, but for simplicity only 2 :) ):

class Entity
{
    // boolean type
    protected $is_public;
    // hashed string
    protected $password;
}

Now I need a form in symfony 2 for that entity with the following dependencies on the password field: When the user clicks the checkbox for $is_public, he does not have to enter a password. On the other hand, when the user wants the entity (in my case a user-group) as non-public, he must enter a password with at least N characters.

How would you do that with the validators shipped with symfony2 framework? Is there a way to achieve my goals?

Thank you in advance,

Andi

Upvotes: 0

Views: 1711

Answers (2)

adavea
adavea

Reputation: 1602

You can specify a callback function that is called at validation time, and have it do pretty much whatever you want. Here are the docs:

http://symfony.com/doc/current/reference/constraints/Callback.html

Note that if you are using translations, you can also specify a string-key in the addViolation call.

$context->addViolation(
  'Acme\DemoBundle\Entity\MyEntity.entityField.validationErrorString1',
  array(), null);

Upvotes: 0

julesbou
julesbou

Reputation: 5780

The unique way i have found is to create a custom Constraint, with a class constraint you can access all properties of your object.

Look at these classes:

and create your own with your logic.

Upvotes: 2

Related Questions