You are here

public static function Captcha::afterBuildCaptcha in Webform 6.x

Same name and namespace in other branches
  1. 8.5 src/Plugin/WebformElement/Captcha.php \Drupal\webform\Plugin\WebformElement\Captcha::afterBuildCaptcha()

After build handler for CAPTCHA elements.

File

src/Plugin/WebformElement/Captcha.php, line 230

Class

Captcha
Provides a 'captcha' element.

Namespace

Drupal\webform\Plugin\WebformElement

Code

public static function afterBuildCaptcha(array $element, FormStateInterface $form_state) {

  // Make sure that the CAPTCHA response supports #title.
  if (isset($element['captcha_widgets']) && isset($element['captcha_widgets']['captcha_response']) && isset($element['captcha_widgets']['captcha_response']['#title'])) {
    if (!empty($element['#captcha_title'])) {
      $element['captcha_widgets']['captcha_response']['#title'] = $element['#captcha_title'];
    }
    if (!empty($element['#captcha_description'])) {
      $element['captcha_widgets']['captcha_response']['#description'] = $element['#captcha_description'];
    }
  }

  // Add image refresh button to captcha form element.
  // @see image_captcha_after_build_process()
  if ($form_state
    ->getFormObject() instanceof WebformSubmissionForm) {
    $is_image_captcha = FALSE;
    if ($element['#captcha_type'] === 'image_captcha/Image') {
      $is_image_captcha = TRUE;
    }
    elseif ($element['#captcha_type'] === 'default') {
      $default_challenge = \Drupal::service('config.manager')
        ->getConfigFactory()
        ->get('captcha.settings')
        ->get('default_challenge');
      if ($default_challenge === 'image_captcha/Image') {
        $is_image_captcha = TRUE;
      }
    }
    if ($is_image_captcha && isset($element['#captcha_info']['form_id'])) {
      $form_id = $element['#captcha_info']['form_id'];
      $uri = Link::fromTextAndUrl(t('Get new captcha!'), new CoreUrl('image_captcha.refresh', [
        'form_id' => $form_id,
      ], [
        'attributes' => [
          'class' => [
            'reload-captcha',
          ],
        ],
      ]));
      $element['captcha_widgets']['captcha_refresh'] = [
        '#theme' => 'image_captcha_refresh',
        '#captcha_refresh_link' => $uri,
        '#parents' => array_merge($element['#parents'], [
          'captcha_widgets',
        ]),
      ];
    }
  }
  return $element;
}