how to create a field of a form in symfony that allows me to obtain an object of the identifier that comes in the request?

0

Good morning,

My question is how to create a field of a form in symfony that allows me to obtain an object from the id that comes in the request ?, without showing me the error that "there are no extra fields".

This is because they send me in a parameter (and the only parameter) the id in the request, what I need to do is a field that converts what comes in that id to an entity (since it is mapped like this, not as an integer but as an entity).

Thank you in advance.

    
asked by devjav 08.07.2016 в 19:04
source

1 answer

0

If I understood correctly, then you could solve it by creating a new Type, say:

use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use AppBundle\Form\EntityToIntTransformer;

class EntityIdType extends AbstractType
{

    private $om;

    public function __construct(ObjectManager $om)
    {
        $this->om = $om;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $transformer = new EntityToIntTransformer($this->om, $options['data_class']);
        $builder->addModelTransformer($transformer);

//        $transformer = new EntityToIntTransformer(
//                $this->om, $options['data_class']
//        );

        //$builder->addModelTransformer($transformer);
    }

    public function configureOptions(\Symfony\Component\OptionsResolver\OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'invalid_message' => 'La entidad no existe.'
        ));
    }

    public function getParent()
    {
        return \Symfony\Component\Form\Extension\Core\Type\HiddenType::class;
    }

}

You register it as a service

services:
    app.form.type.entity_id:
        class: AppBundle\Form\Type\EntityIdType
        arguments: ["@doctrine.orm.entity_manager"]
        tags:
            - {name: form.type, alias: entity_id }

and in the form, you use it as a widget.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $form->add('embarazada', EntityIdType::class, array(
        'data_class' => 'AppBundle\Entity\EntityConcreta',
        'empty_data' => null
    ));
}
    
answered by 04.04.2017 в 14:35