-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.module
750 lines (680 loc) · 25.9 KB
/
token.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
<?php
/**
* @file
* Enhances the token API in core: adds a browseable UI, missing tokens, etc.
*/
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuLinkInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\menu_link_content\MenuLinkContentInterface;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
/**
* Implements hook_help().
*/
function token_help($route_name, RouteMatchInterface $route_match) {
if ($route_name == 'help.page.token') {
$token_tree = \Drupal::service('token.tree_builder')->buildAllRenderable([
'click_insert' => FALSE,
'show_restricted' => TRUE,
'show_nested' => FALSE,
]);
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The <a href=":project">Token</a> module provides a user interface for the site token system. It also adds some additional tokens that are used extensively during site development. Tokens are specially formatted chunks of text that serve as placeholders for a dynamically generated value. For more information, covering both the token system and the additional tools provided by the Token module, see the <a href=":online">online documentation</a>.', [':online' => 'https://www.drupal.org/documentation/modules/token', ':project' => 'https://www.drupal.org/project/token']) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<p>' . t('Your website uses a shared token system for exposing and using placeholder tokens and their appropriate replacement values. This allows for any module to provide placeholder tokens for strings without having to reinvent the wheel. It also ensures consistency in the syntax used for tokens, making the system as a whole easier for end users to use.') . '</p>';
$output .= '<dl>';
$output .= '<dt>' . t('The list of the currently available tokens on this site are shown below.') . '</dt>';
$output .= '<dd>' . \Drupal::service('renderer')->render($token_tree) . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Return an array of the core modules supported by token.module.
*/
function _token_core_supported_modules() {
return ['book', 'field', 'menu_ui'];
}
/**
* Implements hook_theme().
*/
function token_theme() {
$info['token_tree_link'] = [
'variables' => [
'token_types' => [],
'global_types' => TRUE,
'click_insert' => TRUE,
'show_restricted' => FALSE,
'show_nested' => FALSE,
'recursion_limit' => 3,
'text' => NULL,
'options' => [],
],
'file' => 'token.pages.inc',
];
return $info;
}
/**
* Implements hook_block_view_alter().
*/
function token_block_view_alter(&$build, BlockPluginInterface $block) {
if (isset($build['#configuration'])) {
$label = $build['#configuration']['label'];
if ($label != '<none>') {
// The label is automatically escaped, avoid escaping it twice.
// @todo https://www.drupal.org/node/2580723 will add a method or option
// to the token API to do this, use that when available.
$bubbleable_metadata = BubbleableMetadata::createFromRenderArray($build);
$build['#configuration']['label'] = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($label, [], [], $bubbleable_metadata));
$bubbleable_metadata->applyTo($build);
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function token_form_block_form_alter(&$form, FormStateInterface $form_state) {
$token_tree = [
'#theme' => 'token_tree_link',
'#token_types' => [],
];
$rendered_token_tree = \Drupal::service('renderer')->render($token_tree);
$form['settings']['label']['#description'] = t('This field supports tokens. @browse_tokens_link', [
'@browse_tokens_link' => $rendered_token_tree,
]);
$form['settings']['label']['#element_validate'][] = 'token_element_validate';
$form['settings']['label'] += ['#token_types' => []];
}
/**
* Implements hook_field_info_alter().
*/
function token_field_info_alter(&$info) {
$defaults = [
'taxonomy_term_reference' => 'taxonomy_term_reference_plain',
'number_integer' => 'number_unformatted',
'number_decimal' => 'number_unformatted',
'number_float' => 'number_unformatted',
'file' => 'file_url_plain',
'image' => 'file_url_plain',
'text' => 'text_default',
'text_long' => 'text_default',
'text_with_summary' => 'text_default',
'list_integer' => 'list_default',
'list_float' => 'list_default',
'list_string' => 'list_default',
'list_boolean' => 'list_default',
];
foreach ($defaults as $field_type => $default_token_formatter) {
if (isset($info[$field_type])) {
$info[$field_type] += ['default_token_formatter' => $default_token_formatter];
}
}
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function token_date_format_insert() {
token_clear_cache();
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function token_date_format_delete() {
token_clear_cache();
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function token_field_config_presave($instance) {
token_clear_cache();
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function token_field_config_delete($instance) {
token_clear_cache();
}
/**
* Clear token caches and static variables.
*/
function token_clear_cache() {
\Drupal::token()->resetInfo();
\Drupal::service('token.entity_mapper')->resetInfo();
drupal_static_reset('token_menu_link_load_all_parents');
drupal_static_reset('token_book_link_load');
}
/**
* Implements hook_entity_type_alter().
*
* Because some token types to do not match their entity type names, we have to
* map them to the proper type. This is purely for other modules' benefit.
*
* @see \Drupal\token\TokenEntityMapperInterface::getEntityTypeMappings()
* @see http://drupal.org/node/737726
*/
function token_entity_type_alter(array &$entity_types) {
$devel_exists = \Drupal::moduleHandler()->moduleExists('devel');
/* @var $entity_types EntityTypeInterface[] */
foreach ($entity_types as $entity_type_id => $entity_type) {
if (!$entity_type->get('token_type')) {
// Fill in default token types for entities.
switch ($entity_type_id) {
case 'taxonomy_term':
case 'taxonomy_vocabulary':
// Stupid taxonomy token types...
$entity_type->set('token_type', str_replace('taxonomy_', '', $entity_type_id));
break;
default:
// By default the token type is the same as the entity type.
$entity_type->set('token_type', $entity_type_id);
break;
}
}
if ($devel_exists
&& $entity_type->hasViewBuilderClass()
&& !$entity_type->hasLinkTemplate('token-devel')) {
$entity_type->setLinkTemplate('token-devel', "/devel/token/$entity_type_id/{{$entity_type_id}}");
}
}
}
/**
* Return the module responsible for a token.
*
* @param string $type
* The token type.
* @param string $name
* The token name.
*
* @return mixed
* The value of $info['tokens'][$type][$name]['module'] from token info, or
* NULL if the value does not exist.
*/
function _token_module($type, $name) {
$token_info = \Drupal::token()->getTokenInfo($type, $name);
return isset($token_info['module']) ? $token_info['module'] : NULL;
}
/**
* Validate a form element that should have tokens in it.
*
* Form elements that want to add this validation should have the #token_types
* parameter defined.
*
* For example:
* @code
* $form['my_node_text_element'] = [
* '#type' => 'textfield',
* '#title' => t('Some text to token-ize that has a node context.'),
* '#default_value' => 'The title of this node is [node:title].',
* '#element_validate' => ['token_element_validate'],
* '#token_types' => ['node'],
* '#min_tokens' => 1,
* '#max_tokens' => 10,
* ];
* @endcode
*/
function token_element_validate($element, FormStateInterface $form_state) {
$value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
if (empty($value)) {
// Empty value needs no further validation since the element should depend
// on using the '#required' FAPI property.
return $element;
}
$tokens = \Drupal::token()->scan($value);
$title = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
// Validate if an element must have a minimum number of tokens.
if (isset($element['#min_tokens']) && count($tokens) < $element['#min_tokens']) {
$error = \Drupal::translation()->formatPlural($element['#min_tokens'], '%name must contain at least one token.', '%name must contain at least @count tokens.', ['%name' => $title]);
$form_state->setError($element, $error);
}
// Validate if an element must have a maximum number of tokens.
if (isset($element['#max_tokens']) && count($tokens) > $element['#max_tokens']) {
$error = \Drupal::translation()->formatPlural($element['#max_tokens'], '%name must contain at most one token.', '%name must contain at most @count tokens.', ['%name' => $title]);
$form_state->setError($element, $error);
}
// Check if the field defines specific token types.
if (isset($element['#token_types'])) {
$invalid_tokens = \Drupal::token()->getInvalidTokensByContext($tokens, $element['#token_types']);
if ($invalid_tokens) {
$form_state->setError($element, t('%name is using the following invalid tokens: @invalid-tokens.', ['%name' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens)]));
}
}
return $element;
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function token_form_field_config_edit_form_alter(&$form, FormStateInterface $form_state) {
$field_config = $form_state->getFormObject()->getEntity();
$field_storage = $field_config->getFieldStorageDefinition();
if ($field_storage->isLocked()) {
return;
}
$field_type = $field_storage->getType();
if (($field_type == 'file' || $field_type == 'image') && isset($form['settings']['file_directory'])) {
// GAH! We can only support global tokens in the upload file directory path.
$form['settings']['file_directory']['#element_validate'][] = 'token_element_validate';
// Date support needs to be implicitly added, as while technically it's not
// a global token, it is a not only used but is the default value.
// https://www.drupal.org/node/2642160
$form['settings']['file_directory'] += ['#token_types' => ['date']];
$form['settings']['file_directory']['#description'] .= ' ' . t('This field supports tokens.');
}
// Note that the description is tokenized via token_field_widget_form_alter().
$form['description']['#element_validate'][] = 'token_element_validate';
$form['description'] += ['#token_types' => []];
$form['token_tree'] = [
'#theme' => 'token_tree_link',
'#token_types' => [],
'#weight' => $form['description']['#weight'] + 0.5,
];
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*
* Alters the configure action form to add token context validation and
* adds the token tree for a better token UI and selection.
*/
function token_form_action_form_alter(&$form, $form_state) {
if (isset($form['plugin'])) {
switch ($form['plugin']['#value']) {
case 'action_message_action':
case 'action_send_email_action':
case 'action_goto_action':
$form['token_tree'] = [
'#theme' => 'token_tree_link',
'#token_types' => 'all',
'#weight' => 100,
];
$form['actions']['#weight'] = 101;
// @todo Add token validation to the action fields that can use tokens.
break;
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Alters the user e-mail fields to add token context validation and
* adds the token tree for a better token UI and selection.
*/
function token_form_user_admin_settings_alter(&$form, FormStateInterface $form_state) {
$email_token_help = t('Available variables are: [site:name], [site:url], [user:display-name], [user:account-name], [user:mail], [site:login-url], [site:url-brief], [user:edit-url], [user:one-time-login-url], [user:cancel-url].');
foreach (Element::children($form) as $key) {
$element = &$form[$key];
// Remove the crummy default token help text.
if (!empty($element['#description'])) {
$element['#description'] = trim(str_replace($email_token_help, t('The list of available tokens that can be used in e-mails is provided below.'), $element['#description']));
}
switch ($key) {
case 'email_admin_created':
case 'email_pending_approval':
case 'email_no_approval_required':
case 'email_password_reset':
case 'email_cancel_confirm':
// Do nothing, but allow execution to continue.
break;
case 'email_activated':
case 'email_blocked':
case 'email_canceled':
// These fieldsets have their e-mail elements inside a 'settings'
// sub-element, so switch to that element instead.
$element = &$form[$key]['settings'];
break;
default:
continue 2;
}
foreach (Element::children($element) as $sub_key) {
if (!isset($element[$sub_key]['#type'])) {
continue;
}
elseif ($element[$sub_key]['#type'] == 'textfield' && substr($sub_key, -8) === '_subject') {
// Add validation to subject textfields.
$element[$sub_key]['#element_validate'][] = 'token_element_validate';
$element[$sub_key] += ['#token_types' => ['user']];
}
elseif ($element[$sub_key]['#type'] == 'textarea' && substr($sub_key, -5) === '_body') {
// Add validation to body textareas.
$element[$sub_key]['#element_validate'][] = 'token_element_validate';
$element[$sub_key] += ['#token_types' => ['user']];
}
}
}
// Add the token tree UI.
$form['email']['token_tree'] = [
'#theme' => 'token_tree_link',
'#token_types' => ['user'],
'#show_restricted' => TRUE,
'#show_nested' => FALSE,
'#weight' => 90,
];
}
/**
* Prepare a string for use as a valid token name.
*
* @param $name
* The token name to clean.
* @return
* The cleaned token name.
*/
function token_clean_token_name($name) {
static $names = [];
if (!isset($names[$name])) {
$cleaned_name = strtr($name, [' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '']);
$cleaned_name = preg_replace('/[^\w\-]/i', '', $cleaned_name);
$cleaned_name = trim($cleaned_name, '-');
$names[$name] = $cleaned_name;
}
return $names[$name];
}
/**
* Do not use this function yet. Its API has not been finalized.
*/
function token_render_array(array $array, array $options = []) {
$rendered = [];
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
foreach (token_element_children($array) as $key) {
$value = $array[$key];
$rendered[] = is_array($value) ? $renderer->renderPlain($value) : (string) $value;
}
$join = isset($options['join']) ? $options['join'] : ', ';
return implode($join, $rendered);
}
/**
* Do not use this function yet. Its API has not been finalized.
*/
function token_render_array_value($value, array $options = []) {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
$rendered = is_array($value) ? $renderer->renderPlain($value) : (string) $value;
return $rendered;
}
/**
* Coyp of drupal_render_cache_set() that does not care about request method.
*/
function token_render_cache_set(&$markup, $elements) {
// This should only run of drupal_render_cache_set() did not.
if (in_array(\Drupal::request()->server->get('REQUEST_METHOD'), ['GET', 'HEAD'])) {
return FALSE;
}
$original_method = \Drupal::request()->server->get('REQUEST_METHOD');
\Drupal::request()->server->set('REQUEST_METHOD', 'GET');
drupal_render_cache_set($markup, $elements);
\Drupal::request()->server->set('REQUEST_METHOD', $original_method);
}
/**
* Loads menu link titles for all purents of a menu link plugin ID.
*
* @param string $plugin_id
* The menu link plugin ID.
* @param string $langcode
* The language code.
*
* @return string[]
* List of menu link parent titles.
*/
function token_menu_link_load_all_parents($plugin_id, $langcode) {
$cache = &drupal_static(__FUNCTION__, []);
if (!isset($cache[$plugin_id][$langcode])) {
$cache[$plugin_id][$langcode] = [];
/** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$parent_ids = $menu_link_manager->getParentIds($plugin_id);
// Remove the current plugin ID from the parents.
unset($parent_ids[$plugin_id]);
foreach ($parent_ids as $parent_id) {
$parent = $menu_link_manager->createInstance($parent_id);
$cache[$plugin_id][$langcode] = [$parent_id => token_menu_link_translated_title($parent, $langcode)] + $cache[$plugin_id][$langcode];
}
}
return $cache[$plugin_id][$langcode];
}
/**
* Returns the translated link of a menu title.
*
* If the underlying entity is a content menu item, load it to get the
* translated menu item title.
*
* @todo Remove this when there is a better way to get a translated menu
* item title in core: https://www.drupal.org/node/2795143
*
* @param \Drupal\Core\Menu\MenuLinkInterface $menu_link
* The menu link.
* @param string|null $langcode
* (optional) The langcode, defaults to the current language.
*
* @return string
* The menu link title.
*/
function token_menu_link_translated_title(MenuLinkInterface $menu_link, $langcode = NULL) {
$metadata = $menu_link->getMetaData();
if (isset($metadata['entity_id']) && $menu_link->getProvider() == 'menu_link_content') {
/** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
$entity = \Drupal::entityTypeManager()->getStorage('menu_link_content')->load($metadata['entity_id']);
if (!empty($entity)) {
$entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity, $langcode);
return $entity->getTitle();
}
}
return $menu_link->getTitle();
}
/**
* Loads all the parents of the term in the specified language.
*
* @param int $tid
* The term id.
* @param string $langcode
* The language code.
*
* @return string[]
* The term parents collection.
*/
function token_taxonomy_term_load_all_parents($tid, $langcode) {
$cache = &drupal_static(__FUNCTION__, []);
if (!is_numeric($tid)) {
return [];
}
if (!isset($cache[$langcode][$tid])) {
$cache[$langcode][$tid] = [];
/** @var \Drupal\taxonomy\TermStorageInterface $term_storage */
$term_storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$parents = $term_storage->loadAllParents($tid);
// Remove this term from the array.
array_shift($parents);
$parents = array_reverse($parents);
foreach ($parents as $term) {
$translation = \Drupal::service('entity.repository')->getTranslationFromContext($term, $langcode);
$cache[$langcode][$tid][$term->id()] = $translation->label();
}
}
return $cache[$langcode][$tid];
}
function token_element_children(&$elements, $sort = FALSE) {
// Do not attempt to sort elements which have already been sorted.
$sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
// Filter out properties from the element, leaving only children.
$children = [];
$sortable = FALSE;
foreach ($elements as $key => $value) {
if (is_int($key) || $key === '' || $key[0] !== '#') {
$children[$key] = $value;
if (is_array($value) && isset($value['#weight'])) {
$sortable = TRUE;
}
}
}
// Sort the children if necessary.
if ($sort && $sortable) {
uasort($children, 'Drupal\Component\Utility\SortArray::sortByWeightProperty');
// Put the sorted children back into $elements in the correct order, to
// preserve sorting if the same element is passed through
// element_children() twice.
foreach ($children as $key => $child) {
unset($elements[$key]);
$elements[$key] = $child;
}
$elements['#sorted'] = TRUE;
}
return array_keys($children);
}
/**
* Loads all the parents of the book page.
*
* @param array $book
* The book data. The 'nid' key points to the current page of the book.
* The 'p1' ... 'p9' keys point to parents of the page, if they exist, with 'p1'
* pointing to the book itself and the last defined pX to the current page.
*
* @return string[]
* List of node titles of the book parents.
*/
function token_book_load_all_parents(array $book) {
$cache = &drupal_static(__FUNCTION__, []);
if (empty($book['nid'])) {
return [];
}
$nid = $book['nid'];
if (!isset($cache[$nid])) {
$cache[$nid] = [];
$i = 1;
while ($book["p$i"] != $nid) {
$cache[$nid][] = Node::load($book["p$i"])->getTitle();
$i++;
}
}
return $cache[$nid];
}
/**
* Implements hook_entity_base_field_info().
*/
function token_entity_base_field_info(EntityTypeInterface $entity_type) {
// We add a pseudo entity-reference field to track the menu entry created
// from the node add/edit form so that tokens generated at that time that
// reference the menu link can access the yet to be saved menu link.
// @todo Revisit when https://www.drupal.org/node/2315773 is resolved.
if ($entity_type->id() === 'node' && \Drupal::moduleHandler()->moduleExists('menu_ui')) {
$fields['menu_link'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Menu link'))
->setDescription(t('Computed menu link for the node (only available during node saving).'))
->setRevisionable(TRUE)
->setSetting('target_type', 'menu_link_content')
->setClass('\Drupal\token\MenuLinkFieldItemList')
->setTranslatable(TRUE)
->setInternal(TRUE)
->setDisplayOptions('view', [
'label' => 'hidden',
'region' => 'hidden',
])
->setComputed(TRUE)
->setDisplayOptions('form', [
'region' => 'hidden',
]);
return $fields;
}
return [];
}
/**
* Implements hook_form_BASE_FORM_ID_alter() for node_form.
*
* Populates menu_link field on nodes from the menu item on unsaved nodes.
*
* @see menu_ui_form_node_form_submit()
* @see token_entity_base_field_info()
*/
function token_form_node_form_alter(&$form, FormStateInterface $form_state) {
if (!\Drupal::moduleHandler()->moduleExists('menu_ui')) {
return;
}
$form['#entity_builders'][] = 'token_node_menu_link_submit';
}
/**
* Entity builder.
*/
function token_node_menu_link_submit($entity_type, NodeInterface $node, &$form, FormStateInterface $form_state) {
// Entity builders run twice, once during validation and again during
// submission, so we only run this code after validation has been performed.
if (!$form_state->isValueEmpty('menu') && $form_state->getTemporaryValue('entity_validated')) {
// Don't create a menu link if the node is not being saved.
$triggering_element = $form_state->getTriggeringElement();
if (!$triggering_element || !isset($triggering_element['#submit']) || !in_array('::save', $triggering_element['#submit'])) {
return;
}
$values = $form_state->getValue('menu');
if (!empty($values['enabled']) && trim($values['title'])) {
if (!empty($values['menu_parent'])) {
list($menu_name, $parent) = explode(':', $values['menu_parent'], 2);
$values['menu_name'] = $menu_name;
$values['parent'] = $parent;
}
// Construct an unsaved entity.
if ($entity_id = $form_state->getValue(['menu', 'entity_id'])) {
// Use the existing menu_link_content entity.
$entity = MenuLinkContent::load($entity_id);
// If the loaded MenuLinkContent doesn't have a translation for the
// Node's active langcode, create a new translation.
if ($entity->isTranslatable()) {
if (!$entity->hasTranslation($node->language()->getId())) {
$entity = $entity->addTranslation($node->language()->getId(), $entity->toArray());
}
else {
$entity = $entity->getTranslation($node->language()->getId());
}
}
}
else {
if ($node->isNew()) {
// Create a new menu_link_content entity.
$entity = MenuLinkContent::create([
// Lets just reference the UUID for now, the link is not important for
// token generation.
'link' => ['uri' => 'internal:/node/' . $node->uuid()],
'langcode' => $node->language()->getId(),
]);
}
else {
// Create a new menu_link_content entity.
$entity = MenuLinkContent::create([
'link' => ['uri' => 'entity:node/' . $node->id()],
'langcode' => $node->language()->getId(),
]);
}
}
$entity->title->value = trim($values['title']);
$entity->description->value = trim($values['description'] ?? '');
$entity->menu_name->value = $values['menu_name'];
$entity->parent->value = $values['parent'];
$entity->weight->value = isset($values['weight']) ? $values['weight'] : 0;
$entity->isDefaultRevision($node->isDefaultRevision());
$entity->save();
$node->menu_link = $entity;
// Leave this for _menu_ui_node_save() to pick up so we don't end up with
// duplicate menu-links.
$form_state->setValue(['menu', 'entity_id'], $entity->id());
}
}
}
/**
* Implements hook_ENTITY_TYPE_insert for node entities.
*/
function token_node_insert(NodeInterface $node) {
if ($node->hasField('menu_link') && $menu_link = $node->menu_link->entity) {
// Update the menu-link to point to the now saved node.
$menu_link->link = 'entity:node/' . $node->id();
$menu_link->save();
}
}
/**
* Implements hook_ENTITY_TYPE_presave() for menu_link_content.
*/
function token_menu_link_content_presave(MenuLinkContentInterface $menu_link_content) {
drupal_static_reset('token_menu_link_load_all_parents');
}