/
CustomFormFieldLifeCycleSubscriber.php
68 lines (62 loc) · 1.9 KB
/
CustomFormFieldLifeCycleSubscriber.php
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
<?php
declare(strict_types=1);
namespace RZ\Roadiz\Core\Events;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Events;
use Pimple\Container;
use RZ\Roadiz\Core\Entities\CustomFormField;
use RZ\Roadiz\Core\Handlers\CustomFormFieldHandler;
class CustomFormFieldLifeCycleSubscriber implements EventSubscriber
{
/**
* @var Container
*/
private $container;
/**
* @param Container $container
*/
public function __construct(Container $container)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function getSubscribedEvents()
{
return [
Events::prePersist,
];
}
/**
* @param LifecycleEventArgs $event
*/
public function prePersist(LifecycleEventArgs $event)
{
$field = $event->getEntity();
if ($field instanceof CustomFormField) {
/*
* Automatically set position only if not manually set before.
*/
if ($field->getPosition() === 0.0) {
/*
* Get the last index after last node in parent
*/
/** @var CustomFormFieldHandler $customFormFieldHandler */
$customFormFieldHandler = $this->container->offsetGet('custom_form_field.handler');
$customFormFieldHandler->setCustomFormField($field);
$lastPosition = $customFormFieldHandler->cleanPositions(false);
if ($lastPosition > 1) {
/*
* Need to decrement position because current field is already
* in custom-form field collection count.
*/
$field->setPosition($lastPosition - 1);
} else {
$field->setPosition($lastPosition);
}
}
}
}
}