EasyAdminBundle icon indicating copy to clipboard operation
EasyAdminBundle copied to clipboard

How to set default value for AssociationField or NumberField in EasyAdmin 4 based on filter parameter from previous page?

Open logneh4 opened this issue 1 year ago • 3 comments

I'm trying to set a default value for an AssociationField or a NumberField in EasyAdmin 4 based on a filter parameter from the previous page.

I have url: localhost:8080/xxx?game_id=2

I want set to field AssociationField or NumberField default value 2. How to do it?

logneh4 avatar Apr 23 '23 00:04 logneh4

I'm doing something like that:

public function createEntity(string $entityFqcn)
    {
        $entity = parent::createEntity($entityFqcn);
        $gameId = $this->request->getMainRequest()->query->get('game_id');
        if ($gameId) {
          // what you want ...
          $entity->setValue($gameId);
        }
        return $entity;
    }

dwd-akira avatar Apr 23 '23 16:04 dwd-akira

I couldn't figure out how to do this anywhere, but @dwd-akira's code above worked for me. It would be really nice to have this added into the documentation somewhere.

BurningDog avatar Aug 08 '23 14:08 BurningDog

I'm using the following code that processes the '_defaults' query parameter, i.e., localhost:8080/xxx?_defaults[game_id]=2. In my opinion, it is more correct to set data into the form instead of directly in the entity.

For the filters processing, you can do the same but for filters parameter

public function createNewForm(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormInterface
    {
        $form = parent::createNewForm($entityDto, $formOptions, $context);
        if($form->isSubmitted()){
            return $form;
        }
        $defaultValues = $context->getRequest()->get('_defaults_',[]);

        foreach ($defaultValues as $property => $value)
        {
            if(!$form->has($property) || !$entityDto->hasProperty($property)){
                continue;
            }
            if($entityDto->isToManyAssociation($property)){
                continue;
            }
            if($entityDto->isAssociation($property)){
                $targetEntity = $entityDto->getPropertyMetadata($property)->get('targetEntity');
                $id = Uuid::isValid($value)?Uuid::fromString($value):$value;
                $value = $this->container->get('doctrine')->getManagerForClass($targetEntity)->getReference($targetEntity, $id);
            }
            $form->get($property)->setData($value);
        }
        return $form;
    }

misterx avatar Nov 21 '23 11:11 misterx