spinoza
spinoza

Reputation: 206

Symfony form Set Value of non mapped field from database

I have a TextType label field in my form, my Entity is EAV, the structure is : id, targetId, entityTargetName,

In my form I have a non mapped field label a dynamic from database, when rendering my form I must send a query to database with targetId and entityTargetName and get the value of label field and set it to the form.

I know that I can do query builder but my field is not a select, it's a TexType

        ->add('productName ', TextType::class,
            array(
                'mapped'=>false,
            )
        )

Any idea ?

Upvotes: 2

Views: 1482

Answers (1)

a_sarana
a_sarana

Reputation: 512

You can inject entity repository not just for EntityType field.

You can do the following: 1. Create form in your controller in this way (or something similar):

/** @var FormInterface $form */
$form = $this->get('form.factory')->create(MyFormType::class, null, [
    'action' => $this->get('router')->generate('my_action_routename'),
    'method' => 'POST',
    'entityManager' => $this->getDoctrine()->getManager(),
]);

2. Add configureOptions method to your MyFormType class:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'data_class'    => MyModelClass::class,
        'entityManager' => null, // This is important
    ]);
}

3. Use entity manager in this way in your buildForm method and pass it to default value:

$options['entityManager']->getRepository(ProductRepository::class)->getProductName(targetId, entityTargetName);

Hope this helped!

Upvotes: 3

Related Questions