Skip to content

Commit

Permalink
Update README and add trace on change event
Browse files Browse the repository at this point in the history
  • Loading branch information
mikehaertl committed Oct 6, 2017
1 parent 1b8d4e4 commit 3d7e12e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 26 deletions.
32 changes: 6 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,23 +256,23 @@ This will give you:

When persistence is enabled, the component will fire a `languageChanged` event
whenever the language stored in session or cookie changes. Here's an example
how this can be used:
how this can be used to track user languages in the database:

```php
<?php

'urlManager' => [
'class' => 'codemix\localeurls\UrlManager',
'languages' => ['en', 'fr', 'de'],
'on languageChanged' => `\app\helpers\MyHelper::languageChanged',
'on languageChanged' => `\app\components\User::onLanguageChanged',
]
```

The static class method in `MyHelper` could look like this:
The static class method in `User` could look like this:

```php
<?php
public static function languageChanged($event)
public static function onLanguageChanged($event)
{
// $event->language: new language
// $event->oldLanguage: old language
Expand All @@ -285,28 +285,8 @@ public static function languageChanged($event)
}
}
```

You could then for example restore the user language in the `afterLogin` event
of a custom `user` component:

```php
<?php
public function afterLogin($identity, $cookieBased, $duration)
{
parent::afterLogin($identity, $cookieBased, $duration);
$language = $identity->language;
if ($language !==null && Yii::$app->language !== $language) {
Yii::$app
->getResponse()
->redirect(['site/index', 'language' => $language]);
Yii::$app->end();
}
}
```

> **Note:** A language may already have been selected before a new user signs
> up. So remember to also save the app language in the user model when
> inserting a new user.
> **Note:** A language may already have been selected before a user logs in or
> signs up. So you should also save or update the language in these cases.

### Language Detection
Expand Down
1 change: 1 addition & 0 deletions UrlManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ protected function persistLanguage($language)
if ($this->hasEventHandlers(self::EVENT_LANGUAGE_CHANGED)) {
$oldLanguage = $this->loadPersistedLanguage();
if ($oldLanguage !== $language) {
Yii::trace("Triggering languageChanged event: $oldLanguage -> $language", __METHOD__);
$this->trigger(self::EVENT_LANGUAGE_CHANGED, new LanguageChangedEvent([
'oldLanguage' => $oldLanguage,
'language' => $language,
Expand Down

0 comments on commit 3d7e12e

Please sign in to comment.