3

I have 5 fields in one form which is as below:

class ItempriceFormType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {

    $builder->add('pergramprice', 'text', array('required' => false))
            ->add('eighthprice', 'text', array('required' => false))
            ->add('quarterprice', 'text', array('required' => false))
            ->add('halfprice', 'text', array('required' => false))
            ->add('ounceprice', 'text', array('required' => false))
    ;
}

public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'Acme\FrontBundle\Entity\Itemprice',
    ));
}

public function getName() {
    return 'items_price';
}

}

I want to validate only one field means require only one field out of 5 fields. So how can I achieve this with symfony 2 validations.

Thanks in advance.

1 Answer 1

3

you can use custom validator for your validation based on multiple fields, in your Itemprice entity define @Assert\Callback annotation and check if all price fields are empty then show error

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
/**
 * @Assert\Callback(methods={"checkPriceValidation"})
 */
class Itemprice
{
    public function checkPriceValidation(ExecutionContextInterface $context)
    {
        $pergramprice = $this->getPergramprice();
        $eighthprice = $this->getEighthprice();
        $quarterprice = $this->getQuarterprice();
        $halfprice = $this->getHalfprice();
        $ounceprice = $this->getOunceprice();
        if(
        empty($pergramprice)
        && empty($eighthprice)
        && empty($quarterprice)
        && empty($halfprice)
        && empty($ounceprice)
        ){
            $context->addViolationAt('pergramprice', 'Please enter atleast one price');
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.