Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Render / Element / MachineName.php
1 <?php
2
3 namespace Drupal\Core\Render\Element;
4
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Language\LanguageInterface;
8
9 /**
10  * Provides a machine name render element.
11  *
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.
14  *
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.
21  *
22  * Properties:
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
39  *     '[^a-z0-9_]+'.
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
47  *     to FALSE.
48  * - #maxlength: (optional) Maximum allowed length of the machine name. Defaults
49  *   to 64.
50  * - #disabled: (optional) Should be set to TRUE if an existing machine name
51  *   must not be changed after initial creation.
52  *
53  * Usage example:
54  * @code
55  * $form['id'] = array(
56  *   '#type' => 'machine_name',
57  *   '#default_value' => $this->entity->id(),
58  *   '#disabled' => !$this->entity->isNew(),
59  *   '#maxlength' => 64,
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'),
63  *   ),
64  * );
65  * @endcode
66  *
67  * @see \Drupal\Core\Render\Element\Textfield
68  *
69  * @FormElement("machine_name")
70  */
71 class MachineName extends Textfield {
72
73   /**
74    * {@inheritdoc}
75    */
76   public function getInfo() {
77     $class = get_class($this);
78     return [
79       '#input' => TRUE,
80       '#default_value' => NULL,
81       '#required' => TRUE,
82       '#maxlength' => 64,
83       '#size' => 60,
84       '#autocomplete_route_name' => FALSE,
85       '#process' => [
86         [$class, 'processMachineName'],
87         [$class, 'processAutocomplete'],
88         [$class, 'processAjaxForm'],
89       ],
90       '#element_validate' => [
91         [$class, 'validateMachineName'],
92       ],
93       '#pre_render' => [
94         [$class, 'preRenderTextfield'],
95       ],
96       '#theme' => 'input__textfield',
97       '#theme_wrappers' => ['form_element'],
98     ];
99   }
100
101   /**
102    * {@inheritdoc}
103    */
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 : '';
109     }
110     return NULL;
111   }
112
113   /**
114    * Processes a machine-readable name form element.
115    *
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.
122    *
123    * @return array
124    *   The processed element.
125    */
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();
129
130     // Apply default form element properties.
131     $element += [
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' => '',
137       '#suffix' => '',
138     ];
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_]+',
147       'replace' => '_',
148       'standalone' => FALSE,
149       'field_prefix' => $element['#field_prefix'],
150       'field_suffix' => $element['#field_suffix'],
151     ];
152
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'] = [];
157     }
158     $element['#attributes'] += ['dir' => LanguageInterface::DIRECTION_LTR];
159
160     // The source element defaults to array('name'), but may have been overridden.
161     if (empty($element['#machine_name']['source'])) {
162       return $element;
163     }
164
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.
168     $key_exists = NULL;
169     $source = NestedArray::getValue($form_state->getCompleteForm(), $element['#machine_name']['source'], $key_exists);
170     if (!$key_exists) {
171       return $element;
172     }
173
174     $suffix_id = $source['#id'] . '-machine-name-suffix';
175     $element['#machine_name']['suffix'] = '#' . $suffix_id;
176
177     if ($element['#machine_name']['standalone']) {
178       $element['#suffix'] = $element['#suffix'] . ' <small id="' . $suffix_id . '">&nbsp;</small>';
179     }
180     else {
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 . '">&nbsp;</small>';
185
186       $parents = array_merge($element['#machine_name']['source'], ['#field_suffix']);
187       NestedArray::setValue($form_state->getCompleteForm(), $parents, $source['#field_suffix']);
188     }
189
190     $element['#attached']['library'][] = 'core/drupal.machine-name';
191     $options = [
192       'replace_pattern',
193       'replace_token',
194       'replace',
195       'maxlength',
196       'target',
197       'label',
198       'field_prefix',
199       'field_suffix',
200       'suffix',
201     ];
202
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']);
206
207     $element['#attached']['drupalSettings']['machineName']['#' . $source['#id']] = array_intersect_key($element['#machine_name'], array_flip($options));
208     $element['#attached']['drupalSettings']['langcode'] = $language->getId();
209
210     return $element;
211   }
212
213   /**
214    * Form element validation handler for machine_name elements.
215    *
216    * Note that #maxlength is validated by _form_validate() already.
217    *
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).
224    */
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.'));
229     }
230
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.'));
238         }
239         // Otherwise, we assume the default (underscore).
240         else {
241           $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
242         }
243       }
244       else {
245         $form_state->setError($element, $element['#machine_name']['error']);
246       }
247     }
248
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.'));
254       }
255     }
256   }
257
258 }