You are here

public static function YamlFormOptions::processYamlFormOptions in YAML Form 8

Process options and build options widget.

File

src/Element/YamlFormOptions.php, line 65

Class

YamlFormOptions
Provides a form element to assist in creation of options.

Namespace

Drupal\yamlform\Element

Code

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

  // Add validate callback that extracts the associative array of options.
  $element['#element_validate'] = [
    [
      get_called_class(),
      'validateYamlFormOptions',
    ],
  ];

  // Wrap this $element in a <div> that handle #states.
  YamlFormElementHelper::fixStatesWrapper($element);

  // For options with optgroup display a CodeMirror YAML editor.
  if (isset($element['#default_value']) && is_array($element['#default_value']) && self::hasOptGroup($element['#default_value'])) {

    // Build table.
    $element['options'] = [
      '#type' => 'yamlform_codemirror',
      '#mode' => 'yaml',
      '#default_value' => Yaml::encode($element['#default_value']),
      '#description' => t('Key-value pairs MUST be specified as "safe_key: \'Some readable options\'". Use of only alphanumeric characters and underscores is recommended in keys. One option per line.') . '<br/>' . t('Option groups can be created by using just the group name followed by indented group options.'),
    ];
    return $element;
  }
  else {
    $properties = [
      '#label',
      '#labels',
      '#empty_items',
      '#add_more',
    ];
    $element['options'] = array_intersect_key($element, array_combine($properties, $properties)) + [
      '#type' => 'yamlform_multiple',
      '#header' => TRUE,
      '#element' => [
        'value' => [
          '#type' => 'textfield',
          '#title' => t('Option value'),
          '#title_display' => t('invisible'),
          '#placeholder' => t('Enter value'),
        ],
        'text' => [
          '#type' => 'textfield',
          '#title' => t('Option text'),
          '#title_display' => t('invisible'),
          '#placeholder' => t('Enter text'),
        ],
      ],
      '#default_value' => isset($element['#default_value']) ? self::convertOptionsToValues($element['#default_value']) : [],
    ];
    return $element;
  }
}