You are here

class YamlFormEmailConfirm in YAML Form 8

Same name in this branch
  1. 8 src/Element/YamlFormEmailConfirm.php \Drupal\yamlform\Element\YamlFormEmailConfirm
  2. 8 src/Plugin/YamlFormElement/YamlFormEmailConfirm.php \Drupal\yamlform\Plugin\YamlFormElement\YamlFormEmailConfirm

Provides a form element requiring users to double-element and confirm an email address.

Formats as a pair of email addresses fields, which do not validate unless the two entered email addresses match.

Plugin annotation

@FormElement("yamlform_email_confirm");

Hierarchy

Expanded class hierarchy of YamlFormEmailConfirm

File

src/Element/YamlFormEmailConfirm.php, line 18

Namespace

Drupal\yamlform\Element
View source
class YamlFormEmailConfirm extends FormElement {
  use CompositeFormElementTrait;

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    $class = get_class($this);
    return [
      '#input' => TRUE,
      '#size' => 60,
      '#process' => [
        [
          $class,
          'processYamlFormEmailConfirm',
        ],
      ],
      '#pre_render' => [
        [
          $class,
          'preRenderCompositeFormElement',
        ],
      ],
      '#theme_wrappers' => [
        'container',
      ],
      '#required' => FALSE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
    if ($input === FALSE) {
      if (!isset($element['#default_value'])) {
        $element['#default_value'] = '';
      }
      return [
        'mail_1' => $element['#default_value'],
        'mail_2' => $element['#default_value'],
      ];
    }
    else {
      return $input;
    }
  }

  /**
   * Expand an email confirm field into two HTML5 email elements.
   */
  public static function processYamlFormEmailConfirm(&$element, FormStateInterface $form_state, &$complete_form) {
    $element['#tree'] = TRUE;

    // Get shared properties.
    $shared_properties = [
      '#title_display',
      '#description_display',
      '#size',
      '#maxlength',
      '#pattern',
      '#required',
      '#placeholder',
      '#attributes',
    ];
    $element_shared_properties = [
      '#type' => 'email',
    ] + array_intersect_key($element, array_combine($shared_properties, $shared_properties));

    // Get mail 1 email element.
    $mail_1_properties = [
      '#title',
      '#description',
    ];
    $element['mail_1'] = $element_shared_properties + array_intersect_key($element, array_combine($mail_1_properties, $mail_1_properties));
    $element['mail_1']['#attributes']['class'][] = 'yamlform-email';
    $element['mail_1']['#value'] = empty($element['#value']) ? NULL : $element['#value']['mail_1'];

    // Build mail_2 confirm email element.
    $element['mail_2'] = $element_shared_properties;
    $element['mail_2']['#title'] = t('Confirm email');
    foreach ($element as $key => $value) {
      if (strpos($key, '#confirm__') === 0) {
        $element['mail_2'][str_replace('#confirm__', '#', $key)] = $value;
      }
    }
    $element['mail_2']['#attributes']['class'][] = 'yamlform-email-confirm';
    $element['mail_2']['#value'] = empty($element['#value']) ? NULL : $element['#value']['mail_2'];

    // Remove properties that are being applied to the sub elements.
    $element['#required'] = FALSE;
    unset($element['#title']);
    unset($element['#description']);
    unset($element['#maxlength']);
    unset($element['#atributes']);
    $element['#element_validate'] = [
      [
        get_called_class(),
        'validateYamlFormEmailConfirm',
      ],
    ];
    return $element;
  }

  /**
   * Validates an email confirm element.
   */
  public static function validateYamlFormEmailConfirm(&$element, FormStateInterface $form_state, &$complete_form) {
    $mail_1 = trim($element['mail_1']['#value']);
    $mail_2 = trim($element['mail_2']['#value']);
    $has_access = !isset($element['#access']) || $element['#access'] === TRUE;
    if ($has_access) {
      if ((!empty($mail_1) || !empty($mail_2)) && strcmp($mail_1, $mail_2)) {
        $form_state
          ->setError($element['mail_2'], t('The specified email addresses do not match.'));
      }
      else {

        // NOTE: Only mail_1 needs to be validated since mail_2 is the same value.
        // Verify the required value.
        if ($element['mail_1']['#required'] && empty($mail_1)) {
          if (isset($element['#required_error'])) {
            $form_state
              ->setError($element, $element['#required_error']);
          }
          elseif (isset($element['mail_1']['#title'])) {
            $form_state
              ->setError($element, t('@name field is required.', [
              '@name' => $element['mail_1']['#title'],
            ]));
          }
          else {
            $form_state
              ->setError($element);
          }
        }

        // Verify that the value is not longer than #maxlength.
        if (isset($element['mail_1']['#maxlength']) && Unicode::strlen($mail_1) > $element['mail_1']['#maxlength']) {
          $t_args = [
            '@name' => $element['mail_1']['#title'],
            '%max' => $element['mail_1']['#maxlength'],
            '%length' => Unicode::strlen($mail_1),
          ];
          $form_state
            ->setError($element, t('@name cannot be longer than %max characters but is currently %length characters long.', $t_args));
        }
      }
    }

    // Email field must be converted from a two-element array into a single
    // string regardless of validation results.
    $form_state
      ->setValueForElement($element['mail_1'], NULL);
    $form_state
      ->setValueForElement($element['mail_2'], NULL);
    $form_state
      ->setValueForElement($element, $mail_1);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CompositeFormElementTrait::preRenderCompositeFormElement public static function Adds form element theming to an element if its title or description is set.
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.
YamlFormEmailConfirm::getInfo public function Returns the element properties for this element. Overrides ElementInterface::getInfo
YamlFormEmailConfirm::processYamlFormEmailConfirm public static function Expand an email confirm field into two HTML5 email elements.
YamlFormEmailConfirm::validateYamlFormEmailConfirm public static function Validates an email confirm element.
YamlFormEmailConfirm::valueCallback public static function Determines how user input is mapped to an element's #value property. Overrides FormElement::valueCallback