Thursday, March 21, 2013

Unable to set parent_id = id in add or edit actions in self assoc model

Hi
I posted a question on stack overflow that I was hoping someone here could help me figure out. (should have probably posted here first...). Anyway I am having some issues trying to save (both add & edit) into a parent_id column in a Model that I have setup as a self association.

Basically I would like some items to be their own parent by setting parent_id = id. However when I try to do this in the add action it is not saving anything (I use getInsertId() to obtain the ID that was just created and then try to use saveField() to save that into my parent_id. Not working. I then have tried using the edit action/view and setting an item so it is it's own parent, but it doesn't save from there either... any help is greatly appreciated.

Obviously I am still learning but feel this isn't too uncommon of a behavior and can be handled in cakephp (probably rather easily.)

http://stackoverflow.com/questions/15538838/cakephp-save-newly-created-id-in-parent-id-field-of-self-assoc-model

Just to summarize my code

Model Self Associations - Item.php

class Item extends AppModel {
    public $actsAs = array('Tree');

/* Validation rules temporarily removed */

    public $belongsTo = array(
        'ParentItem' => array(
            'className' => 'Item',
            'foreignKey' => 'parent_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )),
    public $hasMany = array(
        'ChildItem' => array(
            'className' => 'Item',
            'foreignKey' => 'parent_id',
            'conditions' => '',
            'fields' => '',
))

Controller Add Action:

    public function add() {
        if ($this->request->is('post')) {
            $this->Item->create();
            unset($this->request->data['Item']['parent_id']);
            if ($this->Item->save($this->request->data)) {
                $last_id = $this->Item->getInsertId();
                $this->Item->saveField('parent_id', $last_id);
                $this->Session->setFlash(__('The item has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The item could not be saved. Please, try again.'));
            }
        }



--
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

No comments: