0

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

Update: When looking into the http headers I see that the browser does the POST request with form data t_and_c_accepted:1 while the checkbox is unchecked.

So Drupal's form api seems to handle the request correct, but why does the browser doesn't post the correct checkbox status value ?

  • 1
    maybe instead of !== 1 use != 1 or better yet empty()? – user21641 Jan 12 '18 at 18:42
  • valid point, but the problem is that $form_state->getValue('t_and_c_accepted') actually returns 1 while it should be 0 if the checkbox is unchecked . So the result of the comparison is correct. – maartend Jan 13 '18 at 11:47
0

ok, I've found the cause of the issue: I rendered $form['t_and_c_accepted'] twice in the twig template which caused the browser to post a value that was different from the checkbox that was visible.

So it was my own mistake but I answer this question anyway in case anyone else would be wasting time solving the same issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.