简体   繁体   中英

Can I populate a Sonata entity export using only getters?

I am building a very simple billing system for a media company using Sonata that includes Payment entities for paying Reporters. The only purpose of a Payment is to be exported to a spreadsheet. We will never edit Payments directly.

I have a bunch of special getters in my Payment entity that don't correspond directly to properties of that entity. Stuff like this:

public function getReporterName():string
{
    return
        $this->reporter->getUser()->getFirstname() .
        ' ' .
        $this->reporter->getUser()->getLastname()
        ;
}

In my Sonata admin class for this entity, I have told my list view to show reporterName as if it is a property. Sonata is smart enough to find and use the getter to retrieve the string I'm looking for. No problem.

The issue comes when I add that pseudo field name into the configureDatagridFilters() method like so:

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('id')
        ->add('paymentComplete')
        ->add('reporterName')
    ;
}

Now I get a nasty message when trying to export a spreadsheet, saying this:

No metadata found for property AppBundle\Entity\Payment::$reporterName . Please make sure your Doctrine mapping is properly configured.

Is there a way to do what I'm trying to do here? Or will I simply have to suck it up and duplicate some data in the database in order to make my export work?

If it helps, I'll reiterate here that we only need this entity for the purpose of exporting to a spreadsheet. It will never be edited manually.

I think you are stuck using two fields (unless you add a mapped field for the full name).
You can use the dot syntax to filter by sub entity properties :

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('id')
        ->add('paymentComplete')
        ->add('reporter.user.firstname', null, ['label' => 'Reporter Firstname'])
        ->add('reporter.user.lastname', null, ['label' => 'Reporter Lastname'])
    ;
}

I ended up working with the dedicated export method to solve this.

https://symfony.com/doc/current/bundles/SonataAdminBundle/reference/action_export.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM