Tuesday, March 1, 2011

How do I circumvent the default HABTM deletion behaviour

I had a problem with updating data in a loop, during the update, the
assoc. HABTM data is wiped in the join table. I was led back to the
Cookbook where I found this is default behaviour (last section, this
page http://book.cakephp.org/view/1034/Saving-Related-Model-Data-HABTM).

What isn't clear (or I can't figure out) is how to prevent this
default behaviour. I have this method in my controller:

function up($id = null, $order = null) {
if (!$id or !$order) {
$this->Session->setFlash(__('Invalid id or order number', true));
$this->redirect(array('action'=>'index'));
}
// Create an array of the image table contents of IDs and Orders.
$conditions = array(
//'fields' => array('id','order'),
'order' => 'Subcategory.order ASC'
);
$subcategories = $this->Subcategory->find('all', $conditions);
// Set the direction for the image to travel (up)
$delta = -1;
// index = the array item you want to move
// delta = the direction and number of spaces to move the item.
$index = $order -1;
$index2 = $index + $delta;
// Move the elements in the array
$temp_item = $subcategories[$index2]['Subcategory']['order'];
$subcategories[$index2]['Subcategory']['order'] =
$subcategories[$index]['Subcategory']['order'];
$subcategories[$index]['Subcategory']['order'] = $temp_item;
// Write it all back to the database
foreach ($subcategories as $subcategory):
$this->Subcategory->create(false);
$this->Subcategory->save($subcategory);
endforeach;
$this->redirect(array('action' => 'index'));
}

You can see I've commented out fields in the conditions in the vain
hope that all the data would be updated. However the behaviour is the
same, gone is the contents of my join table.

I've been shown SortableBehaviour, which I expect will eventually
replace my less esteemed code (I'm a newbie), but I want to fill the
gap in my knowledge and have this work first.

Any assistance would be gratefully received.

Adam.

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.


To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: