forked from esmero/webform_strawberryfield
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webform_strawberryfield.module
378 lines (331 loc) · 13.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
<?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;
/**
* @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';
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 ($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'];
}
// @TODO set in draft if reset?
// $in_draft = $form_state->get('in_draft');
// if ($in_draft !== NULL) {
// $webform_submission->set('in_draft', $in_draft);
//}
// Call the original reset
$submission_form->reset($form, $form_state);
// Give submission our original values!
$form_state->getFormObject()->getEntity()->setData($restored_data);
}
function webform_strawberryfield_node_presave(ContentEntityInterface $entity) {
/** @var \Drupal\Core\Field\FieldItemListInterface[] */
$field_item_lists = $entity->getFields();
// Get the default image settings, return if not saving an image field storage
// or image field entity.
//@TODO refactor this into OcfHelper. That class will deal with Media and Storage
//@TODO even better, refactor this as part of the AS/event driven architecture
// And make all this efforts JSON based plugins.
foreach ($field_item_lists as $field) {
//@TODO diff with original data, if less images, remove usage
$type = $field->getFieldDefinition()->getType();
if ($type == 'strawberryfield_field') {
if (!$field->isEmpty()) {
foreach ($field->getValue() as $delta => $fieldvalue) {
$arrayMedia = json_decode($fieldvalue['value'], TRUE);
if (isset($arrayMedia['as:image'])) {
foreach ($arrayMedia['as:image'] as $id => &$info) {
if (isset($info['dr:url'])) {
// #id and $info['dr:url'] differ when just saved from a webform
// #id is where we really want to store our file
// $info['dr:url'] should be where it is before this runs
if (($id != $info['dr:url'])
&& isset($info['dr:fid'])
&& is_numeric($info['dr:fid'])) {
// @NOTE benefits of this approach is avoiding https://www.drupal.org/project/drupal/issues/2821423
/** @var \Drupal\file\FileInterface[] $files */
$file = File::load($info['dr:fid']);
if ($file) {
$destination_folder = \Drupal::service('file_system')
->dirname($id);
file_prepare_directory(
$destination_folder,
FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS
);
$destination_uri = file_unmanaged_move(
$file->getFileUri(),
$id
);
$file->setFileUri($destination_uri);
try {
$file->save();
} catch (\Drupal\Core\Entity\EntityStorageException $e) {
\Drupal::messenger()->addError(
t(
'Something went wrong when saving file @filename:, please check your logs.',
['@filename'=> $file->getFilename()]
)
);
}
if (!$entity->isNew()) {
// We can not update its usage if the entity is new here
// Because we have no entity id yet
_update_file_usage($file, $entity->id());
}
$info['dr:url'] = $info['url'] = $id;
}
}
}
}
}
$freshvalues = json_encode(
$arrayMedia,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
$json_error = json_last_error();
if ($json_error == JSON_ERROR_NONE) {
// Never ever destroy y peoples meta data!
try {
$field->setValue($freshvalues);
} /* @throws \InvalidArgumentException
* If the value input is inappropriate.
*
* @throws \Drupal\Core\TypedData\Exception\ReadOnlyException
* If the data is read-only. */
catch (\Exception $e) {
$message = $e->getMessage();
\Drupal::messenger()->addError(
$this->t(
'Something went wrong when saving your metadata: @msg.',
['@msg' => trim(sprintf('%s: %s', get_class($e), $message))]
)
);
if (!$entity->isNew()) {
$message = t(
'We could not save provided metadata for field @fieldname at node @id.',
[
'@fieldname' => $field->getName(),
'@id' => $entity->id(),
]
);
\Drupal::logger('strawberryfield')->warning($message);
}
}
}
else {
\Drupal::messenger()->addError(
t(
'Something went wrong when saving your metadata:, please check your logs.'
)
);
}
}
\Drupal::messenger()->addStatus(
t('All your files were correctly and permanently stored')
);
}
}
}
}
function webform_strawberryfield_node_insert(ContentEntityInterface $entity) {
// Only applies to newly created nodes but ::isNew returns false here!.
$field_item_lists = $entity->getFields();
foreach ($field_item_lists as $field) {
//@TODO diff with original data, if less images, remove usage
$type = $field->getFieldDefinition()->getType();
if ($type == 'strawberryfield_field') {
if (!$field->isEmpty()) {
foreach ($field->getValue() as $delta => $fieldvalue) {
$arrayMedia = json_decode($fieldvalue['value'], TRUE);
if (isset($arrayMedia['as:image'])) {
foreach ($arrayMedia['as:image'] as $id => &$info) {
if (($id == $info['dr:url'])
&& isset($info['dr:fid'])
&& is_numeric($info['dr:fid'])) {
$file = File::load($info['dr:fid']);
_update_file_usage($file, $entity->id());
}
}
}
}
}
}
}
}
function _update_file_usage(\Drupal\File\FileInterface $file, int $nodeid) {
if (!$file || !\Drupal::moduleHandler()->moduleExists('file')) {
return;
}
/** @var \Drupal\file\FileUsage\FileUsageInterface $file_usage */
$file_usage = \Drupal::service('file.usage');
if ($file) {
if (!$file->isPermanent()) {
$file->setPermanent();
try {
$file->save();
} catch (\Drupal\Core\Entity\EntityStorageException $e) {
\Drupal::messenger()->addError(
t(
'Something went wrong when saving file @filename:, please check your logs.',
['@filename'=> $file->getFilename()]
)
);
}
}
$file_usage->add($file, 'strawberryfield', 'node', $nodeid);
}
}
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;
}
}
}
}
}