How to update translation cakephp but not main table

限于喜欢 提交于 2019-12-12 03:55:41

问题


I have added translate behaviour to a model, the model comes here

App::uses('AppModel', 'Model');
class Category extends AppModel
{
    public $hasMany = "Product";
    public $validate = array(
        'name' => array(
            'rule' => 'notEmpty'
        )
    );
    public $actsAs = array(
        'Translate' => array(
            'name','folder','show'
        )
    );
    public $name = "Category";

    public $translateModel = 'KeyTranslate';
}

And heres the controller for updating the model

public function admin_edit_translate($id,$locale)
    {

    $this->Category->locale = $locale;          
    $category = $this->Category->findById($id);

    if ($this->request->is('post') || $this->request->is('put')) {
        $this->Category->id = $id;
        if ($this->Category->save($this->request->data)) {
            $this->Session->setFlash('Category translate has been updated');
            //$this->redirect(array('action' => 'edit',$id));
        } else {
            $this->Session->setFlash('Unable to update category');
        }
    }
    if (!$this->request->data) {
        $this->request->data = $category;
    }
    }   

My Problem is that i have a name field in the categories database and when i update or create a new translation it gets updated with the translated value. How do i avoid that


回答1:


You must use Model::locale value to set code language for save in database




回答2:


This happens because the TranslateBehavior uses callbacks like beforeSave and afterSave to save translated content, so it needs to let the model's save operation continue and thus will contain the last translated content.

You could get around this by tricking the TranslateBehavior into thinking the model is saving something by calling the beforeSave and afterSave like this:

$Model = $this->Category;

$Model->create($this->request->data);
$Model->locale = $locale;

$beforeSave = $Model->Behaviors->Translate->beforeSave($Model, array(
    array(
        'callbacks' => true
    )
));

if($beforeSave) {
    $Model->id = $id;
    $Model->Behaviors->Translate->afterSave($Model, true);
}

This way the translation will be saved and the main table will be left untouched. Might not be the best way to save translations though. Why do you need to leave the main table untouched?




回答3:


Callback Behavior::beforeSave is before Model::beforeSave...

but, the simplest way to modify data in Model::beforeSave before Behavior::beforeSave before realy saving is:

$this->Behaviors->Behavior_Name->runtime[Model_Name]['beforeSave'][Field_Name] = '...';


来源:https://stackoverflow.com/questions/15677279/how-to-update-translation-cakephp-but-not-main-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!