Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Data Model Questions

[Solved] Using onAfterWrite to manually set SortOrder


Reply

4 Posts   2053 Views

Avatar
Ryan M.

2 March 2011 at 3:05pm Community Member, 309 Posts

Hi, trying to use onAfterWrite to manually set the SortOrder on a dataobject since I'm not using the DOM to manage the objects, but rather using ModelAdmin.

Here's my code:

function onAfterWrite() {
      parent::onAfterWrite();
      if($this->SortOrder == 0) {
         if($prevObj = DataObject::get('Photo', '', 'Created DESC', '', 1)) {
            $sortOrder = ++$prevObj->SortOrder;
            $this->SortOrder = $sortOrder;
            $this->write();
         } else {
            $this->SortOrder = 1;
            $this->write();
         }
      }
   }

Basically what I'm trying to do is get the last created object, get its SortOrder, increment it and insert it in the new object.
This keeps setting the SortOrder to 1 (the else argument) even though the first argument should work. I tested the object getter using print_r and die, and it does correctly return the last created object. A little stumped here...

Avatar
Ryan M.

2 March 2011 at 3:51pm Community Member, 309 Posts

Update:

I removed the if($prevObj = DataObject::get....) part to test if it would work without checking for a previous object, but I still get the same result - the SortOrder is always set to 1.

Avatar
Ryan M.

2 March 2011 at 3:56pm (Last edited: 2 March 2011 3:57pm), Community Member, 309 Posts

Update #2:

Testing further with print_r, I discovered that doing this:

$obj = DataObject::get('Photo', false, 'Created DESC', false, 1);
      $sort = $obj->SortOrder;
      print_r($obj); die();

Will return the object, however when I replace $obj with $sort in the print_r, it returns nothing at all. Blank! This might be why the value keeps getting set to 1, because it's incrementing on 0 or null.

Avatar
Ryan M.

2 March 2011 at 5:17pm Community Member, 309 Posts

Fixed, apparently it was because using DataObject::get was returning a DataObjectSet, whereas using DataObject::get_one only returned a single object instead, allowing $obj->SortOrder to be fetched.

Final code:

function onAfterWrite() {
      parent::onAfterWrite();
      if($this->SortOrder == 0) {
         if($prevObj = DataObject::get_one('Photo', 'SortOrder > 0')) {
            $sort = ++$prevObj->SortOrder;
            $this->SortOrder = $sort;
            $this->write();
         } else {
            $this->SortOrder = 1;
            $this->write();
         }
      }
   }

I'll leave this thread open for posterity. =D