You are here

class RiddlerSettingsForm in Captcha Riddler 8

Displays the Riddler settings form.

Hierarchy

Expanded class hierarchy of RiddlerSettingsForm

1 string reference to 'RiddlerSettingsForm'
riddler.routing.yml in ./riddler.routing.yml
riddler.routing.yml

File

src/Form/RiddlerSettingsForm.php, line 16

Namespace

Drupal\riddler\Form
View source
class RiddlerSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'riddler_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'riddler.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // This can be rebuilt by ajax, so check for existing values. in $form_state.
    // Run through array values to reset keys in case one was ajax removed.
    $values = $form_state
      ->getValues();
    $riddles = isset($values['riddler']) ? $values['riddler'] : [];

    // Without checking if there was a triggering element, this would reload
    // the original active config instead of deleting the last riddle. The
    // triggering element would be the remove or add another buttons.
    if (empty($riddles) && empty($form_state
      ->getTriggeringElement())) {
      $riddles = $this
        ->config('riddler.settings')
        ->get('riddles');
    }

    // Add CSS for styling settings form.
    $form['#attached']['library'][] = 'riddler/base';

    // Initialize the counter if it hasn't been set. We do it this way so the
    // add more ajax callback can increment the max to create an empty riddle.
    $rebuild_info = $form_state
      ->getRebuildInfo();
    if (!isset($rebuild_info['riddler']['items_count'])) {

      // Nested to avoid unlikely conflicts with other modules.
      $form_state
        ->setRebuildInfo([
        'riddler' => [
          'items_count' => count($riddles) === 0 ? 1 : count($riddles),
        ],
      ]);
    }
    $max = $form_state
      ->getRebuildInfo()['riddler']['items_count'];
    $form['riddler'] = [
      '#tree' => TRUE,
      '#prefix' => '<div id="riddler">',
      '#suffix' => '</div>',
    ];
    $form['riddler']['help'] = [
      '#markup' => $this
        ->t('Add questions that you require users to answer. A random question will be presented to the user on forms as configured in the CAPTCHA settings. Allow more than one correct answer by entering a comma-separated list.'),
      '#prefix' => '<p>',
      '#suffix' => '</p>',
    ];

    // Build or rebuild the riddle fields.
    for ($delta = 0; $delta < $max; $delta++) {
      if (!isset($form['riddler'][$delta])) {
        $element = [
          'question' => [
            '#type' => 'textfield',
            '#title' => 'Riddle ' . ($delta + 1) . ' question',
            '#default_value' => isset($riddles[$delta]) ? $riddles[$delta]['question'] : '',
            '#prefix' => '<div id="row-riddle' . ($delta + 1) . '" class="row-riddle">',
          ],
          'response' => [
            '#type' => 'textfield',
            '#title' => 'Answer',
            '#default_value' => isset($riddles[$delta]) ? $riddles[$delta]['response'] : '',
          ],
          // Delete a row button.
          'delete' => [
            '#type' => 'submit',
            '#value' => $this
              ->t('Remove'),
            '#id' => 'riddle' . $delta,
            '#name' => 'riddle-remove-' . $delta,
            '#submit' => [
              [
                $this,
                'removeSubmit',
              ],
            ],
            '#limit_validation_errors' => [
              [],
            ],
            '#ajax' => [
              'callback' => [
                $this,
                'removeCallback',
              ],
              'wrapper' => 'riddler',
              'method' => 'replace',
              'effect' => 'fade',
            ],
            '#suffix' => '</div>',
          ],
        ];
        $form['riddler'][$delta] = $element;
      }
    }

    // Add a row button.
    $form['add'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add another riddle'),
      '#submit' => [
        [
          $this,
          'addMoreSubmit',
        ],
      ],
      '#limit_validation_errors' => [
        [
          'riddler',
        ],
      ],
      '#ajax' => [
        'callback' => [
          $this,
          'addMoreCallback',
        ],
        'wrapper' => 'riddler',
        'method' => 'replace',
        'effect' => 'fade',
      ],
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Submit function for ajax Add another riddle button.
   *
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function addMoreSubmit(&$form, FormStateInterface &$form_state) {
    $max = count($form_state
      ->getValues()['riddler']);
    $form_state
      ->setRebuildInfo([
      'riddler' => [
        'items_count' => ++$max,
      ],
    ]);
    $form_state
      ->setRebuild(TRUE);
  }

  /**
   * Submit callback for Add another riddle button.
   *
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return mixed
   */
  public function addMoreCallback(&$form, FormStateInterface $form_state) {
    return $form['riddler'];
  }

  /**
   * Submit function for remove a riddle button.
   *
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public function removeSubmit(&$form, FormStateInterface &$form_state) {
    $this
      ->removeFormStateValue($form_state);
    $form_state
      ->setRebuild(TRUE);
  }

  /**
   * Submit callback for remove a riddle button.
   *
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return mixed
   */
  public function removeCallback(&$form, FormStateInterface $form_state) {
    return $form['riddler'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->getTriggeringElement()['#value'] == 'Remove') {
      return;
    }
    $values = $form_state
      ->getValues()['riddler'];
    foreach ($values as $key => $value) {
      if (empty($value['question']) && empty($value['response'])) {
        unset($form_state
          ->getValues('riddler')['riddler'][$key]);
      }
      else {
        if (empty($value['question'])) {
          $form_state
            ->setError($form['riddler'][$key]['question'], $this
            ->t('Please add a question.'));
        }
        if (empty($value['response'])) {
          $form_state
            ->setError($form['riddler'][$key]['response'], $this
            ->t('Please add an answer.'));
        }
      }
    }
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $riddles = $form_state
      ->getValues()['riddler'];
    $this
      ->recursiveUnset($riddles, 'delete');
    $this
      ->config('riddler.settings')
      ->set('riddles', $riddles)
      ->save();
    parent::SubmitForm($form, $form_state);
  }

  /**
   * Remove elements from an array by key.
   */
  private function recursiveUnset(&$array, $unwanted_key) {
    unset($array[$unwanted_key]);
    foreach ($array as &$value) {
      if (is_array($value)) {
        $this
          ->recursiveUnset($value, $unwanted_key);
      }
    }
  }

  /**
   * Remove the riddle row from $form_state->values and $form_state->input.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  private function removeFormStateValue(FormStateInterface $form_state) {
    $trigger = $form_state
      ->getTriggeringElement();
    $row = str_replace('riddle', '', $trigger['#id']);
    $values = $form_state
      ->getValues();
    unset($values['riddler'][$row]);
    $values['riddler'] = array_values($values['riddler']);
    $form_state
      ->setValue('riddler', $values['riddler']);
    $form_state
      ->setUserInput($values);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
RiddlerSettingsForm::addMoreCallback public function Submit callback for Add another riddle button.
RiddlerSettingsForm::addMoreSubmit public function Submit function for ajax Add another riddle button.
RiddlerSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
RiddlerSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
RiddlerSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RiddlerSettingsForm::recursiveUnset private function Remove elements from an array by key.
RiddlerSettingsForm::removeCallback public function Submit callback for remove a riddle button.
RiddlerSettingsForm::removeFormStateValue private function Remove the riddle row from $form_state->values and $form_state->input.
RiddlerSettingsForm::removeSubmit public function Submit function for remove a riddle button.
RiddlerSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
RiddlerSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.