trante
trante

Reputation: 33996

CakePHP controller action setting cookie and passing to helper

I checked typical CakePHP request but couldn't find the solution.

At first myThemeCookie doesn't exist. By setting this cookie, user can select his/her favorite theme and he/she will see that theme in the future.

I have myController and myAction. I have a form in myAction.ctp. User can select theme name.

At first request myAction checks for $_POST. It can't find any value. Action only shows form.

In second request, when user submits form, I send user to myAction again. Action finds $_POST data. Getting theme css address from $_POST. By using myComponent, myThemeCookie is written.

Then I have myLayout.ctp file. This layout file uses myHelper and by using myHelper->getCookieTheme(), it gets theme name from the cookie. But helper gives empty name. So user sees old theme's fonts. (Note that I check cookie data by using $_COOKIE variable in helper)

When I refresh myAction page and make a third request I see that myHelper->getCookieTheme() gives right css file name. And user sees new theme's fonts.

So, after I set a cookie in myAction, I can't see it in my helper method and layout file. But it seems like view/helper files are calculated after controller actions. Do I miss something ?

Upvotes: 0

Views: 533

Answers (1)

floriank
floriank

Reputation: 25698

You don't have to do that in the view at all. Also don't access $_POST directly but use the request object $this->request in the controller.

have a method like checkThemeFromCookie() in your AppController and call it in beforeRender() and read the theme from the cookie, if the value is not empty simply do $this->theme = $themeFromCookie. If the cookie is empty just leave the property or set whatever default theme you want.

References

Upvotes: 0

Related Questions