1
votes

In my project I have two related models that are: Company and CompanyComment. Company hasOne CompanyComment.

Now when I want to update company's information through saveAssociated, I do it the following way:

Controller action:

    public function edit($id = null){

        $this->Company->id=$id;

        $this->Company->recursive = 0;      

        if($this->request->is('post')|| $this->request->is('put')){


            if($this->Company->saveAssociated($this->request->data)){
                $this->Session->setFlash(__('data has been updated'), 'positive_notification');
                $this->redirect(array('controller'=>'companies', 'action'=>'overview'));
            } else{
                $this->Session->setFlash(__('Data has not been updated. '), 'negative_notification');
            }
            }else{
            $this->request->data = $this->Company->read();
            }

    }

And the view is following:

<?php echo $this->Form->create('Company', array('enctype' => 'multipart/form-data'));?>

<fieldset>

    <?php
        echo $this->Form->input('Company.newsletter');
        echo $this->Form->input('CompanyComment.comment_1', array('label'=>__('Domas comment'))); 
        echo $this->Form->input('CompanyComment.comment_2', array('label'=>__('Sunny comment')));
        ?>


    </fieldset>
<?php echo $this->Form->end(__('Update'));?>

Here is the request data before saving:

array(
    'Company' => array(
        'newsletter' => '1'
    ),
    'CompanyComment' => array(
        'comment_1' => 'comment1',
        'comment_2' => 'comment2'
    )
)

But it just would not save the data. Any help or guidance is much appreciated.

Here are the Company model relation:

var $hasOne = 'CompanyComment';

One more remark, the primary key of CompanyComment table is company_id and not the auto incremented id.

2

2 Answers

0
votes

Try this

public function edit($id = null){

    $this->Company->id=$id;

    $this->Company->recursive = 0;     <--Remove this line

    if($this->request->is('post')|| $this->request->is('put')){

 //Change here saveAssociated to saveAll like following
        if($this->Company->saveAll($this->request->data)){
            $this->Session->setFlash(__('data has been updated'), 'positive_notification');
            $this->redirect(array('controller'=>'companies', 'action'=>'overview'));
        } else{
            $this->Session->setFlash(__('Data has not been updated. '), 'negative_notification');
        }
        }else{
        $this->request->data = $this->Company->read();
        }

}
0
votes

You said:

One more remark, the primary key of CompanyComment table is company_id and not the auto incremented id.

Did you change that on your model?

http://book.cakephp.org/2.0/en/models/model-attributes.html

class CompanyComment extends AppModel {
    public $primaryKey = 'company_id';
}