简体   繁体   中英

Sonata Admin configureListFields show through query

I am using sonata admin bundle for admin panel. I want to show data in configureListFields through query. I have table userChoiceProduct and fields :-

User_Id
Product_Id

These fields automatically fill when user select any product and submit form. But these fields no relationship to other table.and I want to show User Email and Product Name in configureListFields bases on User_Id and Product_Id.

Thanks!

I solved this:-

In Sonata Admin list :-

            ->add('User Email', null, array('template' => 'ABCAdminBundle:UserChoiceProduct:user.html.twig'))
    ->add('Product Name', null, array('template' => 'ABCAdminBundle:UserChoiceProduct:prodcut.html.twig'))

I mentioned one twig file (user.html.twig) for example :

<td>{{object.userId|getUserDetail()}}</td>

And create getUserDetail() in twig extension :-

class ABCExtension extends \Twig_Extension {

private $generator;
private $container;

public function __construct(UrlGeneratorInterface $generator, Container $container) {
    $this->generator = $generator;
    $this->container = $container;
}
public function getFilters() {
    return array(
        'getUserDetail' => new \Twig_Filter_Method($this, 'getUserDetail'),
    );
}
public function getUserDetail($userId)
{
    $em = $this->container->get('doctrine')->getManager();
    $user = $em->getRepository('ABCUserBundle:User')->findOneBy(array('id' =>$userId));
    if(empty($user)){
        $userEmail = 'User does not Exist';
        return $userEmail;          
    }else{
        $userEmail = $user->getEmail();
        return $userEmail;
    }
}
}

And then all work is done successfully.

You can use the createQuery method in your admin to customize the parent query, like that :

public function createQuery($context = 'list') {
    $query = parent::createQuery($context);
    $query
        ->addSelect('u')
        ->leftJoin('Path\To\User\Entity', 'u', \Doctrine\ORM\Query\Expr\Join::ON, 't0_.User_Id = u.id')
    ;
    return $query;
}

By getting and replacing t0_ by the prefix of userChoiceProduct table in main query.

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