0

I have implemented a service with the tag config.factory.override. In my class I check if the current user is logged in, and if so I change the system.site.page.front variable to a different page. This kind-of works, but I have a problem with cache. If the first user to visit my site is not logged in that frontpage will be used for everyone, and if a logged in user is first, that version is used for everyone.

This is my current attempt at the getCacheableMetadata:

/**
 * {@inheritdoc}
 */
public function getCacheableMetadata($name) {
  $metadata = new CacheableMetadata();

  $metadata->setCacheContexts([$this->isLoggedIn ? 'user.roles:authenticated' : 'user.roles:anonymous']);

  return $metadata;
}
  • Normally you wouldn't choose between two contexts, because the context defines a condition already, so you could use user.roles:anonymous in both cases. But I don't think this works, in a quick check of the route matching code I couldn't find any evidence that caching depends on the cache metadata you provide here. There are plenty of other options. You can decide later when building and rendering what content you want to display, for rendered output a cache context for user permissions is already default. Or you can redirect, for example anonymous users to a login site. – 4k4 Jun 12 '18 at 7:46
2

As @4k4 commented, I don't think that works.

I'd suggest you either use Page Manager/Panels, which allows to create a page with multiple displays and conditions like based on the user role.

Alternatively, you could create your own controller and return the desired page.

I don't know what you want to do exactly, but yet another option would be to keep two separate pages and redirect authenticated users to the different frontpage. That's similar to how drupal.org works, where you can configure whether your front page should be the default or your dashboard as an authenticated user.

  • Thank you for your answer, and yes, I believe I have to do something like you and 4k4 proposes. I think I will try with a custom controller. My site is mainly for logged in users, but I wanted to provide a landing page for anonymous users. – andeersg Jun 12 '18 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.