Jump to content

New URL hooks do not consider user language


Recommended Posts

In PW version 3.0.173, new hooks for urls were introduced (ProcessWire 3.0.173 core updates: New URL hooks).

The problem is, I am using translatable strings inside the hook, but the language is always default. I can remember there was also a problem within another hook and Ryan mentioned that this is the usual behaviour, because language is always detected before and after the hook but not within.

Maybe someone struggles with the same problem and has found a solution to post it here? I need translatable strings inside this hook.

Link to comment
Share on other sites

I guess you are adding the hook in init(). If you add it at ready() it will work. Init() is too early for the system to know anything about the user or the language...

I think my explanation above is wrong - it works because of the way my language switcher for tracy works! I've updated the code which works for me:

$wire->addHookAfter("/foo", function($event) {
  // first we get a fresh copy of the current user
  $user = $this->wire->pages->getFresh($this->wire->user->id);
  $lang = $user->language;

  // then we set the correct language to retrieve values
  $this->wire->user->language = $lang;

  // output to check results
  $title = $this->wire->pages->get(1)->title;
  return "user name = $user->name, language = $lang, homepate title = $title";

So you are right, the hook does not seem to have the correct language of the user by default. Which it should I guess. Maybe open an issue on github?

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

I found a workaround:

Put the user language inside a session variable and call this session variable inside the hook.

public function init()
        //set language id inside a session variable for later usage in url hook
        $this->wire('session')->set('userlang', $this->wire('user')->language->id);
        // Show details about the blocked IP address inside a panel
        $this->wire->addHook('/detail-view/{ip}', function ($event) {
            $userLang = $this->wire('session')->get('userlang'); // grab current user lang from session
            $this->wire('user')->language = $userLang;
           	// here comes the code


Not really elegant, but it works. Now translatable strings work as expected.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...