You are here

class WebformMapping in Webform 6.x

Same name in this branch
  1. 6.x src/Element/WebformMapping.php \Drupal\webform\Element\WebformMapping
  2. 6.x src/Plugin/WebformElement/WebformMapping.php \Drupal\webform\Plugin\WebformElement\WebformMapping
Same name and namespace in other branches
  1. 8.5 src/Element/WebformMapping.php \Drupal\webform\Element\WebformMapping

Provides a mapping element.

Plugin annotation

@FormElement("webform_mapping");

Hierarchy

Expanded class hierarchy of WebformMapping

1 file declares its use of WebformMapping
WebformMapping.php in src/Plugin/WebformElement/WebformMapping.php
5 #type uses of WebformMapping
EmailWebformHandler::buildElement in src/Plugin/WebformHandler/EmailWebformHandler.php
Build A select other element for email address and names.
OptionsLimitWebformHandler::buildConfigurationForm in modules/webform_options_limit/src/Plugin/WebformHandler/OptionsLimitWebformHandler.php
Form constructor.
TestEntityMappingWebformHandler::buildConfigurationForm in tests/modules/webform_test_handler/src/Plugin/WebformHandler/TestEntityMappingWebformHandler.php
Form constructor.
WebformExampleCustomFormSettingsForm::buildForm in modules/webform_example_custom_form/src/Form/WebformExampleCustomFormSettingsForm.php
Form constructor.
WebformSubmissionExportImportUploadForm::buildConfirmForm in modules/webform_submission_export_import/src/Form/WebformSubmissionExportImportUploadForm.php
Build confirm import form.

File

src/Element/WebformMapping.php, line 18

Namespace

Drupal\webform\Element
View source
class WebformMapping extends FormElement {

  /**
   * Require all.
   */
  const REQUIRED_ALL = 'all';

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#process' => [
        [
          $class,
          'processWebformMapping',
        ],
        [
          $class,
          'processAjaxForm',
        ],
      ],
      '#theme_wrappers' => [
        'form_element',
      ],
      '#filter' => TRUE,
      '#required' => FALSE,
      '#source' => [],
      '#source__description_display' => 'description',
      '#destination' => [],
      '#arrow' => '→',
    ];
  }

  /**
   * Processes a likert scale webform element.
   */
  public static function processWebformMapping(&$element, FormStateInterface $form_state, &$complete_form) {

    // Set translated default properties.
    $element += [
      '#source__title' => t('Source'),
      '#destination__title' => t('Destination'),
      '#arrow' => '→',
    ];
    $arrow = htmlentities($element['#arrow']);

    // Process sources.
    $sources = [];
    foreach ($element['#source'] as $source_key => $source) {
      $source = (string) $source;
      if (!WebformOptionsHelper::hasOptionDescription($source)) {
        $source_description_property_name = NULL;
        $source_title = $source;
        $source_description = '';
      }
      else {
        $source_description_property_name = $element['#source__description_display'] === 'help' ? 'help' : 'description';
        list($source_title, $source_description) = WebformOptionsHelper::splitOption($source);
      }
      $sources[$source_key] = [
        'description_property_name' => $source_description_property_name,
        'title' => $source_title,
        'description' => $source_description,
      ];
    }

    // Setup destination__type depending if #destination is defined.
    if (empty($element['#destination__type'])) {
      $element['#destination__type'] = empty($element['#destination']) ? 'textfield' : 'select';
    }

    // Set base destination element.
    $destination_element_base = [
      '#title_display' => 'invisible',
      '#required' => $element['#required'] === static::REQUIRED_ALL ? TRUE : FALSE,
      '#error_no_message' => $element['#required'] !== static::REQUIRED_ALL ? TRUE : FALSE,
    ];

    // Get base #destination__* properties.
    foreach ($element as $element_key => $element_value) {
      if (strpos($element_key, '#destination__') === 0 && !in_array($element_key, [
        '#destination__title',
      ])) {
        $destination_element_base[str_replace('#destination__', '#', $element_key)] = $element_value;
      }
    }

    // Build header.
    $header = [
      [
        'data' => [
          '#markup' => $element['#source__title'] . ' ' . $arrow,
        ],
      ],
      [
        'data' => [
          '#markup' => $element['#destination__title'],
        ],
      ],
    ];

    // Build rows.
    $rows = [];
    foreach ($sources as $source_key => $source) {
      $default_value = isset($element['#default_value'][$source_key]) ? $element['#default_value'][$source_key] : NULL;

      // Source element.
      $source_element = [
        'data' => [],
      ];
      $source_element['data']['title'] = [
        '#markup' => $source['title'],
      ];
      if ($source['description_property_name'] === 'help') {
        $source_element['data']['help'] = [
          '#type' => 'webform_help',
          '#help' => $source['description'],
          '#help_title' => $source['title'],
        ];
      }
      $source_element['data']['arrow'] = [
        '#markup' => $arrow,
        '#prefix' => ' ',
      ];
      if ($source['description_property_name'] === 'description') {
        $source_element['data']['description'] = [
          '#type' => 'container',
          '#markup' => $source['description'],
          '#attributes' => [
            'class' => [
              'description',
            ],
          ],
        ];
      }

      // Destination element.
      $destination_element = $destination_element_base + [
        '#title' => $source['title'],
        '#required' => $element['#required'],
        '#default_value' => $default_value,
      ];

      // Apply #parents to destination element.
      if (isset($element['#parents'])) {
        $destination_element['#parents'] = array_merge($element['#parents'], [
          $source_key,
        ]);
      }
      switch ($element['#destination__type']) {
        case 'select':
        case 'webform_select_other':
          $destination_element += [
            '#empty_option' => t('- Select -'),
            '#options' => $element['#destination'],
          ];
          break;
      }

      // Add row.
      $rows[$source_key] = [
        'source' => $source_element,
        $source_key => $destination_element,
      ];
    }
    $element['table'] = [
      '#tree' => TRUE,
      '#type' => 'table',
      '#header' => $header,
      '#attributes' => [
        'class' => [
          'webform-mapping-table',
        ],
      ],
    ] + $rows;

    // Build table element with selected properties.
    $properties = [
      '#states',
      '#sticky',
    ];
    $element['table'] += array_intersect_key($element, array_combine($properties, $properties));

    // Add validate callback.
    $element += [
      '#element_validate' => [],
    ];
    array_unshift($element['#element_validate'], [
      get_called_class(),
      'validateWebformMapping',
    ]);
    if (!empty($element['#states'])) {
      WebformFormHelper::processStates($element, '#wrapper_attributes');
    }
    $element['#attached']['library'][] = 'webform/webform.element.mapping';
    return $element;
  }

  /**
   * Validates a mapping element.
   */
  public static function validateWebformMapping(&$element, FormStateInterface $form_state, &$complete_form) {
    $value = NestedArray::getValue($form_state
      ->getValues(), $element['#parents']);

    // Filter values.
    if ($element['#filter']) {
      $value = array_filter($value);
    }

    // Note: Not validating REQUIRED_ALL because each destination element is
    // already required.
    if (Element::isVisibleElement($element) && $element['#required'] && $element['#required'] !== static::REQUIRED_ALL && empty($value)) {
      WebformElementHelper::setRequiredError($element, $form_state);
    }
    $element['#value'] = $value;
    $form_state
      ->setValueForElement($element, $value);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
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.
FormElement::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElementInterface::valueCallback 15
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
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 2
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. 98
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. 4
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.
WebformMapping::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
WebformMapping::processWebformMapping public static function Processes a likert scale webform element.
WebformMapping::REQUIRED_ALL constant Require all.
WebformMapping::validateWebformMapping public static function Validates a mapping element.