You are here

public static function YamlFormLikert::processYamlFormLikert in YAML Form 8

Processes a likert scale form element.

File

src/Element/YamlFormLikert.php, line 41

Class

YamlFormLikert
Provides a form element for a likert scale.

Namespace

Drupal\yamlform\Element

Code

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;
}