Search code examples
symfonysymfony-formssymfony4easyadmin

EasyAdminBundle: how to redirect back to form


In the admin panel created with EasyAdminBundle, the administrator can create a new Booking. I want to add an availability check (via a service) before this new booking instance is persisted into the database. If this check returns false, the admin should be redirected back to the form.

I have extended the EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController class and overridden the persistEntity() function:

...
use EasyCorp\Bundle\EasyAdminBundle\Controller\AdminController as BaseAdminController;

class BookingController extends BaseAdminController
{
    private $availabilityService;

    public function __construct(AvailabilityService $availabilityService)
    {
        $this->availabilityService = $availabilityService;
    }

    protected function persistEntity($booking)
    {
        $checkin = Carbon::instance($booking->getCheckin());
        $checkout = Carbon::instance($booking->getCheckout());

        if($this->availabilityService->checkAvailability($checkin, $checkout)) {
            parent::persistEntity($booking);
        } else {
            return false; //redirect back to the form
        }
    }
}

Solution

  • I have found the solution (Vyctorya led me to the correct path). Make sure that you are only calling the check on the concerned entity with instanceof. If the check fails, redirect the user to the edit form by passing in the referer request header.

      if ($newForm->isSubmitted() && $newForm->isValid()) {
    
         if ($entity instanceof Booking) {
            $formData = $newForm->getData();
    
            if(!$this->availabilityService->checkAvailability($formData->getCheckin(), $formData->getCheckout())) {
               return $this->redirect($this->request->headers->get('referer'));
             }
          }
    
        return $this->redirectToReferrer();
      }