0

I have the following form

function beyond_shipping_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'commerce_checkout_flow_multistep_default') {
    $default_challenge = \Drupal::service('config.manager')
      ->getConfigFactory()
      ->get('captcha.settings')
      ->get('default_challenge');
    $form['captcha'] = [
      '#type' => 'captcha',
      '#captcha_type' => $default_challenge,
    ];
  }

}

The google captcha appears perfectly when the page loads but disappears upon calculating the shipping costs.

From my understanding, the shipping cost calculator reloads the whole form without the google captcha. Therefore, the google captcha validation becomes invalid upon recalculating the cost and the google captcha is not rendered on the page.

The problem is that I don't know where exactly I should make the change in my module to "hook" to the change and rerender the google captcha again. I was struggling to find info about this but didn't manage.

I appreciate your help.

1 Answer 1

0

In Drupal, when a form is rebuilt due to AJAX calls (like recalculating shipping costs), any dynamically added elements need to be added again in the buildForm function or the appropriate form alter hook. Since you're using hook_form_alter, you need to make sure that the CAPTCHA is added back to the form whenever it is rebuilt. To do this, you can implement hook_form_alter and check if the form is being rebuilt during the AJAX callback.

function beyond_shipping_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'commerce_checkout_flow_multistep_default') {
    // Add CAPTCHA to the form
    $default_challenge = \Drupal::service('config.manager')
      ->getConfigFactory()
      ->get('captcha.settings')
      ->get('default_challenge');

    // Always set the CAPTCHA in the form
    $form['captcha'] = [
      '#type' => 'captcha',
      '#captcha_type' => $default_challenge,
    ];

    // Check if the form is being rebuilt during an AJAX callback
    if ($form_state->getTriggeringElement()['#ajax']) {
      // If it's an AJAX request, we can optionally add any necessary logic here
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

not sure this is correct. By the time your ajax check is reached, the captcha is already added isn't it?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.