cookiestypo3typo3-9.x

TYPO3 how to set custom cookie inside a form finisher


typo3 9.5.8.
We are implementing a newsletter subscription flow with multiple steps, on submit of the second step we query graphQL in a finisher to see if the Email is valid to subscribe or not - and we set a cookie with the "state" of the email address.

setcookie("isEmailSubscribable", ($content->data->isEmailSubscribable) ? "1" : "0", time() - 3600, "/", "x.at", false);

We have to display a message on the third step based on that "state" written into a cookie. but no matter what I try the cookie does not get set (I guess).

Whats the deal with cookies and typo3? Is it too late to set a cookie inside a form finisher? But if yes how could I solve this?

Help is much appreciated.


Solution

  • Inside the Finisher:

    // Set a cookie
    $this->getTypoScriptFrontendController()->fe_user->setKey('ses', 'value', 'test');
    
    // Get the cookie
    $this->getTypoScriptFrontendController()->fe_user->getKey('ses', 'test');
    

    Value can be an array, it will be stored serialized in the Database fe_sessions.ses_data


    UPDATE:

    Or you can try it with an PSR-15 Middleware: https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/RequestHandling/Index.html

    In your Middleware Class you get a $request and $response and use them to set or read a cookie:

    // Write a cookie
    $response = $response->withAddedHeader(
        'Set-Cookie',
        $cookieName . '=' . $yourValue . '; Path=/; Max-Age=' . (time()+60*60*24*30)
    );
    
    // Read a cookie
    $request->getCookieParams()[$cookieName];
    

    You just have to check request for email address and maybe an hidden field to detect that your for was submitted.