1

I’m using the Element API plugin to retrieve my entries as JSON. It is available under the /api route. For getting entries in a different locale I pass a locale query param and use it inside the ElementQuery.

All works fine so far, BUT when I want to use Craft::t inside of a transformer, I get the translations from the main locale, because this is where my /api namespace lives.

Is it possible to modify the locale that Craft is set to, from inside the Element API plugin?

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
periodical
  • 106
  • 6

3 Answers3

1

Craft::t() has a whole bunch of parameters you can pass into it.

public static function t($message, $variables = array(), $source = null, $language = null, $category = 'craft')

It sounds like what you're looking for is the 4th one.

Craft::t('my string', null, null, 'es')

Where 'es' would be a target locale other than your main one.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
1

I tried solving my problem by passing the additional parameters to the Craft::t() function mentioned by Brad. For static translations this worked fine, but it still left me with wrong formatted dates inside of twig templates, that were rendered by my transformer.

I found another solution to the problem: Setting the current language globally on the craft instance by using craft()->setLanguage().

Now my code looks like this inside craft/config/elementapi.php:

return [
    'endpoints' => function () {
        'api/galleries' => function () {
            $locale = craft()->request->getQuery('locale', craft()->getLanguage());
            craft()->setLanguage($locale);

            return [
                'elementType' => 'Entry',
                'criteria' => [
                    'section' => 'galleries',
                    'locale' => $locale
                ],
                'transformer' => new GalleryTransformer()
            ];
        }
    }
];

If you set the language globally like this, Craft:t() works like expected, without specifying the additional parameters.

periodical
  • 106
  • 6
1
//get element in the specifict language site        
function langEntry($entry_id) {
    return GlobalSet::find()->id($entry_id)->site("site_name_lang")->one();
}

Can replace GlobaSet for Entry, Section, etc