You are here

function captcha_questions_form_alter in Captcha Questions 8

Same name and namespace in other branches
  1. 7 captcha_questions.module \captcha_questions_form_alter()

Implements hook_form_alter().

File

./captcha_questions.module, line 27
Module file for the Captcha questions module.

Code

function captcha_questions_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Only show captcha questions if user is anonymous.
  if (\Drupal::currentUser()
    ->isAnonymous()) {

    // Fetching variables for form ids, question and description.
    $config = \Drupal::config('captcha_questions.settings');
    $captcha_questions_form_ids = $config
      ->get('captcha_questions_form_ids');
    $question = $config
      ->get('captcha_questions_question');
    $description = $config
      ->get('captcha_questions_description');
    if (in_array($form_id, $captcha_questions_form_ids)) {

      // If we're on a multi page form, find current page.
      $form_page_count = isset($form['details']['page_num']['#value']) ? $form['details']['page_num']['#value'] : 1;

      // Set field to hidden unless on the first page.
      $form['captcha_questions_answer_given'] = [
        '#type' => $form_page_count == 1 ? 'textfield' : 'hidden',
        '#description' => t("@description", [
          '@description' => $description,
        ]),
        '#title' => Html::escape($question),
        '#size' => 60,
        '#required' => TRUE,
      ];
      $form['#validate'][] = 'captcha_questions_form_validate';
    }
    return $form;
  }
}