php - Symfony2 Forms conditional validation on empty fields -
php - Symfony2 Forms conditional validation on empty fields -
i've created form has fields, required status dependend on value entered field (to specific, whether value > 0).
it ordering textbook , if quantity > 0, address-related fields must entered. i've added custom validation callback, can check whether count > 0 , adds violation. gets executed if field not empty (since not "required").
is there way validate, without having utilize required flag on field?
below snippet:
[...] $builder->add('firstname', 'text', array( 'label' => 'label.firstname', 'required' => false, 'property_path' => 'order.firstname', 'constraints' => array( new callback(array('callback' => array($this, 'validateorder'))) ) )); [...] public function validateorder($data, executioncontextinterface $context) { /** @var \symfony\component\form\form $form */ $form = $context->getroot(); if( ( (int)$form->get('count_d')->getdata() > 0 || (int)$form->get('count_f')->getdata() > 0 || (int)$form->get('count_i')->getdata() > 0 ) && $data == '') { $context->addviolation('profile.order.error'); } }
wouldn't more appropriate set callback @ form straight (instead of field)?
public function setdefaultoptions(optionsresolverinterface $resolver) { $resolver->setdefaults(array( 'constraints' => array( new callback(array('callback' => array($this, 'validateorder'))) ) )); }
this way, callback invoked in case...
php forms validation symfony2
Comments
Post a Comment