如何翻译CakePHP3中的选择选项

时间:2016-11-11 09:29:26

标签: select translation cakephp-3.0 options

我尝试用多种语言编写应用程序代码。当我创建我的default.pot时,我看到,我的选择选项将无法翻译。

//UsersTable
<?php

class UsersTable extends Table {

    public $userRoles = ['admin' => 'Administrator', 'author' => 'Author' ...];

}


// UsersController
public function edit($userId = 0) {
    $user = $this->Users->newEntity();
    $this->set("user", $user);
    $this->set("userRoles", $this->Users->userRoles);
}

//edit.ctp
<?php
echo $this->Form->create($user);
echo $this->Form->input("role",["type" => "select","options" => $userRoles,"label" => __("Userrole")]);

我试过这样的事情:

$_userRoles = [];
foreach ($userRoles as $key => $value) {
    $_userRoles[$key] = __($value); // tried also __($value, true)
}

但这会在i18n提取期间产生错误。

如何获得此条目的翻译?

谢谢

1 个答案:

答案 0 :(得分:0)

我认为你必须在Entity Class中定义选项而不是Table Class

在实体中进行更改,如下所示

namespace App\Model\Entity;
use Cake\ORM\Entity;
use Cake\I18n\I18n; //important to use this

class User extends Entity {

    .....

    private $userRoles = ['admin' => 'Administrator', 'author' => 'Author' ...];

    ......

    protected function _getUserRoles() {
        $return=();
        foreach($this->userRoles as $k=>$val)
        {
            $return[$k]=__($value);
        }
        return $return;
    }

    ......
}

UsersController的编辑方法

public function edit($userId = 0) {
    $user = $this->Users->newEntity();
    $this->set("user", $user);
    $this->set("userRoles", $user->user_roles);
}

您的edit.ctp

echo $this->Form->create($user);
echo $this->Form->input("role",["type" => "select","options" => $userRoles,"label" => __("Userrole")]);

在类声明\

之前在表类文件中添加以下行
use Cake\I18n\I18n;

class UsersTable extends Table {

我希望它会对你有所帮助