Vinoth Kumar
Vinoth Kumar

Reputation: 663

Add custom form field that is not in entity - Sonata admin

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!!

Upvotes: 2

Views: 4526

Answers (1)

Bananaapple
Bananaapple

Reputation: 3114

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
    ]);

Upvotes: 5

Related Questions