You are here

public static function YamlFormElementOptions::processYamlFormElementOptions in YAML Form 8

Processes a form element options element.

File

src/Element/YamlFormElementOptions.php, line 71

Class

YamlFormElementOptions
Provides a form element for managing form element options.

Namespace

Drupal\yamlform\Element

Code

public static function processYamlFormElementOptions(&$element, FormStateInterface $form_state, &$complete_form) {
  $element['#tree'] = TRUE;

  // Predefined options.
  // @see (/admin/structure/yamlform/settings/options/manage)
  $options = [];
  $yamlform_options = YamlFormOptionsEntity::loadMultiple();
  foreach ($yamlform_options as $id => $yamlform_option) {

    // Filter likert options for answers to the likert element.
    if ($element['#likert'] && strpos($id, 'likert_') !== 0) {
      continue;
    }
    $options[$id] = $yamlform_option
      ->label();
  }
  asort($options);
  $t_args = [
    '@type' => $element['#likert'] ? t('answers') : t('options'),
    ':href' => Url::fromRoute('entity.yamlform_options.collection')
      ->toString(),
  ];

  // Select options.
  $element['options'] = [
    '#type' => 'select',
    '#description' => t('Please select <a href=":href">predefined @type</a> or enter custom @type.', $t_args),
    '#options' => [
      self::CUSTOM_OPTION => t('Custom...'),
    ] + $options,
    '#attributes' => [
      'class' => [
        'js-' . $element['#id'] . '-options',
      ],
    ],
    '#error_no_message' => TRUE,
    '#default_value' => isset($element['#default_value']) && !is_array($element['#default_value']) ? $element['#default_value'] : '',
  ];

  // Custom options.
  if ($element['#custom__type'] === 'yamlform_multiple') {
    $element['custom'] = [
      '#type' => 'yamlform_multiple',
      '#title' => $element['#title'],
      '#title_display' => 'invisible',
      '#states' => [
        'visible' => [
          'select.js-' . $element['#id'] . '-options' => [
            'value' => '',
          ],
        ],
      ],
      '#error_no_message' => TRUE,
      '#default_value' => isset($element['#default_value']) && !is_string($element['#default_value']) ? $element['#default_value'] : [],
    ];
  }
  else {
    $element['custom'] = [
      '#type' => 'yamlform_options',
      '#title' => $element['#title'],
      '#title_display' => 'invisible',
      '#label' => $element['#likert'] ? t('answer') : t('option'),
      '#labels' => $element['#likert'] ? t('answers') : t('options'),
      '#states' => [
        'visible' => [
          'select.js-' . $element['#id'] . '-options' => [
            'value' => '',
          ],
        ],
      ],
      '#error_no_message' => TRUE,
      '#default_value' => isset($element['#default_value']) && !is_string($element['#default_value']) ? $element['#default_value'] : [],
    ];
  }
  $element['#element_validate'] = [
    [
      get_called_class(),
      'validateYamlFormElementOptions',
    ],
  ];
  return $element;
}