Newer
Older
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
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Exception\InvalidColorException;
use App\Form\ColorType;
use App\Model\ColorVo;
use App\Model\ParentModel;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Type;
class TestHeahdudeController extends AbstractController
{
/**
* @Route("/test-heahdude", name="test_heah_form")
*/
public function index(FormFactoryInterface $formFactory)
{
$form = $formFactory->createNamedBuilder('', FormType::class, null, [
'data_class' => ParentModel::class,
'empty_data' => null, //function () { return new ParentModel('', new ColorVo('foo')); }
])
->setDataMapper(new class implements DataMapperInterface {
public function mapDataToForms($viewData, iterable $forms)
{
if ($viewData === null) {
return;
}
$forms = iterator_to_array($forms);
$forms['color']->setData($viewData->getColor());
$forms['content']->setData($viewData->getContent());
}
public function mapFormsToData(iterable $forms, &$viewData)
{
$forms = iterator_to_array($forms);
try {
$viewData = new ParentModel($forms['content']->getData(), new ColorVo($forms['color']->getData()));
} catch (InvalidColorException $error) {
// What to do here ?!
// This does not work
// $forms['colorCondition']->setData(false);
// Even if it would, the error path is wrong!
}
}
})
->add('color', ColorType::class, [
'constraints' => [
new Type(['type' => 'string']),
new Callback(['callback' => ColorVo::class . '::validateColor'])
]
])
->add('content', TextType::class)
->add('colorCondition', CheckboxType::class, [
'label' => 'Accept color',
'required' => false,
'mapped' => false,
'empty_data' => true,
'constraints' => new IsTrue(['message' => 'Wrong color input'])
])
->getForm();
$form->submit(['color' => 10, 'content' => 'foobar']);
dump($form->getErrors(true, true));
return $this->json([
'message' => 'Welcome to your new controller!',
'path' => 'src/Controller/TestVoFormController.php',
]);
}
}