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.
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');
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With