-
Notifications
You must be signed in to change notification settings - Fork 1
/
localgov_elections.module
929 lines (839 loc) · 29.8 KB
/
localgov_elections.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
<?php
/**
* @file
* LocalGov Elections Reporting module file.
*/
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\views\Plugin\views\cache\CachePluginBase;
use Drupal\views\ViewExecutable;
/**
* Implements hook_theme().
*/
function localgov_elections_theme($existing, $type, $theme, $path) {
return [
'ward_result' => [
'variables' => [
'chart' => NULL,
'result' => NULL,
'analysis' => NULL,
],
],
'election_menu' => [
'variables' => [
'links' => NULL,
],
],
'localgov_elections_results_heading' => [
'variables' => [
'election_type' => '',
],
],
];
}
/**
* Implements hook_entity_presave().
*/
function localgov_elections_entity_presave(EntityInterface $entity) {
if ($entity->getEntityTypeId() == 'node' && $entity->getType() == 'localgov_area_vote') {
// Trigger when division vote saved to update the winning candidate only
// if 'Hold or Gain' stated.
$candidates = $entity->get('localgov_election_candidates');
$finalised = $entity->localgov_election_votes_final?->value;
if ($finalised == 1) {
$results = [];
// Iterate through candidates and store their votes.
foreach ($candidates->referencedEntities() as $candidate) {
$votes = $candidate->get('localgov_election_votes')->value;
$cand_id = $candidate->id();
$results[] = ['cand' => $cand_id, 'votes' => $votes];
}
if ($results) {
// Sort by Vote results into descending order.
$votes = array_column($results, 'votes');
$sorted = array_multisort($votes, SORT_DESC, $results);
// If sort worked, pull 1st result and update localgov_election_winner.
if ($sorted) {
if (isset($results[0])) {
$winner = $results[0]['cand'];
}
// Only update localgov_election_winner if there
// is a result (ie, one or
// more candidates standing and Hold/Gain set.
if (isset($winner)) {
$candidate = Paragraph::load($winner);
$entity->localgov_election_winner = $candidate;
}
}
}
}
else {
if ($original_entity = $entity->original) {
if ($original_entity?->localgov_election_votes_final?->value == 1) {
$entity->localgov_election_winner = NULL;
}
}
}
}
if ($entity->getEntityTypeId() == 'paragraph' && $entity->getType() == 'localgov_election_candidate') {
// We are referencing two instances of the same paragraph, the winning
// localgov_election_candidate. When 'create new revision' is checked, this
// seems to attempt to create two new revisions and the original entity
// reference from the candidates field is broken.
// To mitifate this we can force the paragraph NOT to create a new revision.
$entity->setNewRevision(FALSE);
}
}
/**
* Generate aliases for an election node.
*
* @param Drupal\node\NodeInterface $entity
* The election node.
*
* @return void
* Returns nothing.
*/
function localgov_elections_generate_election_aliases(NodeInterface $entity) {
if ($entity->getType() == 'localgov_election') {
// Check if the parent election node is aliased.
if ($alias = localgov_elections_get_entity_alias('node', $entity->id())) {
// Map page.
$map_page_url = Url::fromRoute('view.localgov_election_electoral_map.page_1', ['node' => $entity->id()]);
$map_path = $map_page_url->toString();
if (!(localgov_elections_alias_exists($map_path))) {
$new_alias = $alias . '/electoral-map';
localgov_elections_create_alias($map_path, $new_alias);
}
// Results timeline.
$results_page_url = Url::fromRoute('view.localgov_election_results_timeline.page_1',
[
'node' => $entity->id(),
]
);
$results_path = $results_page_url->toString();
if (!(localgov_elections_alias_exists($results_path))) {
$new_alias = $alias . '/results';
localgov_elections_create_alias($results_path, $new_alias);
}
// Vote share.
$share_page_url = Url::fromRoute('view.localgov_election_results_vote.page_1',
[
'node' => $entity->id(),
]
);
$share_path = $share_page_url->toString();
if (!(localgov_elections_alias_exists($share_path))) {
$new_alias = $alias . '/share';
localgov_elections_create_alias($share_path, $new_alias);
}
// Electoral candidates.
$candidate_page_url = Url::fromRoute('view.localgov_electoral_candidates.page_1',
[
'node' => $entity->id(),
]
);
$candidate_path = $candidate_page_url->toString();
if (!(localgov_elections_alias_exists($candidate_path))) {
$new_alias = $alias . '/candidates';
localgov_elections_create_alias($candidate_path, $new_alias);
}
}
}
}
/**
* Implements hook_ENTITY_TYPE_update().
*/
function localgov_elections_path_alias_update(EntityInterface $entity) {
/** @var \Drupal\path_alias\Entity\PathAlias $original_entity */
$original_entity = $entity->original;
/** @var \Drupal\path_alias\Entity\PathAlias entity */
if ($entity->getAlias() !== $original_entity->getAlias()) {
$path = $entity->getPath();
$url = Url::fromUserInput($path);
$params = $url->getRouteParameters();
if (is_array($params) && array_key_exists('node', $params)) {
if ($node = Node::load($params['node'])) {
if ($node->bundle() == "localgov_election") {
$cannonical_route = '/' . $node->toUrl()->getInternalPath();
if ($path == $cannonical_route) {
localgov_elections_delete_election_aliases($node);
localgov_elections_generate_election_aliases($node);
}
}
}
}
}
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function localgov_elections_path_alias_insert(EntityInterface $entity) {
$path = $entity->getPath();
$url = Url::fromUserInput($path);
$params = $url->getRouteParameters();
if (is_array($params) && array_key_exists('node', $params)) {
if ($node = Node::load($params['node'])) {
if ($node->bundle() == "localgov_election") {
$cannonical_route = '/' . $node->toUrl()->getInternalPath();
if ($path == $cannonical_route) {
localgov_elections_generate_election_aliases($node);
}
}
}
}
}
/**
* Function to delete an alias by the alias path.
*
* @param string $alias
* The alias path (e.g., '/my-custom-alias').
*/
function localgov_elections_delete_alias_by_alias($alias) {
$storage = \Drupal::entityTypeManager()->getStorage('path_alias');
$alias_entities = $storage->loadByProperties(['alias' => $alias]);
if ($alias_entities) {
try {
if ($alias = current($alias_entities)) {
$alias->delete();
}
}
catch (EntityStorageException $exception) {
\Drupal::logger('localgov_elections')->error($exception->getMessage());
}
}
}
/**
* Delete all election sub-page alias.
*
* @return void
* Returns nothing.
*/
function localgov_elections_delete_election_aliases(NodeInterface $election) {
// Map page.
$map_page_url = Url::fromRoute('view.localgov_election_electoral_map.page_1', ['node' => $election->id()]);
$map_path = $map_page_url->toString();
localgov_elections_delete_alias_by_alias($map_path);
// Results timeline.
$results_page_url = Url::fromRoute('view.localgov_election_results_timeline.page_1',
[
'node' => $election->id(),
]
);
$results_path = $results_page_url->toString();
localgov_elections_delete_alias_by_alias($results_path);
// Electoral candidates.
$candidate_page_url = Url::fromRoute('view.localgov_electoral_candidates.page_1',
[
'node' => $election->id(),
]
);
$candidate_path = $candidate_page_url->toString();
localgov_elections_delete_alias_by_alias($candidate_path);
// Vote share.
$share_page_url = Url::fromRoute('view.localgov_election_results_vote.page_1',
[
'node' => $election->id(),
]
);
$share_path = $share_page_url->toString();
localgov_elections_delete_alias_by_alias($share_path);
}
/**
* Check if an alias exists.
*
* @param string $alias
* The alias.
*
* @return bool
* True if alias exists else false.
*/
function localgov_elections_alias_exists(string $alias) {
// Get the alias manager service.
$alias_manager = \Drupal::service('path_alias.manager');
// Get the internal path for the given alias.
$internal_path = $alias_manager->getPathByAlias($alias);
// Check if the internal path is different from the alias.
// If different, it means the alias maps to an internal path.
return $internal_path !== $alias;
}
/**
* Gets the alias for an entity.
*
* @param string $entity_type
* The entity bundle.
* @param int|string $entity_id
* The entity id.
*
* @return string|null
* Returns alias or null.
*/
function localgov_elections_get_entity_alias(string $entity_type, int|string $entity_id) {
// Load the entity.
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id);
if ($entity instanceof NodeInterface) {
// Get the URL of the entity.
$url = $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
// Get the alias manager service.
$alias_manager = \Drupal::service('path_alias.manager');
// Get the alias for the entity URL.
return $alias_manager->getAliasByPath(parse_url($url, PHP_URL_PATH));
}
else {
return NULL;
}
}
/**
* Creates an alias.
*
* @param string $path
* The internal path.
* @param string $alias
* The new alias.
*
* @return bool
* Returns true if operation was successful. Otherwise, returns false.
*/
function localgov_elections_create_alias(string $path, string $alias): bool {
$path_alias = \Drupal::entityTypeManager()->getStorage('path_alias')->create([
'path' => $path,
'alias' => $alias,
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
]);
try {
$path_alias->save();
return TRUE;
}
catch (EntityStorageException $exception) {
\Drupal::logger('localgov_elections')->error($exception->getMessage());
return FALSE;
}
}
/**
* Implements hook_entity_predelete().
*/
function localgov_elections_entity_predelete(EntityInterface $entity) {
// Triggered just before an Election node is deleted.
if ($entity->getEntityTypeId() == 'node' && $entity->getType() == 'localgov_election') {
$election_id = $entity->id();
$election_title = $entity->getTitle();
// Delete all Division Vote entities referencing this election.
$deleted = 0;
$areas_query = Drupal::entityTypeManager()->getStorage('node')->getQuery();
$areas_query->condition('type', 'localgov_area_vote');
$areas_query->condition('status', 1);
$areas_query->condition('localgov_election', $election_id);
$areas_query->accessCheck(FALSE);
$areas = $areas_query->execute();
if ($areas) {
$areas = Drupal::entityTypeManager()->getStorage('node')->loadMultiple($areas);
foreach ($areas as $area) {
try {
$area->delete();
$deleted++;
}
catch (EntityStorageException $exception) {
\Drupal::logger('localgov_election')->error("Could not delete area with id " . $area->id());
}
}
}
\Drupal::logger('localgov_election')
->notice("Election " . $election_title . " (ID " . $election_id . ") was deleted. " . $deleted . " Division Votes deleted");
Drupal::messenger()
->addStatus($deleted . ' Division Votes deleted from system');
}
}
/**
* Implements hook_views_data_alter().
*/
function localgov_elections_views_data_alter(array &$data) {
$data['node']['ward_majority'] = [
'title' => t('Ward majority'),
'field' => [
'title' => t('Ward majority'),
'help' => t('Calculates the difference between number of votes of first and second results in an electoral area.'),
'id' => 'ward_majority',
],
];
$data['node']['ward_party'] = [
'title' => t('Ward winning party'),
'field' => [
'title' => t('Ward winning party'),
'help' => t('Winning party in an electoral area for an election.'),
'id' => 'ward_party',
],
];
$data['node']['election_turnout'] = [
'title' => t('Election turnout'),
'field' => [
'title' => t('Election turnout'),
'help' => t('Sums all votes cast with all candidates in election plus all spoiled votes.'),
'id' => 'election_turnout',
],
];
$data['node']['election_majority'] = [
'title' => t('Election majority'),
'field' => [
'title' => t('Election majority'),
'help' => t('Counts number of seats in election, divides by 2 and adds 1 to calculate majority.'),
'id' => 'election_majority',
],
];
$data['node']['ward_candidates'] = [
'title' => t('Candidate results for a ward'),
'field' => [
'title' => t('Candidate results for a ward'),
'help' => t('Produces all candidates results for each area/ward in a specific election.'),
'id' => 'ward_candidates',
],
];
$data['node']['ward_candidates_candidate'] = [
'title' => t('Candidate result for a ward'),
'field' => [
'title' => t('Candidate result for a ward'),
'help' => t('Produces all candidates results for each area/ward in a specific election.'),
'id' => 'ward_candidates_candidate',
],
];
$data['node']['ward_candidates_party'] = [
'title' => t('Candidate party result for a ward'),
'field' => [
'title' => t('Candidate party result for a ward'),
'help' => t('Produces all candidates results for each area/ward in a specific election.'),
'id' => 'ward_candidates_party',
],
];
$data['node']['ward_candidates_votes'] = [
'title' => t('Candidate votes result for a ward'),
'field' => [
'title' => t('Candidate votes result for a ward'),
'help' => t('Produces all candidates results for each area/ward in a specific election.'),
'id' => 'ward_candidates_votes',
],
];
$data['taxonomy_term_data']['election_share'] = [
'title' => t('Percentage of election share'),
'field' => [
'title' => t('Percentage of election share'),
'help' => t('List percentage of election share for each party in a specific election.'),
'id' => 'election_share',
],
];
$data['taxonomy_term_data']['election_seats_party'] = [
'title' => t('Election seat wins'),
'field' => [
'title' => t('Election seat wins'),
'help' => t('Sums all seats won by party in this election.'),
'id' => 'election_seats_party',
],
'sort' => [
'id' => 'standard',
],
'filter' => [
'id' => 'standard',
],
];
$data['views']['area_election_results_heading'] = [
'title' => t('Election results heading'),
'help' => t('Sets dynamic heading depending on election type.'),
'area' => [
'id' => 'localgov_elections_results_heading',
],
];
}
/**
* Implements hook_menu_local_tasks_alter().
*/
function localgov_elections_menu_local_tasks_alter(&$data, $route_name) {
// Hide 'Results timelines' tab from all nodes except 'Election' content
// types.
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof NodeInterface) {
// You can get nid and anything else you need from the node object.
$type = $node->getType();
if ($type != 'localgov_election') {
unset($data['tabs'][0]['views_view:view.localgov_election_results_timeline.page_1']);
unset($data['tabs'][0]['views_view:view.localgov_election_results_vote.page_1']);
unset($data['tabs'][0]['views_view:view.localgov_electoral_candidates.page_1']);
unset($data['tabs'][0]['views_view:view.localgov_election_electoral_map.page_1']);
}
else {
$appropriate_fetch_routes = [
"entity.node.canonical",
"entity.node.edit_form",
"entity.node.version_history",
"entity.node.delete_form",
"entity.node.preview_link_generate",
];
// Add the "add area" button to the local tasks if user has permission.
$can_add_areas = Drupal::currentUser()->hasPermission('can fetch boundaries');
if ($can_add_areas && in_array($route_name, $appropriate_fetch_routes, TRUE)) {
$data['tabs'][0]['boundary_fetch'] = [
'#theme' => 'menu_local_task',
'#weight' => 100,
'#link' => [
'title' => t('Add areas'),
'url' => Url::fromRoute('localgov_elections.boundary_fetch',
['node' => $node->id()]),
],
];
}
}
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function localgov_elections_preprocess_node(&$variables) {
$node = $variables['elements']['#node'];
if ($node->bundle() == 'localgov_area_vote') {
$finalised = $node->localgov_election_votes_final?->value;
$not_contested = $node->get('localgov_election_no_contest')?->value;
if ($finalised == 1) {
if ($not_contested) {
$variables['content']['results'] = [
'#children' => t('This seat was not contested.'),
];
}
else {
$block_manager = \Drupal::service('plugin.manager.block');
$plugin_block = $block_manager->createInstance('analysis_block', []);
$analysis = $plugin_block->build();
// Add the cache tags/contexts.
\Drupal::service('renderer')
->addCacheableDependency($analysis, $plugin_block);
$variables['content']['results'] = [
'#theme' => 'ward_result',
'#chart' => [
'#type' => 'view',
'#name' => 'localgov_election_area_results',
'#arguments' => [$node->id()],
],
'#result' => [
'#type' => 'view',
'#name' => 'localgov_election_area_results',
'#display_id' => 'block_2',
'#arguments' => [$node->id()],
],
'#analysis' => $analysis,
'#attached' => ['library' => ['localgov_elections/party_colours']],
];
}
}
else {
$variables['content']['results'] = [
'#children' => t('No results have been declared yet.'),
];
}
}
elseif ($node->bundle() == 'localgov_election') {
if ($node->hasField('localgov_election_majority')) {
$display_majority = $node->get("localgov_election_majority")?->value;
}
else {
$display_majority = FALSE;
}
$variables['content']['results_fieldset'] = [
'#type' => 'container',
'#prefix' => '<div class="county-summary"> <div class="county-summary__header" ><h2>' . t("Seats won") . '</h2></div>',
'#suffix' => '</div>',
];
$variables['content']['results_fieldset']['sub_heading'] = [
'#type' => 'container',
'#prefix' => '<div class="county-summary__subheading">',
'#suffix' => '</div>',
];
$variables['content']['results_fieldset']['sub_heading']['election_results_electorate'] = [
'#type' => 'view',
'#name' => 'localgov_election_results',
'#display_id' => 'block_1',
'#arguments' => [$node->id()],
];
$variables['content']['results_fieldset']['sub_heading']['election_results_turnout'] = [
'#type' => 'view',
'#name' => 'localgov_election_results',
'#display_id' => 'block_2',
'#arguments' => [$node->id()],
];
$variables['content']['results_fieldset']['election_results_by_party'] = [
'#type' => 'view',
'#name' => 'localgov_election_results_via_parties',
'#display_id' => 'block_1',
'#arguments' => [$node->id()],
];
if ($display_majority) {
$variables['content']['results_fieldset']['election_results_majority'] = [
'#type' => 'view',
'#name' => 'localgov_election_results',
'#display_id' => 'block_5',
'#arguments' => [$node->id()],
];
}
$variables['content']['election_results_summary_table'] = [
'#type' => 'view',
'#name' => 'localgov_election_results',
'#display_id' => 'block_3',
'#arguments' => [$node->id()],
];
}
}
/**
* Implements hook_views_pre_render().
*/
function localgov_elections_views_pre_render(ViewExecutable $view) {
if ($view->id() == 'localgov_electoral_candidates') {
$view->element['#attached']['library'][] = 'localgov_elections/electoral_candidates_view';
}
if ($view->id() == 'localgov_election_results_timeline') {
$view->element['#attached']['drupalSettings']['localgov_elections']['parties'] = _localgov_elections_party_colours();
$view->element['#attached']['library'][] = 'localgov_elections/results_timeline';
$view->element['#attached']['library'][] = 'localgov_elections/party_colours';
}
if ($view->id() == 'localgov_election_results_vote') {
$view->element['#attached']['library'][] = 'localgov_elections/results_share';
}
if ($view->id() == 'localgov_election_results') {
if ($view->getDisplay()->display['id'] == 'block_3') {
$view->element['#attached']['library'][] = 'localgov_elections/party_colours';
}
}
}
/**
* Implements hook_views_post_render().
*/
function localgov_elections_views_post_render(ViewExecutable $view, array &$output, CachePluginBase $cache) {
if ($view->id() == 'localgov_election_results_via_parties') {
// Remove rows from rendered output where party is not standing in election
// (these rows will be NULL)
$rows = $output["#rows"]["block_1__election_seats_party_0"]["#data"];
$idx = 0;
$removed = 0;
foreach ($rows as $row) {
if (!isset($row)) {
array_splice($output["#rows"]["block_1__election_seats_party_0"]["#data"], $idx - $removed, 1);
array_splice($output["#rows"]["xaxis"]["#labels"], $idx - $removed, 1);
if (isset($output["#rows"]["block_1__election_seats_party_0"]["#mapped_data"])) {
array_splice($output["#rows"]["block_1__election_seats_party_0"]["#mapped_data"], $idx - $removed, 1);
}
$removed++;
}
$idx++;
}
}
}
/**
* Implements hook_chart_definition_CHART_ID_alter().
*/
function localgov_elections_chart_definition_localgov_election_results_via_parties_block_1_alter(array &$definition, array $element, $chart_id) {
$definition['yAxis'][0]['allowDecimals'] = FALSE;
if (!empty($definition['series'][0]['data'])) {
foreach ($definition['series'][0]['data'] as &$entry) {
if ($entry == NULL) {
$entry = 0;
}
}
}
if ($majority = _localgov_elections_calc_majority()) {
$max = 0;
if (!empty($definition['series'][0]['data'])) {
$max = max($definition['series'][0]['data']);
}
if ($majority > $max) {
$max = $majority;
}
// Allow hiding of plot line.
if ($election = Drupal::request()->get('node')) {
if ($election->hasField("localgov_election_majority")) {
$display_majority_details = $election->get("localgov_election_majority")?->value;
}
else {
$display_majority_details = FALSE;
}
if ($display_majority_details) {
$definition['yAxis'][0]['plotLines'] = [
[
'color' => '#8c8a8a',
'width' => 6,
'value' => $majority,
'dashStyle' => 'LongDash',
],
];
}
$definition['yAxis'][0]['max'] = $max + 4;
}
}
}
/**
* Implements hook_page_attachments_alter().
*/
function localgov_elections_page_attachments(array &$attachments) {
$route = Drupal::routeMatch();
if ($node = $route->getParameter('node')) {
if ($node != NULL && $node instanceof NodeInterface) {
if ($node->bundle() == 'localgov_election') {
$attachments['#attached']['library'][] = 'localgov_elections/election';
}
elseif ($node->bundle() == 'localgov_area_vote') {
$attachments['#attached']['library'][] = 'localgov_elections/division_results';
}
}
}
}
/**
* Implements hook_chart_alter().
*/
function localgov_elections_chart_alter(array &$element, $chart_id) {
$config_obj = \Drupal::configFactory()->getEditable('views.view.localgov_election_results_via_parties');
$chart_library = $config_obj->get('display.default.display_options.style.options.chart_settings.library');
if ($chart_library == 'highcharts') {
$element['#attached']['library'][] = 'localgov_elections/highcharts_overrides';
}
elseif ($chart_library == 'chartjs') {
$element['#attached']['library'][] = 'localgov_elections/chartjs_overrides';
}
$element['#attached']['drupalSettings']['localgov_elections']['parties'] = _localgov_elections_party_colours();
}
/**
* Calculates majority.
*/
function _localgov_elections_calc_majority() {
$node = \Drupal::routeMatch()->getParameter('node');
$majority = NULL;
if ($node instanceof NodeInterface) {
// Arg must be NID of an Election content type.
if ($node->getType() == 'localgov_election') {
$election = $node->id();
// Find all 'Election Area' nodes referencing this election.
$query = \Drupal::entityQuery('node')
->condition('type', 'localgov_area_vote')
->condition('localgov_election', $election);
$query->accessCheck(FALSE);
$num_rows = $query->count()->execute();
$majority = (floor($num_rows / 2)) + 1;
return (int) $majority;
}
}
}
/**
* Gets party colours.
*/
function _localgov_elections_party_colours() {
$results = [];
$terms = Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadByProperties(['vid' => 'localgov_party']);
if ($terms && is_array($terms)) {
foreach ($terms as $term) {
$colour = $term->localgov_election_party_colour?->first()?->color;
$abbr = $term->localgov_election_abbreviation?->value;
if ($colour && $abbr) {
$abbr = strtolower($abbr);
$results[$abbr] = [
'text-colour' => $term->localgov_election_text_colour?->first()?->color,
'colour' => $colour,
'full_name' => $term->name?->value,
'abbr' => $abbr,
];
}
}
}
return $results;
}
/**
* Implements hook_preprocess_HOOK().
*/
function localgov_elections_preprocess_election_menu(&$variables) {
$attributes = new Attribute();
$attributes->setAttribute('id', 'election-menu');
$variables['attributes'] = $attributes;
$current = Drupal::routeMatch()->getRouteName();
foreach ($variables['links'] as $link) {
/** @var Drupal\Core\Link $url */
$url = $link['link'];
if ($url->getUrl()->getRouteName() == $current) {
if ($node = Drupal::routeMatch()->getParameter('node')) {
if ($node instanceof NodeInterface) {
if ($node->bundle() == 'localgov_area_vote') {
return;
}
}
}
$link['attributes']->addClass('active');
}
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function localgov_elections_preprocess_block(&$variables) {
if ($variables['base_plugin_id'] == 'localgov_elections_electionmenu') {
$variables['attributes']['class'][] = 'election-menu-block';
}
// We want to set the page title to be the name of the area,
// But still allow a title like "Election 2024 - Oxford East" in the node
// edit form, so it's easier to find on the /admin/content page.
$node = \Drupal::request()->attributes->get('node');
if ($node && $node instanceof NodeInterface) {
if ($node->bundle() == 'localgov_area_vote') {
if ($variables['base_plugin_id'] == 'localgov_page_header_block') {
$variables['content'][0]['#title'] = $node->get('localgov_election_area_name')->value;
}
}
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function localgov_elections_form_node_localgov_area_vote_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#validate'][] = "localgov_elections_area_vote_form_validation";
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function localgov_elections_form_taxonomy_term_localgov_party_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if (isset($form["name"]["widget"][0]['value'])) {
$form["name"]["widget"][0]['value']["#description"] = t("The party name. Do not enter brackets in the party nameph.");
}
}
/**
* Validation function for area vote node forms.
*/
function localgov_elections_area_vote_form_validation($form, FormStateInterface $form_state) {
$contested = $form_state->getValue('localgov_election_no_contest')['value'];
$candidates = $form_state->getValue('localgov_election_candidates');
$candidate_keys = array_filter(array_keys($candidates), function ($key) {
return is_int($key);
});
if ($contested && count($candidate_keys) > 1) {
$form_state->setErrorByName('localgov_election_candidates', t("If the seat is <b>not</b> contested there should only be one candidate."));
}
if ($contested) {
$storage = $form_state->get('field_storage');
if (isset($storage['#parents']['#fields']['localgov_election_candidates'])) {
$candidates = $storage['#parents']['#fields']['localgov_election_candidates'];
}
if (count($candidate_keys) > 0) {
$candidates = $candidates['paragraphs'];
foreach ($candidates['paragraphs'] as $entry) {
/** @var \Drupal\paragraphs\Entity\Paragraph $entry */
if (isset($entry['entity'])) {
$entry = $entry['entity'];
if (!$entry->get('localgov_election_votes')->isEmpty()) {
$form_state->setErrorByName('localgov_election_candidates', t("If the seat is not contested there should be no votes registered with a candidate. The vote field should be empty."));
}
}
}
}
}
// Should not be able to finalise votes without having at least one candidate.
$finalised = $form_state->getValue('localgov_election_votes_final')['value'];
if ($finalised && count($candidate_keys) < 1) {
$form_state->setErrorByName('localgov_election_candidates', t("You cannot finalise the votes with no candidates"));
}
}