Symfony2 form validation for multiple fields only requires one
I have 5 fields in one form:
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 only want to validate one field that only needs one field of 5 fields. So how can I achieve this with symfony 2.
Thanks in advance.
+3
source to share
1 answer
you can use a custom validator for your validation based on multiple fields, in your organization Itemprice
define @Assert\Callback
annotation and check if all price fields are empty and then show an 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');
}
}
}
+2
source to share