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 Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If you found this post useful, consider leaving a ❤️ or a nice comment!

Got it