Search code examples
twigshopware

Passing variables to template in custom controller without GET/POST request params


I have a specific problem where I have to pass variable to template in custom controller, but I couldn't use POST or GET request (reason being that function that's doing redirect only sends GET request, and I don't want params to be visible to the end user).

Is there a way to set global variable and attach it to context or a session? I also tried to use RequestDataBag, but after redirect I couldn't access previously set data.

Here's what I tried to do:

public function pay(AsyncPaymentTransactionStruct $transaction, RequestDataBag $dataBag, SalesChannelContext $salesChannelContext): RedirectResponse
{
    $returnUrl = $transaction->getReturnUrl();

    $dataBag->add(['test' => 'test1']);

    return new RedirectResponse('/checkout/confirm/custom-controller');
}

and tried to catch it in controller:

public function cliffMarketsBerrySimplify(Request $request, SalesChannelContext $context, RequestDataBag $dataBag)
{
    $data = $dataBag->get('test');

    return $this->renderStorefront('@plugin/storefront/page/checkout/payment/custom-template.html.twig');
}

But $data is empty. Is there other way to approach this problem. Is it possible to set global context variable or attach variable to session and then retrieve it?


Solution

  • I had the same problem with my custom payment plugin for Shopware 6 and I used session to solve it.

    First inject session in your payment handler and then store your variable in the session:

    public function pay(AsyncPaymentTransactionStruct $transaction, RequestDataBag $dataBag, SalesChannelContext $salesChannelContext): RedirectResponse
    {
        $returnUrl = $transaction->getReturnUrl();
    
        $this->session->set('test', 'test1');
    
        return new RedirectResponse('/checkout/confirm/custom-controller');
    }
    

    Then read the variable from the session in your controller and pass it to your template:

    public function cliffMarketsBerrySimplify(Request $request, SalesChannelContext $context, RequestDataBag $dataBag)
    {
        $data = $this->session->remove('test');
    
        return $this->renderStorefront(
            '@plugin/storefront/page/checkout/payment/custom-template.html.twig',
            ['data' => $data]
        );
    }