Yii2 translating data stored in database - php

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;
}
}

Related

Maatwerk Excel Laravel how to set CSV EXPORT delimeter?

Hi i'm using Maatwerk Excel laravel package to export data to XLSX and CSV.
In 2 instances a comma is good.
But now i need to make a CSV where the delimeter is not a comma but something different (a tab or pipe symbol).
I cannot find where to set this.
I tried:
Config::set('Excel::csv.delimeter','|');
Excel::create('CSV Products', function($excel) use ($exports_arr) {
$excel->setTitle('Products');
$excel->setCreator('Me')->setCompany('My company');
$excel->setDescription('Products');
$excel->sheet('sheet1', function($sheet) use ($exports_arr) {
$sheet->fromArray($exports_arr, null, 'A1', false, false);
});
})->download('csv');
But if i look in the config/Excel.php file the comments suggest that this delimeter is only for reading.
Is it even possible to change the Delimeter for EXPORTING CSV files?
Thanks in advance.
The comment states that excel.csv.delimiter is used for reading out a csv file, but in Writers/LaravelExcelWriter.php (line 578) the CSV delimiter is taken from the config, and set as , by default:
$this->writer->setDelimiter(config('excel.csv.delimiter', ','));
Are you sure the Config::set statement works properly?
Try to use:
Config::set('excel.csv.delimeter','|');
and check the value with
Config::get('excel.csv.delimeter');
UPDATE:
As mentioned in this answer, the service provider is registered before the request takes place. Updating the config key during the request won't affect the value that is read earlier by Maatwerk/Excel. A solution is given in the answer, by creating a deferred provider.
I know this is a bit outdated but I was having the same problem recently.
In order to set a custom delimiter while exporting multiple CSV files, you can create a new instance of the use Maatwebsite\Excel\Excel class without using the facade.
Try this:
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Writer;
use Maatwebsite\Excel\QueuedWriter;
use Maatwebsite\Excel\Reader;
...
$reader = new Reader(app()->make('filesystem'));
$writer = new Writer;
$queued_writer = new QueuedWriter($writer);
$writer->setDelimiter('|');
$excel = new Excel($writer, $queued_writer, $reader, app()->make('filesystem'));
$excel->create( ... );
An update on this question: If you are using Laravel Excel 3, you can set it in the config/excel.php file:
return [
'exports' => [
'csv' => [
'delimiter' => '|',
]
]
]
Or if you want to set it dynamically:
\Config::set('excel.exports.csv.delimiter', '|');
use Maatwebsite\Excel\Concerns\WithCustomCsvSettings;
use Maatwebsite\Excel\Concerns\WithCustomQuerySize;
class MyExportClass implements FromView, WithCustomQuerySize, WithCustomCsvSettings
{
use Exportable;
public string $filePath;
public string $disk;
public function getCsvSettings(): array
{
return [
'delimiter' => ",",
];
}
....
}
From documentation:
enter link description here

Translate labels from yml to php file

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;
}

SilverStripe overwriting URLSegmentFilter static

URLSegmentFilter has a static array $default_replacements which holds, among others, the string to convert ampersands to (from & to -and-) for URL's.
I'm trying to extend the class and overwrite this static to translate the ampersand convert (only value is english and).
How can I overwrite the owner static for this goal?
class URLSegmentFilterExtension extends Extension {
private static $default_replacements = array(
'/&/u' => '-and-', // I need to translate this using _t()
'/&/u' => '-and-', // And this one
'/\s|\+/u' => '-',
'/[_.]+/u' => '-',
'/[^A-Za-z0-9\-]+/u' => '',
'/[\/\?=#]+/u' => '-',
'/[\-]{2,}/u' => '-',
'/^[\-]+/u' => '',
'/[\-]+$/u' => ''
);
}
First of all: The URLSegmentFilter mainly operates in the CMS context, where you usually just have a single locale (depending on the settings of the editing Member). So using _t() alone might not be very helpful? So you'd probably have to get the current editing locale (assuming you're using Fluent or Translatable) and set the locale for translations temporarily.
I don't see a way to hook in translations via an Extension there. I think you'd be better off creating a custom subclass and use it via Injector.
Something like this should work:
<?php
class TranslatedURLSegmentFilter extends URLSegmentFilter
{
public function getReplacements()
{
$currentLocale = i18n::get_locale();
$contentLocale = Translatable::get_current_locale();
// temporarily set the locale to the content locale
i18n::set_locale($contentLocale);
$replacements = parent::getReplacements();
// merge in our custom replacements
$replacements = array_merge($replacements, array(
'/&/u' => _t('TranslatedURLSegmentFilter.UrlAnd', '-and-'),
'/&/u' => _t('TranslatedURLSegmentFilter.UrlAnd', '-and-')
));
// reset to CMS locale
i18n::set_locale($currentLocale);
return $replacements;
}
}
Then you have to enable the custom URLSegmentFilter via config by putting something like this in your mysite/_config/config.yml file:
Injector:
URLSegmentFilter:
class: TranslatedURLSegmentFilter
Update: The above example assumes you're using the Translatable module. If you're using Fluent, replace the following line:
$contentLocale = Translatable::get_current_locale();
with:
$contentLocale = Fluent::current_locale();
You can update configuration dynamically in mysite/_config.php
$defaultReplacements = Config::inst()->get('URLSegmentFilter', 'default_replacements');
$translatedAnd = _t('URLSegmentFilter.And','-and-');
$defaultReplacements['/&/u'] = $translatedAnd;
$defaultReplacements['/&/u'] = $translatedAnd;
Config::inst()->Update('URLSegmentFilter', 'default_replacements', $defaultReplacements);

Laravel: Where to store global arrays data and constants?

I just started working with Laravel. I need to rewrite a whole system I made some years ago, using Laravel 4 as base framework. In my old system, I used to have a constant.php file with some constants declared, and a globals.php file which contained lots of array sets (for example, categories statuses, type of events, langs, etc.). By doing so, I could use something like
foreach ( $langs as $code => $domain ) {
// Some stuff
}
anywhere in my app.
My question is, how can I store that info in the so called "laravel way". I tried using some sort of object to store this info, setting this as a service and creating for it a facade:
app/libraries/Project/Constants.php
namespace PJ;
class Constants {
public static $langs = [
'es' => 'www.domain.es',
'en' => 'www.domain.us',
'uk' => 'www.domain.uk',
'br' => 'www.domain.br',
'it' => 'www.domain.it',
'de' => 'www.domain.de',
'fr' => 'www.domain.fr'
];
}
app/libraries/Project/ConstantsServiceProvider.php
namespace PJ;
use Illuminate\Support\ServiceProvider;
class ConstantsServiceProvider extends ServiceProvider {
public function register() {
$this->app->singleton('PJConstants', function() {
return new Constants;
});
}
}
app/libraries/Project/ConstantsFacade.php
namespace PJ;
use Illuminate\Support\Facades\Facade;
class ConstantsFacade extends Facade {
protected static function getFacadeAccessor() {
return 'PJConstants';
}
}
composer.json
"psr-4": {
"PJ\\": "app/libraries/Project"
},
and so I access that property as PJ\Constants::$langs.
This works, but I doubt it is the most efficient or correct way of doing it. I mean, is it the right way to "propagate" a variable by creating a whole Service Provider and facades and all such stuff? Or where should I put this data?
Thanks for any advice.
EDIT # 01
Data I want to pass to all controllers and views can be directly set in script, like in the example at the beginning of my post, but it can also be generated dynamically, from a database for example. This data could be a list of categories. I need them in all views to generate a navigation bar, but I also need them to define some routing patterns (like /category/subcategory/product), and also to parse some info in several controllers (Like get info from the category that holds X product).
My array is something like:
$categories = [
1 => ['name' => 'General', 'parent' => 0, 'description' => 'Lorem ipsum...'],
2 => ['name' => 'Nature', 'parent' => 0, 'description' => 'Lorem ipsum...'],
3 => ['name' => 'World', 'parent' => 0, 'description' => 'Lorem ipsum...'],
4 => ['name' => 'Animals', 'parent' => 2, 'description' => 'Lorem ipsum...']
]
Just as an example. Index is the id of the category, and the Value is info associated with the category.
I need this array, also, available in all Controllers and Views.
So, should I save it as a Config variable? How else could I store these data; what would be the best and semantically correct way?
For most constants used globally across the application, storing them in config files is sufficient. It is also pretty simple
Create a new file in the app/config directory. Let's call it constants.php
In there you have to return an array of config values.
return [
'langs' => [
'es' => 'www.domain.es',
'en' => 'www.domain.us'
// etc
]
];
And you can access them as follows
Config::get('constants.langs');
// or if you want a specific one
Config::get('constants.langs.en');
And you can set them as well
Config::set('foo.bar', 'test');
Note that the values you set will not persist. They are only available for the current request.
Update
The config is probably not the right place to store information generated from the database. You could just use an Eloquent Model like:
class Category extends Eloquent {
// db table 'categories' will be assumed
}
And query all categories
Category::all();
If the whole Model thing for some reason isn't working out you can start thinking about creating your own class and a facade. Or you could just create a class with all static variables and methods and then use it without the facade stuff.
For Constants
Create constants.php file in the config directory:-
define('YOUR_DEFINED_CONST', 'Your defined constant value!');
return [
'your-returned-const' => 'Your returned constant value!'
];
You can use them like:-
echo YOUR_DEFINED_CONST . '<br>';
echo config('constants.your-returned-const');
For Static Arrays
Create static_arrays.php file in the config directory:-
class StaticArray
{
public static $langs = [
'es' => 'www.domain.es',
'en' => 'www.domain.us',
'uk' => 'www.domain.uk',
'br' => 'www.domain.br',
'it' => 'www.domain.it',
'de' => 'www.domain.de',
'fr' => 'www.domain.fr'
];
}
You can use it like:-
echo StaticArray::$langs['en'];
Note: Laravel includes all config files automatically, so no need of manual include :)
Create common constants file in Laravel
app/constants.php
define('YOUR_CONSTANT_VAR', 'VALUE');
//EX
define('COLOR_TWO', 'red');
composer.json
add file location at autoload in composer.json
"autoload": {
"files": [
"app/constants.php"
]
}
Before this change can take effect, you must run the following command in Terminal to regenerate Laravel’s autoload files:
composer dump-autoload
For global constants in Laravel 5, I don't like calling Config for them. I define them in Route group like this:
// global contants for all requests
Route::group(['prefix' => ''], function() {
define('USER_ROLE_ADMIN','1');
define('USER_ROLE_ACCOUNT','2');
});
I think the best way is to use localization.
Create a new file messages.php in resources/lang/en (en because that is what is set in my config/app 'locale'=>'en')
return an array of all your values
return [
'welcome' => 'Welcome to our application'
];
to retrieve for laravel 5.3 and below
echo trans('messages.welcome');
or
echo Lang::get('messages.welcome');
for 5.4 use
echo __('messages.welcome')
laravel 5.0 localization
or
laravel 5.4 localization
Just to add to the above answer you will have to include the config class before you could start using it in Laravel 5.3
use Illuminate\Support\Facades\Config;
Atleast in Laravel 5.4, in your constructor you can create them;
public function __construct()
{
\Config::set('privileged', array('user1','user2');
\Config::set('SomeOtherConstant', 'my constant');
}
Then you can call them like this in your methods;
\Config::get('privileged');
Especially useful for static methods in the Model, etc...
Reference on Laracasts.com https://laracasts.com/discuss/channels/general-discussion/class-apphttpcontrollersconfig-not-found
Just put a file constants.php file into the config directory and define your constants in that file, that file will be auto loaded,
Tested in Laravel 6+
Create a constants class:
<?php
namespace App\Support;
class Constants {
/* UNITS */
public const UNIT_METRIC = 0;
public const UNIT_IMPERIAL = 1;
public const UNIT_DEFAULT = UNIT_METRIC;
}
Then use it in your model, controller, whatever:
<?php
namespace App\Models;
use App\Support\Constants;
class Model
{
public function units()
{
return Constants::UNIT_DEFAULT;
}
}

Clearing Validation Error Messages from a Zend Form Element

I have a form element for capturing email addresses. I am using Zend_Validate_EmailAddress on the element, and it generates error messages that aren't very user-friendly.
My first step was to specify new messages that were more user-friendly, but some of the checks simply don't lend themselves to a user-friendly message. I then tried to simply clear those messages after running isValid() on the form and specify my own, but none of the functions I've found will clear the messages.
What I've tried and results
setErrorMessages() - Values set here seem to be ignored altogether
clearErrorMessages() - Seems to be ignored
setErrors() - Adds my message, but leaves the others intact
This is the code that displays the errors in my custom view script:
<?php if ($this->element->hasErrors()): ?>
<?php echo $this->formErrors($this->element->getMessages()); ?>
<?php endif; ?>
MY SOLUTION
I'm awarding Gordon with the answer, because his solution is most complete, but I ended up using the addErrorMessage() function on the element like this:
$element->addValidator('EmailAddress', false, $this->_validate['EmailAddress'])
->addErrorMessage("'%value%' is not a valid email address");
$element->addValidator('Date', false, array('MM/dd/yyyy'))
->addErrorMessage("Date must be in MM/DD/YYYY format");
From the Reference Guide (emphasis mine):
Some developers may wish to provide custom error messages for a validator. The $options argument of the Zend_Form_Element::addValidator() method allows you to do so by providing the key 'messages' and mapping it to an array of key/value pairs for setting the message templates. You will need to know the error codes of the various validation error types for the particular validator.
So you can do:
$form = new Zend_Form;
$username = new Zend_Form_Element_Text('username');
$username->addValidator('regex', false, array(
'/^[a-z]/i',
'messages' => array(
'regexInvalid' => 'foo',
'regexNotMatch' => 'bar',
'regexErrorous' => 'baz'
)
));
$form->addElement($username);
$form->isValid(array('username' => '!foo'));
which will then render 'bar' for the error message, because the regex does not match because it doesnt start with a letter from a-Z.
This is equivalent to using:
$username->setErrorMessages(
array(
'regexNotMatch' => 'The value %value% must start with a-Z',
…
)
);
I've used a different pattern to illustrate how to use the validated value in the pattern.
You can also use setErrors, if you want to delete any default templates, e.g.
$username->setErrors(array('The value must start with a-Z'));
Whatever you do, you have to configure that before validating with isValid. Once the validation is run, the Zend_Form_Element will contain the default error message otherwise. I am not aware of any way to reset that then (though someone might want to correct me on that).
Further quoting the reference guide:
A better option is to use a Zend_Translate_Adapter with your form. Error codes are automatically passed to the adapter by the default Errors decorator; you can then specify your own error message strings by setting up translations for the various error codes of your validators.
All the validation messages can be customized from the file in
http://framework.zend.com/svn/framework/standard/trunk/resources/languages/en
The file should be in APPLICATION_PATH/resources/languages, but can really be placed anywhere as long as you tell Zend_Translate where to find it.
When you define a form element like this
$titel = new Zend_Form_Element_Text ( "titel" );
$titel->setLabel ( "Titel" )->setRequired ( true )
->addValidator ( 'regex', false, array ("/[\pL\pN_\-]+/" ) );
you can specify a error message in your view script
<?php
$form = $this->form;
$errorsMessages =$this->form->getMessages();
?>
<div>
<label>Titel</label> <?php echo $form->titel->renderViewHelper()?>
<?php
if(isset($errorsMessages['titel'])){
echo "<p class='error'>There's something wrong!</p>";
}
?>
</div>
I don't know if this conforms your way but I really like defining my forms this way ;)
One way you can attack it is to create your own custom validator by extending the validator you plan on using and overriding the messages. For instance, looking at Zend_Validate_Alnum, it looks like this:
class Zend_Validate_Alnum extends Zend_Validate_Abstract
{
const INVALID = 'alnumInvalid';
const NOT_ALNUM = 'notAlnum';
const STRING_EMPTY = 'alnumStringEmpty';
[ ... ]
protected $_messageTemplates = array(
self::INVALID => "Invalid type given. String, integer or float expected",
self::NOT_ALNUM => "'%value%' contains characters which are non alphabetic and no digits",
self::STRING_EMPTY => "'%value%' is an empty string",
);
[ ... ]
}
Override the $_messageTemplates array in your own class like this
class My_Validate_Alnum extends Zend_Validate_Alnum
{
protected $_messageTemplates = array(
self::INVALID => "My invalid message",
self::NOT_ALNUM => "foo",
self::STRING_EMPTY => "'%value%' is bar",
);
[ ... ]
}
Then instead of using Zend_Validate_Alnum, use My_Validate_Alnum as your validator. Custom validators are very simple to create.

Categories