You are here

class AssociativeArray in Map Widget 8

Class KeyValuePair provides a form element for entering paired values.

@package Drupal\map_widget\Render\Element

Properties:

  • #count: The number textfield pairs to build for input.
  • #size: The size of the input element in characters.
  • #key_placeholder: The splaceholder on the key textfield.
  • #value_placeholder: The placeholder on the value textfield.

Usage example:

$form['map'] = [
  '#type' => 'map_associative',
  '#value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL,
  '#key_placeholder' => $this
    ->getSetting('key_placeholder'),
  '#value_placeholder' => $this
    ->getSetting('value_placeholder'),
  '#size' => $this
    ->getSetting('size'),
];

Plugin annotation

@FormElement("map_associative");

Hierarchy

Expanded class hierarchy of AssociativeArray

1 #type use of AssociativeArray
AssociativeArrayWidget::valueForm in src/Plugin/Field/FieldWidget/AssociativeArrayWidget.php
Helper function to build the value form element array.

File

src/Element/AssociativeArray.php, line 32

Namespace

Drupal\map_widget\Element
View source
class AssociativeArray extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#count' => 1,
      '#size' => 60,
      '#key_placeholder' => NULL,
      '#value_placeholder' => NULL,
      '#process' => [
        [
          $class,
          'processAssociativeArray',
        ],
      ],
      '#element_validate' => [
        [
          $class,
          'validateAssociativeArray',
        ],
      ],
      '#theme_wrappers' => [
        'fieldset',
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if (is_array($input)) {
      $value = [];
      foreach ($input as $item) {
        if (self::hasValue($item['value'])) {
          $value[$item['key']] = $item['value'];
        }
      }
      return $value;
    }
    if (!isset($element['#default_value'])) {
      $element['#default_value'] = [];
    }
    return [];
  }

  /**
   * Form API callback: Processes an associative array form element.
   *
   * This method is assigned as a #element_validate callback
   * in getInfo() method.
   */
  public static function validateAssociativeArray(&$element, FormStateInterface $form_state, &$complete_form) {
    if (isset($element['#value']) && is_array($element['#value'])) {
      $form_state
        ->setValueForElement($element, $element['#value']);
    }
  }

  /**
   * Form API callback: Processes an associative array form element.
   *
   * This method is assigned as a #process callback in getInfo() method.
   */
  public static function processAssociativeArray(&$element, FormStateInterface $form_state, &$complete_form) {
    $elementIndex = 0;
    if (empty($element['#default_value'])) {

      // One empty pair if there is no value.
      $element[$elementIndex] = self::arrayElementForm('', '', $element['#size'], $element['#key_placeholder'], $element['#value_placeholder'], $element['#required']);
    }
    foreach ($element['#default_value'] as $key => $value) {

      // Each key/value pair in it's own mini form.
      $element[$elementIndex] = self::arrayElementForm($key, $value, $element['#size'], $element['#key_placeholder'], $element['#value_placeholder'], $element['#required']);
      $elementIndex++;
    }
    for ($extra = $elementIndex; $extra < $element['#count']; $extra++) {

      // Add extra empty pairs if the count is more than then number of pairs.
      $element[$extra] = self::arrayElementForm('', '', $element['#size'], $element['#key_placeholder'], $element['#value_placeholder'], FALSE);
    }
    return $element;
  }

  /**
   * Helper function for building a single key/value pair form.
   *
   * This method is used in a Form API callback and so needs to be static.
   *
   * @param string $key
   *   The key.
   * @param string $value
   *   The value.
   * @param int $size
   *   The field size in characters.
   * @param string $keyPlaceholder
   *   The placeholder for the key field.
   * @param string $valuePlaceholder
   *   The placeholder for the value field.
   * @param bool $required
   *   Is the field required.
   *
   * @return array
   *   The render array for the key/value pair.
   */
  public static function arrayElementForm($key, $value, $size, $keyPlaceholder, $valuePlaceholder, $required) {
    return [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'map-associative-element',
        ],
      ],
      '#attached' => [
        'library' => [
          'map_widget/associative_element',
        ],
      ],
      'key' => [
        '#type' => 'textfield',
        '#default_value' => $key,
        '#size' => $size,
        '#placeholder' => $keyPlaceholder,
        '#required' => $required,
        '#attributes' => [
          'class' => [
            'map-associative--key',
          ],
        ],
      ],
      'value' => [
        '#type' => 'textfield',
        '#default_value' => $value,
        '#size' => $size,
        '#placeholder' => $valuePlaceholder,
        '#required' => $required,
        '#attributes' => [
          'class' => [
            'map-associative--value',
          ],
        ],
      ],
    ];
  }

  /**
   * Helper function to exclude "truly empty" values.
   *
   * Any value besides null or an empty string is considered a valid value.
   *
   * @param mixed $value
   *   The value.
   *
   * @return bool
   *   True anything other than null or empty string.
   */
  public static function hasValue($value) {
    return !is_null($value) && $value !== '';
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssociativeArray::arrayElementForm public static function Helper function for building a single key/value pair form.
AssociativeArray::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
AssociativeArray::hasValue public static function Helper function to exclude "truly empty" values.
AssociativeArray::processAssociativeArray public static function Form API callback: Processes an associative array form element.
AssociativeArray::validateAssociativeArray public static function Form API callback: Processes an associative array form element.
AssociativeArray::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback
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.