forked from backdrop-contrib/conditional_fields
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conditional_fields.module
2125 lines (1874 loc) · 77.2 KB
/
conditional_fields.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
* Define dependencies between fields based on their states and values.
*
* Conditional Fields for Backdrop is basically an user interface for the States
* API, plus the ability to hide fields on certain conditions when viewing
* content.
*/
/**
* Dependency is triggered if the dependee has a certain value.
*/
define('CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET', 1);
/**
* Dependency is triggered if the dependee has all values.
*/
define('CONDITIONAL_FIELDS_DEPENDENCY_VALUES_AND', 2);
/**
* Dependency is triggered if the dependee has any of the values.
*/
define('CONDITIONAL_FIELDS_DEPENDENCY_VALUES_OR', 3);
/**
* Dependency is triggered if the dependee has only one of the values.
*/
define('CONDITIONAL_FIELDS_DEPENDENCY_VALUES_XOR', 4);
/**
* Dependency is triggered if the dependee does not have any of the values.
*/
define('CONDITIONAL_FIELDS_DEPENDENCY_VALUES_NOT', 5);
/**
* Dependency is triggered if the dependee values match a regular expression.
*/
define('CONDITIONAL_FIELDS_DEPENDENCY_VALUES_REGEX', 6);
/**
* Field view setting. Dependent is shown only if the dependency is triggered.
*/
define('CONDITIONAL_FIELDS_FIELD_VIEW_EVALUATE', 1);
/**
* Field view setting. Dependent is shown only if the dependee is shown as well.
*/
define('CONDITIONAL_FIELDS_FIELD_VIEW_HIDE_ORPHAN', 2);
/**
* Field view setting. Dependent is highlighted if the dependency is not
* triggered.
*/
define('CONDITIONAL_FIELDS_FIELD_VIEW_HIGHLIGHT', 3);
/**
* Field view setting. Dependent has a textual description of the dependency.
*/
define('CONDITIONAL_FIELDS_FIELD_VIEW_DESCRIBE', 4);
/**
* Field view setting. Dependent is shown only if the dependee is shown as well
* and the dependency evaluates to TRUE.
*/
define('CONDITIONAL_FIELDS_FIELD_VIEW_HIDE_UNTRIGGERED_ORPHAN', 5);
/**
* Field edit setting. Dependent is shown only if the dependee is shown as well.
*/
define('CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_ORPHAN', 1);
/**
* Field edit setting. Dependent is shown only if the dependee is shown as well
* and the dependency evaluates to TRUE.
*/
define('CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_UNTRIGGERED_ORPHAN', 2);
/**
* Field edit setting. Dependent is reset to its default values if the
* dependency was not triggered when the form is submitted.
*/
define('CONDITIONAL_FIELDS_FIELD_EDIT_RESET_UNTRIGGERED', 3);
/**
* Load include files for admin pages.
*/
module_load_include('inc', 'conditional_fields', 'includes/conditional_fields.admin');
/**
* Implements hook_permission().
*/
function conditional_fields_permission() {
return array(
'administer dependencies' => array(
'title' => t('Administer dependencies'),
'description' => t('View, edit and delete field dependencies.'),
),
);
}
/**
* Implements hook_menu().
*/
function conditional_fields_menu() {
$items = array();
// Ensure the following is not executed until field_bundles is working and
// tables are updated. Needed to avoid errors on initial installation.
if (defined('MAINTENANCE_MODE')) {
return $items;
}
$items['admin/structure/dependencies'] = array(
'title' => 'Field dependencies',
'description' => 'Administer field dependencies for the site.',
'page callback' => 'conditional_fields_dependencies_overview_page',
'access arguments' => array('administer dependencies'),
'file' => 'includes/conditional_fields.admin.inc',
);
$items['admin/structure/dependencies/overview'] = array(
'title' => 'Overview',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => 1,
);
$items['admin/structure/dependencies/edit/%conditional_fields_dependency'] = array(
'title' => 'Edit dependency',
'page callback' => 'backdrop_get_form',
'page arguments' => array('conditional_fields_dependency_edit_form', 4),
'access arguments' => array('administer dependencies'),
'file' => 'includes/conditional_fields.admin.inc',
);
$items['admin/structure/dependencies/delete/%conditional_fields_dependency'] = array(
'title' => 'Delete dependency',
'page callback' => 'backdrop_get_form',
'page arguments' => array('conditional_fields_dependency_delete_form', 4),
'access arguments' => array('administer dependencies'),
'file' => 'includes/conditional_fields.admin.inc',
);
// Some of the following code is copied from field_ui_menu().
// Create tabs for all possible bundles.
$entities = entity_get_info();
foreach ($entities as $entity_type => $entity_info) {
if ($entity_info['fieldable']) {
$items["admin/structure/dependencies/$entity_type"] = array(
'title' => $entity_info['label'],
'page arguments' => array(NULL, 3),
'access arguments' => array('administer dependencies'),
'type' => MENU_LOCAL_TASK,
'weight' => 2,
);
foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
if (module_exists('field_ui') && isset($bundle_info['admin'])) {
// Extract path information from the bundle and replace any "magic"
// wildcard with a normal one.
$path = preg_replace('/(%[a-z0-9_]*)/', '%', $bundle_info['admin']['path']);
if (isset($bundle_info['admin']['bundle argument'])) {
$bundle_pos = $bundle_info['admin']['bundle argument'];
}
else {
$bundle_pos = $bundle_name;
}
$items["$path/dependencies"] = array(
'title' => $entity_type == 'comment' ? 'Comment dependencies' : 'Manage dependencies',
'page callback' => 'conditional_fields_dependencies_overview_page',
'page arguments' => array($bundle_pos, $entity_type),
'type' => MENU_LOCAL_TASK,
'weight' => $entity_type == 'comment' ? 4 : 2,
'file' => 'includes/conditional_fields.admin.inc',
'access arguments' => array('administer dependencies'),
);
}
}
}
}
return $items;
}
/**
* Implements hook_forms().
*
* Maps all dependency add forms to the same callback.
*/
function conditional_fields_forms() {
foreach (entity_get_info() as $entity_type => $entity_info) {
if ($entity_info['fieldable']) {
foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
$forms['conditional_fields_dependency_add_form_' . $entity_type . '_' . $bundle_name] = array(
'callback' => 'conditional_fields_dependency_add_form',
'callback arguments' => array($entity_type, $bundle_name),
);
}
}
}
return $forms;
}
/**
* Implements hook_element_info_alter().
* Adds an #after_build function to all form elements.
*/
function conditional_fields_element_info_alter(&$types) {
foreach ($types as $type => $info) {
$types[$type]['#after_build'][] = 'conditional_fields_element_after_build';
}
}
/**
* Processes form elements with dependencies.
*
* Just adds a #conditional_fields property to the form with the needed
* data, which is used later in conditional_fields_form_after_build():
* - The fields #parents property.
* - Field dependencies data.
*/
function conditional_fields_element_after_build($element, &$form_state) {
// Some fields are wrapped in containers before processing. Wrapped data must
// take precedence over the container, because Entity Translation and
// possibly other modules add #field_name to the container as well.
if (isset($element['#language'], $element[$element['#language']], $element[$element['#language']]['#field_name'])) {
$field = $element[$element['#language']];
}
elseif (isset($element['#field_name'])) {
$field = $element;
}
else {
return $element;
}
$form = &$form_state['complete_form'];
// Avoid processing fields in fields_ui administration pages.
if (backdrop_substr($form['#form_id'], 0, 9) == 'field_ui_') {
return $element;
}
// Some fields do not have entity type and bundle properties. In this case we
// try to use the properties from the form. This is not an optimal solution,
// since in case of fields in entities within entities they might not correspond,
// and their dependencies will not be loaded.
if (isset($field['#entity_type'], $field['#bundle'])) {
$entity_type = $field['#entity_type'];
$bundle = $field['#bundle'];
}
elseif (isset($form['#entity_type'], $form['#bundle'])) {
$entity_type = $form['#entity_type'];
$bundle = $form['#bundle'];
}
else {
return $element;
}
$dependencies = conditional_fields_load_dependencies($entity_type, $bundle);
if (!$dependencies) {
return $element;
}
// Attach dependent.
$field_instance_id = $entity_type . '.' . $bundle . '.' . $field['#field_name'];
if (isset($dependencies['dependents'][$field_instance_id])) {
foreach ($dependencies['dependents'][$field_instance_id] as $id => $dependency) {
$dependency_parts = explode('.', $dependency['dependee']);
$dependee_field_name = array_pop($dependency_parts);
if (!isset($form['#conditional_fields'][$field['#field_name']]['dependees'][$id])) {
conditional_fields_attach_dependency($form, array('#field_name' => $dependee_field_name), $field, $dependency['options'], $id);
}
}
}
// Attach dependee.
// TODO: collect information about every element of the dependee widget, not
// just the first encountered. This bottom-up approach would allow us to
// define per-element sets of dependency values.
if (isset($dependencies['dependees'][$field_instance_id])) {
foreach ($dependencies['dependees'][$field_instance_id] as $id => $dependency) {
$dependent_parts = explode('.', $dependency['dependent']);
$dependent_field_name = array_pop($dependent_parts);
if (!isset($form['#conditional_fields'][$field['#field_name']]['dependents'][$id])) {
conditional_fields_attach_dependency($form, $field, array('#field_name' => $dependent_field_name), $dependency['options'], $id);
}
}
}
return $element;
}
/**
* Attaches a single dependency to a form.
*
* Call this function when defining or altering a form to create dependencies
* dynamically.
*
* @param $form
* The form where the dependency is attached.
* @param $dependee
* The dependee field form element. Either a string identifying the element
* key in the form, or a fully built field array. Actually used properties of
* the array are #field_name and #parents.
* @param $dependent
* The dependent field form element. Either a string identifying the element
* key in the form, or a fully built field array. Actually used properties of
* the array are #field_name and #field_parents.
* @param $options
* An array of dependency options with the following key/value pairs:
* - state: The state applied to the dependent when the dependency is
* triggered. See conditional_fields_states() for available states.
* - condition: The condition for the dependency to be triggered. See
* conditional_fields_conditions() for available conditions.
* - values_set: One of the following constants:
* - CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET: Dependency is
* triggered if the dependee has a certain value defined in 'value'.
* - CONDITIONAL_FIELDS_DEPENDENCY_VALUES_AND: Dependency is triggered if
* the dependee has all the values defined in 'values'.
* - CONDITIONAL_FIELDS_DEPENDENCY_VALUES_OR: Dependency is triggered if the
* dependee has any of the values defined in 'values'.
* - CONDITIONAL_FIELDS_DEPENDENCY_VALUES_XOR: Dependency is triggered if
* the dependee has only one of the values defined in 'values'.
* - CONDITIONAL_FIELDS_DEPENDENCY_VALUES_NOT: Dependency is triggered if
* the dependee does not have any of the values defined in 'values'.
* - value: The value to be tested when 'values_set' is
* CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET. An associative array with
* the same structure of the dependee field values as found in
* $form_states['values] when the form is submitted. You can use
* field_default_extract_form_values() to extract this array.
* - values: The array of values to be tested when 'values_set' is not
* CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET.
* - value_form: An associative array with the same structure of the dependee
* field values as found in $form_state['input']['value']['field'] when the
* form is submitted.
* - effect: The jQuery effect associated to the state change. See
* conditional_fields_effects() for available effects and options.
* - effect_options: The options for the active effect.
* - element_view: An associative array of field view behaviors with
* CONDITIONAL_FIELDS_FIELD_VIEW_* constants as keys and the same constants
* as values for enabled behaviors and 0 for disabled behaviors.
* See conditional_fields_behaviors() for descriptions.
* - element_view_per_role: Set to 1 to activate field view settings per role.
* - element_view_roles: An associative array of field view settings per role
* where the keys are role ids and the values are arrays with the same
* structure of 'element_view'.
* - element_edit: An associative array of field edit behaviors with
* CONDITIONAL_FIELDS_FIELD_EDIT_* constants as keys and the same constants
* as values for enabled behaviors and 0 for disabled behaviors.
* See conditional_fields_behaviors() for descriptions.
* - element_edit_per_role: Set to 1 to activate field edit settings per role.
* - element_edit_roles: An associative array of field edit settings per role
* where the keys are role ids and the values are arrays with the same
* structure of 'element_edit'.
* - selector: (optional) Custom jQuery selector for the dependee.
* @param $id
* (internal use) The identifier for the dependency. Omit this parameter when
* attaching a custom dependency.
*
* Note that you don't need to manually set all these options, since default
* settings are always provided.
*/
function conditional_fields_attach_dependency(&$form, $dependee, $dependent, $options, $id = 0) {
$options += conditional_fields_dependency_default_options();
// The absence of the $id parameter identifies a custom dependency.
if (!$id) {
// String values are accepted to simplify usage of this function with custom
// forms.
if (is_string($dependee) && is_string($dependent)) {
$dependee = array(
'#field_name' => $dependee,
'#parents' => array($dependee),
);
$dependent = array(
'#field_name' => $dependent,
'#field_parents' => array($dependent),
);
// Custom dependencies have automatically assigned a progressive id.
static $current_id;
if (!$current_id) {
$current_id = 1;
}
$id = $current_id;
$current_id++;
}
}
// Attach dependee.
// Use the #array_parents property of the dependee instead of #field_parents
// since we will need access to the full structure of the widget.
if (isset($dependee['#parents'])) {
$form['#conditional_fields'][$dependee['#field_name']]['parents'] = $dependee['#array_parents'];
$form['#conditional_fields'][$dependee['#field_name']]['dependents'][$id] = array(
'dependent' => $dependent['#field_name'],
'options' => $options,
);
}
// Attach dependent.
if (isset($dependent['#field_parents'])) {
$dependent_parents = $dependent['#field_parents'];
}
elseif (isset($dependent['#parents'])) {
$dependent_parents = $dependent['#parents'];
}
if (isset($dependent_parents)) {
$form['#conditional_fields'][$dependent['#field_name']]['field_parents'] = $dependent_parents;
$form['#conditional_fields'][$dependent['#field_name']]['dependees'][$id] = array(
'dependee' => $dependee['#field_name'],
'options' => $options,
);
}
// Actual processing is done in conditional_fields_form_after_build().
// Append the property so the callback runs last.
_conditional_fields_element_add_property($form, '#after_build', 'conditional_fields_form_after_build', 'append');
}
/**
* after_build callback for forms with dependencies.
*
* Builds and attaches #states properties to dependent fields, adds additional
* visual effects handling to the States API and attaches a validation callback
* to the form that handles validation of dependent fields.
*/
function conditional_fields_form_after_build($form, &$form_state) {
// Dependencies data is attached in conditional_fields_element_after_build().
if (empty($form['#conditional_fields'])) {
return $form;
}
$effects = array();
$state_handlers = conditional_fields_states_handlers();
// Cycle all dependents.
foreach ($form['#conditional_fields'] as $dependent => $dependent_info) {
$states = array();
if (empty($dependent_info['dependees'])) {
continue;
}
$dependent_location = array_merge($dependent_info['field_parents'], array($dependent));
$dependent_form_field = backdrop_array_get_nested_value($form, $dependent_location);
// Cycle the dependant's dependees.
foreach ($dependent_info['dependees'] as $dependency) {
$dependee = $dependency['dependee'];
if (empty($form['#conditional_fields'][$dependee])) {
continue;
}
$dependee_info = $form['#conditional_fields'][$dependee];
$dependee_form_field = backdrop_array_get_nested_value($form, $dependee_info['parents']);
$options = $dependency['options'];
// Load field edit behaviors.
// If this dependent has multiple dependees, only the logic of the first
// dependency will be taken into account.
if (!isset($behaviors)) {
$behaviors = conditional_fields_field_behaviors('edit', $options);
}
// Determine if the dependee is in the form.
if (empty($dependee_form_field) || (isset($dependee_form_field['#access']) && $dependee_form_field['#access'] == FALSE)) {
// Apply orphan dependent behaviors.
/*
if (in_array(CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_UNTRIGGERED_ORPHAN, $behaviors)) {
// TODO
$is_triggered = TRUE;
if ($is_orphan && !$is_triggered) {
$form[$dependent]['#access'] = FALSE;
}
}
*/
if (in_array(CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_ORPHAN, $behaviors)) {
$dependent_form_field['#access'] = FALSE;
}
unset($behaviors[CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_UNTRIGGERED_ORPHAN]);
unset($behaviors[CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_ORPHAN]);
unset($behaviors[CONDITIONAL_FIELDS_FIELD_EDIT_RESET_UNTRIGGERED]);
continue;
}
unset($behaviors[CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_UNTRIGGERED_ORPHAN]);
unset($behaviors[CONDITIONAL_FIELDS_FIELD_EDIT_HIDE_ORPHAN]);
// Build a jQuery selector if it was not overridden by a custom value.
// Note that this may be overridden later by a state handler.
if (!$options['selector']) {
$options['selector'] = conditional_fields_field_selector($dependee_form_field);
}
else {
// Replace the language placeholder in the selector with current language.
$options['selector'] = str_replace('%lang', $dependee_form_field['#language'], $options['selector']);
}
if ($options['condition'] != 'value') {
// Conditions different than "value" are always evaluated against TRUE.
$state = array($options['state'] => array($options['selector'] => array($options['condition'] => TRUE)));
}
else {
// Build the values that trigger the dependency.
$values = array();
if ($options['values_set'] == CONDITIONAL_FIELDS_DEPENDENCY_VALUES_WIDGET) {
$values[$options['condition']] = $options['value_form'];
}
elseif ($options['values_set'] == CONDITIONAL_FIELDS_DEPENDENCY_VALUES_REGEX) {
$values[$options['condition']] = $options['value'];
}
elseif ($options['values_set'] == CONDITIONAL_FIELDS_DEPENDENCY_VALUES_AND) {
$values[$options['condition']] = count($options['values']) == 1 ? $options['values'][0] : $options['values'];
}
else {
if ($options['values_set'] == CONDITIONAL_FIELDS_DEPENDENCY_VALUES_XOR) {
// XOR behaves like OR with added 'xor' element.
$values[] = 'xor';
}
elseif ($options['values_set'] == CONDITIONAL_FIELDS_DEPENDENCY_VALUES_NOT) {
// NOT behaves like OR with switched state.
$options['state'] = strpos($options['state'], '!') === 0 ? backdrop_substr($options['state'], 1) : '!' . $options['state'];
}
// OR, NOT and XOR conditions are obtained with a nested array.
foreach ($options['values'] as $value) {
$values[] = array($options['condition'] => $value);
}
}
$state = array($options['state'] => array($options['selector'] => $values));
$dependee_form_state = isset($dependee_form_field['#field_parents'], $dependee_form_field['#field_name'], $dependee_form_field['#language']) ? field_form_get_state($dependee_form_field['#field_parents'], $dependee_form_field['#field_name'], $dependee_form_field['#language'], $form_state) : NULL;
// Execute special handler for fields that need further processing.
// The handler has no return value. Modify the $state parameter by
// reference if needed.
foreach ($state_handlers as $handler => $handler_conditions) {
if (array_intersect_assoc($handler_conditions, $dependee_form_field) == $handler_conditions) {
$handler($dependee_form_field, $dependee_form_state, $options, $state);
}
}
}
// Add validation callback to element if the dependency can be evaluated.
if (in_array($options['condition'], array('value', 'empty', '!empty', 'checked', '!checked'))) {
_conditional_fields_element_add_property($dependent_form_field, '#element_validate', 'conditional_fields_dependent_validate', 'append');
}
// Add the $state into the correct logic group in $states.
foreach ($state as $key => $constraints) {
foreach ($constraints as $selector => $constraint) {
// Add the constraint in an array to avoid overwriting other
// dependencies' states with the same selector.
$states[$key][$options['grouping']][$selector][] = $constraint;
}
}
// Build effect settings for effects with options.
// TODO: add dependee key to allow different effects on the same selector.
if ($options['effect'] && $options['effect'] != 'show') {
$selector = conditional_fields_field_selector(backdrop_array_get_nested_value($form, array($dependent_location[0])));
// Convert numeric strings to numbers.
foreach ($options['effect_options'] as &$effect_option) {
if (is_numeric($effect_option)) {
$effect_option += 0;
}
}
$effects[$selector] = array(
'effect' => $options['effect'],
'options' => $options['effect_options'],
);
}
// Apply reset dependent to default if untriggered behavior.
if (in_array(CONDITIONAL_FIELDS_FIELD_EDIT_RESET_UNTRIGGERED, $behaviors)) {
// Add property to element so conditional_fields_dependent_validate() can
// pick it up.
$dependent_form_field['#conditional_fields_reset_if_untriggered'] = TRUE;
unset($behaviors[CONDITIONAL_FIELDS_FIELD_EDIT_RESET_UNTRIGGERED]);
}
}
// Execute custom behaviors callbacks.
if (!empty($behaviors)) {
foreach ($behaviors as $behavior) {
$behavior($form, $form_state, $dependent, $dependent_info);
}
}
unset($behaviors);
if (empty($states)) {
continue;
}
// Save the modified field back into the form.
backdrop_array_set_nested_value($form, $dependent_location, $dependent_form_field);
// Map the states based on the conjunctions.
$states_new = array();
foreach ($states as $state_key => $value) {
// As the main object is ANDed together we can add the AND items directly.
if (!empty($states[$state_key]['AND'])) {
$states_new[$state_key] = $states[$state_key]['AND'];
}
// The OR and XOR groups are moved into a sub-array that has numeric keys
// so that we get a JSON array and not an object, as required by the States
// API for OR and XOR groupings.
if (!empty($states[$state_key]['OR'])) {
$or = array();
foreach ($states[$state_key]['OR'] as $constraint_key => $constraint_value) {
$or[] = array($constraint_key => $constraint_value);
}
// '1' as a string so that we get an object (which means logic groups
// are ANDed together).
$states_new[$state_key]['1'] = $or;
}
if (!empty($states[$state_key]['XOR'])) {
$xor = array('xor');
foreach ($states[$state_key]['XOR'] as $constraint_key => $constraint_value) {
$xor[] = array($constraint_key => $constraint_value);
}
// '2' as a string so that we get an object.
$states_new[$state_key]['2'] = $xor;
}
}
$states = $states_new;
// Add the #states property to the dependent field.
backdrop_array_set_nested_value($form, array_merge($dependent_location, array('#states')), $states);
$has_states = TRUE;
}
if (empty($has_states)) {
return $form;
}
$form['#attached']['library'][] = array('conditional_fields', 'conditional_fields');
// Add effect settings to the form.
if ($effects) {
$form['#attached']['js'][] = array(
'data' => array(
'conditionalFields' => array(
'effects' => $effects,
),
),
'type' => 'setting',
);
}
// Validation callback to manage dependent fields validation.
$form['#validate'][] = 'conditional_fields_form_validate';
// Initialize validation information every time the form is rendered to avoid
// stale data after a failed submission.
$form_state['conditional_fields_untriggered_dependents'] = array();
return $form;
}
/**
* Dependent field validation callback.
*
* If the dependencies of a dependent field are not triggered, the validation
* errors that it might have thrown must be removed, together with its submitted
* values. This will simulate the field not being present in the form at all.
* In this field-level callback we just collect needed information and store it
* in $form_state. Values and errors will be removed in a single sweep in
* conditional_fields_form_validate(), which runs at the end of the validation
* cycle.
*
* @see conditional_fields_form_validate()
*/
function conditional_fields_dependent_validate($element, &$form_state, $form) {
if (isset($element['#access']) && !$element['#access']) {
return;
}
$dependent = $element[$element['#language']];
// Check if this field's dependencies were triggered.
$triggered = conditional_fields_evaluate_dependencies($dependent, $form, $form_state);
// If true - previous validation errors (like 'required') will be shown.
$show_previous_errors = TRUE;
if ($evaluated_dependencies = conditional_fields_evaluate_dependencies($dependent, $form, $form_state, FALSE)) {
foreach ($evaluated_dependencies[$dependent['#field_name']] as $operator) {
foreach ($operator as $state => $result) {
// Silently suppress errors if became invisible or optional
// (skip further processing).
if ($triggered && in_array($state, array('!required', '!visible'))) {
$show_previous_errors = FALSE;
}
// The same with hidden fields that did not become visible.
if (!$triggered && $state == 'visible') {
$show_previous_errors = FALSE;
}
if ($triggered && $state == 'required') {
$show_previous_errors = FALSE;
$key_exists = NULL;
$input_state = backdrop_array_get_nested_value($form_state['values'], $dependent['#parents'], $key_exists);
if ($key_exists) {
// Remove the 'value' of the 'add more' button.
unset($input_state['add_more']);
}
$input_state = (is_null($input_state)) ? array() : $input_state;
if (isset($dependent['#field_name'])) {
$field = field_info_field($dependent['#field_name']);
$input_state = _field_filter_items($field, $input_state);
}
$info = field_info_field($dependent['#field_name']);
$function = $info['module'] . '_field_is_empty';
if (!empty($input_state)) {
$is_empty = TRUE;
foreach ($input_state as $value) {
if (function_exists($function)) {
$is_empty = $is_empty && $function($value, $info);
}
}
//TEMP see #2028085
if (isset($info['type']) && ($info['type'] == 'list_boolean')) {
$is_empty = TRUE;
foreach ($input_state as $value) {
if (function_exists($function)) {
$is_empty = $is_empty && ($value['value'] == 0);
}
}
}
}
// If conditionally required field is empty, show the error.
if (empty($input_state) || $is_empty) {
$title = '';
if (isset($dependent['#title'])) {
$title = $dependent['#title'];
}
elseif (isset($dependent[0]['#title'])) {
$title = $dependent[0]['#title'];
}
form_error($element, t('!name field is required.', array('!name' => $title)));
}
}
}
}
}
if ($show_previous_errors) {
return;
}
// Mark submitted values for removal. We have to remove them after all fields
// have been validated to avoid collision between dependencies.
$form_state_addition['parents'] = $dependent['#array_parents'];
// Optional behavior: reset the field to its default values.
// Default values are always valid, so it's safe to skip validation.
if (!empty($element['#conditional_fields_reset_if_untriggered']) && !$triggered) {
$form_state_addition['reset'] = TRUE;
}
// Tag validation errors previously set on this field for removal in
// conditional_fields_form_validate().
$errors = form_get_errors();
if ($errors) {
$error_key = implode('][', $dependent['#parents']);
foreach ($errors as $name => $error) {
// An error triggered by this field might have been set on a descendant
// element. This also means that so there can be multiple errors on the
// same field (even though Backdrop doesn't support multiple errors on the
// same element).
if (strpos($name, $error_key) === 0) {
$field_errors[$name] = $error;
}
}
}
if (!empty($field_errors)) {
$form_state_addition['errors'] = $field_errors;
}
$form_state['conditional_fields_untriggered_dependents'][] = $form_state_addition;
}
/**
* Extracts field values from a field element of a submitted form.
*
* @return
* The requested field values parent. Actual field vales are stored under the
* key $element['#field_name'].
*/
function conditional_fields_field_get_values($element, $form_state) {
// Fall back to #parents to support custom dependencies.
$parents = !empty($element['#field_parents']) ? $element['#field_parents'] : $element['#parents'];
return backdrop_array_get_nested_value($form_state['values'], $parents);
}
/**
* Validation callback for any form with conditional fields.
*
* This validation callback is added to all forms that contain fields with
* dependencies. It removes all validation errors from dependent fields whose
* dependencies are not triggered, which were collected at field-level
* validation in conditional_fields_dependent_validate().
*
* @see conditional_fields_dependent_validate()
*/
function conditional_fields_form_validate($form, &$form_state) {
if (empty($form_state['conditional_fields_untriggered_dependents'])) {
return;
}
$untriggered_dependents_errors = array();
foreach ($form_state['conditional_fields_untriggered_dependents'] as $field) {
$dependent = backdrop_array_get_nested_value($form, $field['parents']);
$field_values_location = conditional_fields_field_get_values($dependent, $form_state);
// If we couldn't find a location for the field's submitted values, let the
// validation errors pass through to avoid security holes.
if (!isset($field_values_location[$dependent['#field_name']])) {
if (!empty($field['errors'])) {
$untriggered_dependents_errors = array_merge($untriggered_dependents_errors, $field['errors']);
}
continue;
}
if (!empty($field['reset'])) {
$dependent_info = field_form_get_state($dependent['#field_parents'], $dependent['#field_name'], $dependent['#language'], $form_state);
$field_values_location[$dependent['#field_name']][$dependent['#language']] = field_get_default_value($dependent_info['instance']['entity_type'], NULL, $dependent_info['field'], $dependent_info['instance'], $dependent['#language']);
}
// Save the changed array back in place.
// Do not use form_set_value() since it assumes that the values are located at
// $form_state['values'][ ... $element['#parents'] ... ], while the
// documentation of hook_field_widget_form() states that field values are
// $form_state['values'][ ... $element['#field_parents'] ... ].
backdrop_array_set_nested_value($form_state['values'], $dependent['#field_parents'], $field_values_location);
if (!empty($field['errors'])) {
$untriggered_dependents_errors = array_merge($untriggered_dependents_errors, $field['errors']);
}
}
if (!empty($untriggered_dependents_errors)) {
// Since Backdrop provides no clean way to selectively remove error messages,
// we have to store all current form errors and error messages, clear them,
// filter out from our stored values the errors originating from untriggered
// dependent fields, and then reinstate remaining errors and messages.
$errors = array_diff_assoc((array) form_get_errors(), $untriggered_dependents_errors);
form_clear_error();
$error_messages = backdrop_get_messages('error');
$removed_messages = array_values($untriggered_dependents_errors);
// Reinstate remaining errors.
foreach ($errors as $name => $error) {
form_set_error($name, $error);
// form_set_error() calls backdrop_set_message(), so we have to filter out
// these from the messages to avoid duplicates.
$removed_messages[] = $error;
}
// Reinstate remaining error messages (which, at this point, are messages that
// were originated outside of the validation process).
foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
backdrop_set_message($message, 'error');
}
}
}
/**
* Helper function to add a property/value pair to a render array safely without
* overriding any pre-existing value.
*
* @param $position
* 'append' if $value should be inserted at the end of the $element[$property]
* array, any other value to insert it at the beginning.
*
*/
function _conditional_fields_element_add_property(&$element, $property, $value, $position = 'prepend') {
// Avoid overriding default element properties that might not yet be set.
if (!isset($element[$property])) {
$element[$property] = isset($element['#type']) ? element_info_property($element['#type'], $property, array()) : array();
}
if (in_array($value, $element[$property])) {
return;
}
switch ($position) {
case 'append':
$element[$property] = array_merge($element[$property], (array) $value);
break;
case 'prepend':
default:
$element[$property] = array_merge((array) $value, $element[$property]);
break;
}
}
/**
* Implements hook_entity_view_alter().
*
* Applies entity view logic to conditional fields.
*/
function conditional_fields_entity_view_alter(&$build, $type) {
if (!(isset($build['#entity_type'], $build['#bundle']) && $dependencies = conditional_fields_load_dependencies($build['#entity_type'], $build['#bundle']))) {
return;
}
$evaluated_dependents = array();
foreach ($dependencies['dependents'] as $dependent => $dependency) {
if (empty($build[$dependent]['#access'])) {
continue;
}
foreach ($dependency as $dependency_options) {
$dependee = $dependency_options['dependee'];
$options = $dependency_options['options'];
// We can interface with the States API only through the Value condition.
if ($options['condition'] != 'value') {
continue;
}
// Determine field view behaviors.
// If this dependent has multiple dependencies, only the logic of the
// first dependency will be taken into account.
if (!isset($behaviors)) {
$behaviors = conditional_fields_field_behaviors('view', $options);
}
// Manage orphan fields (dependents with no dependees).
$evaluate = in_array(CONDITIONAL_FIELDS_FIELD_VIEW_EVALUATE, $behaviors);
$hide_orphan = in_array(CONDITIONAL_FIELDS_FIELD_VIEW_HIDE_ORPHAN, $behaviors);
$hide_untriggered_orphan = in_array(CONDITIONAL_FIELDS_FIELD_VIEW_HIDE_UNTRIGGERED_ORPHAN, $behaviors);
$is_orphan = empty($build[$dependee]['#access']);
if ($is_orphan) {
// Hide the dependent. No need to evaluate the dependency.
if ($hide_orphan) {
$build[$dependent]['#access'] = FALSE;
continue;
}
if ($hide_untriggered_orphan) {
$evaluate = TRUE;
}
if ($evaluate) {
// We have to look for the dependee in the entity object.
// TODO: Is it possible to avoid hardcoding this?
switch ($type) {
case 'node':
$entity_property = '#node';
break;
case 'user':
$entity_property = '#account';
break;
case 'term':
$entity_property = '#term';
break;
case 'field_collection_item':
case 'profile2':
default:
$entity_property = '#entity';
}
// If we didn't find the field, there is nothing more we can do.
if (!isset($build[$entity_property]->$dependee)) {
continue;
}
$items = $build[$entity_property]->$dependee;
// Values are keyed by language here, remove it.
$items = array_shift($items);
}
}
else {
$items = $build[$dependee]['#items'];
}
if ($evaluate) {
$evaluated_dependents[$dependent][$options['grouping']][] = conditional_fields_evaluate_dependency('view', $items, $options);
}
}