Optional embed form in Symfony 2

前端 未结 5 1956
予麋鹿
予麋鹿 2021-01-16 11:00

I have two entities in my system: Person and Phone as the following code.

class Person
{
    /**
     * @ORM\\Id
     * @ORM\\Colum         


        
5条回答
  •  春和景丽
    2021-01-16 11:18

    I would try this method:

    create additional method in your Phone entity which validates if all fields are null or all fields are not null (these two cases are correct) - and then return true. If some fields are null and some aren't return false. Add an assert annotation to your new method - this will be your new constraint.

    /**
     * @Assert\True(message = "Fill all fields or leave all them blank")
     */
    

    And this should work.

    For more information look here: http://symfony.com/doc/master/book/validation.html#getters

    edit:

    Try this one:

    define your custom validation method (this one which check if any of phone fields is filled) as Callback (at the top of the class):

     * @Assert\Callback(methods={"checkPhoneFields"})
     */
     class Phone {
    

    Next you mark field wich have to be validated with validation group, eg.

    /**
     * @ORM\Column(type="string", length=16, groups={"phone_validation"})
     */
    private $number;
    

    And the last thing, in your custom constraint method you need to switch on "phone_validation" group if any of field isn't empty:

    public function checkPhoneFields(ExecutionContext $context) {
        if (/* fields are not empty */) {
            $context->getGraphWalker()->walkReference($this, 'phone_validation', $context->getPropertyPath(), true);
        }
    

    And that should work.

提交回复
热议问题