-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathAjaxAttributesBundle.php
More file actions
51 lines (42 loc) · 1.55 KB
/
AjaxAttributesBundle.php
File metadata and controls
51 lines (42 loc) · 1.55 KB
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
<?php
namespace Solspace\Freeform\Bundles\Form\Attributes;
use Solspace\Freeform\Events\Forms\RenderTagEvent;
use Solspace\Freeform\Form\Form;
use Solspace\Freeform\Library\Attributes\Attributes;
use Solspace\Freeform\Library\Bundles\FeatureBundle;
use Solspace\Freeform\Library\Serialization\FreeformSerializer;
use yii\base\Event;
class AjaxAttributesBundle extends FeatureBundle
{
public function __construct(
private FreeformSerializer $serializer,
) {
Event::on(
Form::class,
Form::EVENT_RENDER_BEFORE_CLOSING_TAG,
[$this, 'attachAttributeManifest']
);
}
public function attachAttributeManifest(RenderTagEvent $event): void
{
$form = $event->getForm();
$attributes = $form->getAttributes();
$fields = [];
foreach ($form->getFields() as $field) {
$field->addError('attribute-trigger');
$fieldAttributes = $field->getAttributes();
$field->removeError('attribute-trigger');
$fields[$field->getHandle()] = $fieldAttributes->toArray();
}
$manifest = [
'form' => [
'success' => $attributes->getSuccess()->toArray(),
'error' => $attributes->getErrors()->toArray(),
],
'fields' => $fields,
];
$serialized = $this->serializer->serialize($manifest, 'json');
$manifestAttributes = new Attributes(['data-attributes-manifest' => $serialized]);
$event->addChunk("<div{$manifestAttributes}></div>");
}
}