2014-01-20 79 views
1

以下是我們如何使用cakephp模型關係翻譯行爲。我正在努力提高這段代碼的質量。Cakephp翻譯行爲

public function edit($id = null) { 
    if (!$this->Faq->exists($id)) { 
     throw new NotFoundException(__('Invalid faq')); 
    } 
    if ($this->request->is('post') || $this->request->is('put')) { 
     if ($this->Faq->saveMany($this->request->data)) { 
      $this->Session->setFlash('The faq has been saved', 'default', array('class' => 'success')); 
      $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash(__('The faq could not be saved. Please, try again.')); 
     } 
    } else { 
     $options = array('conditions' => array('Faq.' . $this->Faq->primaryKey => $id)); 
     $this->request->data = $this->Faq->find('first', $options); 
    } 
    $languages = $this->Language->getlangs(); 
    if(is_array($this->{$this->modelClass}->belongsTo)) { 
     foreach($this->{$this->modelClass}->belongsTo as $relation => $model) { 
      foreach($languages as $lang){ 
        $this->{$this->modelClass}->$model['className']->locale = $lang['Language']['language_locale']; 
       $faqCategories[$lang['Language']['language_locale']] = $this->Faq->FaqCategory->find('list', array('conditions' => array('FaqCategory.is_active' => 1), 'recursive' => 1)); 
      } 
     } 
    } 
    $this->set(compact('faqCategories')); 
} 

它工作正常,但我想有一個具有相同功能的質量代碼。 在此先感謝。

回答

0

TranslateBehavior實際上非常容易安裝,並且只需很少的配置即可使用。在本節中,您將學習如何添加和設置要在任何模型中使用的行爲。

如果您在使用TranslateBehavior時遇到可疑問題,請務必爲您的查詢設置「字段」鍵。否則,您最終可能會生成無效的SQL。

****初始化i18n的數據庫表****

./cake i18n 

對於正確的佈局。

class Post extends AppModel { 
    public $actsAs = array(
     'Translate' 
    ); 
} 

閱讀翻譯內容

默認情況下,TranslateBehavior會自動獲取,並添加基於當前區域的數據。當前語言環境從L10n類指定的Configure :: read('Config.language')中讀取。您可以使用

$Model->locale