Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

View the products of the logged-in user

Symfony : 6.1.4
EasyAdmin :4.3.5

I try to display the products created by the logged in user. By default, all products are displayed regardless of the author.

ProductCrudController.php

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class ProductCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Product::class;
    }
    public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
    {
        $response = parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters);
        $response->andWhere('entity.creator = :creator')->setParameter('creator', ???????);
        return $response;
    }

[...]

}

Problem : I need to get the id of the user who created the product.

But I can’t get it back via $_SESSION :

enter image description here

{{dump(app.user)}}

enter image description here

One solution I can think of is to use app.user.id in ProductCrudController.php but it is a php file. Do you have any leads to achieve this or other ideas?

>Solution :

You should be able to use $this->getUser() in your controller and retrieve the current logged in user and use it to filter your products.

public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
    return parent::createIndexQueryBuilder($searchDto, $entityDto, $fields, $filters)
        ->andWhere('entity.creator = :creator')
        ->setParameter('creator', $this->getUser());
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading