3 namespace Drupal\Core\Render\Element;
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Language\LanguageInterface;
10 * Provides a machine name render element.
12 * Provides a form element to enter a machine name, which is validated to ensure
13 * that the name is unique and does not contain disallowed characters.
15 * The element may be automatically populated via JavaScript when used in
16 * conjunction with a separate "source" form element (typically specifying the
17 * human-readable name). As the user types text into the source element, the
18 * JavaScript converts all values to lower case, replaces any remaining
19 * disallowed characters with a replacement, and populates the associated
20 * machine name form element.
23 * - #machine_name: An associative array containing:
24 * - exists: A callable to invoke for checking whether a submitted machine
25 * name value already exists. The arguments passed to the callback will be:
26 * - The submitted value.
27 * - The element array.
28 * - The form state object.
29 * In most cases, an existing API or menu argument loader function can be
30 * re-used. The callback is only invoked if the submitted value differs from
31 * the element's #default_value.
32 * - source: (optional) The #array_parents of the form element containing the
33 * human-readable name (i.e., as contained in the $form structure) to use as
34 * source for the machine name. Defaults to array('label').
35 * - label: (optional) Text to display as label for the machine name value
36 * after the human-readable name form element. Defaults to t('Machine name').
37 * - replace_pattern: (optional) A regular expression (without delimiters)
38 * matching disallowed characters in the machine name. Defaults to
40 * - replace: (optional) A character to replace disallowed characters in the
41 * machine name via JavaScript. Defaults to '_' (underscore). When using a
42 * different character, 'replace_pattern' needs to be set accordingly.
43 * - error: (optional) A custom form error message string to show, if the
44 * machine name contains disallowed characters.
45 * - standalone: (optional) Whether the live preview should stay in its own
46 * form element rather than in the suffix of the source element. Defaults
48 * - #maxlength: (optional) Maximum allowed length of the machine name. Defaults
50 * - #disabled: (optional) Should be set to TRUE if an existing machine name
51 * must not be changed after initial creation.
55 * $form['id'] = array(
56 * '#type' => 'machine_name',
57 * '#default_value' => $this->entity->id(),
58 * '#disabled' => !$this->entity->isNew(),
60 * '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
61 * '#machine_name' => array(
62 * 'exists' => array($this, 'exists'),
67 * @see \Drupal\Core\Render\Element\Textfield
69 * @FormElement("machine_name")
71 class MachineName extends Textfield {
76 public function getInfo() {
77 $class = get_class($this);
80 '#default_value' => NULL,
84 '#autocomplete_route_name' => FALSE,
86 [$class, 'processMachineName'],
87 [$class, 'processAutocomplete'],
88 [$class, 'processAjaxForm'],
90 '#element_validate' => [
91 [$class, 'validateMachineName'],
94 [$class, 'preRenderTextfield'],
96 '#theme' => 'input__textfield',
97 '#theme_wrappers' => ['form_element'],
104 public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
105 if ($input !== FALSE && $input !== NULL) {
106 // This should be a string, but allow other scalars since they might be
107 // valid input in programmatic form submissions.
108 return is_scalar($input) ? (string) $input : '';
114 * Processes a machine-readable name form element.
116 * @param array $element
117 * The form element to process. See main class documentation for properties.
118 * @param \Drupal\Core\Form\FormStateInterface $form_state
119 * The current state of the form.
120 * @param array $complete_form
121 * The complete form structure.
124 * The processed element.
126 public static function processMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
127 // We need to pass the langcode to the client.
128 $language = \Drupal::languageManager()->getCurrentLanguage();
130 // Apply default form element properties.
132 '#title' => t('Machine-readable name'),
133 '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
134 '#machine_name' => [],
135 '#field_prefix' => '',
136 '#field_suffix' => '',
139 // A form element that only wants to set one #machine_name property (usually
140 // 'source' only) would leave all other properties undefined, if the defaults
141 // were defined by an element plugin. Therefore, we apply the defaults here.
142 $element['#machine_name'] += [
143 'source' => ['label'],
144 'target' => '#' . $element['#id'],
145 'label' => t('Machine name'),
146 'replace_pattern' => '[^a-z0-9_]+',
148 'standalone' => FALSE,
149 'field_prefix' => $element['#field_prefix'],
150 'field_suffix' => $element['#field_suffix'],
153 // By default, machine names are restricted to Latin alphanumeric characters.
154 // So, default to LTR directionality.
155 if (!isset($element['#attributes'])) {
156 $element['#attributes'] = [];
158 $element['#attributes'] += ['dir' => LanguageInterface::DIRECTION_LTR];
160 // The source element defaults to array('name'), but may have been overridden.
161 if (empty($element['#machine_name']['source'])) {
165 // Retrieve the form element containing the human-readable name from the
166 // complete form in $form_state. By reference, because we may need to append
167 // a #field_suffix that will hold the live preview.
169 $source = NestedArray::getValue($form_state->getCompleteForm(), $element['#machine_name']['source'], $key_exists);
174 $suffix_id = $source['#id'] . '-machine-name-suffix';
175 $element['#machine_name']['suffix'] = '#' . $suffix_id;
177 if ($element['#machine_name']['standalone']) {
178 $element['#suffix'] = $element['#suffix'] . ' <small id="' . $suffix_id . '"> </small>';
181 // Append a field suffix to the source form element, which will contain
182 // the live preview of the machine name.
183 $source += ['#field_suffix' => ''];
184 $source['#field_suffix'] = $source['#field_suffix'] . ' <small id="' . $suffix_id . '"> </small>';
186 $parents = array_merge($element['#machine_name']['source'], ['#field_suffix']);
187 NestedArray::setValue($form_state->getCompleteForm(), $parents, $source['#field_suffix']);
190 $element['#attached']['library'][] = 'core/drupal.machine-name';
203 /** @var \Drupal\Core\Access\CsrfTokenGenerator $token_generator */
204 $token_generator = \Drupal::service('csrf_token');
205 $element['#machine_name']['replace_token'] = $token_generator->get($element['#machine_name']['replace_pattern']);
207 $element['#attached']['drupalSettings']['machineName']['#' . $source['#id']] = array_intersect_key($element['#machine_name'], array_flip($options));
208 $element['#attached']['drupalSettings']['langcode'] = $language->getId();
214 * Form element validation handler for machine_name elements.
216 * Note that #maxlength is validated by _form_validate() already.
218 * This checks that the submitted value:
219 * - Does not contain the replacement character only.
220 * - Does not contain disallowed characters.
221 * - Is unique; i.e., does not already exist.
222 * - Does not exceed the maximum length (via #maxlength).
223 * - Cannot be changed after creation (via #disabled).
225 public static function validateMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
226 // Verify that the machine name not only consists of replacement tokens.
227 if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
228 $form_state->setError($element, t('The machine-readable name must contain unique characters.'));
231 // Verify that the machine name contains no disallowed characters.
232 if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
233 if (!isset($element['#machine_name']['error'])) {
234 // Since a hyphen is the most common alternative replacement character,
235 // a corresponding validation error message is supported here.
236 if ($element['#machine_name']['replace'] == '-') {
237 $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
239 // Otherwise, we assume the default (underscore).
241 $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
245 $form_state->setError($element, $element['#machine_name']['error']);
249 // Verify that the machine name is unique.
250 if ($element['#default_value'] !== $element['#value']) {
251 $function = $element['#machine_name']['exists'];
252 if (call_user_func($function, $element['#value'], $element, $form_state)) {
253 $form_state->setError($element, t('The machine-readable name is already in use. It must be unique.'));