You are here

class YamlFormOptions in YAML Form 8

Same name in this branch
  1. 8 src/Element/YamlFormOptions.php \Drupal\yamlform\Element\YamlFormOptions
  2. 8 src/Entity/YamlFormOptions.php \Drupal\yamlform\Entity\YamlFormOptions

Provides a form element to assist in creation of options.

This provides a nicer interface for non-technical users to add values and labels for options, possible within option groups.

Plugin annotation

@FormElement("yamlform_options");

Hierarchy

Expanded class hierarchy of YamlFormOptions

1 file declares its use of YamlFormOptions
YamlFormUiOptionsForm.php in modules/yamlform_ui/src/YamlFormUiOptionsForm.php
3 #type uses of YamlFormOptions
YamlFormElementOptions::processYamlFormElementOptions in src/Element/YamlFormElementOptions.php
Processes a form element options element.
YamlFormLikert::form in src/Plugin/YamlFormElement/YamlFormLikert.php
Gets the actual configuration form array to be built.
YamlFormUiOptionsForm::editForm in modules/yamlform_ui/src/YamlFormUiOptionsForm.php
Edit form options source code form.

File

src/Element/YamlFormOptions.php, line 19

Namespace

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

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#label' => t('option'),
      '#labels' => t('options'),
      '#empty_items' => 5,
      '#add_more' => 1,
      '#process' => [
        [
          $class,
          'processYamlFormOptions',
        ],
      ],
      '#theme_wrappers' => [
        'form_element',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input === FALSE) {
      if (!isset($element['#default_value'])) {
        return [];
      }
      $options = is_string($element['#default_value']) ? Yaml::decode($element['#default_value']) : $element['#default_value'];
      if (self::hasOptGroup($options)) {
        return $options;
      }
      return self::convertOptionsToValues($options);
    }
    elseif (is_array($input) && isset($input['options'])) {
      return is_string($input['options']) ? Yaml::decode($input['options']) : $input['options'];
    }
    else {
      return NULL;
    }
  }

  /**
   * Process options and build options widget.
   */
  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;
    }
  }

  /**
   * Validates form options element.
   */
  public static function validateYamlFormOptions(&$element, FormStateInterface $form_state, &$complete_form) {
    $options_value = NestedArray::getValue($form_state
      ->getValues(), $element['options']['#parents']);
    if (is_string($options_value)) {
      $options = Yaml::decode($options_value);
    }
    else {
      $options = self::convertValuesToOptions($options_value);
    }

    // Validate required options.
    if (!empty($element['#required']) && empty($options)) {
      if (isset($element['#required_error'])) {
        $form_state
          ->setError($element, $element['#required_error']);
      }
      elseif (isset($element['#title'])) {
        $form_state
          ->setError($element, t('@name field is required.', [
          '@name' => $element['#title'],
        ]));
      }
      else {
        $form_state
          ->setError($element);
      }
      return;
    }
    $form_state
      ->setValueForElement($element, $options);
  }

  /****************************************************************************/

  // Helper functions.

  /****************************************************************************/

  /**
   * Convert values from yamform_multiple element to options.
   *
   * @param array $values
   *   An array of values.
   *
   * @return array
   *   An array of options.
   */
  public static function convertValuesToOptions(array $values = []) {
    $options = [];
    foreach ($values as $value) {
      $option_value = $value['value'];
      $option_text = $value['text'];

      // Populate empty option value or option text.
      if ($option_value === '') {
        $option_value = $option_text;
      }
      elseif ($option_text === '') {
        $option_text = $option_value;
      }
      $options[$option_value] = $option_text;
    }
    return $options;
  }

  /**
   * Convert options to values for yamform_multiple element.
   *
   * @param array $options
   *   An array of options.
   *
   * @return array
   *   An array of values.
   */
  public static function convertOptionsToValues(array $options = []) {
    $values = [];
    foreach ($options as $value => $text) {
      $values[] = [
        'value' => $value,
        'text' => $text,
      ];
    }
    return $values;
  }

  /**
   * Determine if options array contains an OptGroup.
   *
   * @param array $options
   *   An array of options.
   *
   * @return bool
   *   TRUE if options array contains an OptGroup.
   */
  public static function hasOptGroup(array $options) {
    foreach ($options as $option_text) {
      if (is_array($option_text)) {
        return TRUE;
      }
    }
    return FALSE;
  }

}

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.
YamlFormOptions::convertOptionsToValues public static function Convert options to values for yamform_multiple element.
YamlFormOptions::convertValuesToOptions public static function Convert values from yamform_multiple element to options.
YamlFormOptions::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
YamlFormOptions::hasOptGroup public static function Determine if options array contains an OptGroup.
YamlFormOptions::processYamlFormOptions public static function Process options and build options widget.
YamlFormOptions::validateYamlFormOptions public static function Validates form options element.
YamlFormOptions::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback