-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhdbt_admin_tools.module
More file actions
1150 lines (1009 loc) · 38 KB
/
hdbt_admin_tools.module
File metadata and controls
1150 lines (1009 loc) · 38 KB
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @file
* Contains alterations for content.
*/
declare(strict_types=1);
use Drupal\config_rewrite\ConfigRewriterInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Url;
use Drupal\hdbt_admin_tools\Form\SiteSettings;
use Drupal\hdbt_admin_tools\Plugin\Field\FieldType\SelectIcon;
use Drupal\helfi_api_base\Link\UrlHelper;
use Drupal\helfi_tpr\Entity\Service;
use Drupal\node\NodeInterface;
use Drupal\user\UserInterface;
/**
* Implements hook_rewrite_config_update().
*/
function hdbt_admin_tools_config_rewrite_config_update(string $module, ConfigRewriterInterface $configRewriter): void {
// Rewrite module configuration.
if ($module === 'hdbt_admin_tools') {
$configRewriter->rewriteModuleConfig('hdbt_admin_tools');
}
}
/**
* Register routes to apply Gin’s content edit form layout.
*
* @return array
* An array of route names.
*
* @see GinContentFormHelper->isContentForm()
*/
function hdbt_admin_tools_gin_content_form_routes(): array {
// Apply gin theme to TPR unit, TPR service and Taxonomy terms.
return [
'entity.tpr_unit.add_form',
'entity.tpr_unit.edit_form',
'entity.tpr_service.add_form',
'entity.tpr_service.edit_form',
'entity.tpr_service_channel.add_form',
'entity.tpr_service_channel.edit_form',
'entity.tpr_errand_service.add_form',
'entity.tpr_errand_service.edit_form',
'entity.tpr_ontology_word_details.add_form',
'entity.tpr_ontology_word_details.edit_form',
'entity.taxonomy_term.add_form',
'entity.taxonomy_term.edit_form',
];
}
/**
* Implements hook_modules_installed().
*/
function hdbt_admin_tools_modules_installed(array $modules) : void {
// Modules containing entities which needs color palette field.
$moduleList = [
'helfi_node_announcement',
'helfi_node_landing_page',
'helfi_node_news_item',
'helfi_node_page',
'helfi_tpr_config',
];
if (!in_array($moduleList, $modules)) {
return;
}
// Install color palette field to selected entities.
$fields = [
'color_palette',
'hide_sidebar_navigation',
];
$entityTypes = [
'node',
'tpr_unit',
'tpr_service',
];
foreach ($entityTypes as $entityType) {
foreach ($fields as $field) {
$entityDefinitionUpdateManager = \Drupal::entityDefinitionUpdateManager();
$fieldDefinitions = \Drupal::service('entity_field.manager')
->getFieldDefinitions($entityType, $entityType);
if (
!empty($fieldDefinitions[$field]) &&
$fieldDefinitions[$field] instanceof FieldStorageDefinitionInterface
) {
$entityDefinitionUpdateManager->installFieldStorageDefinition(
$field,
$entityType,
'hdbt_admin_tools',
$fieldDefinitions[$field]
);
}
}
}
}
/**
* Implements hook_theme().
*/
function hdbt_admin_tools_theme(): array {
return [
'selection_widget' => [
'render element' => 'element',
'preprocess functions' => [
'template_preprocess_selection_widget',
'template_preprocess_select',
],
],
'select_icon_widget' => [
'render element' => 'element',
'preprocess functions' => [
'template_preprocess_select_icon',
'template_preprocess_select',
],
],
'select_icon' => [
'variables' => [
'icon_id' => NULL,
'icon_label' => NULL,
],
],
];
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function hdbt_admin_tools_form_node_form_alter(&$form, &$form_state, $form_id): void {
switch ($form_id) {
case 'node_landing_page_edit_form':
case 'node_landing_page_form':
case 'node_page_edit_form':
case 'node_page_form':
// Control Hero paragraph visibility via checkbox states.
$form['field_hero']['#states'] = [
'visible' => [
':input[name="field_has_hero[value]"]' => ['checked' => TRUE],
],
];
break;
}
// Custom submit callback.
$form['actions']['submit']['#submit'][] = 'hdbt_admin_tools_node_form_submit_callback';
}
/**
* Form submit callback for node forms.
*
* Redirect content editor to correct translation after saving the node.
*/
function hdbt_admin_tools_node_form_submit_callback($form, FormStateInterface $form_state): void {
if ($lang_code = $form_state->get('langcode')) {
$language = [
'language' => \Drupal::languageManager()->getLanguage($lang_code),
];
if ($nid = $form_state->get('nid')) {
$node = [
'node' => $nid,
];
$form_state->setRedirect('entity.node.canonical', $node, $language);
}
}
}
/**
* Implements hook_language_switch_links_alter().
*/
function hdbt_admin_tools_language_switch_links_alter(array &$links): void {
$route_match = Drupal::routeMatch();
$entity = FALSE;
// Determine if the current route represents an entity.
if (
($route = $route_match->getRouteObject()) &&
($parameters = $route->getOption('parameters'))
) {
foreach ($parameters as $name => $options) {
if (
isset($options['type']) &&
str_starts_with($options['type'], 'entity:')
) {
$parameter = $route_match->getParameter($name);
if (
$parameter instanceof ContentEntityInterface &&
$parameter->hasLinkTemplate('canonical')
) {
$entity = $parameter;
break;
}
}
}
}
$language_resolver = \Drupal::service('helfi_api_base.default_language_resolver');
$primary_languages = $language_resolver->getDefaultLanguages();
// Compare the links with current entity and check for possible translations.
foreach ($links as $lang_code => &$link) {
$link['#abbreviation'] = $lang_code;
if (in_array($lang_code, $primary_languages)) {
$link['#primary_language'] = TRUE;
}
if (!$entity instanceof ContentEntityInterface) {
continue;
}
if (!$entity->hasTranslation($lang_code)) {
$link['#untranslated'] = TRUE;
continue;
}
if (
method_exists($entity->getTranslation($lang_code), 'isPublished') &&
!$entity->getTranslation($lang_code)->isPublished()
) {
$link['#untranslated'] = TRUE;
}
}
}
/**
* Gets the current page main entity.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* Current page main entity.
*/
function hdbt_admin_tools_get_page_entity(): ?EntityInterface {
$page_entity = &drupal_static(__FUNCTION__, NULL);
if (!empty($page_entity)) {
return $page_entity;
}
$types = array_keys(Drupal::entityTypeManager()->getDefinitions());
$route = Drupal::routeMatch();
$params = $route->getParameters()->all();
foreach ($types as $type) {
foreach (['revision' => $type . '_revision', 'canonical' => $type] as $route_name => $version) {
if (!empty($params[$version]) && $route->getRouteName() === "entity.$type.$route_name") {
return $params[$version];
}
}
}
return NULL;
}
/**
* Implements hook_preprocess_HOOK().
*/
function hdbt_admin_tools_preprocess_page(&$variables): void {
$variables['has_sidebar'] = FALSE;
// Handle sidebar visibility.
$entity = hdbt_admin_tools_get_page_entity();
if ($entity instanceof ContentEntityInterface) {
// Set has_hero variable according to field_has_hero and existence of
// field_hero reference.
if ($entity->hasField('field_hero')) {
$variables['has_hero'] = !$entity->get('field_hero')->isEmpty() && (
!$entity->hasField('field_has_hero') ||
$entity->get('field_has_hero')->value
);
}
// Handle sidebar visibility.
hdbt_admin_tools_handle_sidebar_visibility($variables, $entity);
}
}
/**
* Handle sidebar visibility based on current entity menu links.
*
* @param array $variables
* Variables array.
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* Content entity, like tpr_service, tpr_unit or node.
*/
function hdbt_admin_tools_handle_sidebar_visibility(array &$variables, ContentEntityInterface $entity): void {
// The entities that need to be handled listed as content type => entity type.
$allowed_entities = [
'page' => 'node',
'news_item' => 'node',
'tpr_unit' => 'tpr_unit',
'tpr_service' => 'tpr_service',
];
/** @var \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler */
$moduleHandler = Drupal::service('module_handler');
// Trigger hook_sidebar_visibility_allowed_entities_alter().
// Allow modules to alter the list of allowed entities.
$moduleHandler->alter('sidebar_visibility_allowed_entities', $allowed_entities);
// Get possible (node) content type.
$content_type = $entity instanceof NodeInterface ? $entity->getType() : FALSE;
// Check if (node) content type is in allowed content types.
if ($content_type && !array_key_exists($content_type, $allowed_entities)) {
return;
}
// Check if entity type is in allowed entity types.
if (!in_array($entity->getEntityTypeId(), $allowed_entities)) {
return;
}
$variables['has_sidebar_first'] = FALSE;
$variables['has_sidebar_second'] = FALSE;
// Load menu links for the current page entity.
$menu_link_manager = Drupal::service('plugin.manager.menu.link');
$menu_links = $menu_link_manager->loadLinksByRoute(
"entity.{$entity->getEntityTypeId()}.canonical",
[$entity->getEntityTypeId() => $entity->id()],
'main'
);
// If there are links in current language, apply "has_sidebar_first" variable
// to indicate twig templates how to render the sidebar.
// However, if the menu link is set to first level, do not render the
// sidebar.
if (!empty($menu_links)) {
$lang_code = \Drupal::languageManager()
->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
->getId();
foreach ($menu_links as $menu_link) {
/** @var \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent $menu_link */
if ($menu_link) {
/** @var \Drupal\menu_link_content\Entity\MenuLinkContent $menu_link_content */
$menu_link_content = \Drupal::service('entity.repository')
->loadEntityByUuid('menu_link_content', $menu_link->getDerivativeId());
if (
$menu_link_content->hasTranslation($lang_code) &&
!empty($menu_link_content->getParentId())
) {
$variables['has_sidebar_first'] = TRUE;
}
}
}
}
// Hide the sidebar and menu if the current entity has
// "hide sidebar navigation" value set.
if (
$entity->hasField('hide_sidebar_navigation') &&
$entity->get('hide_sidebar_navigation')->value
) {
$variables['has_sidebar_first'] = FALSE;
}
// Check if page entity has sidebar content field available and set
// "has_sidebar_second" variable accordingly.
if (
$entity->hasField('field_sidebar_content') &&
!$entity->get('field_sidebar_content')->isEmpty()
) {
$variables['has_sidebar_second'] = TRUE;
}
// Enable sidebar second for News item.
if ($content_type === 'news_item') {
$variables['has_sidebar_second'] = TRUE;
}
// Enable sidebar second for TPR service if important links exists.
if ($entity instanceof Service && !$entity->get('links')->isEmpty()) {
$variables['has_sidebar_second'] = TRUE;
}
// Allow modules to override sidebar visibility.
$moduleHandler->alter('sidebar_visibility', $variables, $entity);
}
/**
* Implements hook_preprocess_HOOK().
*/
function hdbt_admin_tools_preprocess_toolbar(&$variables): void {
if ($variables['element']['#attributes']['id'] === 'toolbar-administration') {
$theme_handler = Drupal::service('theme_handler');
if (!$theme_handler->themeExists('hdbt')) {
return;
}
$variables['#attached']['library'][] = 'hdbt/environment-indicator';
$environment = getenv('APP_ENV');
$environments = ['local', 'testing', 'staging', 'production', 'development'];
foreach ($environments as $value) {
if ($environment === $value) {
$variables['attributes']['class'][] = 'env-' . $value;
}
}
}
}
/**
* Implements hook_toolbar_alter().
*/
function hdbt_admin_tools_toolbar_alter(&$items): void {
foreach ($items as &$value) {
if (!array_key_exists('#attached', $value)) {
continue;
}
if (is_array($value['#attached']['library'])) {
$value['#attached']['library'][] = 'hdbt_admin_tools/menu_styles';
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Alter config translation edit form.
*/
function hdbt_admin_tools_form_config_translation_form_alter(&$form, &$form_state, $form_id): void {
$form_ids = [
'config_translation_add_form',
'config_translation_edit_form',
];
if (in_array($form_id, $form_ids)) {
$settings = &$form['config_names']['hdbt_admin_tools.site_settings'];
// Don't translate global fields.
$settings['footer_settings']['footer_color']['#disabled'] = TRUE;
$settings['site_settings']['koro']['#disabled'] = TRUE;
$settings['site_settings']['theme_color']['#disabled'] = TRUE;
}
}
/**
* Provides options for the color palettes field.
*
* @todo Check if this is needed.
*
* @return array
* An array of possible key and value options.
*
* @see options_allowed_values()
*/
function hdbt_admin_tools_color_palette_allowed_values(): array {
return SiteSettings::getColorPalettes();
}
/**
* Provides default value for the color palettes field.
*
* @return array
* An array of possible key and value options.
*
* @see options_allowed_values()
*/
function hdbt_admin_tools_color_palette_default_value(): array {
$cached = \Drupal::cache()->get('hdbt_settings:theme_color');
if ($cached) {
return [
['value' => $cached->data],
];
}
// @todo Find out if we can change the hdbt_admin_tools configuration prefix without BC breaks.
$settings = \Drupal::config('hdbt_admin_tools.site_settings');
return ($value = $settings->get('site_settings.theme_color')) ? [['value' => $value]] : [];
}
/**
* Implements hook_form_BASE_FORM_ID_alter() for \Drupal\taxonomy\TermForm.
*/
function hdbt_admin_tools_form_taxonomy_term_form_alter(array &$form, FormStateInterface $form_state) {
// Move relations into sidebar.
$form['relations']['#group'] = 'advanced';
/** @var \Drupal\Core\Entity\ContentEntityFormInterface $form_object */
$form_object = $form_state->getFormObject();
/** @var \Drupal\taxonomy\TermInterface $term */
$term = $form_object->getEntity();
// Move pathauto into sidebar.
$form['path_settings'] = [
'#type' => 'details',
'#title' => t('URL path settings'),
'#open' => !empty($form['path']['widget'][0]['alias']['#value']),
'#group' => 'advanced',
'#access' =>
!empty($form['path']['#access']) &&
$term->hasField('path') &&
$term->get('path')->access('edit'),
'#attributes' => [
'class' => ['path-form'],
],
'#attached' => [
'library' => ['path/drupal.path'],
],
'#weight' => 30,
];
$form['path']['#group'] = 'path_settings';
}
/**
* Implements hook_entity_bundle_field_info_alter().
*/
function hdbt_admin_tools_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle): void {
if ($entity_type->id() === 'paragraph' && $bundle == 'hero') {
// Add constraint to check if Hero image is mandatory.
if (array_key_exists('field_hero_image', $fields)) {
$fields['field_hero_image']->addConstraint('HeroImage', []);
}
}
// Add constraint to check that Hero entity exists when necessary.
if (
array_key_exists('field_has_hero', $fields) &&
array_key_exists('field_hero', $fields)
) {
$fields['field_has_hero']->addConstraint('Hero', []);
}
if ($entity_type->id() === 'paragraph' && $bundle == 'image_gallery') {
// Add constraint to check if image gallery has two gallery items.
if (array_key_exists('field_gallery_item', $fields)) {
$fields['field_gallery_item']->addConstraint('ImageGallery', []);
}
}
}
/**
* Implements hook_field_widget_single_element_WIDGET_TYPE_form_alter().
*/
function hdbt_admin_tools_field_widget_single_element_paragraphs_form_alter(&$element, &$form_state, $context): void {
/* Hero designs:
*
* background-image = "Background image"
* diagonal = "Diagonal"
* with-image-bottom = "Image on the bottom"
* with-image-left = "Image on the left"
* with-image-right = "Image on the right"
* without-image-center = "Without image, align center"
* without-image-left = "Without image, align left"
* with-search = "With search"
*/
// Early return if paragraph type is not set.
if (!isset($element['#paragraph_type'])) {
return;
}
// Perform alterations to Hero paragraph.
if ($element['#paragraph_type'] == 'hero') {
// Hero designs & hero design selection.
$design_select = ':input[name="field_hero[' . $element['#delta'] . '][subform][field_hero_design][0]"]';
// Show description only if design needs it.
$element['subform']['field_hero_desc']['#states'] = [
'invisible' => [
[$design_select => ['value' => 'background-image']],
'or',
[$design_select => ['value' => 'with-search']],
],
];
// Show image only if design needs it.
$element['subform']['field_hero_image']['#states'] = [
'invisible' => [
[$design_select => ['value' => 'without-image-center']],
'or',
[$design_select => ['value' => 'without-image-left']],
],
];
// Show link and link design only if design needs them.
$link_states = [
'visible' => [
[$design_select => ['value' => 'background-image']],
],
];
$element['subform']['field_hero_link']['#states'] = $link_states;
$element['subform']['field_hero_link_design']['#states'] = $link_states;
$fields = [
'field_hero_desc',
'field_hero_image',
'field_hero_link',
'field_hero_link_design',
];
// Set types if they're missing to prevent undefined index error in
// /core/lib/Drupal/Core/Form/FormHelper.php:211.
foreach ($fields as $field) {
if (!isset($element['subform'][$field]['#type'])) {
$element['subform'][$field]['#type'] = '';
}
}
}
// Perform alterations to Columns paragraph.
if ($element['#paragraph_type'] == 'columns') {
// Attach columns toggle JS when necessary.
$element['#attached']['library'][] = 'hdbt_admin_tools/columns-toggle';
}
// Perform alterations to Banner paragraph.
if ($element['#paragraph_type'] == 'banner') {
// Banner design selection.
$design_select = ':input[name="field_content[' . $element['#delta'] . '][subform][field_banner_design][0]"]';
// Show icon only if design needs it.
$element['subform']['field_icon']['#states'] = [
'visible' => [
[$design_select => ['value' => 'align-left']],
'or',
[$design_select => ['value' => 'align-left-secondary']],
],
];
}
}
/**
* Implements hook_form_FORM_ID_alter().
*
* Add a title, design and target fields to EditorLinkDialog.
*/
function hdbt_admin_tools_form_editor_link_dialog_alter(&$form, FormStateInterface $form_state) {
if (isset($form_state->getUserInput()['editor_object'])) {
$input = $form_state->getUserInput()['editor_object'];
$form_state->set('link_element', $input);
$form_state->setCached(TRUE);
}
else {
// Retrieve the link element's attributes from form state.
$input = $form_state->get('link_element') ?: [];
}
// Helper function to retrieve form field default values.
$get_default_value = function ($attribute_name, $fallback = '') use ($input) {
return !empty($input[$attribute_name]) ? $input[$attribute_name] : $fallback;
};
$form['#attached']['library'][] = 'hdbt_admin_tools/modal_window_position';
$form['#attached']['library'][] = 'hdbt_admin_tools/link_plugin_enhancements';
$form['attributes']['data-link-text'] = [
'#type' => 'textfield',
'#title' => t('Link text'),
'#default_value' => $get_default_value('data-link-text'),
'#maxlength' => 512,
];
$form['attributes']['data-protocol'] = [
'#type' => 'select',
'#title' => t('Protocol'),
'#default_value' => $get_default_value('data-protocol'),
'#options' => [
'false' => t('Select'),
'https://' => t('https://'),
'http://' => t('http://'),
'tel:' => t('tel:'),
'mailto:' => t('mailto:'),
],
'#weight' => -100,
];
$form['attributes']['data-design'] = [
'#type' => 'select',
'#title' => t('Design'),
'#default_value' => $get_default_value('data-design'),
'#options' => [
'link' => t('Default'),
'hds-button hds-button--primary' => t('Button primary'),
'hds-button hds-button--secondary' => t('Button secondary'),
'hds-button hds-button--supplementary' => t('Button supplementary'),
],
'#weight' => 1,
];
$form['attributes']['data-selected-icon'] = [
'#title' => t('Icon'),
'#theme' => 'select_icon_widget',
'#type' => 'select_icon_element',
'#default_value' => $get_default_value('data-selected-icon', NULL),
'#options' => SelectIcon::loadIcons(),
'#weight' => 2,
'#attributes' => [
'class' => [
'link-plugin-select-design',
],
],
];
$form['attributes']['target'] = [
'#title' => t('Open in new window/tab'),
'#type' => 'checkbox',
'#default_value' => $get_default_value('target', FALSE),
'#return_value' => '_blank',
'#weight' => 3,
];
$form['attributes']['target_check'] = [
'#title' => t('The link meets the accessibility requirements'),
'#description' => t('I have made sure that the description of this link clearly states that it will open in a new tab. <a href="@wcag-techniques" target="_blank">See WCAG 3.2.5 accessibility requirement (the link opens in a new tab).</a>', [
'@wcag-techniques' => 'https://www.w3.org/WAI/WCAG21/Techniques/general/G200.html',
]),
'#type' => 'checkbox',
'#default_value' => $get_default_value('target', FALSE) === '_blank',
'#weight' => 3,
'#states' => [
'visible' => [
':input[name="attributes[target]"]' => ['checked' => TRUE],
],
'required' => [
':input[name="attributes[target]"]' => ['checked' => TRUE],
],
],
];
$form['advanced'] = [
'#type' => 'details',
'#title' => t('Advanced settings'),
'#weight' => 4,
];
$form['attributes']['title'] = [
'#type' => 'textfield',
'#title' => t('Title'),
'#description' => t(
'Populates the title attribute of the link, usually shown as a small tooltip on hover.'
),
'#default_value' => '',
'#maxlength' => 512,
'#group' => 'advanced',
];
$form['attributes']['id'] = [
'#type' => 'textfield',
'#title' => t('ID'),
'#description' => t(
'Allows linking to this content using a URL fragment (#). Must be unique.'
),
'#default_value' => $get_default_value('id'),
'#maxlength' => 512,
'#group' => 'advanced',
];
// Add validation callback for empty attributes.
array_unshift(
$form['#validate'],
'_hdbt_admin_tools_attributes_validate'
);
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function hdbt_admin_tools_form_linkit_editor_dialog_form_alter(&$form, FormStateInterface $form_state) {
hdbt_admin_tools_form_editor_link_dialog_alter($form, $form_state);
}
/**
* Validation for link attributes.
*
* String "true" / "false" values are handled in javascript.
* See: ./modules/hdbt_admin_tools/assets/js/plugins/hds-button/plugin.js.
*/
function _hdbt_admin_tools_attributes_validate(array &$form, FormStateInterface $form_state) {
$attributes = $form_state->getValue('attributes');
/** @var \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler */
$moduleHandler = Drupal::service('module_handler');
// Let other modules alter the CKEditor link dialog form validation.
$moduleHandler->alter('helfi_form_editor_link_dialog', $form, $form_state);
// Allow icons only for the links with button design.
if (isset($attributes['data-selected-icon'])) {
if ($attributes['data-design'] === 'link' || empty($attributes['data-selected-icon'])) {
$form_state->unsetValue(['attributes', 'data-selected-icon']);
}
}
// Remove empty values to prevent rendering them in markup.
foreach (['target', 'target_check', 'title'] as $attribute) {
if (isset($attributes[$attribute]) && empty($attributes[$attribute])) {
$form_state->setValue(['attributes', $attribute], FALSE);
}
}
// If the accessibility consent is not accepted,
// uncheck the open in new window / tab checkbox.
if ($attributes['target'] && !$attributes['target_check']) {
$form_state->setValue(['attributes', 'target'], FALSE);
}
// Check if user has input value to href attribute.
if (array_key_exists('href', $attributes) && !empty($attributes['href'])) {
// Get Url object based on the href attribute.
$url = UrlHelper::parse($attributes['href']);
// Check if current link is external (not whitelisted) and
// set data attributes accordingly.
/** @var \Drupal\helfi_api_base\Link\InternalDomainResolver $resolver */
$resolver = \Drupal::service('helfi_api_base.internal_domain_resolver');
$is_external = $resolver->isExternal($url);
// Set form value is-external based on domain resolver.
$form_state->setValue(['attributes', 'data-is-external'], $is_external ? 'true' : 'false');
// Parse URL scheme from the href attribute and set it as data variable.
$scheme = parse_url(($is_external) ? $url->getUri() : $attributes['href'], PHP_URL_SCHEME);
// Check for tel-link.
$scheme = (empty($scheme) && str_contains($attributes['href'], 'tel:')) ? 'tel' : $scheme;
// Construct a protocol value for external links if user has not selected
// any value for the protocol.
if ($is_external && empty($scheme) && $attributes['data-protocol'] === 'false') {
$scheme = ($scheme === 'https' || $scheme === 'http') ? $scheme . '://' : $scheme;
}
// Set scheme to data-protocol attribute.
$form_state->setValue(['attributes', 'data-protocol'], !(empty($scheme)) ? $scheme : 'false');
}
}
/**
* Implements hook_preprocess_HOOK().
*
* Set paragraph information as data-attributes for the paragraph dropbutton.
*/
function hdbt_admin_tools_preprocess_links__dropbutton__operations__paragraphs(&$variables) {
$buttons = &$variables['links'];
if ($buttons && is_array($buttons)) {
// Attach paragraph selection library.
$variables['attributes']['class'][] = 'select-paragraph';
// Get paragraph types.
$paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraphs_type');
$paragraph_types = $paragraph_storage->loadMultiple();
// Go through buttons and set the necessary data-attributes.
$paragraph_images = [];
foreach ($buttons as $button) {
/** @var \Drupal\paragraphs\Entity\ParagraphsType $bundle */
$bundle = $paragraph_types[$button['text']['#bundle_machine_name']];
$paragraph_images[] = str_replace('_', '-', $bundle->get('id'));
}
// Set images for the paragraph preview tool.
$design_selection_manager = \Drupal::service('hdbt_admin_tools.design_selection_manager');
$variables['#attached']['drupalSettings']['selectParagraph']['images'] = $design_selection_manager->getImages('paragraph', $paragraph_images);
$variables['#attached']['library'][] = 'hdbt_admin_tools/select_paragraph';
// Go through buttons and set the necessary data-attributes.
foreach ($buttons as &$button) {
/** @var \Drupal\paragraphs\Entity\ParagraphsType $bundle */
$bundle = $paragraph_types[$button['text']['#bundle_machine_name']];
$image = str_replace('_', '-', $bundle->get('id'));
$button['attributes']->setAttribute('data-paragraph-title', $bundle->get('label'));
$button['attributes']->setAttribute('data-paragraph-description', $bundle->get('description'));
$button['attributes']->setAttribute('data-paragraph-image', $image);
// Fix the translation when paragraph type names are being rendered.
$button['text']['#value'] = t('@type', ['@type' => $bundle->get('label')]);
}
}
}
/**
* Implements hook_form_alter().
*/
function hdbt_admin_tools_form_alter(&$form, $form_state) {
// Handle only admin routes.
if (!\Drupal::service('router.admin_context')->isAdminRoute()) {
return;
}
// Perform alterations for Drupal core and contrib module field titles,
// descriptions and field visibility based on customer needs.
if ($form_state->getFormObject() instanceof EntityForm) {
// Alter revision log title based on customer needs.
if (isset($form['revision_log'])) {
$form['revision_log']['widget'][0]['value']['#title'] = t('Version notes', [], ['context' => 'HDBT Admin tools']);
}
// Alter metatags based on customer needs.
if (isset($form['field_metatags'])) {
$field_metatags = &$form['field_metatags']['widget'][0];
// Remove basic tags description.
unset($form['field_metatags']['widget'][0]['basic']['#description']);
// Alter the preamble and intro text markup.
$field_metatags['preamble']['#markup'] = '<p><strong>' . t('Editing metadata', [], ['context' => 'HDBT Admin tools']) . '</strong></p>';
$field_metatags['intro_text']['#markup'] = '<p>' . t('Can be left unchanged. Tokens can be used to set metadata.', [], ['context' => 'HDBT Admin tools']) . '</p>';
// Alter basic tags title field descriptions.
$field_metatags['basic']['title']['#title'] = t('Title', [], ['context' => 'HDBT Admin tools']);
$field_metatags['basic']['title']['#description'] = t('Page title is visible in search results and browser tab heading. The title is set automatically and does not need to be set here. Recommended max. length: 55–65 characters.', [], ['context' => 'HDBT Admin tools']);
// Alter basic tags description field title and descriptions.
$field_metatags['basic']['description']['#title'] = t('Description for search engines', [], ['context' => 'HDBT Admin tools']);
$field_metatags['basic']['description']['#description'] = t('A succinct description of the page content. Max. 160 characters. May be visible in search results. The description is fetched from the Lead-field and does not need to be set here.', [], ['context' => 'HDBT Admin tools']);
}
// Alter liftup image help texts and descriptions based on customer needs.
if (isset($form['field_liftup_image'])) {
$field_liftup_image = &$form['field_liftup_image']['widget'];
$field_liftup_image['open_button']['#value'] = t('Add image', [], ['context' => 'HDBT Admin tools']);
if (isset($field_liftup_image['#field_prefix']['empty_selection'])) {
$field_liftup_image['#field_prefix']['empty_selection'] = [
'#markup' => t('Image is not selected.', [], ['context' => 'HDBT Admin tools']),
];
}
}
// Alter publish on and unpublish on titles based on customer needs.
if (isset($form['publish_on']) && isset($form['unpublish_on'])) {
$form['publish_on']['widget'][0]['value']['#title'] = t('Release time', [], ['context' => 'HDBT Admin tools']);
$form['unpublish_on']['widget'][0]['value']['#title'] = t('Hiding the page', [], ['context' => 'HDBT Admin tools']);
}
}
}
/**
* Implements hook_form_FORM_ID_alter().
*/
function hdbt_admin_tools_form_openid_connect_login_form_alter(&$form, $form_state) {
// Alter the login form submit button texts for Tunnistamo login.
$text = t('Login with Tunnistamo', [], ['context' => 'HDBT Admin tools']);
$form['openid_connect_client_tunnistamo_login']['#value'] = $text;
}
/**
* Implements hook_entity_base_field_info().
*/
function hdbt_admin_tools_entity_base_field_info(EntityTypeInterface $entity_type): array {
$fields = [];
// Entity types to be updated.
$entity_types = [
'node',
'tpr_unit',
'tpr_service',
];
// Add color palette field to each entity type.
if (in_array($entity_type->id(), $entity_types)) {
$fields['color_palette'] = BaseFieldDefinition::create('list_string')
->setRequired(FALSE)
->setTranslatable(FALSE)
->setLabel(t('Color palette'))
->setSettings([
'allowed_values_function' => 'Drupal\hdbt_admin_tools\Form\SiteSettings::getColorPalettes',
])
->setDisplayOptions('form', [
'type' => 'color_palette_field_widget',
'weight' => 0,
]);
$fields['hide_sidebar_navigation'] = BaseFieldDefinition::create('boolean')
->setRequired(FALSE)
->setTranslatable(FALSE)
->setLabel(t('Hide sidebar navigation from this page'))
->setDefaultValue(FALSE)
->setRevisionable(TRUE)
->setDisplayConfigurable('form', TRUE);
}
return $fields;
}
/**
* Implements hook_entity_presave().
*/
function hdbt_admin_tools_entity_presave($entity): void {
if (