1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the Sonata Project package. |
7
|
|
|
* |
8
|
|
|
* (c) Thomas Rabaix <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Sonata\DoctrinePHPCRAdminBundle\Form\Listener; |
15
|
|
|
|
16
|
|
|
use Doctrine\Common\Collections\Collection; |
17
|
|
|
use Symfony\Component\Form\FormBuilder; |
18
|
|
|
use Symfony\Component\Form\FormEvent; |
19
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccess; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* A listener for the parent form object to reorder a children collection based |
23
|
|
|
* on the order in the form request, which reflects the frontend order. Just |
24
|
|
|
* setting the right order will make PHPCR-ODM persist the reorderings. |
25
|
|
|
* |
26
|
|
|
* @author David Buchmann <[email protected]> |
27
|
|
|
*/ |
28
|
|
|
class CollectionOrderListener |
29
|
|
|
{ |
30
|
|
|
/** |
31
|
|
|
* @var string |
32
|
|
|
*/ |
33
|
|
|
private $name; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param string $name the form field name used for the collection |
37
|
|
|
*/ |
38
|
|
|
public function __construct($name) |
39
|
|
|
{ |
40
|
|
|
$this->name = $name; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Reorder the children of the parent form data at $this->name. |
45
|
|
|
* |
46
|
|
|
* For whatever reason we have to go through the parent object, just |
47
|
|
|
* getting the collection from the form event and reordering it does |
48
|
|
|
* not update the stored order. |
49
|
|
|
*/ |
50
|
|
|
public function onSubmit(FormEvent $event): void |
51
|
|
|
{ |
52
|
|
|
$form = $event->getForm()->getParent(); |
53
|
|
|
$data = $form->getData(); |
54
|
|
|
|
55
|
|
|
if (!\is_object($data)) { |
56
|
|
|
return; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$accessor = PropertyAccess::createPropertyAccessor(); |
60
|
|
|
$newCollection = $accessor->getValue($data, $this->name); |
61
|
|
|
if (!$newCollection instanceof Collection) { |
62
|
|
|
return; |
63
|
|
|
} |
64
|
|
|
/* @var $newCollection Collection */ |
65
|
|
|
|
66
|
|
|
$newCollection->clear(); |
67
|
|
|
|
68
|
|
|
/** @var $item FormBuilder */ |
69
|
|
|
foreach ($form->get($this->name) as $key => $item) { |
70
|
|
|
if ($item->has('_delete') && $item->get('_delete')->getData()) { |
71
|
|
|
// do not re-add a deleted child |
72
|
|
|
continue; |
73
|
|
|
} |
74
|
|
|
if ($item->getName() && !is_numeric($item->getName())) { |
75
|
|
|
// keep key in collection |
76
|
|
|
$newCollection[$item->getName()] = $item->getData(); |
77
|
|
|
} else { |
78
|
|
|
$newCollection[] = $item->getData(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|