MachineName.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Form\FormStateInterface;
  5. use Drupal\Core\Language\LanguageInterface;
  6. /**
  7. * Provides a machine name render element.
  8. *
  9. * Provides a form element to enter a machine name, which is validated to ensure
  10. * that the name is unique and does not contain disallowed characters.
  11. *
  12. * The element may be automatically populated via JavaScript when used in
  13. * conjunction with a separate "source" form element (typically specifying the
  14. * human-readable name). As the user types text into the source element, the
  15. * JavaScript converts all values to lower case, replaces any remaining
  16. * disallowed characters with a replacement, and populates the associated
  17. * machine name form element.
  18. *
  19. * Properties:
  20. * - #machine_name: An associative array containing:
  21. * - exists: A callable to invoke for checking whether a submitted machine
  22. * name value already exists. The arguments passed to the callback will be:
  23. * - The submitted value.
  24. * - The element array.
  25. * - The form state object.
  26. * In most cases, an existing API or menu argument loader function can be
  27. * re-used. The callback is only invoked if the submitted value differs from
  28. * the element's initial #default_value. The initial #default_value is
  29. * stored in form state so AJAX forms can be reliably validated.
  30. * - source: (optional) The #array_parents of the form element containing the
  31. * human-readable name (i.e., as contained in the $form structure) to use as
  32. * source for the machine name. Defaults to array('label').
  33. * - label: (optional) Text to display as label for the machine name value
  34. * after the human-readable name form element. Defaults to t('Machine name').
  35. * - replace_pattern: (optional) A regular expression (without delimiters)
  36. * matching disallowed characters in the machine name. Defaults to
  37. * '[^a-z0-9_]+'.
  38. * - replace: (optional) A character to replace disallowed characters in the
  39. * machine name via JavaScript. Defaults to '_' (underscore). When using a
  40. * different character, 'replace_pattern' needs to be set accordingly.
  41. * - error: (optional) A custom form error message string to show, if the
  42. * machine name contains disallowed characters.
  43. * - standalone: (optional) Whether the live preview should stay in its own
  44. * form element rather than in the suffix of the source element. Defaults
  45. * to FALSE.
  46. * - #maxlength: (optional) Maximum allowed length of the machine name. Defaults
  47. * to 64.
  48. * - #disabled: (optional) Should be set to TRUE if an existing machine name
  49. * must not be changed after initial creation.
  50. *
  51. * Usage example:
  52. * @code
  53. * $form['id'] = array(
  54. * '#type' => 'machine_name',
  55. * '#default_value' => $this->entity->id(),
  56. * '#disabled' => !$this->entity->isNew(),
  57. * '#maxlength' => 64,
  58. * '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
  59. * '#machine_name' => array(
  60. * 'exists' => array($this, 'exists'),
  61. * ),
  62. * );
  63. * @endcode
  64. *
  65. * @see \Drupal\Core\Render\Element\Textfield
  66. *
  67. * @FormElement("machine_name")
  68. */
  69. class MachineName extends Textfield {
  70. /**
  71. * {@inheritdoc}
  72. */
  73. public function getInfo() {
  74. $class = get_class($this);
  75. return [
  76. '#input' => TRUE,
  77. '#default_value' => NULL,
  78. '#required' => TRUE,
  79. '#maxlength' => 64,
  80. '#size' => 60,
  81. '#autocomplete_route_name' => FALSE,
  82. '#process' => [
  83. [$class, 'processMachineName'],
  84. [$class, 'processAutocomplete'],
  85. [$class, 'processAjaxForm'],
  86. ],
  87. '#element_validate' => [
  88. [$class, 'validateMachineName'],
  89. ],
  90. '#pre_render' => [
  91. [$class, 'preRenderTextfield'],
  92. ],
  93. '#theme' => 'input__textfield',
  94. '#theme_wrappers' => ['form_element'],
  95. ];
  96. }
  97. /**
  98. * {@inheritdoc}
  99. */
  100. public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  101. if ($input !== FALSE && $input !== NULL) {
  102. // This should be a string, but allow other scalars since they might be
  103. // valid input in programmatic form submissions.
  104. return is_scalar($input) ? (string) $input : '';
  105. }
  106. return NULL;
  107. }
  108. /**
  109. * Processes a machine-readable name form element.
  110. *
  111. * @param array $element
  112. * The form element to process. See main class documentation for properties.
  113. * @param \Drupal\Core\Form\FormStateInterface $form_state
  114. * The current state of the form.
  115. * @param array $complete_form
  116. * The complete form structure.
  117. *
  118. * @return array
  119. * The processed element.
  120. */
  121. public static function processMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
  122. // We need to pass the langcode to the client.
  123. $language = \Drupal::languageManager()->getCurrentLanguage();
  124. // Apply default form element properties.
  125. $element += [
  126. '#title' => t('Machine-readable name'),
  127. '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
  128. '#machine_name' => [],
  129. '#field_prefix' => '',
  130. '#field_suffix' => '',
  131. '#suffix' => '',
  132. ];
  133. // A form element that only wants to set one #machine_name property (usually
  134. // 'source' only) would leave all other properties undefined, if the defaults
  135. // were defined by an element plugin. Therefore, we apply the defaults here.
  136. $element['#machine_name'] += [
  137. 'source' => ['label'],
  138. 'target' => '#' . $element['#id'],
  139. 'label' => t('Machine name'),
  140. 'replace_pattern' => '[^a-z0-9_]+',
  141. 'replace' => '_',
  142. 'standalone' => FALSE,
  143. 'field_prefix' => $element['#field_prefix'],
  144. 'field_suffix' => $element['#field_suffix'],
  145. ];
  146. // Store the initial value in form state. The machine name needs this to
  147. // ensure that the exists function is not called for existing values when
  148. // editing them.
  149. $initial_values = $form_state->get('machine_name.initial_values') ?: [];
  150. // Store the initial values in an array so we can differentiate between a
  151. // NULL default value and a new machine name element.
  152. if (!array_key_exists($element['#name'], $initial_values)) {
  153. $initial_values[$element['#name']] = $element['#default_value'];
  154. $form_state->set('machine_name.initial_values', $initial_values);
  155. }
  156. // By default, machine names are restricted to Latin alphanumeric characters.
  157. // So, default to LTR directionality.
  158. if (!isset($element['#attributes'])) {
  159. $element['#attributes'] = [];
  160. }
  161. $element['#attributes'] += ['dir' => LanguageInterface::DIRECTION_LTR];
  162. // The source element defaults to array('name'), but may have been overridden.
  163. if (empty($element['#machine_name']['source'])) {
  164. return $element;
  165. }
  166. // Retrieve the form element containing the human-readable name from the
  167. // complete form in $form_state. By reference, because we may need to append
  168. // a #field_suffix that will hold the live preview.
  169. $key_exists = NULL;
  170. $source = NestedArray::getValue($form_state->getCompleteForm(), $element['#machine_name']['source'], $key_exists);
  171. if (!$key_exists) {
  172. return $element;
  173. }
  174. $suffix_id = $source['#id'] . '-machine-name-suffix';
  175. $element['#machine_name']['suffix'] = '#' . $suffix_id;
  176. if ($element['#machine_name']['standalone']) {
  177. $element['#suffix'] = $element['#suffix'] . ' <small id="' . $suffix_id . '">&nbsp;</small>';
  178. }
  179. else {
  180. // Append a field suffix to the source form element, which will contain
  181. // the live preview of the machine name.
  182. $source += ['#field_suffix' => ''];
  183. $source['#field_suffix'] = $source['#field_suffix'] . ' <small id="' . $suffix_id . '">&nbsp;</small>';
  184. $parents = array_merge($element['#machine_name']['source'], ['#field_suffix']);
  185. NestedArray::setValue($form_state->getCompleteForm(), $parents, $source['#field_suffix']);
  186. }
  187. $element['#attached']['library'][] = 'core/drupal.machine-name';
  188. $options = [
  189. 'replace_pattern',
  190. 'replace_token',
  191. 'replace',
  192. 'maxlength',
  193. 'target',
  194. 'label',
  195. 'field_prefix',
  196. 'field_suffix',
  197. 'suffix',
  198. ];
  199. /** @var \Drupal\Core\Access\CsrfTokenGenerator $token_generator */
  200. $token_generator = \Drupal::service('csrf_token');
  201. $element['#machine_name']['replace_token'] = $token_generator->get($element['#machine_name']['replace_pattern']);
  202. $element['#attached']['drupalSettings']['machineName']['#' . $source['#id']] = array_intersect_key($element['#machine_name'], array_flip($options));
  203. $element['#attached']['drupalSettings']['langcode'] = $language->getId();
  204. return $element;
  205. }
  206. /**
  207. * Form element validation handler for machine_name elements.
  208. *
  209. * Note that #maxlength is validated by _form_validate() already.
  210. *
  211. * This checks that the submitted value:
  212. * - Does not contain the replacement character only.
  213. * - Does not contain disallowed characters.
  214. * - Is unique; i.e., does not already exist.
  215. * - Does not exceed the maximum length (via #maxlength).
  216. * - Cannot be changed after creation (via #disabled).
  217. */
  218. public static function validateMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
  219. // Verify that the machine name not only consists of replacement tokens.
  220. if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
  221. $form_state->setError($element, t('The machine-readable name must contain unique characters.'));
  222. }
  223. // Verify that the machine name contains no disallowed characters.
  224. if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
  225. if (!isset($element['#machine_name']['error'])) {
  226. // Since a hyphen is the most common alternative replacement character,
  227. // a corresponding validation error message is supported here.
  228. if ($element['#machine_name']['replace'] == '-') {
  229. $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
  230. }
  231. // Otherwise, we assume the default (underscore).
  232. else {
  233. $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
  234. }
  235. }
  236. else {
  237. $form_state->setError($element, $element['#machine_name']['error']);
  238. }
  239. }
  240. // Verify that the machine name is unique. If the value matches the initial
  241. // default value then it does not need to be validated as the machine name
  242. // element assumes the form is editing the existing value.
  243. $initial_values = $form_state->get('machine_name.initial_values') ?: [];
  244. if (!array_key_exists($element['#name'], $initial_values) || $initial_values[$element['#name']] !== $element['#value']) {
  245. $function = $element['#machine_name']['exists'];
  246. if (call_user_func($function, $element['#value'], $element, $form_state)) {
  247. $form_state->setError($element, t('The machine-readable name is already in use. It must be unique.'));
  248. }
  249. }
  250. }
  251. }