0

I created a custom form with a textbox and a button. When the user clicks on that button, an ajax call should take place.

When I click on that button for the first time, a page refresh takes place. Only when I click on the button for the second time, my ajax-function is called.

I don't know what I'm doing wrong, so I would be greatful for any suggestion.


function buildForm(array $form, FormStateInterface $form_state) 
{      
    //Oorspronkelijk staat van formpost:
    $_SESSION['formpost'] == 'rrn_nok';

    array_push($form['#attributes']['class'], 'col-12');

    $form["foutmeldingen"] = array(
        '#type' => 'container',
        '#prefix' => '<div id="edit-foutmeldingen" class="webform-messages">',
        '#suffix' => '</div>',          
    );

    $form['group_rrn'] = array(
        '#type' => 'container',            
        '#prefix' => '<div id="controle-rrn">',
        '#suffix' => '</div>',
    );
    
    $form['group_rrn']['rijksregisternummer'] = [
        '#type' => 'textfield',
        '#required' => TRUE,
        '#title' => 'Rijksregisternummer',            
        '#attributes' => [              
          'data-inputmask-mask' => '999999-999-99',          
          'class' => ['js-webform-input-mask'],
        ],
    ];
    $form['group_rrn']['rijksregisternummer']['#attached']['library'][] = 'webform/webform.element.inputmask';

    $form['group_rrn']['actions'] = array(
        '#type' => 'button',
        '#value' => 'Ga verder',
        '#attributes' => array('class' => array('btn', 'btn-primary')),
        '#ajax' => [
            'callback' => '::ajaxRijksregisternummer',
            'event' => 'click',
            'wrapper' => 'aanvraag',
            'progress' => array(
                'type' => 'throbber',
                'message' => 'Even geduld',
            ),                
        ],      
    );

    $form['group_form'] = array(
      '#type' => 'container',            
      '#prefix' => '<div id="aanvraag">',
      '#suffix' => '</div>',
  );
    
    $form['group_form']['landen'] = array(
      '#type' => 'textfield',
      '#title' => 'Kies land(en)',
      '#autocomplete_route_name' => 'tools.reisdocumentenautocomplete',
      '#autocomplete_route_parameters' => array(),    
      '#description' => "Typ de beginletters van het land en kies uit de lijst. Voor meerdere landen typ je een ',' en herhaal dezelfde werkwijze.",
    );

    $form['group_form']['startdatum'] = [
      '#type' => 'date',
      '#title' => 'Kies startdatum',
      '#date_format' => 'd-m-Y',           
      '#attributes' => [     
        'min' => format_date(strtotime("+7 day", time()), 'html_date'),         
        'data-inputmask-mask' => '99-99-9999',          
        'class' => ['js-webform-input-mask'],
      ],
    ];

    $form['group_form']['einddatum'] = [
      '#type' => 'date',
      '#title' => 'Kies einddatum',
      '#date_format' => 'd-m-Y', 
      '#attributes' => [     
        'min' => format_date(strtotime("+7 day", time()), 'html_date'),         
        'data-inputmask-mask' => '99-99-9999',          
        'class' => ['js-webform-input-mask'],
      ],          
    ];

    $form['group_form']['bestelling'] = array(
      '#type' => 'checkboxes',
      '#options' => array(
        'Dit Rijksregisternummer' => 'Dit Rijksregisternummer', 
        'Partner' => 'Partner', 
        'Kinderen' => 'Kinderen', 
        'Andere PTL' => 'Andere personen ten laste'),
      '#title' => 'Bestelling',   
    );

    $form['group_form']['email'] = array(
      '#type' => 'email',
      '#title' => 'Jouw e-mailadres',     
    );

    $form['group_form']['telefoon'] = array(
      '#type' => 'textfield',
      '#title' => 'Jouw telefoonnummer',  
      '#maxlength' => 10,        
    );

    $form['group_form']['partner_rrn'] = array(
      '#type' => 'hidden',
      '#attributes' => array('id' => 'edit-partner-rrn'),
    );
    $form['group_form']['fed'] = array(
      '#type' => 'hidden',
      '#attributes' => array('id' => 'edit-fed'),
    );

    $form['group_form']['actions'] = array(
      '#type' => 'button',
      '#value' => 'Verzenden',
      '#attributes' => array('class' => array('btn', 'btn-primary')),
      '#ajax' => [
        'callback' => '::ajaxSubmit',
        'event' => 'click',
        'progress' => array(
            'type' => 'throbber',
            'message' => 'Even geduld',
        ),
        '#validate' => array('myformname__do_validate'),                
    ],
      
  );

    return $form;
}

This is the CallBack function:

function ajaxRijksregisternummer($form, $form_state) {
    $response = new AjaxResponse();
    $rijksregisternummer = $form_state->getValue('rijksregisternummer');
    if(ReisdocumentenForm::isCorrectRijksregisternummer($rijksregisternummer)){
        $member = '';
        if(ReisdocumentenForm::isMemberApiCall($rijksregisternummer, $member)){
          $_SESSION['formpost'] = 'rrn_ok';
          $form['group_form']['email']['#required'] = TRUE;
          $response->addCommand(new CssCommand('#controle-rrn', ['display' => 'none']));
          $hasPartner = $member['hasPartner'];
          $federatie = $member['federation'];
          $partner = '';
          if($hasPartner == 'true'){
            $partner = $member['partnerInfo'];                
          }
          $response->addCommand(new InvokeCommand(NULL, 'AjaxCallBackShowAanvraag', [$hasPartner, $partner, $federatie]));              
        } else {
            $markup = '<div data-drupal-messages-fallback="" class="hidden"></div><div data-drupal-messages=""><div role="contentinfo" aria-label="Foutmelding"><div role="alert"><h2 class="visually-hidden">Foutmelding</h2>Dit formulier is enkel voor leden van ons ziekenfonds.</div></div></div>';
            $response->addCommand(new AppendCommand('#edit-foutmeldingen', $markup));
        }
    }
    else {
        $markup = '<div data-drupal-messages-fallback="" class="hidden"></div><div data-drupal-messages=""><div role="contentinfo" aria-label="Foutmelding"><div role="alert"><h2 class="visually-hidden">Foutmelding</h2>Geen correct rijksregisternummer.</div></div></div>';
        $response->addCommand(new AppendCommand('#edit-foutmeldingen', $markup));
    }
    return $response;
}

Kind regards!

8
  • 1
    Where is the rest of the code?
    – Kevin
    Commented May 28, 2021 at 12:49
  • I added the extra code.
    – FreMun
    Commented May 28, 2021 at 13:55
  • I mean, your form build code. What is the aanvraag wrapper?
    – Kevin
    Commented May 28, 2021 at 14:45
  • I edited my post again, and added the full buildform function. Please let me know if more info is needed.
    – FreMun
    Commented May 31, 2021 at 6:46
  • 1
    This looks like the button doesn't have ajax javascript attached the first time you click. Check this with the browser debugging tools why the ajax library is not properly loaded and attached. If the ajax libraries and settings are not present at all then provide more info how the form is embedded in the page. Might be a defective block plugin or template.
    – 4uk4
    Commented Jun 1, 2021 at 19:07

1 Answer 1

0

I found the solution for my problem. It was not the form, but the block in which the form was loaded, that was the problem. I disabled the caching and now it works as expected.

/**
 * Provides a 'ReisdocumentenBlock' block.
 *
 * @Block(
 *   id = "ReisdocumentenBlock_block",
 *   admin_label = @Translation("ReisdocumentenBlock socmut"),
 *   category = @Translation("socmut")
 * )
 */
class ReisdocumentenBlock extends BlockBase implements BlockPluginInterface
{
    /**
     * {@inheritdoc}
     */
    public function build()
    {
        $form = \Drupal::formBuilder()->getForm('Drupal\tools\Form\ReisdocumentenForm');            
        return $form;
        }
    }

    /**
     * Disable caching for ajax problem with form
     */
    public function getCacheMaxAge() {
        return 0;
    }
}

I'm still curious to know that maybee I can solve this with a certain cache context instead of disableing all the cache?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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