translate

Module to handle translations
53 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

#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

#7015 report it
Reolbox at 2012/02/19 07:41am
db languages

hi great plugin! really love it!

my languages are stored in database (nl, fr, ...). Because the user must be able to add languages by itself.

What is the best way to pass all the currently installed languages in the db to the 'acceptedLanguages' property?

many thanks

#6976 report it
Asgaroth at 2012/02/16 10:58am
Google Translate is no longer free

If you were planing to use google translate feature of this module, beware! Google Translate API it is no longer free, if you want to use this feature you should have the paid version.

Important: Google Translate API v2 is now available as a paid service only, and the number of requests your application can make per day is limited. As of December 1, 2011, Google Translate API v1 is no longer available; it was officially deprecated on May 26, 2011
#5870 report it
Nacesprin at 2011/11/21 01:31pm
Update records in missing.php view with CJuiDialog

@gusnips:

Hello. I think it would wonderful that missing translations could be created/edited through CJuiDialogBox. From this manner, all translations were managed in one screen:

http://www.yiiframework.com/wiki/263/cgridview-update-create-records-in-a-cjuidialog/

#5213 report it
Revelis Luc Bonnin at 2011/09/22 09:38am
Case sensitive Db environment issue

If you are using MySQL in MacOsX or Linux env (case sensitive) you won't be able to use "SourceMessage" neither "Message" database tables name. Your MySQL instance will create "sourcemessage" and "message" tables. Even if you are using Windows environment in localhost, you probably have an unix production environment...

To avoid a Yii exception, don't forget to add this piece of code in your config/main.php

'messages'=>array(
            'class'=>'CDbMessageSource',
            'onMissingTranslation' => array('TranslateModule', 'missingTranslation'),
        'sourceMessageTable'=>'sourcemessage', // will not use Yii Core framework/i18n/CdbMessageSource.php public case sensitive attributes values.
        'translatedMessageTable'=>'message',   // will not use Yii Core framework/i18n/CdbMessageSource.php public case sensitive attributes values.
        ),
#4757 report it
Gustavo at 2011/08/11 04:56pm
@dinhtrung

Thanks. Im glad you liked and was useful to you.

As for the google api key, I just added a link right above the comments where you can set up and turn on the translate api.

I just uploaded a new version that will log the error instead of throw an exception.

If this is not the problem, let me know in the forum with more details and I'll look for the problem. I just re-tested here at localhost and worked just fine.

#4756 report it
dinhtrung at 2011/08/11 03:47pm
Greate module

Although I have some difficult to set it up, and Google API doesn't work on testdrive on my localhost, but your work is great. For now, I can use CPhpMessageSource for static translation, and CDbMessageSource for dynamic (menu labels, category name..) one. Also, I separate the code in layout in a block, so I could render it partial on some page of my choice. Thanks for a great module.

#4381 report it
Gustavo at 2011/07/02 05:00pm
@ismail

Hi you dont need any model sample data, the data is auto-generated when you use Yii::t method

as for the table's structure, I can't think of a better one, also I don't see the need to change it

BTW, it uses the same structure as CDbMessageSource

Gustavo

#4380 report it
bipu at 2011/07/02 03:34pm
model with sample data

it would be better if any one figure out how to create a mysql schema with at least 3 column value for both "SourceMessage" and "Message" table in easy way.

#4352 report it
Gustavo at 2011/06/28 07:08am
Project Page

Hey schmunk. Im glad you are interested in the extension

for now, there is just this page and the forum topic to provide support

If you find it usefull, I may create a google project page for it

If you have any doubt on how to use it or find any bugs, PM me or leave a post in the forum topic

Gustavo

#4336 report it
schmunk at 2011/06/27 10:30am
Project Page

Do you have the code in subversion or git?

#4082 report it
Gustavo at 2011/06/04 10:26am
Hey Luki

The case is wrong it should be acceptedLanguages with capital "L"

Thanks for pointing that out, I'll fix the examples here in the extension page

Gustavo

#4081 report it
lukasz at 2011/06/04 10:19am
big problem...

I got error:

Field "MPTranslate.acceptedlanguages" undefined. /home/luky/public_html/fb_shop/framework/YiiBase.php(217)

205 { 206 unset($args[0]); 207 $class=new ReflectionClass($type); 208 // Note: ReflectionClass::newInstanceArgs() is available for PHP 5.1.3+ 209 // $object=$class->newInstanceArgs($args); 210 $object=call_user_func_array(array($class,'newInstance'),$args); 211 } 212 } 213 else 214 $object=new $type; 215 216 foreach($config as $key=>$value) 217 $object->$key=$value; 218 219 return $object;

I have config: 'components'=>array( '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', 'pl'=>'Polski', ), ), )

if I remove key: 'acceptedlanguages' from config. - Working, but I haven't langugaes in menu :(

#3906 report it
toshi at 2011/05/19 08:57pm
Google Translate

Hey, you did it. Thanks it's really usefully and handy to use.

#3815 report it
Asgaroth at 2011/05/10 11:52am
Interesting

Looks really interesting definitively gonna give it a try.

Leave a comment

Please to leave your comment.

Create extension