Yii 1.1: translate

Module to handle translations
59 followers

Module to handle translations

This extension collects all untranslated messages in the page and then you can add a button to translate, translate automatically using google translate, check for missing translations, edit translations and more.

Basic usage:

echo Yii::t('app','Some text').' - '.Yii::t('app','some other text');
Yii::app()->translate->editLink('Translate');

Setup

In your config :

<?php
return array(
    'preload'=>array('translate'),//either here or somewhere in the beginning
    //set up and import the module
    'modules'=>array(
        'translate'
    ),
    'import'=>array(
        'application.modules.translate.TranslateModule'
    ),
    'components'=>array(
        //define the class and its missingTranslation event
        'messages'=>array(
            'class'=>'CDbMessageSource',
            'onMissingTranslation' => array('TranslateModule', 'missingTranslation'),
        ),
        'translate'=>array(//if you name your component something else change TranslateModule
            'class'=>'translate.components.MPTranslate',
            //any avaliable options here
            'acceptedLanguages'=>array(
                  'en'=>'English',
                  'pt'=>'Portugues',
                  'es'=>'Español'
            ),
        ),
    )
);

Do not forget to create the tables like described here

the id of message source must be auto-incremental

the name of the tables can be modified

CREATE TABLE SourceMessage
(
    id INTEGER PRIMARY KEY AUTO_INCREMENT,
    category VARCHAR(32),
    message TEXT
);
CREATE TABLE Message
(
    id INTEGER,
    language VARCHAR(16),
    translation TEXT,
    PRIMARY KEY (id, language),
    CONSTRAINT FK_Message_SourceMessage FOREIGN KEY (id)
         REFERENCES SourceMessage (id) ON DELETE CASCADE ON UPDATE RESTRICT
);

How to use

Extract the file to protected/modules

somewhere in your application define the language like the following:

//shortcut
$translate=Yii::app()->translate;
//in your layout add
echo $translate->dropdown();
//adn this
if($translate->hasMessages()){
  //generates a to the page where you translate the missing translations found in this page
  echo $translate->translateLink('Translate');
  //or a dialog
  echo $translate->translateDialogLink('Translate','Translate page title');
}
//link to the page where you edit the translations
echo $translate->editLink('Edit translations page');
//link to the page where you check for all unstranslated messages of the system
echo $translate->missingLink('Missing translations page');

Options avaliable

string $defaultLanguage

defaults language to use if none is set.

if null, it will receive Yii target language

array $dialogOptions

options of the dialog

string $googleApiKey

your google translate api key.

set this if you wish to use googles translate service to translate the messages

array $acceptedLanguages

an array containing the languages accepted by your application.

if not set, it will receive an array containing the target language and the source language

boolean $autoTranslate=false

wheter to auto translate the missing messages found on the page. Needs google api key to set

boolean $autoSetLanguage=true

wheter to automatically set the language on the initialization of the component.

Methods avaliable

for the translate components use it like this:

Yii::app()->translate->someMethod($someArg);

string getLanguage()

Returns the language in use. The language is determined by many variables: session, post, get, header in this order. It will filter the language by using accepted languages. If is set "en_US" and it is not avaliable, then it will check if "en" is avaliable.

string setLanguage($language=null)

If $language is null then it will use getLanguage to determine it. It doesn't check if the language is in the accepted languages. Returns the language setted.

boolean hasMessage()

Return wheter there are messages to be translated in this page

string dropdown()

Returns a dropdown containing all accepted languages with an onchange event that will change the application's language.

string googleTranslate($message,$targetLanguage=null,$sourceLanguage=null)

Translate some message from $sourceLanguage to $targetLanguage using google translate api. Option GoogleApiKey must be defined to use this service.

array getGoogleAcceptedLanguages($targetLanguage=null)

returns an array containing all languages accepted by google translate. Option googleApiKey must be defined to use this service.

string translateLink($label,$type='link')

Generates a link or button to the page where you translate the missing translations found in this page

string translateDialogLink($label,$title=null,$type='link')

Generates a link or button that generates a dialog to the page where you translate the missing translations found in this page.

string editLink($label,$type='link')

Creates a link to the page where you edit the translations.

string missingLink($label,$type='link')

Creates a link to the page where you check all missing translations

type for any link can be 'button' or 'link'

if you are running php 5.3 you can use any method like this MPTranslate::someMethod($someArg);

For the TranslateModule

MPTranslate translator()

returns the translate component

string t($message,$params=array())

used internally for the module to translate its content

string $translateComponentId='translate'

the id of the translate component.

Version

0.2.4: 29/08/2011

  • Fixed bug when no translation found.
  • Fixed typos in documentation.
  • Changed file encoding of all files to utf-8

0.2.3: 18/08/2011

  • options languageKey is now a constant named ID
  • Google errors are now logged instead of beeing treated as an exception

0.2.2: 23/05/2011

  • Fixed pagination in dialog and textarea size

0.2.1: 20/05/2011

  • Fixed some minor bugs

0.2: 18/05/2011

  • complete rewrite of the code to allow easier customization
  • added google translate support (thanks to Toshi)
  • added defaultLanguage (thanks to duna)
  • fixed a couple of minor bugs
  • added a lof of new funcionalities

0.1: 10/05/2011

-first release

Resources

Get a google API key

CDbMessageSource

Forum support

GitHub repository

Notes

This module will slow down your application, use it for development only

It's not fully tested. I'm expecting your feedback to improve it

Total 20 comments

#16792 report it
Gustavo at 2014/03/28 12:29am
@Nabi

1-It doesn't have this ability yet. Could you open a ticket in github page? As soon as I have time I'll implement it.

2-For none of those pages? It should have. It showed to me last time I check. I'll take a look around and get back to you

3-You are probably right! I actually didn't check this scenario but the logic is right. I usually use only in development and enable it in admin application

#16783 report it
Nabi at 2014/03/27 06:14am
about slow

3- Note about your last paragraph that you said this module is slow, I against with this subject! Note that when exist missing translated word, execute one query for each Yii:t, and this is correct and was slow, But If you do translate all words in all language, so don't execute addition query and was fast.

#16782 report it
Nabi at 2014/03/27 06:14am
bug in show pagination

2- The pagination of translate/edit/missing page, didn't show! I thinks it's a bug.

#16781 report it
Nabi at 2014/03/27 06:14am
how store all messages in database

Thanks for great module.

1- In here when visit a page, store all words(in current page) of Yii::t in database, but how can store all words of all .php files in database just by one click, be like yiic message messages/config.php command.

#15781 report it
dacoder at 2013/12/16 03:37pm
not able to translate all the components of the page

Is it possible to translate the whole page without using Yii::t on each content type ? I was hoping for something that works on the lines of me selecting a language and the whole page showing translated to the selected language.

#15250 report it
Rajith R at 2013/10/21 03:34am
@Shahcheraghean

translate/edit

and

translate/edit/missing

are two important actions!

#15249 report it
Rajith R at 2013/10/21 03:32am
@Shahcheraghean

to set language dynamically

$lan='en_us';
Yii::app()->translate->setLanguage($lan);

You set $lan according your wish at main layout or somewhere else!!

#15248 report it
Shahcheraghean at 2013/10/21 03:18am
@Rajith R

Yes please, Usage and configurations?! So Thanks.

#15246 report it
Rajith R at 2013/10/21 02:11am
@Shahcheraghean

Usage examples?

#15129 report it
Shahcheraghean at 2013/10/10 03:21am
Examples?!

Hi there. Is there any more examples?....

#14659 report it
Rajith R at 2013/09/02 05:44am
@theparisian

Not clear!! can you please explain

#14655 report it
theparisian at 2013/09/01 03:01pm
redirect after switching language

Hi,

First of all, thank you for this great extension :) In TranslateBaseController.php there's a redirect() method. From what I understood, this is called when the user selects a new language. I've got an iFrame in the page I'm using, and you may know, in some browsers an iFrame needs to be "manually" refreshed in order to reload with the right content. So I've put the following line of code, right after registerScript() call:

Yii::app()->getClientScript()->registerScript("reloadIframe","var frame=document.getElementById('teaser'); frame.src=frame.src;",CClientScript::POS_READY);

I know this code does the job to refresh the ifram, but it doesn't seem to be used at all in the page after the redirection. Am I missing anything?

Thanks for your help.

theparisian

#14200 report it
Gustavo at 2013/07/25 08:00pm
@tenebriox

Hey tenebriox I didn't write unit tests for it, but it has been stable for some time now.

about load for some users only, yes I only load it on administrative application, but I guess you can check if user has access in onBeginRequest event (before the application dispatch the route) and add the module dinamically if he has

Yii::app()->setModules(array('translate'));

and define the component as usual

also check access before add links to translate pages

Cheers, Gustavo

#14163 report it
tenebriox at 2013/07/24 05:50am
Dynamically load this module

Hi, First of all thank you for this awesome work, very useful :)

You say this module will slow down your application, use it for development only. So, is it possible to load this module dynamically just for special users ?

It's not fully tested. I'm expecting your feedback to improve it Did you write unit tests ? Is it possible to get them ?

#10313 report it
Rajith R at 2012/10/19 03:32am
where and how i use these options?

array $acceptedLanguages

#7340 report it
Revelis Luc Bonnin at 2012/03/15 02:51am
getPreferedLanguage false doesn't managed yet

Hi, I found an issue in your extension when i try to run W3C validator which doesn't include preferedlanguage in his http header request. In your components/MPTranslate, line 205, il your $language was retrieve using getPreferedLanguage (and if it returned false), you will throw a 500 error.

// l.205 where $language has to be a string
if(!key_exists($language,$this->acceptedLanguages)){

I fixed it adding a simple check.

if(($language=@$this->_cache['language'])!==null)
            return $language;
        elseif(Yii::app()->getSession()->contains($key))
            $language=Yii::app()->getSession()->get($key);
        elseif(isset($_POST[$key]) && !empty($_POST[$key]))
            $language=$_POST[$key];
        elseif(isset($_GET[$key]) && !empty($_GET[$key]))
            $language=$_GET[$key];
       //else
//            $language=Yii::app()->getRequest()->getPreferredLanguage();
        else if (Yii::app()->getRequest()->getPreferredLanguage()!=false)
            $language=Yii::app()->getRequest()->getPreferredLanguage();
        else
            $language=$this->defaultLanguage;
 
        if(!key_exists($language,$this->acceptedLanguages)){

I hope it can help...

#7156 report it
Gustavo at 2012/02/28 10:24pm
@oceatoon

Thanks ! I'm happy that it was useful to you

I believe that the functionality you are looking for is in the "editLink" method that method will create a link to the page where you edit the translations

Cheers, Gustavo

#7153 report it
Tibor Katelbach at 2012/02/28 01:12pm
get keys and translations of a page (allready translated ones)

Hi gusnips great thanks for your extension it's really usefull I'm using translate as my main translation tool in my site

The list of missing translations is really usefull when I'm on a page. but now that I have done all the missing translations, it would be great to have all keys for editing at any time. it would work similarly as missing index but would list all the keys with the translations of the active language for the page we are on. is something like this maybe allready available ? hard to set up ? Thanks again

#7103 report it
BlueFire at 2012/02/23 04:06pm
If using google change language code to work

with google 'en_us' is not working you have to change it to 'en'

in the config file:

'sourceLanguage'    =>'en',
#7089 report it
Gustavo at 2012/02/23 08:11am
@Reolbox

Hi Thanks for your feedback ! Glad to hear was useful for you

The best way would be to use CHtml::listData method passing the languages model as parameter

Leave a comment

Please to leave your comment.

Create extension