Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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 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
40  *     '[^a-z0-9_]+'.
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
48  *     to FALSE.
49  * - #maxlength: (optional) Maximum allowed length of the machine name. Defaults
50  *   to 64.
51  * - #disabled: (optional) Should be set to TRUE if an existing machine name
52  *   must not be changed after initial creation.
53  *
54  * Usage example:
55  * @code
56  * $form['id'] = array(
57  *   '#type' => 'machine_name',
58  *   '#default_value' => $this->entity->id(),
59  *   '#disabled' => !$this->entity->isNew(),
60  *   '#maxlength' => 64,
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'),
64  *   ),
65  * );
66  * @endcode
67  *
68  * @see \Drupal\Core\Render\Element\Textfield
69  *
70  * @FormElement("machine_name")
71  */
72 class MachineName extends Textfield {
73
74   /**
75    * {@inheritdoc}
76    */
77   public function getInfo() {
78     $class = get_class($this);
79     return [
80       '#input' => TRUE,
81       '#default_value' => NULL,
82       '#required' => TRUE,
83       '#maxlength' => 64,
84       '#size' => 60,
85       '#autocomplete_route_name' => FALSE,
86       '#process' => [
87         [$class, 'processMachineName'],
88         [$class, 'processAutocomplete'],
89         [$class, 'processAjaxForm'],
90       ],
91       '#element_validate' => [
92         [$class, 'validateMachineName'],
93       ],
94       '#pre_render' => [
95         [$class, 'preRenderTextfield'],
96       ],
97       '#theme' => 'input__textfield',
98       '#theme_wrappers' => ['form_element'],
99     ];
100   }
101
102   /**
103    * {@inheritdoc}
104    */
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 : '';
110     }
111     return NULL;
112   }
113
114   /**
115    * Processes a machine-readable name form element.
116    *
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.
123    *
124    * @return array
125    *   The processed element.
126    */
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();
130
131     // Apply default form element properties.
132     $element += [
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' => '',
138       '#suffix' => '',
139     ];
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_]+',
148       'replace' => '_',
149       'standalone' => FALSE,
150       'field_prefix' => $element['#field_prefix'],
151       'field_suffix' => $element['#field_suffix'],
152     ];
153
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
156     // editing them.
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);
163     }
164
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'] = [];
169     }
170     $element['#attributes'] += ['dir' => LanguageInterface::DIRECTION_LTR];
171
172     // The source element defaults to array('name'), but may have been overridden.
173     if (empty($element['#machine_name']['source'])) {
174       return $element;
175     }
176
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.
180     $key_exists = NULL;
181     $source = NestedArray::getValue($form_state->getCompleteForm(), $element['#machine_name']['source'], $key_exists);
182     if (!$key_exists) {
183       return $element;
184     }
185
186     $suffix_id = $source['#id'] . '-machine-name-suffix';
187     $element['#machine_name']['suffix'] = '#' . $suffix_id;
188
189     if ($element['#machine_name']['standalone']) {
190       $element['#suffix'] = $element['#suffix'] . ' <small id="' . $suffix_id . '">&nbsp;</small>';
191     }
192     else {
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 . '">&nbsp;</small>';
197
198       $parents = array_merge($element['#machine_name']['source'], ['#field_suffix']);
199       NestedArray::setValue($form_state->getCompleteForm(), $parents, $source['#field_suffix']);
200     }
201
202     $element['#attached']['library'][] = 'core/drupal.machine-name';
203     $options = [
204       'replace_pattern',
205       'replace_token',
206       'replace',
207       'maxlength',
208       'target',
209       'label',
210       'field_prefix',
211       'field_suffix',
212       'suffix',
213     ];
214
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']);
218
219     $element['#attached']['drupalSettings']['machineName']['#' . $source['#id']] = array_intersect_key($element['#machine_name'], array_flip($options));
220     $element['#attached']['drupalSettings']['langcode'] = $language->getId();
221
222     return $element;
223   }
224
225   /**
226    * Form element validation handler for machine_name elements.
227    *
228    * Note that #maxlength is validated by _form_validate() already.
229    *
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).
236    */
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.'));
241     }
242
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.'));
250         }
251         // Otherwise, we assume the default (underscore).
252         else {
253           $form_state->setError($element, t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
254         }
255       }
256       else {
257         $form_state->setError($element, $element['#machine_name']['error']);
258       }
259     }
260
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.'));
269       }
270     }
271   }
272
273 }