2012-04-13 4 views
0

Я выполнил инструкции в руководстве по настройке поведения перевода с помощью CakePHP 2.1, а также this question here on Stack. Я не получаю никаких ошибок, но мои переведенные сообщения не сохраняются в моей таблице i18n.CakePHP 2.x Поведение переводов не сохраняется на i18n Таблица

Вот мой PostModel.php:

class Post extends AppModel { 

    public $title = 'Post'; 
    public $name = 'Post'; 
    public $body = 'Post'; 

    public $actAs = array(
     'Translate' => array(
      'title' => 'titleTranslation', 
      'body' => 'bodyTranslation' 
     ) 
    ); 

    public $validate = array(
     'title' => array(
      'rule' => 'notEmpty' 
     ), 
     'body' => array(
      'rule' => 'notEmpty' 
     ) 
    ); 

} 

А вот мои добавления и редактирования функций в PostsController.php:

public function add() { 
     if ($this->request->is('post')) { 
      $this->Post->locale = 'fre'; 
      $this->Post->create(); 

     if ($this->Post->save($this->request->data)) { 
      $this->Session->setFlash(__('Your post has been saved.', true)); 
      $this->redirect(array('action' => 'admin')); 
     } else { 
      $this->Session->setFlash(__('Unable to add your post.', true)); 
     } 
    } 
} 

public function edit($id = null) { 
    $this->Post->id = $id; 
    if ($this->request->is('get')) 
    { 
     $this->Post->locale = 'fre'; 
     $this->request->data = $this->Post->read(); 
    } 
    else 
    { 
     if ($this->Post->save($this->request->data)) 
     { 
      $this->Post->locale = 'fre'; 
      $this->Session->setFlash(__('Your post has been updated.', true)); 
      $this->redirect(array('action' => 'admin')); 
     } 
     else 
     { 
      $this->Session->setFlash(__('Unable to update your post.', true)); 
     } 
    } 
} 

Я инициализируется таблицу i18n с помощью консоли. Должен ли я отказаться от таблицы и попробовать повторить инициализацию? Не знаю, почему там будет проблема.

ответ

0

Попробуйте добавить это в форме на add.ctp:

<?php 
    echo $this->Form->create('Post'); 
    echo $this->Form->input('Post.title.fre'); 
    echo $this->Form->input('Post.body.fre'); 
    //Something more... 
    echo $this->Form->end(__('Submit')); 
?> 

в вашем edit.ctp:

<?php 
    echo $this->Form->create('Post'); 
    echo $this->Form->input('id'); 
    echo $this->Form->input('Post.title.fre', array('value'=>$this->request->data['titleTranslation'][0]['content')); 
    echo $this->Form->input('Post.body.fre', array('value'=>$this->request->data['bodyTranslation'][0]['content')); 
    //Something more... 
    echo $this->Form->end(__('Submit')); 
?> 

предполагая индекс данных [ 'titleTranslation'] [0] в французский, легко видеть массив в представлении я рекомендую использовать DebugKit https://github.com/cakephp/debug_kit

Я надеюсь, что это поможет

2

Более многоразовое решение добавить к вашим AppModel:

class AppModel extends Model { 
    public $actsAs = array('Containable'); 

    /** 
    * Converts structure of translated content by TranslateBehavior to be compatible 
    * when saving model 
    * 
    * @link http://rafal-filipek.blogspot.com/2009/01/translatebehavior-i-formularze-w.html 
    */ 
    public function afterFind($results, $primary = false) { 
     if (isset($this->Behaviors->Translate)) { 
      foreach ($this->Behaviors->Translate->settings[$this->alias] as $value) { 
       foreach ($results as $index => $row) { 
        if (array_key_exists($value, $row)) { 
         foreach($row[$value] as $locale) { 
          if (isset($results[$index][$this->alias][$locale['field']])) { 
           if (!is_array($results[$index][$this->alias][$locale['field']])) { 
            $results[$index][$this->alias][$locale['field']] = array(); 
           } 
           $results[$index][$this->alias][$locale['field']][$locale['locale']] = $locale['content']; 
          } 
         } 
        } 
       } 
      } 
     } 
     return $results; 
    } 
} 

Этот код автоматически преобразует то, что возвращает TranslateBehavior, чтобы иметь возможность создавать форму многоязычной как:

echo $this->Form->input('Category.name.eng'); 
echo $this->Form->input('Category.name.deu'); 
echo $this->Form->input('Category.name.pol'); 

Проверен на CakePHP 2.3. И я обнаружил, что теперь Model->saveAssociated() требуется вместо Model->save().

+0

Спасибо, redd. Недавно я не работал над этим проектом, но я проверю ваш ответ и посмотрю, работает ли он. – deewilcox

0

Использование saveMany instedof save. он работает отлично для меня.

0

Для тех, у кого такая же проблема: правильная переменная $actsAs, а не $actAs.

Смежные вопросы