You are here

class YamlFormLikert in YAML Form 8

Same name in this branch
  1. 8 src/Element/YamlFormLikert.php \Drupal\yamlform\Element\YamlFormLikert
  2. 8 src/Plugin/YamlFormElement/YamlFormLikert.php \Drupal\yamlform\Plugin\YamlFormElement\YamlFormLikert

Provides a form element for a likert scale.

Plugin annotation

@FormElement("yamlform_likert");

Hierarchy

Expanded class hierarchy of YamlFormLikert

1 file declares its use of YamlFormLikert
YamlFormLikert.php in src/Plugin/YamlFormElement/YamlFormLikert.php

File

src/Element/YamlFormLikert.php, line 13

Namespace

Drupal\yamlform\Element
View source
class YamlFormLikert extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#process' => [
        [
          $class,
          'processYamlFormLikert',
        ],
        [
          $class,
          'processAjaxForm',
        ],
      ],
      '#theme_wrappers' => [
        'form_element',
      ],
      '#required' => FALSE,
      '#questions' => [],
      // Using #answers insteads of #options to prevent triggering
      // \Drupal\Core\Form\FormValidator::performRequiredValidation().
      '#answers' => [],
      '#na_answer' => FALSE,
      '#na_answer_text' => '',
      '#na_answer_value' => '',
    ];
  }

  /**
   * Processes a likert scale form element.
   */
  public static function processYamlFormLikert(&$element, FormStateInterface $form_state, &$complete_form) {

    // Get answer with optional N/A.
    self::processYamlFormLikertAnswers($element);

    // Build header.
    $header = [
      'likert_question' => [
        'question' => FALSE,
      ],
    ] + $element['#answers'];

    // Randomize questions.
    if (!empty($element['#questions_randomize'])) {
      shuffle($element['#questions']);
    }

    // Build rows.
    $rows = [];
    foreach ($element['#questions'] as $question_key => $question_title) {
      $value = isset($element['#value'][$question_key]) ? $element['#value'][$question_key] : NULL;
      $row = [];

      // Must format the label as an item so that inline form errors will be
      // displayed.
      $row['likert_question'] = [
        '#type' => 'item',
        '#title' => $question_title,
        // Must include an empty <span> so that the item's value is
        // not required.
        '#value' => '<span></span>',
        '#required' => $element['#required'],
      ];
      foreach ($element['#answers'] as $answer_key => $answer_title) {
        $row[$answer_key] = [
          '#parents' => [
            $element['#name'],
            $question_key,
          ],
          '#type' => 'radio',
          '#title' => $answer_title,
          '#title_display' => 'after',
          // Must cast values as strings to prevent NULL and empty strings.
          // from being evaluated as 0.
          '#return_value' => (string) $answer_key,
          '#value' => (string) $value,
        ];
      }
      $rows[$question_key] = $row;
    }
    $element['table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#attributes' => [
        'class' => [
          'yamlform-likert-table',
        ],
        'data-likert-answers-count' => count($element['#answers']),
      ],
    ] + $rows;

    // Build table element with selected properties.
    $properties = [
      '#states',
      '#sticky',
    ];
    $element['table'] += array_intersect_key($element, array_combine($properties, $properties));
    $element['#tree'] = TRUE;
    $element['#element_validate'] = [
      [
        get_called_class(),
        'validateYamlFormLikert',
      ],
    ];
    $element['#attached']['library'][] = 'yamlform/yamlform.element.likert';
    return $element;
  }

  /**
   * Get likert element's answer which can include an N/A option.
   *
   * @param array $element
   *   The element.
   */
  public static function processYamlFormLikertAnswers(array &$element) {
    if (empty($element['#na_answer']) || empty($element['#answers'])) {
      return;
    }
    $na_value = !empty($element['#na_answer_value']) ? $element['#na_answer_value'] : (string) t('N/A');
    $na_text = !empty($element['#na_answer_text']) ? $element['#na_answer_text'] : $na_value;
    $element['#answers'] += [
      $na_value => $na_text,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    $default_value = [];
    foreach ($element['#questions'] as $question_key => $question_title) {
      $default_value[$question_key] = NULL;
    }
    if ($input === FALSE) {
      $element += [
        '#default_value' => [],
      ];
      return $element['#default_value'] + $default_value;
    }
    $value = $default_value;
    foreach ($value as $allowed_key => $default) {
      if (isset($input[$allowed_key]) && is_scalar($input[$allowed_key])) {
        $value[$allowed_key] = (string) $input[$allowed_key];
      }
    }
    return $value;
  }

  /**
   * Validates a likert element.
   */
  public static function validateYamlFormLikert(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = $element['#value'];
    if (!empty($element['#required'])) {
      foreach ($element['#questions'] as $question_key => $question_title) {
        if (empty($value[$question_key])) {
          $form_state
            ->setError($element['table'][$question_key]['likert_question'], t('@name field is required.', [
            '@name' => $question_title,
          ]));
        }
      }
    }
    $form_state
      ->setValueForElement($element, $value);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
FormElement::processAutocomplete public static function Adds autocomplete functionality to elements.
FormElement::processPattern public static function #process callback for #pattern form element property.
FormElement::validatePattern public static function #element_validate callback for #pattern form element property.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. 92
RenderElement::preRenderAjaxForm public static function Adds Ajax information about an element to communicate with JavaScript.
RenderElement::preRenderGroup public static function Adds members of this group as actual elements for rendering.
RenderElement::processAjaxForm public static function Form element processing handler for the #ajax form property. 1
RenderElement::processGroup public static function Arranges elements into groups.
RenderElement::setAttributes public static function Sets a form element's class attribute. Overrides ElementInterface::setAttributes
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.
YamlFormLikert::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
YamlFormLikert::processYamlFormLikert public static function Processes a likert scale form element.
YamlFormLikert::processYamlFormLikertAnswers public static function Get likert element's answer which can include an N/A option.
YamlFormLikert::validateYamlFormLikert public static function Validates a likert element.
YamlFormLikert::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback