3 namespace Rapsys\AirBundle\Form\Extension\Type
;
5 use Doctrine\Persistence\ManagerRegistry
;
6 use Symfony\Component\Form\DataTransformerInterface
;
7 use Symfony\Component\Form\Exception\TransformationFailedException
;
8 use Symfony\Component\Form\Extension\Core\Type\HiddenType
;
9 use Symfony\Component\Form\FormBuilderInterface
;
10 use Symfony\Component\OptionsResolver\Options
;
11 use Symfony\Component\OptionsResolver\OptionsResolver
;
14 * Hidden Entity Type class definition
16 * @see https://symfony.com/doc/current/form/create_custom_field_type.html
18 class HiddenEntityType
extends HiddenType
implements DataTransformerInterface
{
20 * @var ManagerRegistry $dm
32 * @param ManagerRegistry $doctrine
34 public function __construct(ManagerRegistry
$doctrine) {
35 $this->dm
= $doctrine;
43 public function configureOptions(OptionsResolver
$resolver) {
45 parent
::configureOptions($resolver);
47 // Derive "data_class" option from passed "data" object
48 $class = function (Options
$options) {
49 return isset($options['data']) && \
is_object($options['data']) ? \
get_class($options['data']) : null;
52 $resolver->setDefaults([
63 public function buildForm(FormBuilderInterface
$builder, array $options): void {
64 #$this->entityClass = sprintf('App\Entity\%s', ucfirst($builder->getName()));
65 #var_dump($builder->getName());
66 #$this->entityClass = sprintf('App\Entity\%s', ucfirst($builder->getName()));
67 //$this->dataClass[$builder->getName()] = $options['data_class'];
69 //Set class from options['class']
70 $this->class = $options['class'];
73 if (empty($this->class)) {
74 //Set class from namespace and field name
75 $this->class = str_replace('Form\\Extension\\Type', 'Entity\\' ,__NAMESPACE__
).ucfirst($builder->getName());
78 //Set this as model transformer
79 //XXX: clone the model transformer to allow multiple hiddenentitytype field with different class
80 $builder->addModelTransformer(clone $this);
83 public function transform($data): string {
84 // Modified from comments to use instanceof so that base classes or interfaces can be specified
85 if ($data === null || !$data instanceof $this->class) {
89 $res = $data->getId();
94 public function reverseTransform($data) {
101 $rep = $this->dm
->getRepository($this->class);
102 $res = $rep->findOneById($data);
103 } catch (\Exception
$e) {
104 throw new TransformationFailedException($e->getMessage());
108 throw new TransformationFailedException(sprintf('A %s with id "%s" does not exist!', $this->class, $data));