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.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

[Solved] Using onAfterWrite to manually set SortOrder


Go to End


4 Posts   3984 Views

Avatar
Ryan M.

Community Member, 309 Posts

2 March 2011 at 3:05pm

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.

Community Member, 309 Posts

2 March 2011 at 3:51pm

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.

Community Member, 309 Posts

2 March 2011 at 3:56pm

Edited: 02/03/2011 3:57pm

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.

Community Member, 309 Posts

2 March 2011 at 5:17pm

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