简体   繁体   中英

Embbed listview to formview with sonata admin bundle

What is the best way to embbed the datagrid list of an SonataAdmin entity to another entity EditForm ?

I can't find the process in the doc.

Thanks for your help

Go to the desired list. Copy the url from your browser:

Now with jQuery :

$.get(url_you_just_copied, function(result){
   console.log(result);
};

Have a look at what you are getting back from the listAction call and adapt the request parameters (filters, ...) accordingly to get the list you wanted.

Next to have a clean solution you need to generate your url with the twig helper: https://stackoverflow.com/a/15857401/5758328

Here is how i did it using the sonataBlockBundle to display a list of emails:

Block service class:

namespace Librinfo\EmailBundle\Block;

use Doctrine\ORM\EntityManager;
use Librinfo\EmailBundle\Entity\Email;
use Sonata\BlockBundle\Block\BlockContextInterface;
use Sonata\BlockBundle\Block\Service\TextBlockService;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\HttpFoundation\Response;

class EmailsListBlock extends TextBlockService
{
    /**
     * @var EntityManager
     */
    protected $manager;

    /**
     * @param EntityManager $manager
     */
    public function setManager(EntityManager $manager) {
        $this->manager = $manager;
    }

    /**
     * {@inheritdoc}
     */
    public function execute(BlockContextInterface $blockContext, Response $response = null)
    {
        $settings = $blockContext->getSettings();
        $targetEntity = $settings['target_entity'];
        $maxResults = $settings['max_results'];
        $emails = $this->getEmails($targetEntity, $maxResults);

        return $this->renderResponse($blockContext->getTemplate(), array(
            'block' => $blockContext->getBlock(),
            'settings' => $settings,
            'emails' => $emails,
        ), $response);
    }

    /**
     * {@inheritdoc}
     */
    public function configureSettings(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'content' => 'Insert your custom content here',
            'template' => 'LibrinfoEmailBundle:Block:block_emails_list.html.twig',
            'target_entity' => null,
            'max_results' => 20,
        ));
    }

    /**
     * @param object $targetEntity
     * @param int $maxResults
     * @return array
     * @throws \Exception
     */
    private function getEmails($targetEntity, $maxResults)
    {
        if (!$targetEntity || !is_object($targetEntity))
            return [];
        $rc = new \ReflectionClass($targetEntity);
        if (!$rc->hasProperty('emailMessages'))
            return [];

        $repo = $this->manager->getRepository($rc->getName());
        if (method_exists($repo, 'getEmailMessagesQueryBuilder')) {
            $qb = $repo->getEmailMessagesQueryBuilder($targetEntity->getId());
        }
        else {
            $repo = $this->manager->getRepository(Email::class);
            $targets = strtolower($rc->getShortName()) . 's'; // ex. contacts
            $qb = $repo->createQueryBuilder('e')
                ->leftJoin('e.'.$targets, 't')
                ->where('t.id = :targetid')
                ->setParameter('targetid', $targetEntity->getId())
            ;
        }
        $qb->orderBy('e.updatedAt', 'desc')
            ->setMaxResults($maxResults);

        return $qb->getQuery()->getResult();
    }


}

Service definition:

librinfo.email.block.emails_list:
        class: Librinfo\EmailBundle\Block\EmailsListBlock
        arguments:
            - librinfo.email.block.emails_list
            - '@templating'
        calls:
            - [setManager, [@doctrine.orm.entity_manager]]
        tags: [{ name: sonata.block }]

and the template (abbreviated)

{% extends sonata_block.templates.block_base %}

{% block block %}
    <table class="table table-bordered table-striped sonata-ba-list emails-history">
        <thead>
            <tr>
                <th>Expéditeur</th>
                <th>Destinataires</th>
                <th>Objet</th>
                <th>Envoyé</th>
                <th>Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            {% for email in emails %}
                <tr data-email-id="{{ email.id }}">
then use it like this in your edit template: 

    {{ sonata_block_render({'type': 'librinfo.email.block.emails_list'}, {'target_entity': object}) }}

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