Wednesday, September 25, 2013

Cakephp not able to save associated model

(X-posting from SO)

I've a model `CloudApp` which has HABTM relationship with `Policy` model e.g:

    class CloudApp extends AppModel {
        public $displayField = 'name';        
        public $hasAndBelongsToMany = array(
            'Policy' => array(
                'className' => 'Policy',
                'joinTable' => 'cloudapp_policies',
                'foreignKey' => 'cloud_app_id',
                'associationForeignKey' => 'policy_id',
                'unique' => 'keepExisting',
            )
        );
    
    }

`Policy` model looks like this- 

    class Policy extends AppModel {
            public $belongsTo = 'CloudApp'; 
    }




When I use scaffolding, everything works fine- I am able to multi-select policies for CloudApp that I am saving. 


But when I try to manually save data, associated data in Policy model is not getting saved.


Here is my `add` controller- 

public function add() {
    $this->loadModel('Policy');
    $this->set('policies', $this->Policy->find('list', array(
                'fields' => array('Policy.name')
    )));

    if ($this->request->is('post')) {
        pr($this->request->data);
        $this->CloudApp->saveAll($this->request->data);        }
}

add.ctp looks like this-


    echo $this->Form->create('CloudApp');
    ?>
    <fieldset>
        <legend><?php echo __('Add Application'); ?></legend>
        <?php    
        echo $this->Form->input('name');
        echo $this->Form->input('policies', array(
            'multiple' => true
        ));    
        
        ?>
    </fieldset>
    <?php echo $this->Form->end(__('Submit')); ?>

Output of  `pr($this->request->data);` is- 

    Array
    (
        [CloudApp] => Array
            (
                [name] => 123
                [policies] => Array
                    (
                        [0] => 18
                        [1] => 19
                        [2] => 20
                    )
    
            )
    
    )


What am I doing wrong?

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/groups/opt_out.

No comments: