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 :

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one server—search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!