【发布时间】:2016-03-29 08:25:00
【问题描述】:
我有一个表格,其中包含所有条目,包括多种语言的所有翻译:如何在翻译字段上创建分页排序链接? (蛋糕3.1.6)
总结:这行不通,我不能这样按翻译排序:
$this->Paginator->sort('_translations.es.title', 'Spanish')
加长版:
- 我正在使用带有 translate behavior 的 i18n 表。
- 我在一个表格中列出了所有翻译(多种语言)。
- 现在我想在翻译上使用 pagination sort links(按语言排序)。
| Title ENGLISH | Title SPANISH | Title GERMAN | = pagination sort links
| ---------------- | ---------------- | --------------- |
| Christmas | Navidad | Weihnachten |
| Spring | Primavera | Frühling |
| ...
这是我的简化测试设置:
Articles 表只有一个字段 title 需要翻译。
i18n 表默认设置为 described in the book。
烘焙表格类/src/Model/Table/ArticlesTable.php,添加翻译行为:
public function initialize(array $config) {
// ... default config (removed in this post to simplify code)
$this->addBehavior('Translate', ['fields' => ['title']]); // added this line
}
烘焙Entity类/src/Model/Entity/Article.php,添加TranslateTrait:
namespace App\Model\Entity;
use Cake\ORM\Behavior\Translate\TranslateTrait; // added this line
use Cake\ORM\Entity;
class Article extends Entity {
protected $_accessible = [
'*' => true,
'id' => false,
];
use TranslateTrait; // added this line
}
烘焙Controller /src/Controller/ArticlesController.php,修改如下:
namespace App\Controller;
use App\Controller\AppController;
class ArticlesController extends AppController {
public $paginate = [
'sortWhitelist' => [ // Allow pagination sort on this fields:
'title',
'_translations.es.title',
'_translations.de.title'
]
];
public function index() {
$query = $this->Articles->find('translations'); // Retrieve All Translations
$this->set('articles', $this->paginate($query));
}
}
烘焙视图 /src/Template/Articles/index.ctp,修改/简化:
<table>
<tr>
<th><?= $this->Paginator->sort('title', 'English') ?></th>
<th><?= $this->Paginator->sort('_translations.es.title', 'Spanish') ?></th>
<th><?= $this->Paginator->sort('_translations.de.title', 'German') ?></th>
</tr>
<?php foreach ($articles as $article): ?>
<tr>
<td><?= h($article->title) ?></td>
<td><?= h($article->_translations['es']->title) ?></td>
<td><?= h($article->_translations['de']->title) ?></td>
</tr>
<?php endforeach; ?>
</table>
表格中的翻译显示正确,但无法按翻译字段排序。当我点击翻译的分页链接时,我收到以下错误:
SQLSTATE[42S22]:未找到列:1054 未知列 '_translations.es' 在“订单子句”中
SQL Query:
SELECT Articles.id AS `Articles__id`,
Articles.title AS `Articles__title`,
Articles.created AS `Articles__created`,
Articles.modified AS `Articles__modified`
FROM articles Articles
ORDER BY _translations.es asc LIMIT 20 OFFSET 0
在this similar question 中使用了Posts_title_translation.content 格式-我不知道这是从哪里来的,但我也尝试过这种方式(当然我还在分页器白名单中添加了字段名称的变体):
$this->Paginator->sort('Articles_title_translation', 'Spanish')
$this->Paginator->sort('Articles_title_translation.es', 'Spanish')
$this->Paginator->sort('Articles_title_translation.content', 'Spanish')
$this->Paginator->sort('Articles_title_translation.es.content', 'Spanish')
他们都没有工作......(显然)
如何按标题字段的 i18n 翻译对表格项进行排序?
【问题讨论】:
标签: sorting cakephp pagination cakephp-3.1 cakephp-3.x