我正在尝试使用 CakePHP translate behavior以一种形式添加一个包含多个翻译的项目。
如何验证翻译字段?例如,需要特定的语言?
假设您有一个简单的items
表,其中包含一个单独的翻译表 items_i18n
,按照书中的描述进行设置。作为一个简单的例子,该items
表只有一个title
要翻译的字段,我想以title
五种语言保存。所以我制作了这样的表格(在add
视图模板中):
echo $this->Form->create($item, ['controller' => 'Items', 'action' => 'add']);
echo $this->Form->input('title', ['label' => __('English')]);
echo $this->Form->input('_translations.es.title', ['label' => __('Spanish')]);
echo $this->Form->input('_translations.fr.title', ['label' => __('French')]);
echo $this->Form->input('_translations.de.title', ['label' => __('German')]);
echo $this->Form->input('_translations.it.title', ['label' => __('Italian')]);
echo $this->Form->button(__('Save'), ['type' => 'submit']);
echo $this->Form->end();
并像这样保存在控制器(add
动作/功能)中:
$item = $this->Items->newEntity();
if ($this->request->is('post')) {
$translations = [
'es' => ['title' => $this->request->data['_translations']['es']['title']],
'fr' => ['title' => $this->request->data['_translations']['fr']['title']],
'de' => ['title' => $this->request->data['_translations']['de']['title']],
'it' => ['title' => $this->request->data['_translations']['it']['title']],
];
foreach ($translations as $lang => $data) {
$item->translation($lang)->set($data, ['guard' => false]);
}
$item = $this->Items->patchEntity($item, $this->request->data, ['validate' => 'default'] );
if ( $this->Items->save($item) ) { $this->Flash->success(__('Saved.')); }
else { $this->Flash->error(__('Not saved.')); }
}
$this->set('item', $item);
这是在没有验证的情况下工作,或者如果我只有“本机”title
字段的验证规则(应该,我简化了 stackoverflow 的代码并为示例重命名了一些部分,所以可能有一些拼写错误,但你应该明白...)。
现在让我们进一步假设语言英语(默认)和西班牙语是必需的,其他语言字段是可选的。我怎样才能做到这一点?
在ItemsTable
我尝试过这样的验证:
class ItemsTable extends Table {
public function validationDefault(Validator $validator) {
$validator
// Title English (default field)
->requirePresence('title')
->notEmpty('title', __('Required field'))
// Title Spanish (translate behaviour field)
->requirePresence('_translations.es.title')
->notEmpty('_translations.es.title', __('Required field'))
;
return $validator;
}
}
但这总是会带来验证错误“此字段是必需的”,因为patchEntity($item, $this->request->data);
会导致翻译被丢弃。我通过GitHub 上关于保存工作流程的一个未解决的问题知道这一点(顺便说一句,此请求 +1 :)。
所以目前我不确定在使用 CakePHP 翻译行为时是否有办法为翻译字段定义验证规则......所需的语言字段只是一个例子,如果你想验证同样的问题,例如 min/max外语输入字段的长度...