我已经实现了CakePHP的翻译行为,一切都相当顺利,但是我现在注意到,当我contain()一个应该翻译的模型时,我从i18n表翻译的数据并不存在。
翻译行为对包含的模型不起作用吗?如果是这样的话,这不是几乎完全消除了这种行为的任何用处吗?(或者可能只有我--但我几乎所有的东西都使用了Containable )。
如果我打算大量使用Containable,有没有一种不同的“CakePHP方式”可以相当容易地进行翻译?
发布于 2013-04-05 18:24:39
我也遇到过类似的问题,我从谷歌上看了几十页,但还是找不到一个简单的解决方案。经过一些调试之后,我创建了这个变通方法的代码片段。请考虑到这只是一个黑客行为。它主要是为Croogo编写的,因此相关模型将在网站上显示为已翻译。但我已经浏览了翻译行为,它应该也适用于它。基本上就是粘贴到你的AppModel类中。这是为Cake 2.x准备的
// DIRTY LITTLE HACKS, FORCING TRANSLATE BEHAVIOR AFTERFIND CALLBACK
/**
* Hacking the afterFind so it will call the afterFind() from
* behavior
* Pase this in your AppModel Class
*
* @param array $results
* @param bool $primary
* @return array
*/
public function afterFind(array $results, $primary = false) {
parent::afterFind($results, $primary);
# calling only if not primary model, as they get translated pretty well
if (!$primary) {
# iterating behaviors to look for one that has something to do
# with translations ( Translate for cake general behavior, CroogoTranslate for Croogo based apps )
foreach ($this->Behaviors->enabled() as $behavior) {
if (preg_match('/(.*)[T|t]ranslate(.*)/', $behavior)) {
# setting locale, not sure if it gets set on secondary models
$this->locale = Configure::read('Config.language');
# hacking the result set to match behaviours requirments
# so basically creating the result set to look like called from originated model
# $k => array('ModelAlias' => array $results)
$results_tmp = array(
0 => array(
$this->alias => $results,
)
);
# if we find such behavior we force it's afterFind with prepared data
$results = $this->Behaviors->{$behavior}->afterFind($this, $results_tmp, true); # forcing true on primary - CroogoTranslate requires that
# restoring orginal structure like nothing ever happened
$results = $results[0][$this->alias];
# not sure if should break or not ?
# on one hand what's the point of having multiple translate behaviors in one app ?
# on the other i've seen more weird stuff that multiple translate behaviors
break;
}
}
}
return $results;
}发布于 2012-11-06 22:24:41
显然,这是一个常见的问题。CakePHP食谱中有一些关于如何处理它的提示:
http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html
https://stackoverflow.com/questions/13226771
复制相似问题