开发者

Symfony 2 Form validation with dependencies

开发者 https://www.devze.com 2023-03-24 21:09 出处:网络
I have an entity with 2 fields (of course some more, but for simplicity only 2 :) ): class Entity { // boolean type

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,

An开发者_如何转开发di


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:

  • UniqueEntityValidator.php
  • UniqueEntity.php

and create your own with your logic.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消