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 :

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay