Doctrine and Symfony - changing requirement of text input based on selection of a choice field -


i working on form in company crm adds job database. had been quite simple, it's gotten more complex need conditionally require fields based on specific choices in previous fields.

when job added, there different statuses, booked, active, complete , on hold. there field called start_date required unless status chosen booked. however, don't know how change dynamically, , if make date field not required , status isn't booked , date isn't filled in - mean job won't correctly added.

here 2 fields need work together:

$builder->add('status', choicetype::class,     array(         'label' => 'initial status',         'required' => true,         'placeholder' => 'please choose',         'attr' => array(             'class' => 'form-control'         ),         'choices' => $this->status_list     )); $builder->add('job_date', texttype::class,     array(         'label' => 'job date',         'required' => true,         'attr' => array(             'class' => 'pickr form-control'         )     )); 

the choices status being follows:

$status_list = array(     'to booked' => 'to_be_booked',     'current' => 'active',     'ready invoice' => 'ready',     'incomplete' => 'incomplete',     'complete' => 'complete' ); 

if status chosen to_be_booked requirement needs lifted job_date field, other status needs required.

how can done?

you add pre_submit form event check if value of second field correct

$builder->addeventlistener(formevents::pre_submit, function (formevent $formevent) {     $data = $formevent->getdata();     $form = $formevent->getform();     if ('to_be_booked' !== $data['status']) {         if(!isset($data['job_date']) || empty($data['job_date'])) {             $form->adderror(new formerror('the job date mandatory'));             return;         }     } }) 

with error added form if no job_date submit , status isn't to_be_booked

please check https://symfony.com/doc/current/form/events.html more details of symfony form events

if constraint isn't specific form global application should use custom validators, please check https://symfony.com/doc/current/validation/custom_constraint.html


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -