-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoe_contact_forms.module
1068 lines (975 loc) · 38.4 KB
/
oe_contact_forms.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
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
* OpenEuropa Contact Forms module.
*/
declare(strict_types=1);
use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Entity\Element\EntityAutocomplete;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\contact\ContactFormInterface;
use Drupal\contact\Entity\ContactForm;
use Drupal\contact\Entity\Message;
/**
* Implements hook_form_FORM_ID_alter() for contact_storage_export().
*/
function oe_contact_forms_form_contact_storage_export_alter(&$form, FormStateInterface $form_state) {
// Remove ip_address to be GDPR compliant.
unset($form['advanced']['columns']['#options']['ip_address']);
}
/**
* Implements hook_form_FORM_ID_alter() for contact_form_form().
*/
function oe_contact_forms_form_contact_form_form_alter(&$form, FormStateInterface $form_state) {
/** @var \Drupal\contact\ContactFormEditForm $form_object */
$form_object = $form_state->getFormObject();
if (!in_array($operation = $form_object->getOperation(), ['edit', 'add'], TRUE)) {
// Only alter the edit and add forms.
return;
}
/** @var \Drupal\contact\ContactFormInterface $contact_form */
$contact_form = $form_object->getEntity();
$is_corporate_form = (boolean) ($form_state->getValue('is_corporate_form') ?? $contact_form->getThirdPartySetting('oe_contact_forms', 'is_corporate_form', FALSE));
$triggered_element = $form_state->getTriggeringElement();
if (!empty($triggered_element['#submit'])) {
$is_corporate_form = TRUE;
}
// Remove disable message as it's not used in corporate contact forms.
$form['contact_storage_disabled_form_message']['#states'] = [
'visible' => [
':input[name="is_corporate_form"]' => ['checked' => FALSE],
],
];
// Adding checkbox with ajax callback that manages additional fields.
$form['is_corporate_form'] = [
'#type' => 'checkbox',
'#title' => t('Is corporate form'),
'#description' => t("Check this box if you'd like to make this a corporate form."),
'#default_value' => $is_corporate_form,
'#ajax' => [
'callback' => '_oe_contact_forms_is_corporate_form_ajax_callback',
'wrapper' => 'corporate-fields-wrapper',
],
];
$form['corporate_fields'] = [
'#type' => 'container',
'#attributes' => [
'id' => ['corporate-fields-wrapper'],
],
];
if ($is_corporate_form) {
$form['corporate_fields']['topics_fieldset'] = [
'#type' => 'fieldset',
'#title' => t('Topics'),
'#prefix' => '<div id="topics-fieldset-wrapper">',
'#suffix' => '</div>',
'#description' => t("Please select the topics and the associated email addresses the users can choose when submitting the form. For multiple email addresses, please separate them with a comma."),
];
$topics = $contact_form->getThirdPartySetting('oe_contact_forms', 'topics', []);
$num_topics = $form_state->get('num_topics');
$n = count($topics);
$topics_limit_validation_errors = [];
// No values added yet.
if ($num_topics === NULL && $n === 0) {
$num_topics = 1;
}
// Any saved values.
if ($num_topics === NULL && $n > 0) {
$num_topics = $n;
}
$form_state->set('num_topics', $num_topics);
for ($i = 0; $i < $num_topics; $i++) {
if (isset($topics[$i])) {
$topic_name = $topics[$i]['topic_name'];
$topic_email_address = $topics[$i]['topic_email_address'];
}
$topics_limit_validation_errors[] = [
'corporate_fields',
'topics_fieldset',
'group',
$i,
'topic_name',
];
$topics_limit_validation_errors[] = [
'corporate_fields',
'topics_fieldset',
'group',
$i,
'topic_email_address',
];
$form['corporate_fields']['topics_fieldset']['group'][$i]['topic_name'] = [
'#type' => 'textfield',
'#title' => t('Topic name'),
'#required' => TRUE,
'#default_value' => $topic_name ?? '',
];
$form['corporate_fields']['topics_fieldset']['group'][$i]['topic_email_address'] = [
'#type' => 'textfield',
'#title' => t('Topic email address(es)'),
'#required' => TRUE,
'#default_value' => $topic_email_address ?? '',
];
}
$form['corporate_fields']['topics_fieldset']['actions'] = [
'#type' => 'actions',
];
$form['corporate_fields']['topics_fieldset']['actions']['add_topic'] = [
'#type' => 'submit',
'#value' => t('Add topic'),
'#submit' => ['_oe_contact_forms_add_one_callback'],
'#ajax' => [
'callback' => '_oe_contact_forms_add_more_callback',
'wrapper' => 'topics-fieldset-wrapper',
],
'#limit_validation_errors' => $topics_limit_validation_errors,
];
$form['corporate_fields']['topics_fieldset']['actions']['remove_topic'] = [
'#type' => 'submit',
'#value' => t('Remove topic'),
'#submit' => ['_oe_contact_forms_remove_callback'],
'#ajax' => [
'callback' => '_oe_contact_forms_add_more_callback',
'wrapper' => 'topics-fieldset-wrapper',
],
'#limit_validation_errors' => [],
];
$form['corporate_fields']['topic_label'] = [
'#type' => 'textfield',
'#title' => t('Topic label'),
'#description' => t("Please specify the label for the Topics field. Leave empty for the default: 'Topic'."),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'topic_label', ''),
];
$form['corporate_fields']['email_subject'] = [
'#type' => 'textfield',
'#title' => t('Email subject'),
'#required' => TRUE,
'#description' => t("Please specify the subject of the email."),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'email_subject', ''),
];
$form['corporate_fields']['header'] = [
'#type' => 'textarea',
'#title' => t('Header'),
'#description' => t("Please specify the text to be displayed above the contact form for users that submit it."),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'header', ''),
];
$form['corporate_fields']['privacy_policy'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'node',
'#attributes' => ['data-autocomplete-first-character-blacklist' => '/#?'],
'#title' => t('Privacy policy link'),
'#required' => TRUE,
'#description' => t("Link to form privacy policy/data protection page."),
'#element_validate' => [
[
'\Drupal\link\Plugin\Field\FieldWidget\LinkWidget',
'validateUriElement',
],
],
'#maxlength' => 2048,
'#process_default_value' => FALSE,
'#default_value' => _oe_contact_forms_get_privacy_default($contact_form->getThirdPartySetting('oe_contact_forms', 'privacy_policy', '')),
];
$form['corporate_fields']['includes_fields_in_messages'] = [
'#type' => 'checkbox',
'#title' => t('Includes fields in email message and auto-reply'),
'#description' => t('Check this box if you would like to include in the message and in the auto-reply the values submitted by the user.'),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'includes_fields_in_messages', FALSE),
];
$form['corporate_fields']['allow_canonical_url'] = [
'#type' => 'checkbox',
'#title' => t('Allow canonical URL'),
'#description' => t("Check this box if you would like this contact form to be exposed at its default canonical URL."),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'allow_canonical_url', FALSE),
];
$form['corporate_fields']['expose_as_block'] = [
'#type' => 'checkbox',
'#title' => t('Expose as block'),
'#description' => t("Check this box if you would like to expose this contact form as a block."),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'expose_as_block', TRUE),
];
$form['corporate_fields']['alternative_name'] = [
'#type' => 'checkbox',
'#title' => t('Use First name and Last name for the form'),
'#description' => t('Check this box if you would like to have separate First and Last name fields.'),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'alternative_name', FALSE),
];
$form['corporate_fields']['optional_fields'] = [
'#type' => 'checkboxes',
'#title' => t('Optional fields'),
'#options' => [
'oe_country_residence' => t('Country of residence'),
'oe_preferred_language' => t('Preferred contact language'),
'oe_alternative_language' => t('Alternative contact language'),
'oe_telephone' => t('Phone'),
],
'#description' => t("Please specify which optional fields you'd like to include in the form."),
'#default_value' => $contact_form->getThirdPartySetting('oe_contact_forms', 'optional_fields', []),
];
$form['corporate_fields']['override_languages'] = [
'#type' => 'details',
'#title' => t('Override languages'),
'#states' => [
'invisible' => [
':input[name="corporate_fields[optional_fields][oe_preferred_language]"]' => ['checked' => FALSE],
],
],
];
$skos_concept_storage = \Drupal::entityTypeManager()->getStorage('skos_concept');
$default_language_values = array_values($skos_concept_storage->loadMultiple(_oe_contact_forms_contact_language_values()));
$override_languages_settings = $contact_form->getThirdPartySetting('oe_contact_forms', 'override_languages', []);
$form['corporate_fields']['override_languages']['oe_preferred_language_options'] = [
'#type' => 'multivalue',
'#title' => t('Preferred contact language options'),
'target' => [
'#type' => 'entity_autocomplete',
'#target_type' => 'skos_concept',
'#selection_handler' => 'default:skos_concept',
'#selection_settings' => [
'concept_schemes' => [
'http://publications.europa.eu/resource/authority/language',
],
],
],
'#default_value' => empty($override_languages_settings['oe_preferred_language_options']) ? $default_language_values : array_values($skos_concept_storage->loadMultiple($override_languages_settings['oe_preferred_language_options'])),
];
$form['corporate_fields']['override_languages']['oe_alternative_language_options'] = [
'#type' => 'multivalue',
'#title' => t('Alternative contact language options'),
'target' => [
'#type' => 'entity_autocomplete',
'#target_type' => 'skos_concept',
'#selection_handler' => 'default:skos_concept',
'#selection_settings' => [
'concept_schemes' => [
'http://publications.europa.eu/resource/authority/language',
],
],
],
'#states' => [
'visible' => [
':input[name="corporate_fields[optional_fields][oe_alternative_language]"]' => ['checked' => TRUE],
],
],
'#default_value' => empty($override_languages_settings['oe_alternative_language_options']) ? $default_language_values : array_values($skos_concept_storage->loadMultiple($override_languages_settings['oe_alternative_language_options'])),
];
// To not flatten the data in $form_state.
$form['#tree'] = TRUE;
$form['#validate'][] = '_oe_contact_forms_email_validate';
}
$form['#attached']['library'][] = 'oe_contact_forms/related_checkboxes';
$form['#entity_builders'][] = '_oe_contact_forms_contact_form_builder';
}
/**
* Gets the URI without the 'internal:' or 'entity:' scheme.
*
* The following two forms of URIs are transformed:
* - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings;
* - 'internal:' URIs: the scheme is stripped.
*
* It's sad that LinkWidget::getUriAsDisplayableString() is a protected method,
* and we can't benefit from its implementation.
*
* @param string $uri
* The URI to get the displayable string for.
*
* @return string
* The URI without the 'internal:' or 'entity:' scheme
*
* @see \Drupal\link\Plugin\Field\FieldWidget\LinkWidget::getUriAsDisplayableString()
*/
function _oe_contact_forms_get_privacy_default(string $uri): string {
$scheme = parse_url($uri, PHP_URL_SCHEME);
// By default, the displayable string is the URI.
$displayable_string = $uri;
// A different displayable string may be chosen in case of the 'internal:'
// or 'entity:' built-in schemes.
if ($scheme === 'internal') {
$uri_reference = explode(':', $uri, 2)[1];
// @todo '<front>' is valid input for BC reasons, may be removed by
// https://www.drupal.org/node/2421941
$path = parse_url($uri, PHP_URL_PATH);
if ($path === '/') {
$uri_reference = '<front>' . substr($uri_reference, 1);
}
$displayable_string = $uri_reference;
}
elseif ($scheme === 'entity') {
[$entity_type, $entity_id] = explode('/', substr($uri, 7), 2);
// Show the 'entity:' URI as the entity autocomplete would.
// @todo Support entity types other than 'node'. Will be fixed in
// https://www.drupal.org/node/2423093.
if ($entity_type == 'node' && $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id)) {
$displayable_string = EntityAutocomplete::getEntityLabels([$entity]);
}
}
elseif ($scheme === 'route') {
$displayable_string = ltrim($displayable_string, 'route:');
}
return $displayable_string;
}
/**
* Clear block cached definitions.
*/
function _oe_contact_forms_clear_block_cached_definitions(): void {
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function oe_contact_forms_contact_form_presave(EntityInterface $entity) {
_oe_contact_forms_clear_block_cached_definitions();
// Invalidate form display cache tags if config is changed,
// since the EntityFormDisplay is not in storage we compose the tag.
Cache::invalidateTags(['config:core.entity_form_display.contact_message.' . $entity->id() . '.corporate_default']);
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function oe_contact_forms_contact_form_delete(EntityInterface $entity) {
_oe_contact_forms_clear_block_cached_definitions();
}
/**
* Default ajax callback for Topics.
*
* @param array $form
* The form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* Topics fieldset.
*/
function _oe_contact_forms_add_more_callback(array &$form, FormStateInterface $form_state): array {
return $form['corporate_fields']['topics_fieldset'];
}
/**
* Add element to the form based on ajax.
*
* @param array $form
* The form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
function _oe_contact_forms_add_one_callback(array &$form, FormStateInterface $form_state): void {
$num_topics = $form_state->get('num_topics');
$num_topics++;
$form_state->set('num_topics', $num_topics);
$form_state->setRebuild();
}
/**
* Remove element from the form based on ajax.
*
* @param array $form
* The form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
function _oe_contact_forms_remove_callback(array &$form, FormStateInterface $form_state): void {
$num_topics = $form_state->get('num_topics');
if ($num_topics > 1) {
$num_topics--;
}
$form_state->set('num_topics', $num_topics);
$form_state->setRebuild();
}
/**
* Ajax callback: Return markup for 'corporate_fields'.
*
* According 'is_corporate_form' value.
*
* @param array $form
* The form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* Corporate fields.
*/
function _oe_contact_forms_is_corporate_form_ajax_callback(array &$form, FormStateInterface $form_state): array {
return $form['corporate_fields'];
}
/**
* Entity builder for the contact form edit form with third party options.
*
* @param string $entity_type
* The contact form entity.
* @param \Drupal\contact\ContactFormInterface $contact_form
* The contact form entity.
* @param array $form
* The form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
function _oe_contact_forms_contact_form_builder($entity_type, ContactFormInterface $contact_form, array &$form, FormStateInterface $form_state): void {
// When ajax is triggered the form is rebuilt with empty recipients,
// causing invalid arguments in Drupal\contact\ContactFormEditForm::form()L96.
$recipients = $contact_form->getRecipients();
if (!is_array($recipients)) {
$contact_form->setRecipients((array) $recipients);
}
$is_corporate_form = (boolean) $form_state->getValue('is_corporate_form');
$values = $form_state->getValue('corporate_fields');
$triggered_element = $form_state->getTriggeringElement();
if (!empty($triggered_element['#submit']) && in_array('_oe_contact_forms_add_one_callback', $triggered_element['#submit'])) {
$is_corporate_form = FALSE;
}
// Multivalue field isn't processed fully in ajax request, so exit if
// 'Remove topic' or 'Add another item' buttons has been clicked to prevent
// saving wrong values.
if (in_array($triggered_element['#name'], [
'corporate_fields_override_languages_oe_preferred_language_options_add_more',
'corporate_fields_override_languages_oe_alternative_language_options_add_more',
])) {
return;
}
if (!empty($triggered_element['#parents'][3]) && $triggered_element['#parents'][3] === 'remove_topic') {
return;
}
$contact_form->setThirdPartySetting('oe_contact_forms', 'is_corporate_form', $is_corporate_form);
if ($is_corporate_form && !empty($values)) {
if (empty($values['optional_fields']['oe_preferred_language'])) {
// Uncheck alternative language if preferred language is unchecked.
$values['optional_fields']['oe_alternative_language'] = 0;
}
$values['override_languages']['oe_preferred_language_options'] = _oe_contact_forms_prepare_language_option_values($values, 'oe_preferred_language', 'oe_preferred_language_options');
$values['override_languages']['oe_alternative_language_options'] = _oe_contact_forms_prepare_language_option_values($values, 'oe_alternative_language', 'oe_alternative_language_options');
$contact_form->setThirdPartySetting('oe_contact_forms', 'topic_label', $values['topic_label']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'email_subject', $values['email_subject']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'header', $values['header']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'privacy_policy', $values['privacy_policy']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'includes_fields_in_messages', $values['includes_fields_in_messages']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'allow_canonical_url', $values['allow_canonical_url']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'expose_as_block', $values['expose_as_block']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'optional_fields', $values['optional_fields']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'override_languages', $values['override_languages']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'topics', $values['topics_fieldset']['group']);
$contact_form->setThirdPartySetting('oe_contact_forms', 'alternative_name', $values['alternative_name']);
}
else {
$fields = [
'topic_label',
'email_subject',
'header',
'privacy_policy',
'includes_fields_in_messages',
'allow_canonical_url',
'expose_as_block',
'optional_fields',
'override_languages',
'topics',
'alternative_name',
];
foreach ($fields as $field) {
$contact_form->unsetThirdPartySetting('oe_contact_forms', $field);
}
}
}
/**
* Prepares contact language options.
*
* @param array $values
* Form values.
* @param string $field
* Name of contact language field.
* @param string $field_options
* Name of contact language options field.
*
* @return array
* List of languages to save.
*/
function _oe_contact_forms_prepare_language_option_values(array $values, string $field, string $field_options): array {
// Save language options if contact language is used and they are overridden.
if (empty($values['optional_fields'][$field])) {
return [];
}
$language_values = array_column($values['override_languages'][$field_options], 'target');
$language_values = array_unique($language_values);
if ($language_values === _oe_contact_forms_contact_language_values()) {
return [];
}
return $language_values;
}
/**
* Validate topics email addresses if set.
*
* @param array $form
* The form.
* @param Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*/
function _oe_contact_forms_email_validate(array &$form, FormStateInterface $form_state): void {
$values = $form_state->getValue('corporate_fields');
$topics_fieldset = &$values['topics_fieldset'];
$email_validator = \Drupal::service('email.validator');
foreach ($topics_fieldset['group'] as $delta => &$topic) {
if (empty($topic['topic_email_address'])) {
continue;
}
// Validate each email separately.
$recipients = explode(',', $topic['topic_email_address']);
foreach ($recipients as $key => &$recipient) {
$recipient = trim($recipient);
if (!$email_validator->isValid($recipient)) {
$form_state->setErrorByName("corporate_fields][topics_fieldset][group][$delta][topic_email_address", t('%recipient is an invalid email address.', ['%recipient' => $recipient]));
}
}
$topic['topic_email_address'] = implode(',', $recipients);
}
// Set trimmed values.
$form_state->setValue('corporate_fields', $values);
}
/**
* Implements hook_form_FORM_ID_alter() for contact_message_form().
*/
function oe_contact_forms_form_contact_message_form_alter(&$form, FormStateInterface $form_state, $form_id) {
/** @var \Drupal\Core\Entity\ContentEntityForm $form_object */
$form_object = $form_state->getFormObject();
/** @var \Drupal\contact\MessageInterface $contact_message */
$contact_message = $form_object->getEntity();
/** @var \Drupal\contact\Entity\ContactForm $contact_form */
$contact_form = ContactForm::load($contact_message->bundle());
// We only want corporate fields on corporate forms.
if (!$contact_form->getThirdPartySetting('oe_contact_forms', 'is_corporate_form', FALSE)) {
$fields = [
'oe_country_residence',
'oe_telephone',
'oe_topic',
'oe_preferred_language',
'oe_alternative_language',
'oe_first_name',
'oe_last_name',
];
foreach ($fields as $field) {
if (!isset($form[$field])) {
continue;
}
$form[$field]['#access'] = FALSE;
}
}
elseif (strpos($form_id, 'corporate_default') !== FALSE) {
// Set proper order and options for contact language fields for the new
// submission of the contact form.
$optional_selected = $contact_form->getThirdPartySetting('oe_contact_forms', 'optional_fields', []);
$override_languages = $contact_form->getThirdPartySetting('oe_contact_forms', 'override_languages', []);
foreach (['oe_preferred_language', 'oe_alternative_language'] as $field_name) {
if (in_array($field_name, $optional_selected)) {
$language_options = $override_languages[$field_name . '_options'] ?: _oe_contact_forms_contact_language_values();
_oe_contact_forms_build_select_language_field($form, $field_name, $language_options);
}
}
if (in_array('oe_preferred_language', $optional_selected)) {
// Preferred language is required if shown.
$form['oe_preferred_language']['widget'][0]['target_id']['#required'] = TRUE;
}
}
}
/**
* Builds select box with options from configuration.
*
* Since there are 8000+ items in language vocabulary we can't use
* skos_concept_entity_reference_options_select as is. So build select box
* using provided options.
*
* @param array $form
* Contact message form.
* @param string $field
* Field name.
* @param array $settings
* Configuration.
*/
function _oe_contact_forms_build_select_language_field(array &$form, string $field, array $settings): void {
$options = [];
$entities = \Drupal::entityTypeManager()->getStorage('skos_concept')->loadMultiple($settings);
$entity_repository = \Drupal::service('entity.repository');
foreach ($entities as $id => $entity) {
$entity = $entity_repository->getTranslationFromContext($entity);
$options[$id] = $entity->label();
}
$widget = &$form[$field]['widget'][0]['target_id'];
$widget['#type'] = 'select';
$widget['#options'] = $options;
$widget['#empty_option'] = t('Select');
$widget['#empty_value'] = '';
unset($widget['#selection_settings']);
unset($widget['#size']);
}
/**
* Implements hook_entity_base_field_info().
*/
function oe_contact_forms_entity_base_field_info(EntityTypeInterface $entity_type) {
if ($entity_type->id() == 'contact_message') {
$fields = [];
$fields['oe_first_name'] = BaseFieldDefinition::create('string')
->setLabel(t('First name'))
->setRequired(TRUE)
->setDisplayOptions('form', [
'type' => 'string_textfield',
])
->setDisplayOptions('view', [
'weight' => 0,
]);
$fields['oe_last_name'] = BaseFieldDefinition::create('string')
->setLabel(t('Last name'))
->setRequired(TRUE)
->setDisplayOptions('form', [
'type' => 'string_textfield',
])
->setDisplayOptions('view', [
'weight' => 0,
]);
$fields['oe_country_residence'] = BaseFieldDefinition::create('skos_concept_entity_reference')
->setLabel(t('Country of residence'))
->setSetting('target_type', 'skos_concept')
->setSetting('handler', 'default:skos_concept')
->setSetting('handler_settings', [
'target_bundles' => NULL,
'auto_create' => FALSE,
'concept_schemes' => [
'http://publications.europa.eu/resource/authority/country',
],
'concept_subset' => 'non_deprecated_countries',
])
->setDisplayOptions('form', [
'type' => 'skos_concept_entity_reference_options_select',
'settings' => [
'sort' => 'label',
],
])
->setDisplayOptions('view', [
'weight' => 0,
'settings' => [
'link' => FALSE,
],
]);
$fields['oe_preferred_language'] = oe_contact_forms_create_language_base_field(t('Preferred contact language'));
$fields['oe_alternative_language'] = oe_contact_forms_create_language_base_field(t('Alternative contact language'));
$fields['oe_telephone'] = BaseFieldDefinition::create('telephone')
->setLabel(t('Phone'))
->setSettings([
'default_value' => '',
'max_length' => 255,
])
->setDisplayOptions('form', [
'type' => 'telephone_default',
])
->setDisplayOptions('view', [
'weight' => 0,
]);
$fields['oe_topic'] = BaseFieldDefinition::create('list_string')
->setLabel(t('Topic'))
->setDisplayOptions('form', [
'type' => 'options_select',
])
->setDisplayOptions('view', [
'weight' => 0,
])
->setSetting('allowed_values_function', '_oe_contact_forms_topic_values')
->setRequired(TRUE);
return $fields;
}
}
/**
* Creates language base fields.
*
* @param \Drupal\Component\Render\MarkupInterface $title
* Field label.
*
* @return \Drupal\Core\Field\BaseFieldDefinition
* Base field definition.
*/
function oe_contact_forms_create_language_base_field(MarkupInterface $title): BaseFieldDefinition {
return BaseFieldDefinition::create('skos_concept_entity_reference')
->setLabel($title)
->setSetting('target_type', 'skos_concept')
->setSetting('handler', 'default:skos_concept')
->setSetting('handler_settings', [
'target_bundles' => NULL,
'auto_create' => FALSE,
'concept_schemes' => [
'http://publications.europa.eu/resource/authority/language',
],
])
->setDisplayOptions('form', [
'type' => 'skos_concept_entity_reference_autocomplete',
])
->setDisplayOptions('view', [
'weight' => 0,
'settings' => [
'link' => FALSE,
],
]);
}
/**
* Set dynamic allowed values for the topic field.
*
* @param \Drupal\Core\Field\BaseFieldDefinition $definition
* The base field definition.
* @param \Drupal\contact\Entity\Message|null $entity
* The entity being created if applicable.
* @param bool $cacheable
* Boolean indicating if the results are cacheable.
*
* @return array
* An array of possible key and value options.
*
* @see options_allowed_values()
*/
function _oe_contact_forms_topic_values(BaseFieldDefinition $definition, ?Message $entity = NULL, &$cacheable = TRUE): array {
/** @var \Drupal\contact\ContactFormInterface $contact_form */
$contact_form = $entity->getContactForm();
$topics = $contact_form->getThirdPartySetting('oe_contact_forms', 'topics', []);
$options = [];
foreach ($topics as $topic) {
$topic_name = $topic['topic_name'];
$options[$topic_name] = $topic_name;
}
// There could be more then 1 contact form on page,
// so let's make sure the right options are used.
$cacheable = FALSE;
return $options;
}
/**
* Implements hook_entity_type_alter().
*/
function oe_contact_forms_entity_type_alter(array &$entity_types) {
/** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
// Set the form handler class for messages to corporate implementation.
$entity_types['contact_message']->setFormClass('corporate_default', '\Drupal\oe_contact_forms\Form\ContactMessageForm');
}
/**
* Implements hook_form_FORM_ID_alter() for contact_form_disable_form().
*/
function oe_contact_forms_form_contact_form_disable_form_alter(&$form, FormStateInterface $form_state, $form_id) {
/** @var \Drupal\contact\ContactFormInterface $contact_form */
$contact_form = $form_state->getFormObject()->getEntity();
if (!$contact_form->getThirdPartySetting('oe_contact_forms', 'is_corporate_form', FALSE)) {
// Only alter disable form if its a corporate contact forms.
return;
}
// Remove disable message as it's not used in corporate contact forms.
unset($form['contact_storage_disabled_form_message']);
}
/**
* Implements hook_entity_form_display_alter().
*/
function oe_contact_forms_entity_form_display_alter(EntityFormDisplayInterface $form_display, array $context) {
// Order the fields.
if ($context['entity_type'] == 'contact_message' && $context['form_mode'] == 'corporate_default') {
$form_display
->setComponent('header', [
'weight' => -1,
])
->setComponent('name', [
'weight' => 0,
])
->setComponent('oe_first_name', [
'weight' => 0,
])
->setComponent('oe_last_name', [
'weight' => 0,
])
->setComponent('mail', [
'weight' => 1,
])
->setComponent('subject', [
'weight' => 2,
])
->setComponent('message', [
'weight' => 3,
])
->setComponent('oe_topic', [
'weight' => 4,
])
->setComponent('oe_country_residence', [
'weight' => 5,
'type' => 'skos_concept_entity_reference_options_select',
'settings' => [
'sort' => 'label',
],
])
->setComponent('oe_preferred_language', [
'weight' => 6,
'type' => 'skos_concept_entity_reference_autocomplete',
])
->setComponent('oe_alternative_language', [
'weight' => 7,
'type' => 'skos_concept_entity_reference_autocomplete',
])
->setComponent('oe_telephone', [
'weight' => 8,
])
->setComponent('copy', [
'weight' => 9,
])
->setComponent('privacy_policy', [
'weight' => 10,
]);
}
}
/**
* Implements hook_mail_alter().
*/
function oe_contact_forms_mail_alter(&$message) {
// Check if it's a corporate contact form.
$is_corporate_form = FALSE;
$mail_ids = [
'contact_page_mail',
'contact_page_copy',
'contact_page_autoreply',
];
if (!isset($message['params']['contact_form'])) {
return;
}
/** @var \Drupal\contact\ContactFormInterface $contact_form */
$contact_form = $message['params']['contact_form'];
$is_corporate_form = (boolean) $contact_form->getThirdPartySetting('oe_contact_forms', 'is_corporate_form', FALSE);
if (!$is_corporate_form || !in_array($message['id'], $mail_ids)) {
return;
}
// Change subject for corporate mail, copy and reply.
$message['subject'] = $contact_form->getThirdPartySetting('oe_contact_forms', 'email_subject');
// Set back the auto-reply in case contact_storage re-rendered it.
// @see contact_storage_mail_alter.
if ($message['key'] === 'page_autoreply') {
$message['body'] = [$contact_form->getReply()];
}
if ($message['key'] !== 'page_mail') {
return;
}
// Provided values are automatically included in the email message body, so
// we remove them when they are not set to be included.
$includes_fields_in_messages = (boolean) $contact_form->getThirdPartySetting('oe_contact_forms', 'includes_fields_in_messages', FALSE);
if (!$includes_fields_in_messages && count($message['body']) === 2) {
unset($message['body'][1]);
}
}
/**
* Implements hook_ENTITY_TYPE_create_access().
*/
function oe_contact_forms_contact_message_create_access(AccountInterface $account, array $context, $entity_bundle) {
if (!$entity_bundle) {
return AccessResult::neutral();
}
/** @var \Drupal\contact\Entity\ContactForm $contact_form */
$contact_form = ContactForm::load($entity_bundle);
if (!$contact_form) {
return AccessResult::neutral();
}
// Leave default contact forms untouched.
if (!$contact_form->getThirdPartySetting('oe_contact_forms', 'is_corporate_form', FALSE)) {
return AccessResult::neutral()->addCacheableDependency($contact_form);
}
if ($account->hasPermission('access corporate contact form')) {
return AccessResult::allowed()->cachePerPermissions()->addCacheTags($contact_form->getCacheTags());
}
return AccessResult::forbidden()->cachePerPermissions();
}
/**
* List of languages in contact language options fields by default.
*/
function _oe_contact_forms_contact_language_values(): array {
return [
'http://publications.europa.eu/resource/authority/language/BUL',
'http://publications.europa.eu/resource/authority/language/SPA',
'http://publications.europa.eu/resource/authority/language/CES',
'http://publications.europa.eu/resource/authority/language/DAN',
'http://publications.europa.eu/resource/authority/language/DEU',
'http://publications.europa.eu/resource/authority/language/EST',
'http://publications.europa.eu/resource/authority/language/ELL',
'http://publications.europa.eu/resource/authority/language/ENG',
'http://publications.europa.eu/resource/authority/language/FRA',
'http://publications.europa.eu/resource/authority/language/GLE',
'http://publications.europa.eu/resource/authority/language/HRV',
'http://publications.europa.eu/resource/authority/language/ITA',
'http://publications.europa.eu/resource/authority/language/LAV',
'http://publications.europa.eu/resource/authority/language/LIT',
'http://publications.europa.eu/resource/authority/language/HUN',
'http://publications.europa.eu/resource/authority/language/MLT',
'http://publications.europa.eu/resource/authority/language/NLD',
'http://publications.europa.eu/resource/authority/language/POL',
'http://publications.europa.eu/resource/authority/language/POR',
'http://publications.europa.eu/resource/authority/language/RON',
'http://publications.europa.eu/resource/authority/language/SLK',
'http://publications.europa.eu/resource/authority/language/SLV',
'http://publications.europa.eu/resource/authority/language/FIN',
'http://publications.europa.eu/resource/authority/language/SWE',
];
}
/**
* Implements hook_locale_translation_projects_alter().
*/
function oe_contact_forms_locale_translation_projects_alter(&$projects) {
$projects['oe_contact_forms']['info']['interface translation server pattern'] = \Drupal::service('extension.path.resolver')->getPath('module', 'oe_contact_forms') . '/translations/%project-%language.po';
}
/**