Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 form validation for multiple field require only one

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.

like image 836
Jigar Pancholi Avatar asked Dec 11 '25 10:12

Jigar Pancholi


1 Answers

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');
        }
    }
}
like image 91
M Khalid Junaid Avatar answered Dec 14 '25 00:12

M Khalid Junaid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!