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

ListMapper $fieldDescriptionOptions as a callable #6741

Closed vv12131415 closed 3 years ago

vv12131415 commented 3 years ago

Feature Request

I have a case, when I want to check if user has referrals. Referrals is a doctrine collection. What I need to display is if user has or has no referrals. Currently what I can do is https://symfony.com/doc/current/bundles/SonataAdminBundle/reference/action_list.html#displaying-a-non-model-field

But when I want to do this without changing query I would like to get something like this


            ->add('hasReferrals', null, [
                'code' => function (User $user): bool {
                    return $user->getReferrals()->isEmpty();
                }
            ])

this way building admin panel becomes faster

Currently for the feature I want to have I see

method_exists() expects parameter 2 to be string, object given

sonata-project/admin-bundle/src/Admin/BaseFieldDescription.php (line 393) (my current version is 3.83)

VincentLanglet commented 3 years ago

Here: https://github.com/sonata-project/SonataAdminBundle/blob/3.x/src/Admin/BaseFieldDescription.php#L423-L449

We could do something like

        foreach ($getters as $getter) {
            if (\is_callable($getter)) {
                return $getter($object, ...$parameters);
            elseif (\is_string($getter)) {
                if (method_exists($object, $getter) && \is_callable([$object, $getter])) {
                    $this->cacheFieldGetter($object, $fieldName, 'getter', $getter);

                    return $object->{$getter}(...$parameters);
                }
            } else {
                throw exception() // We support only callable and string
            }
        }

Do you want to do the PR @vladyslavstartsev ?

vv12131415 commented 3 years ago

Yes, weekends