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 initial #default_value. The initial #default_value is
32 * stored in form state so AJAX forms can be reliably validated.
33 * - source: (optional) The #array_parents of the form element containing the
34 * human-readable name (i.e., as contained in the $form structure) to use as
35 * source for the machine name. Defaults to array('label').
36 * - label: (optional) Text to display as label for the machine name value
37 * after the human-readable name form element. Defaults to t('Machine name').
38 * - replace_pattern: (optional) A regular expression (without delimiters)
39 * matching disallowed characters in the machine name. Defaults to
41 * - replace: (optional) A character to replace disallowed characters in the
42 * machine name via JavaScript. Defaults to '_' (underscore). When using a
43 * different character, 'replace_pattern' needs to be set accordingly.
44 * - error: (optional) A custom form error message string to show, if the
45 * machine name contains disallowed characters.
46 * - standalone: (optional) Whether the live preview should stay in its own
47 * form element rather than in the suffix of the source element. Defaults
49 * - #maxlength: (optional) Maximum allowed length of the machine name. Defaults
51 * - #disabled: (optional) Should be set to TRUE if an existing machine name
52 * must not be changed after initial creation.
56 * $form['id'] = array(
57 * '#type' => 'machine_name',
58 * '#default_value' => $this->entity->id(),
59 * '#disabled' => !$this->entity->isNew(),
61 * '#description' => $this->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
62 * '#machine_name' => array(
63 * 'exists' => array($this, 'exists'),
68 * @see \Drupal\Core\Render\Element\Textfield
70 * @FormElement("machine_name")
72 class MachineName extends Textfield {
77 public function getInfo() {
78 $class = get_class($this);
81 '#default_value' => NULL,
85 '#autocomplete_route_name' => FALSE,
87 [$class, 'processMachineName'],
88 [$class, 'processAutocomplete'],
89 [$class, 'processAjaxForm'],
91 '#element_validate' => [
92 [$class, 'validateMachineName'],
95 [$class, 'preRenderTextfield'],
97 '#theme' => 'input__textfield',
98 '#theme_wrappers' => ['form_element'],
105 public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
106 if ($input !== FALSE && $input !== NULL) {
107 // This should be a string, but allow other scalars since they might be
108 // valid input in programmatic form submissions.
109 return is_scalar($input) ? (string) $input : '';
115 * Processes a machine-readable name form element.
117 * @param array $element
118 * The form element to process. See main class documentation for properties.
119 * @param \Drupal\Core\Form\FormStateInterface $form_state
120 * The current state of the form.
121 * @param array $complete_form
122 * The complete form structure.
125 * The processed element.
127 public static function processMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
128 // We need to pass the langcode to the client.
129 $language = \Drupal::languageManager()->getCurrentLanguage();
131 // Apply default form element properties.
133 '#title' => t('Machine-readable name'),
134 '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'),
135 '#machine_name' => [],
136 '#field_prefix' => '',
137 '#field_suffix' => '',
140 // A form element that only wants to set one #machine_name property (usually
141 // 'source' only) would leave all other properties undefined, if the defaults
142 // were defined by an element plugin. Therefore, we apply the defaults here.
143 $element['#machine_name'] += [
144 'source' => ['label'],
145 'target' => '#' . $element['#id'],
146 'label' => t('Machine name'),
147 'replace_pattern' => '[^a-z0-9_]+',
149 'standalone' => FALSE,
150 'field_prefix' => $element['#field_prefix'],
151 'field_suffix' => $element['#field_suffix'],
154 // Store the initial value in form state. The machine name needs this to
155 // ensure that the exists function is not called for existing values when
157 $initial_values = $form_state->get('machine_name.initial_values') ?: [];
158 // Store the initial values in an array so we can differentiate between a
159 // NULL default value and a new machine name element.
160 if (!array_key_exists($element['#name'], $initial_values)) {
161 $initial_values[$element['#name']] = $element['#default_value'];
162 $form_state->set('machine_name.initial_values', $initial_values);
165 // By default, machine names are restricted to Latin alphanumeric characters.
166 // So, default to LTR directionality.
167 if (!isset($element['#attributes'])) {
168 $element['#attributes'] = [];
170 $element['#attributes'] += ['dir' => LanguageInterface::DIRECTION_LTR];
172 // The source element defaults to array('name'), but may have been overridden.
173 if (empty($element['#machine_name']['source'])) {
177 // Retrieve the form element containing the human-readable name from the
178 // complete form in $form_state. By reference, because we may need to append
179 // a #field_suffix that will hold the live preview.
181 $source = NestedArray::getValue($form_state->getCompleteForm(), $element['#machine_name']['source'], $key_exists);
186 $suffix_id = $source['#id'] . '-machine-name-suffix';
187 $element['#machine_name']['suffix'] = '#' . $suffix_id;
189 if ($element['#machine_name']['standalone']) {
190 $element['#suffix'] = $element['#suffix'] . ' <small id="' . $suffix_id . '"> </small>';
193 // Append a field suffix to the source form element, which will contain
194 // the live preview of the machine name.
195 $source += ['#field_suffix' => ''];
196 $source['#field_suffix'] = $source['#field_suffix'] . ' <small id="' . $suffix_id . '"> </small>';
198 $parents = array_merge($element['#machine_name']['source'], ['#field_suffix']);
199 NestedArray::setValue($form_state->getCompleteForm(), $parents, $source['#field_suffix']);
202 $element['#attached']['library'][] = 'core/drupal.machine-name';
215 /** @var \Drupal\Core\Access\CsrfTokenGenerator $token_generator */
216 $token_generator = \Drupal::service('csrf_token');
217 $element['#machine_name']['replace_token'] = $token_generator->get($element['#machine_name']['replace_pattern']);
219 $element['#attached']['drupalSettings']['machineName']['#' . $source['#id']] = array_intersect_key($element['#machine_name'], array_flip($options));
220 $element['#attached']['drupalSettings']['langcode'] = $language->getId();
226 * Form element validation handler for machine_name elements.
228 * Note that #maxlength is validated by _form_validate() already.
230 * This checks that the submitted value:
231 * - Does not contain the replacement character only.
232 * - Does not contain disallowed characters.
233 * - Is unique; i.e., does not already exist.
234 * - Does not exceed the maximum length (via #maxlength).
235 * - Cannot be changed after creation (via #disabled).
237 public static function validateMachineName(&$element, FormStateInterface $form_state, &$complete_form) {
238 // Verify that the machine name not only consists of replacement tokens.
239 if (preg_match('@^' . $element['#machine_name']['replace'] . '+$@', $element['#value'])) {
240 $form_state->setError($element, t('The machine-readable name must contain unique characters.'));
243 // Verify that the machine name contains no disallowed characters.
244 if (preg_match('@' . $element['#machine_name']['replace_pattern'] . '@', $element['#value'])) {
245 if (!isset($element['#machine_name']['error'])) {
246 // Since a hyphen is the most common alternative replacement character,
247 // a corresponding validation error message is supported here.
248 if ($element['#machine_name']['replace'] == '-') {
249 $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and hyphens.'));
251 // Otherwise, we assume the default (underscore).
253 $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
257 $form_state->setError($element, $element['#machine_name']['error']);
261 // Verify that the machine name is unique. If the value matches the initial
262 // default value then it does not need to be validated as the machine name
263 // element assumes the form is editing the existing value.
264 $initial_values = $form_state->get('machine_name.initial_values') ?: [];
265 if (!array_key_exists($element['#name'], $initial_values) || $initial_values[$element['#name']] !== $element['#value']) {
266 $function = $element['#machine_name']['exists'];
267 if (call_user_func($function, $element['#value'], $element, $form_state)) {
268 $form_state->setError($element, t('The machine-readable name is already in use. It must be unique.'));