Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a custom action in EasyAdmin 3?

I have a CrudController for my entity, Participant. I want to add a custom action, sendAcknowledgementEmail. The EasyAdmin docs doesn't mention anything about the custom function parameters or return values.

I have the following code

public function configureActions(Actions $actions): Actions
{
    $send_acknowledgement_email = Action::new('sendAcknowledgementEmail', 'Send Acknowledgement Email', 'fa fa-send')
        ->linkToCrudAction('sendAcknowledgementEmail');

    return $actions
        ->add(Crud::PAGE_INDEX, $send_acknowledgement_email)
        ->add(Crud::PAGE_EDIT, $send_acknowledgement_email)
    ;
}

public function sendAcknowledgementEmail() //Do I need parameters?
{
    //How do I get the Entity?

    //What should I return?
}

So far, EasyAdmin detects the custom function but I get an error "The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned null. Did you forget to add a return statement somewhere in your controller?"

How do I continue from here?

like image 324
ceochronos Avatar asked Aug 08 '20 06:08

ceochronos


1 Answers

The v3.x of the bundle is quite new and the documentation is not perfect yet.

Based on Ceochronos answer, here is my implementation for a clone action.

public function configureActions(Actions $actions): Actions
{
    $cloneAction = Action::new('Clone', '')
        ->setIcon('fas fa-clone')
        ->linkToCrudAction('cloneAction');

    return $actions
        ->add(Crud::PAGE_INDEX, $cloneAction);

}

public function cloneAction(AdminContext $context)
{
    $id     = $context->getRequest()->query->get('entityId');
    $entity = $this->getDoctrine()->getRepository(Product::class)->find($id);

    $clone = clone $entity;

    // custom logic 
    $clone->setEnabled(false);
    // ...
    $now = new DateTime();
    $clone->setCreatedAt($now);
    $clone->setUpdatedAt($now);

    $this->persistEntity($this->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $clone);
    $this->addFlash('success', 'Product duplicated');

    return $this->redirect($this->get(CrudUrlGenerator::class)->build()->setAction(Action::INDEX)->generateUrl());
}
like image 68
Kaizoku Gambare Avatar answered Sep 30 '22 03:09

Kaizoku Gambare