On Mon, Feb 28, 2011 at 9:32 PM, adam_g2000 <a...@designcollective.co.nz> wrote: > Hi Guys, > > I've got a HABTM relationship between subcategories and resources. > There is a resources_subcategories join table. I've written a method > on subcategories that changes the order field in a record by > decrementing it. It's a bit like the tree behaviour (which I may > resort to if I cannot get this to work). > > 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->save($subcategory, false, > array('id', > 'order')); > endforeach; > $this->redirect(array('action' => 'index')); > } > > This all works perfectly except for one thing. Each time this method > is run the entire contents of the join table is erased. I need an > idiot check. Can anyone see what it is I am doing wrong? Thanks in > advance for any help anyone can offer.
There are (used to be?) situations where records are first removed upon saving. Something to do with associations. Reasons are hazy. But a couple of things stand out in your code. First, you're not calling create() before save(). Second, the shuffling looks odd to me. $temp_item isn't a record, for example, but the order. Presumably an integer. Is this what you want? Anyway, have you seen SortableBehavior? Works for me. http://bakery.cakephp.org/articles/dardosordi/2008/07/29/sortablebehavior-sort-your-models-arbitrarily -- 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+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php