0

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
        }
    }
}
4

2 回答 2

1

我认为您应该改写 newAction 并编辑

if ($newForm->isSubmitted() && $newForm->isValid()) {

像这样

if ($newForm->isSubmitted() && $newForm->isValid()) {
   if ($this->availabilityService->checkAvailability($entity)) {

如果这不符合您的需要,您可以为 EasyAdminEvents::PRE_PERSIST 编写一个 EventListener 并将重定向返回到 newAction。当事件在新实体和已编辑实体上分派时,EventListener 会更加复杂。

于 2018-11-28T16:16:54.593 回答
0

我找到了解决方案(Vyctorya 引导我找到了正确的路径)。确保您仅使用 调用对相关实体的检查instanceof。如果检查失败,则通过传入引用请求标头将用户重定向到编辑表单。

  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();
  }
于 2018-11-28T21:42:48.040 回答