CakePHP的翻译行为不适用于Containable

时间:2012-11-05 06:04:28

标签: cakephp behavior translate containable cakephp-2.3

我已经实现了CakePHP的翻译行为,一切都相当顺利,但我现在已经注意到,当我i18n模型是contain()时,{{1}}表中的翻译数据不存在应该翻译。

翻译行为对包含的模型不起作用吗?如果是这样,那么这几乎没有完全消除这种行为的任何用处吗? (或者也许只是我 - 但我几乎可以使用Containable。)

如果我计划大量使用Containable,是否有一种不同的“CakePHP方式”可以轻松地进行翻译?

2 个答案:

答案 0 :(得分:0)

显然这是一个常见问题。 CakePHP Cookbook有一些关于如何处理它的提示:

http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html

答案 1 :(得分:0)

我遇到过类似的问题,从谷歌阅读了几十页,但找不到解决我问题的简单方法。经过一些调试后,我创建了此变通方法代码段。请注意这是一个黑客攻击。它主要是为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;
    }