sonata-project / SonataAdminBundle

The missing Symfony Admin Generator
https://docs.sonata-project.org/projects/SonataAdminBundle
MIT License
2.11k stars 1.26k forks source link

Allow unmapped show fields #8210

Closed amacrobert-meq closed 1 day ago

amacrobert-meq commented 1 month ago

Feature Request

Unmapped show fields

In an admin's configureFormFields(), it is possible to provide fields in the admin that are not mapped to the admin's subject by setting 'mapped' => false in the field options. For example, this would add a "custom_field" text field for a property that's not necessarily part of the entity.

class SomeEntityAdmin extends AbstractAdmin
{
    // ...

    protected function configureFormFields(FormMapper $form): void
    {
        // ...

        $form->add(
            'custom_field',
            TextType::class,
            [
                'mapped' => false,
                'data' => $custom_field_value,
            ]
        );
    }
}

It would be useful to have a similar option for properties added in configureShowFields().

Currently, all fields added in configureShowMapper() must exist as properties or methods on the admin's subject. In the following code, the mapped option is not implemented, so rendering the show page results in an error An exception has been thrown during the rendering of a template ("User Error: Call to undefined method App\Entity\SomeEntity::getCustomField()").

class SomeEntityAdmin extends AbstractAdmin
{
    // ...

    protected function configureShowFields(ShowMapper $show): void
    {
        // ...

        $show->add(
            'custom_field',
            null,
            [
                'mapped' => false,
                'data' => $custom_field_value,
                'template' => 'show_custom_field.html.twig',
            ]
        );
    }
}

Current workaround

In the above example, a workaround would be to add a getCustomField() property to SomeEntity that always returns null. That allows rendered to get past that method call and then just get the data value in the custom template with {{ field_description.options.data }}. This is not ideal because it requires adding vestigial code to entities.

I am happy to work on a solution for this, but I'm not familiar with Sonata internals so I'd much appreciate any guidance on where to start :)

VincentLanglet commented 1 day ago

This already exists.

You should use 'virtual_field' => true

And I think there is also something like a TemplateType.