Change language without reload

Hey everyone

So i setup some files in messages/<language>/ with my translations.

I added a function:

public function actionSetLanguage (&#036;language)


{


    Yii::app()-&gt;setLanguage(&#036;language);


    &#036;this-&gt;render('index');       


}

to the SiteController, but i don’t want to render the index, i want

to stay on the same page i was before. How can i do that, and how can

i do that on a page with a form without losing the form data.

Thanks in advance!

Cheers,

3One

I’m really just guessing here.

I think —but I’m not sure— it’s possible to post the form data as is (without validation) to your setLanguage action so that it’s rendered back when index is reloaded.

Otherwise, I believe I would load the translated labels by PHP into hidden form fields, or Javascript variables, and then apply the translation with jQuery when necessary (for instance [font=“Courier New”]$(‘label’).html($(‘label’).next().html());[/font] provided you hide each translated label after its original label in the form.)

But it’s not very efficient or elegant. Let’s say it’s a fallback solution if you don’t find better.

[color="#006400"]/* Moved from Tips, Snippets to Yii 1.1 General Discussion - it’s not a snippet nor a tutorial… */[/color]

You can put the path in querystring and use it to come back.

You can also save "old" path in a form and use:


$this->redirect($_POST['redirect_to']); 


<?php


class Controller extends CController {


    public function actionSetLanguage ($language,$redirect)

    {

        Yii::app()->setLanguage($language);

        $this->redirect($redirect); 

    }


    public function createUrl($route, $params = array(), $ampersand = '&') {

        return parent::createUrl($route, array_merge(

                                array('lang' => Yii::app()->language), $params

                        ), $ampersand);

    }


}

Grazie sensorario

What is the use that now i have always the language in my URL?

Also my page always stays on english, even when i click on my testlink:

<a href="index.php?r=site/setLanguage&language=de&redirect=index.php?<?php echo $_SERVER["QUERY_STRING"] ?>">set to german</a>

I did the adjustments you suggested.

anyone? please?

ok putting this in every view:

if(isset($_GET[‘lang’])) { Yii::app()->setLanguage($_GET[‘lang’]); }

seems to have solved this, but i find this pretty ugly, is this really necessary?

Look in our wiki.

And maybe extensions too.

This is a common scenario and people have developed solutions for it many times.

thanks, i think this is what i was looking for:

http://www.yiiframework.com/wiki/26/setting-and-maintaining-the-language-in-application-i18n/

so far i’ve been sticking to the tutorials