1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Riclep\StoryblokForms\Blocks; |
4
|
|
|
|
5
|
|
|
use Riclep\StoryblokForms\Traits\HasNames; |
6
|
|
|
use Riclep\StoryblokForms\Traits\InFieldset; |
7
|
|
|
use Riclep\StoryblokForms\Traits\ToJson; |
8
|
|
|
|
9
|
|
|
class LsfFieldset extends \Riclep\Storyblok\Block |
10
|
|
|
{ |
11
|
|
|
use HasNames, InFieldset, ToJson; |
|
|
|
|
12
|
|
|
|
13
|
|
|
protected string $type = 'fieldset'; |
14
|
|
|
|
15
|
|
|
//// potentially all fields in a fieldset could be name <input name="fieldsetname[fieldname]"> |
16
|
|
|
/// this would out a multidimensional array in the response. |
17
|
|
|
/// makes validation harder? |
18
|
|
|
|
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Returns all the validation rules for the fields in this Fieldset |
22
|
|
|
* |
23
|
|
|
* @return array |
24
|
|
|
*/ |
25
|
|
|
public function validationRules(): array |
26
|
|
|
{ |
27
|
|
|
$rules = []; |
28
|
|
|
|
29
|
|
|
$this->fields->filter(function($field) { |
|
|
|
|
30
|
|
|
return $field->component() !== 'lsf-text-note'; |
31
|
|
|
})->each(function ($field) use (&$rules) { |
32
|
|
|
$rules = array_merge($rules, $field->validationRules()); |
33
|
|
|
}); |
34
|
|
|
|
35
|
|
|
return $rules; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Returns all the error messages for the fields in this Fieldset |
40
|
|
|
* |
41
|
|
|
* @return array |
42
|
|
|
*/ |
43
|
|
|
public function errorMessages(): array |
44
|
|
|
{ |
45
|
|
|
$rules = []; |
46
|
|
|
|
47
|
|
|
$this->fields->each(function ($field) use (&$rules) { |
|
|
|
|
48
|
|
|
$rules = array_merge($rules, $field->errorMessages()); |
49
|
|
|
}); |
50
|
|
|
|
51
|
|
|
return $rules; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Returns the Fieldset’s response after the form has been submitted and validated |
56
|
|
|
* |
57
|
|
|
* @param $input |
58
|
|
|
* @return array |
59
|
|
|
*/ |
60
|
|
|
public function response($input): array |
61
|
|
|
{ |
62
|
|
|
return [ |
63
|
|
|
'label' => $this->label, |
|
|
|
|
64
|
|
|
'name' => $this->name, |
|
|
|
|
65
|
|
|
'response' => $this->fields->map(function ($field) use ($input) { |
|
|
|
|
66
|
|
|
|
67
|
|
|
// Handle empty radio buttons etc. sending nothing in POST request |
68
|
|
|
// does allow empty $input break anything? |
69
|
|
|
if (!$input || !array_key_exists($field->name, $input)) { |
70
|
|
|
$input[$field->name] = null; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return $field->response($input[$field->name]); |
74
|
|
|
})->keyBy('name')->toArray(), |
75
|
|
|
'type' => $this->type, |
76
|
|
|
]; |
77
|
|
|
} |
78
|
|
|
} |