forked from esmero/webform_strawberryfield
-
Notifications
You must be signed in to change notification settings - Fork 1
/
webform_strawberryfield.module
714 lines (644 loc) · 25.3 KB
/
webform_strawberryfield.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
<?php
/**
* @file
* Contains strawberryfield.module.
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\webform\WebformSubmissionForm;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\file\Entity\File;
use Drupal\format_strawberryfield\Tools\IiifHelper;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\image\Entity\ImageStyle;
use Drupal\webform\WebformSubmissionInterface;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Entity\EntityInterface;
use Drupal\webform_strawberryfield\Plugin\WebformHandler\strawberryFieldharvester;
use Ramsey\Uuid\Uuid;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Drupal\Core\Render\Element;
/**
* Alters a webform to help with embbeding in a node crud context.
*
* Implements hook_form_alter()
*
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form_id
*/
function webform_strawberryfield_form_alter(&$form,FormStateInterface $form_state, $form_id) {
//@TODO if wizard make elements of progress-marker direct links to that wizard page
if (strpos($form_id, 'webform_') === FALSE || strpos($form_id, 'node_') === 0) {
return;
}
/** @var \Drupal\webform\WebformSubmissionForm $submission_form */
$submission_form = $form_state->getFormObject();
$form['#attached']['library'][] = 'webform_strawberryfield/webform_strawberryfield.nodeactions.toggle';
$form['#attached']['library'][] = 'webform_strawberryfield/webform_strawberryfield.nodeactions.cameraroll';
if (strpos($form_id, 'webform_submission') === 0
&& $submission_form instanceof WebformSubmissionForm) {
// @TODO check if we should use instead \Drupal\webform\WebformSubmissionForm::isAjax
// I'm not totally convinced since we could be "ajaxifying" a webform here
// that was not set as such in it's saved settings.
/** @var \Drupal\webform\Entity\WebformSubmission $webform_submission */
$webform_submission = $submission_form->getEntity();
$isWidget = FALSE;
// @see \Drupal\webform_strawberryfield\Controller @var $data_defaults
if (array_key_exists('strawberry_field_widget_state_id', $webform_submission->getData())) {
$isWidget = TRUE;
// Since we are just using webform to act as a widget, we tell workspace module all is safe here.
//@TODO this is giving issues. Workspace can not serialize Webformsubmission form
// Probably related to some dependency injection that includes and open DB reference
//$form_state->set('workspace_safe', true);
}
if (!$isWidget ) {
return;
}
if (isset($form['actions']['reset'])) {
$form['actions']['reset']['#submit'] = ['webform_strawberryfield_widget_reset'];
}
/* @TODO make this a valid switch
// We should not make close object available if inline
// add a close model button
$query = \Drupal::request()->query->all();
$is_ajax = (!empty($query['ajax_form'])) ? TRUE : FALSE;
$webform_close_controller_url = Url::fromRoute(
'webform_strawberryfield.close_modal_webform');
if ($is_ajax) {
$form['actions']['closemodal'] = [
'#type' => 'link',
'#title' => t('Close Window'),
'#url' => $webform_close_controller_url,
'#attributes' => [
'class' => [
'use-ajax',
'button',
],
],
'#weight' => 100,
];
}*/
if ($form_state->get('current_page') === 'webform_preview') {
/** @var \Drupal\webform\WebformSubmissionForm $submission_form */
$submission_form = $form_state->getFormObject();
foreach ($form['elements'] as $key => &$element) {
if (isset($element['#type']) && ($element['#type'] == 'webform_wizard_page')) {
$form['actions']['edit_wizard_page_'.$key][] = [
'#type' => 'submit',
'#value' => 'edit '.$element['#title'],
'#submit' => [
'webform_strawberryfield_go_to_page',
],
'#attributes' => [
'class' => ['js-webform-novalidate'],
],
'#ajax' => [
'callback' => [$submission_form, 'submitAjaxForm'],
'event' => 'click',
'disable-refocus' => true,
'effect' => 'fade',
'speed' => 1000,
'progress' => [
'type' => 'throbber',
'message' => '',
]
],
'#page' => $key,
];
}
}
}
}
}
/**
* Custom Jump-to-a-webform-page wizard callback.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function webform_strawberryfield_go_to_page(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\webform\WebformSubmissionForm $submission_form */
$submission_form = $form_state->getFormObject();
/* @TODO: Use this valuable page number for something.
$trigger = $form_state->getTriggeringElement();
$current_page = $form_state->get('current_page');
$wizard_page_id = $trigger['#page'];
*/
// Submit using Mr. Wizard of WebOz.
$submission_form->gotoPage($form, $form_state);
}
/**
* Custom Reset Webform callback.
*
* This callback only resets to initial values but never resets whole state.
* Needed to avoid our Webform widget to disconnect from its temp storage.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function webform_strawberryfield_widget_reset(array &$form, FormStateInterface $form_state) {
/** @var \Drupal\webform\WebformSubmissionForm $submission_form */
$submission_form = $form_state->getFormObject();
/** @var \Drupal\webform\Entity\WebformSubmission $webform_submission */
$webform_submission = $submission_form->getEntity();
/** @var \Drupal\webform\WebformInterface $webform */
$webform = $webform_submission->getWebform();
// @TODO investigate how to use \Drupal\webform\WebformSubmissionInterface::getOriginalData
// Instead of copy, store, restore way i'm applying here.
// Iterate over our own passed from field data
$keeparound = array();
foreach ($webform_submission->getData() as $keys => $data) {
if (strpos($keys, 'strawberry_field') !== FALSE) {
$keeparound[$keys] = $data;
}
}
// We should always have at least 3 keys
// "strawberry_field_widget_state_id"
// "strawberry_field_widget_source_entity_uuid"
// "strawberry_field_stored_values"
// @see \Drupal\webform_strawberryfield\Controller @var $data_defaults
$restored_data = array();
if (!empty($keeparound)) {
// This brings stored data to the outside so webform can see it again
$restored_data = $keeparound + $keeparound['strawberry_field_stored_values'];
}
// Call the original reset
$submission_form->reset($form, $form_state);
// Give submission our original values!
$form_state->getFormObject()->getEntity()->setData($restored_data);
}
/**
* Totally cosmetic hide/display main entity save button when in webform mode.
*
* Implements hook_FORM_ID_form_alter()
*
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form_id
*/
function webform_strawberryfield_form_node_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
//$node = $form_state->getFormObject()->getEntity();
// Means this form has a webform widget
if (isset($form_state->getStorage()['webform_machine_name'])){
$input = $form_state->getUserInput();
if ((!isset($input['_triggering_element_name'])) || (isset($input['_triggering_element_value']) && $input['_triggering_element_value'] != 'Save Metadata')) {
foreach ($form['actions'] as $key => &$buttons) {
if ($key == 'delete') {
$buttons['#access'] = FALSE;
}
elseif ($key == 'preview') {
$buttons['#access'] = FALSE;
}
}
}
}
}
/**
* Implements hook_theme().
*/
function webform_strawberryfield_theme() {
$info = [
'webform_metadata_nominatim' => [
'render element' => 'element',
],
'webform_metadata_panoramatour' => [
'render element' => 'element',
],
'webform_inline_fieldwidget_form' => [
'variables' => [],
'template' => 'webform_strawberryfield-inlinefieldwidget',
'base hook' => 'webform'
],
'webform_handler_strawberryfieldharvester_summary' => [
'variables' => ['settings' => NULL, 'handler' => []],
'template' => 'webform-handler-strawberryfield-webform-handler-summary',
]
];
return $info;
}
/**
* Prepares variables for location composite element templates.
*
* Default template: webform-metadata-nominatim.html.twig.
*
* @param array $variables
* An associative array containing:
* - element: An associative array containing the properties of the element.
*/
function template_preprocess_webform_metadata_nominatim(array &$variables) {
$variables['content'] = $variables['element'];
unset($variables['content']['value']);
unset($variables['content']['nominatim']);
unset($variables['content']['feature']);
$variables['fetchbox'] = $variables['element']['value'];
$variables['fetchbox_button'] = $variables['element']['nominatim'];
$variables['fetchbox_table'] = $variables['element']['feature'];
}
/**
* Prepares variables for location composite element templates.
*
* Default template: webform-metadata-panoramatour.html.twig.
*
* @param array $variables
* An associative array containing:
* - element: An associative array containing the properties of the element.
*/
function template_preprocess_webform_metadata_panoramatour(array &$variables) {
$variables['content'] = $variables['element'];
}
/**
* Implements hook_theme_suggestions_HOOK_alter() for webforms.
*
* @param $suggestions
* @param array $variables
*/
function webform_strawberryfield_theme_suggestions_webform_alter(&$suggestions, array $variables) {
// Add our own webform suggestion based on a given data attribute set by
// \Drupal\webform_strawberryfield\Element\WebformWithOverride::preRenderWebformElement
$element = $variables['element'];
// This is in particular for 'webform_inline_fieldwidget' element
// This is not triggering when the form has validation errors
// WebformWithOverride::preRenderWebformElement is not able to set the attribute
// Probably we need a better way
if (isset($element['#attributes']['data-webform-inline-fieldwidget'])) {
$suggestions = ['webform_inline_fieldwidget_form', 'webform_inline_fieldwidget_form__' . $element['#webform_id']];
}
}
/**
* Implements hook_preprocess_HOOK()
*
* @see template_preprocess_webform_element_image_file()
*
* @param array $variables
* An associative array containing the following key:
* - element: The webform element.
* - value: The content for the element.
* - options Associative array of options for element.
* - file: The element's File object.
* - style_name: An image style name.
* - format: Image formatting (link or modal)
*/
function webform_strawberryfield_preprocess_webform_element_image_file(
array &$variables
) {
if (!empty($variables['file'])) {
// TODO do we need a setting for this?
$max_width = 320;
//@TODO this is quite a copy of what Format_strawberry does. We should
// Move all that logic to helper methods into \Drupal\format_strawberryfield\Tools\IiifHelper
/** @var \Drupal\file\FileInterface $file */
$file = $variables['file'];
$variables['image']['#type'] = 'container';
unset($variables['image']['#theme']);
$variables['image']['singleimage']['#attributes'] = $variables['image']['#attributes'];
unset($variables['image']['#uri']);
unset($variables['image']['#attributes']);
$style_name = $variables['style_name'];
$format = $variables['format'];
$uri = $file->getFileUri();
$filename = $file->getFilename();
$fileextension = pathinfo(
$filename,
PATHINFO_EXTENSION
);
$url = Url::fromUri(file_create_url($uri));
if (!$file->isTemporary()) {
$iiifserversettings = \Drupal::config(
'format_strawberryfield.iiif_settings'
);
$iiifhelper = new IiifHelper(
$iiifserversettings->get('pub_server_url'),
$iiifserversettings->get('int_server_url')
);
// Deal with Drupal 8.8.x only now
$iiifidentifier = urlencode(
\Drupal::service('stream_wrapper_manager')->getTarget(
$file->getFileUri()
)
);
if ($iiifidentifier == NULL || empty($iiifidentifier)) {
// Nothing to do, lets leave this untouched.
return;
}
$iiifpublicinfojson = $iiifhelper->getPublicInfoJson($iiifidentifier);
$iiifsizes = $iiifhelper->getImageSizes($iiifidentifier);
if (!$iiifsizes) {
$message = t(
'We could not fetch Image sizes from IIIF @url',
[
'@url' => $iiifpublicinfojson,
]
);
\Drupal::logger('webform_strawberryfield')->warning($message);
// Nothing to do, lets leave this untouched.
return;
}
else {
//@see \template_preprocess_image for further theme_image() attributes.
// Look. This one uses the public accesible base URL. That is how world works.
$iiifserverthumb = "{$iiifserversettings->get('pub_server_url')}/{$iiifidentifier}" . "/full/{$max_width},/0/default.jpg";
$url = $iiifserverthumb;
}
}
else {
// Its a temporary file, just uploaded, IIIF can not see it yet
$route_parameters = [
'uuid' => $file->uuid(),
'format' => 'default.' . $fileextension,
];
$publicurl = Url::fromRoute(
'format_strawberryfield.tempiiifbinary',
$route_parameters
);
$url = $publicurl->toString();
// Extract EXIF and show it to the user!
$scheme = \Drupal::service('stream_wrapper_manager')->getScheme($uri);
$templocation = NULL;
// If the file isn't stored locally make a temporary copy.
if (!isset(
\Drupal::service('stream_wrapper_manager')
->getWrappers(StreamWrapperInterface::LOCAL)[$scheme]
)) {
// Local stream.
$cache_key = md5($uri);
$templocation = \Drupal::service('file_system')->copy(
$uri,
'temporary://sbr_' . $cache_key . '.' . $fileextension,
FileSystemInterface::EXISTS_REPLACE
);
$templocation = \Drupal::service('file_system')->realpath(
$templocation
);
}
else {
$templocation = \Drupal::service('file_system')->realpath(
$file->getFileUri()
);
}
if ($templocation) {
$result = exec(
'exiftool -json -q -a -gps:all -Common "-gps*" -xmp:all -ImageWidth -ImageHeight -Canon -Nikon-AllDates -pdf:all -ee -MIMEType ' . escapeshellarg(
$templocation
),
$output,
$status
);
if ($status == 0) {
$more_str = implode('', $output);
$json = json_decode($more_str, TRUE);
$json_error = json_last_error();
//This will end with all data in an [0] index.
if ($json_error == JSON_ERROR_NONE && count($json)) {
$rows = [];
foreach ($json[0] as $key => $value) {
if (!in_array($key, ['Directory', 'SourceFile'])) {
$rows[] = [$key, $value];
}
}
$more = [
'#type' => 'table',
'#caption' => t('EXIF Data'),
'#header' => [t('Property'), t('Value')],
'#rows' => $rows,
];
}
else {
$more = 'Sorry, we could not fetch EXIF data for this file';
}
$variables['image']['exif'] = [
'#theme' => 'webform_element_more',
'#more' => $more,
'#more_title' => t('Exif'),
];
}
}
}
$is_image = in_array(
$fileextension,
['gif', 'png', 'jpg', 'jpeg', 'jp2', 'tiff']
);
// Build image.
if ($is_image && \Drupal::moduleHandler()->moduleExists(
'image'
) && $style_name && ImageStyle::load($style_name)) {
$variables['image']['singleimage'] = [
'#theme' => 'image_style',
'#style_name' => $variables['style_name'],
];
}
else {
// Note: The 'image' template uses root-relative paths.
// The 'image' is preprocessed to use absolute URLs.
// @see webform_preprocess_image().
$variables['image']['singleimage'] = [
'#theme' => 'image',
];
}
// Change the class from webform-image-file to webform-strawberryfield-image-file
// to avoid webform_preprocess_image() messing up our IIIF link
// by appending the current global.
// @TODO Style element here feels like a hack. We can do better
$variables['image']['singleimage'] += [
'#uri' => $url,
'#attributes' => [
'class' => ['webform-strawberryfield-image-file'],
'alt' => $filename,
'title' => $filename,
'style' => "max-width:{$max_width}px;height:auto",
],
];
// For the Results table always display the file name as a tooltip.
if (strpos(
\Drupal::routeMatch()->getRouteName(),
'webform.results_submissions'
) !== FALSE) {
$variables['attached']['library'][] = 'webform/webform.tooltip';
$variables['image']['singleimage']['#attributes']['class'][] = 'js-webform-tooltip-link';
}
// Wrap 'image' in a link/modal.
if ($format && $format != 'image') {
$variables['image']['singleimage'] = [
'#type' => 'link',
'#title' => $variables['image'],
'#url' => $url,
];
switch ($format) {
case 'modal':
$variables['image']['singleimage'] += [
'#attributes' => [
'class' => [
'js-webform-image-file-modal',
'webform-image-file-modal',
],
],
'#attached' => ['library' => ['webform/webform.element.image_file.modal']],
];
break;
case 'link':
$variables['image']['singleimage'] += ['#attributes' => ['class' => ['webform-image-file-link']]];
break;
}
}
}
}
/**
* Implements hook_entity_operation_alter().
*/
function webform_strawberryfield_entity_operation_alter(array &$operations, EntityInterface $entity) {
if ($entity->getEntityTypeId() == 'webform_submission') {
/** @var \Drupal\webform\WebformInterface $webform */
$webform = $entity->getWebform();
if (\Drupal::service('router.route_provider')->getRouteByName("webform_strawberryfield.webform_submission.ingestentities_form")) {
$operations['ingest_ado'] = [
'title' => t('Create ADO'),
'url' => Url::fromRoute("webform_strawberryfield.webform_submission.ingestentities_form", ['webform' => $webform->id(), 'webform_submission' => $entity->id()]),
'weight' => 50,
];
}
}
}
/**
* Implements hook_format_strawberryfield_twigcontext_alter().
*/
function webform_strawberryfield_format_strawberryfield_twigcontext_alter(array &$context) {
// This will inject into the context of any of our webform operations
// The elements of the webform used to ingest! so we can
// Get stuff like #description, #title, etc.
$context['data_webform_elements'] = FALSE;
$data = $context['data'];
// Should we cover the option of having an array/ multiple webforms?
if (isset($data['strawberry_field_widget_id']) && !empty($data['strawberry_field_widget_id'])) {
try {
/* @var $webform \Drupal\webform\Entity\Webform */
$webform = \Drupal::entityTypeManager()
->getStorage('webform')
->load($data['strawberry_field_widget_id']);
if ($webform) {
$elements = $webform->getElementsDecodedAndFlattened();
$context['data_webform_elements'] = $elements;
}
} catch (\Exception $e) {
$context['data_webform_elements'] = FALSE;
}
}
}
/**
* Implements hook_webform_submission_form_alter().
*
* Pre populates a Webform with a SBF source if conditions are great.
*/
function webform_strawberryfield_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
$hash = \Drupal::request()->query->get('do', NULL);
if ($hash == NULL || !Uuid::isValid($hash)) {
return;
}
/* @var $submission_form \Drupal\webform\WebformSubmissionForm */
$submission_form = $form_state->getFormObject();
$qualifies = FALSE;
/* @var $webform_submission \Drupal\webform\Entity\WebformSubmission */
$webform_submission = $submission_form->getEntity();
$webform = $webform_submission->getWebform();
foreach ($webform->getHandlers() as $id => $webform_handler) {
if (($webform_handler instanceof strawberryFieldharvester) && $webform_handler->isEnabled()) {
$configuration = $webform_handler->getConfiguration();
if (isset($configuration['settings']['ado_prepopulate_enabled']) && $configuration['settings']['ado_prepopulate_enabled']) {
$qualifies = TRUE;
}
}
}
if ($qualifies && !empty($form['#webform_id'])) {
// Check access first
try {
//@var $entities \Drupal\Core\Entity\ContentEntityInterface[] */
$entities = \Drupal::entityTypeManager()
->getStorage('node')
->loadByProperties(['uuid' => $hash]);
// IF this does not work, either the entity is new! or it does not exist at all.
} catch (\Exception $e) {
// NO fuzz, just go your way
return;
}
if ($entities) {
foreach ($entities as $entity) {
// Means there was an entity stored! hu!
// if you are following this you will know this foreach
// makes little sense because we will either get a single one or none
// but! makes sense anyway, shorter than checking if there, and if so
// getting the first!
//@var $source_entity \Drupal\Core\Entity\FieldableEntityInterface */
$vid = \Drupal::entityTypeManager()
->getStorage('node')
->getLatestRevisionId($entity->id());
$source_entity = $vid ? \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid) : $entity;
if (!$source_entity->access('view')) {
throw new AccessDeniedHttpException('Sorry, seems like you (pretty sure) are not allowed to see this, do this or to be here at all!');
}
if (($sbf_fields = \Drupal::service('strawberryfield.utility')
->bearsStrawberryfield($entity))) {
foreach ($sbf_fields as $field_name) {
/* @var $field \Drupal\Core\Field\FieldItemInterface */
$field = $entity->get($field_name);
/* @var \Drupal\strawberryfield\Field\StrawberryFieldItemList $field */
foreach ($field->getIterator() as $delta => $itemfield) {
/** @var $itemfield \Drupal\strawberryfield\Plugin\Field\FieldType\StrawberryFieldItem */
// So. Also we may want to check which ones have default data
// And we may want to filter those out
// Tokens/preprocessed logic should always win.
$existing_elements = $webform->getElementsInitializedFlattenedAndHasValue('view');
$fullvalues = $itemfield->provideDecoded(TRUE);
// Remove any ADO/NODE specific elements
// Basically anything we have added in our enrichment diet/plan
// Identified by keys that contain a colon.
// Or that the user can not create because of 'create' operation being
// not allowed for it.
$fullvalues_clean = array_filter(
$fullvalues,
function ($key) use ($existing_elements) {
return (strpos($key,':') === FALSE) && isset($existing_elements[$key]);
},
ARRAY_FILTER_USE_KEY
);
webform_strawberryfield_recursive_set_default_value($form['elements'], $fullvalues_clean, 1);
$old_values = $form_state->getValues();
$webform_submission->setOriginalData($fullvalues_clean);
$form_state->setValues($old_values + $fullvalues_clean);
if (!empty($fullvalues)) {
// Only populate one entry if many SBFs are around
// @TODO. Add configs to this so admins can choose which CMODEL
// and which Content
break 2;
}
}
}
}
}
}
}
}
function webform_strawberryfield_recursive_set_default_value(&$form_elements, array $values_to_set, $level = 1){
if (!is_array($form_elements)) {
return;
}
$valid_form_elements = Element::children($form_elements);
foreach($valid_form_elements as $key){
$subkeys = Element::children($form_elements[$key]);
if(is_array($subkeys) && !empty($subkeys)){
//We need to loop through it.
webform_strawberryfield_recursive_set_default_value($form_elements[$key], $values_to_set, $level + 1);
}
else{
if (isset($form_elements[$key]['#webform_key']) && isset($values_to_set[$form_elements[$key]['#webform_key']])){
// A Match. Means we have it in our Values to set
// This is a little bit of a blind thing
// @TODO If the Webform element has the same key but can not contain the value is something we need
// to check that!
// Would not hurt to check if the user has access too?
if (!isset($form_elements[$key]['#default_value'])) {
$form_elements[$key]['#default_value'] = $values_to_set[$form_elements[$key]['#webform_key']];
}
}
}
}
}