DEV Community

Cover image for AssociationField with entity parameter in QueryBuilder
neothone
neothone

Posted on

2 1 1 1

AssociationField with entity parameter in QueryBuilder

If you need to restrict the results displayed in an AssociationField in Easyadmin with a condition on the current entity which you are editing, you can do this:

<?php

class ProductCrud extends AbstractCrudController
{
    public function __construct(
        private readonly ProductRepository $productRepository,
        private readonly RequestStack $requestStack,
    ) {
    }

    public static function getEntityFqcn(): string
    {
        return Product::class;
    }

    /**
     * @return iterable<FieldInterface>
     */
    public function configureFields(string $pageName): iterable
    {
        $entityId = $this->requestStack->getCurrentRequest()->attributes->get('entityId');
        $currentProduct = null;
        if (null != $entityId) {
            $currentProduct = $this->productRepository->find($entityId);
        }

        return [
            AssociationField::new('defaultPrice')
                ->setQueryBuilder(
                    fn (QueryBuilder $queryBuilder) => $queryBuilder
                        ->andWhere('entity.product = :product')
                        ->setParameter('product', $currentProduct)
                ),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, I want only displayed prices link to the current product (ManyToOne relation defaultPrice on Product, ManyToOne relation product on Price, OneToMany relation prices on Product).

This is a solution for this issues :

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Permit.io Launch week

Auth that fits in your CI/CD - Permit CLI Launch Week

Live demos, daily drops, and giveaways — see how the Permit CLI can automate fine-grained access control straight from your terminal.

Sign up

👋 Kindness is contagious

Please show some love ❤️ or share a kind word in the comments if you found this useful!

Got it!