D8 checkbox value incorrect in custom validation

by maartend   Last Updated January 12, 2018 17:07 PM

I have a custom form like this :

public function buildForm(array $form, FormStateInterface $form_state){

      $form['first_name'] = [
        '#type' => 'textfield',
        '#title' => t('First name'),
      ];

      $form['t_and_c_accepted'] =[
         '#type' => 'checkbox',
         '#title'=> t('I accept the terms and conditions'),
         '#return_value' => 1,              
         '#default_value' => 0,
      ];    
 }

public function validateForm(array &$form, FormStateInterface $form_state){

          $values = $form_state->getValues();       
          if(empty($values['first_name'])){
             $form_state->setErrorByName('[first_name]', t('Fill in a first name'));
          }

          if($values['t_and_c_accepted'] !== 1){
             $form_state->setErrorByName('[t_and_c_accepted]', t('Accept the t&c's);
          }
    }
  1. If I uncheck the checkbox and submit the form, it gives me an error about the unchecked checkbox, as expected.
  2. If I check the checkbox, leave the first_name empty and submit the form, it gives me an error that my fist_name is empty, as expected.
  3. But if I then fill in first_name, UNcheck the checkbox an submit. The validation passes! So not as expected.
  4. If I then go back to the form (back from my landing page), I can reiterate this sequence

I have monitored the $form_state->getValue('t_and_c_accepted') value throughout my tests and it gives me indeed value=1 during the unexpected behavior. So it is consistent with what I see, but I have absolutely no idea what's going on.

So any help would be appreciated

Tags : 8 forms


Related Questions




Reuse form from another module in multistep form

Updated May 21, 2015 22:03 PM