Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
TextfieldWidget.php 3.57 KiB
<?php

declare(strict_types=1);

namespace Drupal\ui_patterns\Plugin\UiPatterns\Source;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\ui_patterns\Attribute\Source;
use Drupal\ui_patterns\SourcePluginPropValue;

/**
 * Plugin implementation of the source.
 */
#[Source(
  id: 'textfield',
  label: new TranslatableMarkup('Textfield'),
  description: new TranslatableMarkup('One-line text field.'),
  prop_types: ['string', 'identifier'],
  tags: ['widget', 'widget:dismissible']
)]
class TextfieldWidget extends SourcePluginPropValue implements TrustedCallbackInterface {

  /**
   * {@inheritdoc}
   */
  public static function trustedCallbacks() {
    return ['validatePattern'];
  }

  /**
   * Validate pattern.
   *
   * #element_validate callback for #pattern form element property.
   *
   * @param array $element
   *   An associative array containing the properties and children of the
   *    generic form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @see https://www.drupal.org/project/drupal/issues/2633550
   * @see https://www.drupal.org/project/webform/issues/3002374
   */
  public static function validatePattern(array &$element, FormStateInterface $form_state) : void {
    if ($element['#value'] !== '') {
      // JavaScript-escaped Unicode characters to PCRE escape sequence format.
      $pcre_pattern = preg_replace('/\\\\u([a-fA-F0-9]{4})/', '\\x{\\1}', $element['#pattern']);
      $pattern = '{^(?:' . $pcre_pattern . ')$}u';
      if (!preg_match($pattern, $element['#value'])) {
        if (!empty($element['#pattern_error'])) {
          $form_state->setError($element, $element['#pattern_error']);
        }
        else {
          $form_state->setError($element, t('%name field is not in the right format.', ['%name' => $element['#title']]));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state): array {
    $form = parent::settingsForm($form, $form_state);
    $form['value'] = [
      '#type' => 'textfield',
      '#default_value' => $this->getSetting('value'),
    ];
    $this->addRequired($form['value']);
    $description = [];
    if (isset($this->propDefinition["pattern"])) {
      $form['value']['#pattern'] = $this->propDefinition["pattern"];
      $description[] = $this->t("Constraint: @pattern", ["@pattern" => $this->propDefinition["pattern"]]);
    }
    if (isset($this->propDefinition["maxLength"])) {
      $form['value']['#maxlength'] = $this->propDefinition["maxLength"];
      $form['value']['#size'] = $this->propDefinition["maxLength"];
      $description[] = $this->t("Max length: @length", ["@length" => $this->propDefinition["maxLength"]]);
    }
    if (!isset($this->propDefinition["pattern"]) && isset($this->propDefinition["minLength"])) {
      $form['value']['#pattern'] = "^.{" . $this->propDefinition["minLength"] . ",}$";
      $description[] = $this->t("Min length: @length", ["@length" => $this->propDefinition["minLength"]]);
    }
    if (isset($form['value']['#pattern']) && !isset($form['value']['#title'])) {
      $form['value']['#title'] = $this->propDefinition["title"] ?? $this->propId;
    }
    $form['value']["#description"] = implode("; ", $description);
    // @todo change when issue https://www.drupal.org/project/drupal/issues/2633550 is fixed.
    if (isset($form['value']['#pattern'])) {
      $form['value']['#element_validate'][] = [static::class, 'validatePattern'];
    }
    return $form;
  }

}