Translate labels from yml to php file - php

I have a YAML file with a bunch of translations, like this:
wizard
admin
title: example
And I'm calling it on the PHP file like this:
public function getTypesChart(){
$charts = array(
array(
'title' => 'wizard.admin.title'
),
);
return $charts;
}
But the only output I get it's "wizard.admin.title" instead of "example".

You need to call the translator service, like this (assuming you are in a controller, or where you have your service container):
public function getTypesChart(){
$charts = array(
array(
'title' => $this->get('translator')->trans('wizard.admin.title')
),
);
return $charts;
}

Unless you put your translation key in something automatically translated (like form's field label), you need to explicitly ask translation to do the job.
Assuming your code is in some controller you can call:
$this->get("translator")->trans("wizard.admin.title");

There are multiple problems here. First and foremost is that your input is not valid YAML:
wizard
admin
title: example
Although you can have multiline unquoted scalars in YAML, as in:
x: wizard
admin
title
(which is the same as doing x: 'wizard admin title' or x: wizard admin title) such scalars cannot be used as keys for a mapping.
Being invalid, you'll have to correct your YAML to be:
wizard:
admin:
title: example
after correcting that, make sure you call the translater
public function getTypesChart(){
$charts = array(
array(
'title' => $this->get('translator')->trans('wizard.admin.title')
),
);
return $charts;
}

Related

Yii2 translating data stored in database

I'm working with Yii2 Framework, and already configured i18n component using this guide:
http://thecodeninja.net/2014/12/i18n-with-yii-2-advanced-template/
So, I can now translate strings within my php files using Yii::t() function. Translatable strings are extracted using $ ./yii message/extract console command, which generates proper translation files.
I now need to display translations for strings stored in the database.
I could use Yii:t() with a variable instead of a string as an argument like this
echo Yii:t('app', $some_string_from_db );
and make a new php file with some code like this
<?php
function dbStringsToTranslate() {
$o = Yii::t('app','db english string 1');
$o.= Yii::t('app','db english string 2');
$o.= Yii::t('app','db english string 3');
return $o;
}
This way $ ./yii message/extract command will find the needed translations.
This is working Ok, but of course $ ./yii message/extract is throwing some warnings anywhere I use Yii:t() with variables.
Skipping line 39. Make sure both category and message are static strings.
I think this is not a big deal, but well, here is my question:
Is this a right way to translate strings stored in a database?
Is there a better way to accomplish this?
You can check out this extension. https://github.com/creocoder/yii2-translateable it allows for attaching behaviors to models to support multiple languages.
I am using it now in a projects and it is easy to use.
I was having the same problem, and I found the solution with this module. In the module configuration you have the 'tables' array, in which you can specify which field(s) of which table(s) should be translated.
Then, the module has its own 'scan' action (equivalent to message/extract) with which it adds all the translatable strings to database (using DbMessageSource): all Yii::t, the specified database fields, and many more (even javascript, check the docs). It also has a nice user interface to do the translations, it's awesome!
For example, with the following configuration the field name from table nationality will be scanned and added for its translation (i.e country names):
'modules' => [
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
...
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => 'nationality', // table name
'columns' => ['name'], // names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
'categoryPrefix' => 'lx-' //
]
]
],
],
You can generate php file with some fake Yii:t() calls.
For example:
$filename = Yii::getAlias('#frontend/runtime/fake-category-translations.php');
$str = '<?php' . PHP_EOL;
foreach (Category::find()->all() as $category) {
$str .= "Yii::t('category', '{$category->name}');" . PHP_EOL;
}
file_put_contents($filename, $str);
In output this file will be something like this:
<?php
Yii::t('category', 'Art & Design');
Yii::t('category', 'Creativity');
Yii::t('category', 'Educational');
Yii::t('category', 'Education');
Yii::t('category', 'Lifestyle');
Yii::t('category', 'Casual');
So, now you can just call console method for searching untranslated strings:
php yii message/extract #frontend/messages/config.php
I know this is old but I faced same thing with rest API, and here is how I went about resolving it. Note that When saving I used
$post->comment = Yii::t('app', 'My Nice Comment here');
$post->save();
class Post extends ActiveRecord
{
public function fields()
{
$fields = parent::fields();
$fields['comment'] = function ($model) {
return Yii::t('app', $model->comment);
};
return $fields;
}
}

Yii php: Displaying a widget in a Tab

i've been using Yii framework for some time now, and i've been really having a good time especially with these widgets that makes the development easier. I'm using Yii bootsrap for my extensions..but i'm having a little trouble understanding how each widget works.
My question is how do i display the widget say a TbDetailView inside a tab?
i basically want to display contents in tab forms..however some of them are in table forms...some are in lists, detailviews etc.
I have this widget :
$this->widget('bootstrap.widgets.TbDetailView',array(
'data'=>$model,
'attributes'=>$attributes1,
));
that i want to put inside a tab
$this->widget('bootstrap.widgets.TbWizard', array(
'tabs' => $tabs,
'type' => 'tabs', // 'tabs' or 'pills'
'options' => array(
'onTabShow' => 'js:function(tab, navigation, index) {
var $total = navigation.find("li").length;
var $current = index+1;
var $percent = ($current/$total) * 100;
$("#wizard-bar > .bar").css({width:$percent+"%"});
}',
),
and my $tabs array is declared like this :
$tabs = array('studydetails' =>
array(
'id'=>'f1study-create-studydetails',
'label' => 'Study Details',
'content' =>//what do i put here?),
...
...);
when i store the widget inside a variable like a $table = $this->widget('boots....);
and use the $table variable for the 'content' parameter i get an error message like:
Object of class TbDetailView could not be converted to string
I don't quite seem to understand how this works...i need help..Thanks :)
You can use a renderPartial() directly in your content, like this:
'content'=>$this->renderPartial('_tabpage1', [] ,true),
Now yii will try to render a file called '_tabpage1.php' which should be in the same folder as the view rendering the wizard. You must return what renderPartial generates instead of rendering it directly, thus set the 3rd parameter to true.
The third parameter that the widget() function takes is used to capture output into a variable like you are trying to do.
from the docs:
public mixed widget(string $className, array $properties=array ( ), boolean $captureOutput=false)
$this->widget('class', array(options), true)
Right now you are capturing the object itself in the variable trying to echo out an object. Echo only works for things that can be cast to a string.

how to set common code once in YII

i wanted to know in which file we can set common code, for example i wanted to set timezone to UTC, instead of putting same code in all controllers file is there any way to put the code once and it will be reflect in all files.
You may create your file in ''components'' folder. You can see this folder in "protected" folder.
Or you can write your code in controller.php
File path: webroot/protected/components/Controller.php
Can you please try to add the codes in bootstrap.php file
If you need to set the server time you can check here.It is a simple method
Change time zone
Use application params, ie:
// config part
return array(
// ...
'params' => array(
'myParam' => 123
)
// ...
);
// Then in app use
Yii::app()->params['myParam'] // Will return 123
You can also create your own params holder as component, ie:
// config part
'components' => array(
'myConfigs' => array(
'class' => 'ext.MyConfigs'
'myParam1' => 123,
'myParam2' => 'blah'
)
)
// Component in extensions
class MyConfigs extends CComponent
{
public $myParam1;
public $myParam2 = 'defaultValue';
}
// Then in app use it:
Yii::app()->myConfigs->myParam1 // will return 123

Seed Silverstripe database

Is it possible to "seed" a database like you can in rails? I want to use a seed in combination with an imageobject manager so that I can get records by title.
Based on your comment left on Ingo's answer, you want to add a requireDefaultRecords() method to your page class.
The below is from a recent project and ensures there is a particular user group, but you can do the same with any type of DataObject (e.g. Page).
public function requireDefaultRecords() {
// Make sure there is a readers security group
$group = Group::get('Group')->filter('Code', 'readers')
if ( !$group->exists() ) {
$group = Group::create(array('Title' => 'Readers'));
$group->write();
}
}
This function is run on all DataObject classes when you do a build.
You can set the default values of your page $db variables by setting the $defaults array.
class Page extends SiteTree {
public static $db = array(
'Title' => 'Text',
'Description' => 'Text'
);
public static $defaults = array(
'Title' => 'Default Title',
'Description' => 'Default Description'
);
...
}
Not quite sure what you mean by "seed" in this context. There's a "data-generator" module which writes random data with educated guesses on the ORM column types.

How to get user data in form in Symfony 1.2?

I'm using Symfony 1.2 in a standard Propel form class.
public function configure()
{
$this->setWidgets(array(
'graduate_job_title' => new sfWidgetFormInput( array(), array( 'maxlength' => 80, 'size' => 30, 'value' => '' ) )
));
//etc
}
However, I want the value of this field to come from the user information, which I'd normally access using $this->getUser()->getAttribute( '...' ). However, this doesn't seem to work in the form.
What should I be using?
It's a very bad idea to rely on the sfContext instance.
It's better to pass what you need during sfForm initialization in the options array parameter.
http://www.symfony-project.org/api/1_4/sfForm
__contruct method
for example in your action:
$form = new myForm(null,
array('attributeFoo' =>
$this->getUser()->getAttribute('attributeFoo'));
and then retrieve the value inside the form class:
$this->getOption('attributeFoo');
cirpo
Does that work?
sfContext::getInstance()->getUser()->getAttribute('...');
// Edit : See cirpo's recommandation on the use of sfContext instead.
If someone need the same in admin (backend) here is a solution:
http://blog.nevalon.de/en/wie-nutze-ich-die-rechteverwaltung-in-symfony-admin-generator-formularen-20100729
In Symfony 1.4, object $sf_user

Categories