/
SelectAttributeChoicesCollectionType.php
105 lines (86 loc) · 2.88 KB
/
SelectAttributeChoicesCollectionType.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
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
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Bundle\AttributeBundle\Form\Type\AttributeType\Configuration;
use Ramsey\Uuid\Uuid;
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class SelectAttributeChoicesCollectionType extends AbstractType
{
/** @var string */
private $defaultLocaleCode;
public function __construct(TranslationLocaleProviderInterface $localeProvider)
{
$this->defaultLocaleCode = $localeProvider->getDefaultLocaleCode();
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (null !== $data) {
$fixedData = [];
foreach ($data as $key => $values) {
if (!is_int($key)) {
$fixedData[$key] = $this->resolveValues($values);
continue;
}
if (!array_key_exists($this->defaultLocaleCode, $values)) {
continue;
}
$newKey = $this->getUniqueKey();
$fixedData[$newKey] = $this->resolveValues($values);
if ($form->offsetExists($key)) {
$type = get_class($form->get($key)->getConfig()->getType()->getInnerType());
$options = $form->get($key)->getConfig()->getOptions();
$form->remove($key);
$form->add($newKey, $type, $options);
}
}
$event->setData($fixedData);
}
});
}
/**
* {@inheritdoc}
*/
public function getParent(): string
{
return CollectionType::class;
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix(): string
{
return 'sylius_select_attribute_choices_collection';
}
private function getUniqueKey(): string
{
return Uuid::uuid1()->toString();
}
private function resolveValues(array $values): array
{
$fixedValues = [];
foreach ($values as $locale => $value) {
if ('' !== $value && null !== $value) {
$fixedValues[$locale] = $value;
}
}
return $fixedValues;
}
}