Search code examples
controllertwigsymfony4

Symfony4 button in twig to call function in a controller doesn't work


I followed this to create a button to call a function but it is not working. No error message and the redirect works. But the order status doesn't change.... Can anyone find what is the wrong with it?

my button in twig

<a href="{{ path('change_order_status', { id : NewOrder.id }) }}" class="btn btn-primary">change status</a>

my controller


    /**
     * @param order $target
     *
     * @Route("/admin/order", name="change_order_status")
     */
    public function changeOrderStatus(order $target)
    {
        echo dump($target);
        if (!$target instanceof Order) {
         return;
        }
        $OrderStatus = $this->orderStatusRepository->find(OrderStatus::IN_PROGRESS);
        $target->setOrderStatus($OrderStatus);
        $target->setOrderDate(new \DateTime());
        $em = $this->getEntityManager();         
        $em->persist($Order);         
        $em->flush(); 
    }
}

Solution

  • There are multiple flaws in the code:

    • Your controller has no redirection (not even a response) so if the code is complete, the redirection you see won't come from Symfony.
    • the action parameter $target is type-hinted with order but the object is of type Order (case matters!)
      • when the type-hint is correct, the instanceof check if redundant
    • you are persisting $Order but not $target so the variable name is wrong