Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

forms - Conditional field validation that depends on another field

I need to change the validation of some field in a form. The validator is configured via a quite large yml file. I wonder if there is any way to do validation on two fields at once. In my case I have two fields that cannot be both empty. At least one has to be filled.

Unfortunately till now I just could see that the validation are defined on a per-field basis, not on multiple fields together.

The question is: is it possible in the standard yml configurations to perform the aforementioned validation?

thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suggest you to look at Custom validator, especially Class Constraint Validator.

I won't copy paste the whole code, just the parts which you will have to change.


Extends the Constraint class.

src/Acme/DemoBundle/Validator/Constraints/CheckTwoFields.php

<?php

namespace AcmeDemoBundleValidatorConstraints;

use SymfonyComponentValidatorConstraint;

/**
 * @Annotation
 */
class CheckTwoFields extends Constraint
{
    public $message = 'You must fill the foo or bar field.';

    public function validatedBy()
    {
            return 'CheckTwoFieldsValidator';
    }

    public function getTargets()
    {
            return self::CLASS_CONSTRAINT;
    }
}

Define the validator by extending the ConstraintValidator class, foo and bar are the 2 fields you want to check:

src/Acme/DemoBundle/Validator/Constraints/CheckTwoFieldsValidator.php

namespace AcmeDemoBundleValidatorConstraints;

use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;

class CheckTwoFieldsValidator extends ConstraintValidator
{
    public function validate($protocol, Constraint $constraint)
    {
        if ((empty($protocol->getFoo())) && (empty($protocol->getBar()))) {
            $this->context->addViolationAt('foo', $constraint->message, array(), null);
        }
    }
}

Use the validator:

src/Acme/DemoBundle/Resources/config/validation.yml

AcmeDemoBundleEntityAcmeEntity:
    constraints:
        - AcmeDemoBundleValidatorConstraintsCheckTwoFields: ~

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...