2
votes

I'm using Sonata Admin in my project. I need to render a field that doesn't belong to entity.

Consider entity User with fields username & password. But I also need a extra field as hobby in form but it is not needed in User entity.

    $formMapper
       ->add('username')
       ->add('password')
       ->add('hobby');

But I'm getting the symfony error as,

Neither the property "hobby" nor one of the methods "getHobby()", "hobby()", "isHobby()", "hasHobby()", "__get()" exist and have public access in class "App\Entity\User".

How can I solve this? Thanks in advance!!

1
Well, you can probably do it with the answer provided by Bananaapple, but where you will store the hobby? - revengeance
"hobby" is just a example field. I have several fields like hobby which needs to be stored in multiple tables. - Vinoth Kumar
ah, got you. then you need to use preUpdate hook to access the data and do something with it. :) - revengeance
Yeah! I have used $this->getForm()->get('hobby')->getData(); to get the value of "hobby" - Vinoth Kumar

1 Answers

5
votes

This answer for Symfony2 should still hold true if I am not mistaken: How to add additional non-entity fields to entity form in Symfony2

In symfony 2.1+, use mapped:

$form = $this->createFormBuilder($promo)
    ->add('code', 'text')
    ->add('image', 'file', array(
                "mapped" => false,
            ))
    ->getForm();

https://symfony.com/doc/current/reference/forms/types/entity.html#mapped

type: boolean default: true

If you wish the field to be ignored when reading or writing to the object, you can set the mapped option to false.

So for your case it should be something like:

$formMapper
    ->add('username')
    ->add('password')
    ->add('hobby', null, [
        'mapped' => false
    ]);