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've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

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

Make ModelAdmin sort relation attributes in result table


Go to End


1487 Views

Avatar
opex

Community Member, 7 Posts

7 October 2011 at 10:07am

Edited: 07/10/2011 10:10am

Hi,

I'm looking into the possibility to get ModelAdmin to sort a result table on a relation attribute. To gain a better understanding of what I'm trying to accomplish I'm going to provide my current working solution (of which I'm not very proud ;))

class MyModel extends DataObject {
	$has_one = array('Owner' => 'Member');
	$summary_fields = array('Owner.Title');
	...
	public function extendedSQL($filter = "", $sort = "", $limit = "", $join = "", $having = "") {
		$query = parent::extendedSQL($filter, $sort, $limit, $join, $having);
		// As ugly as ugly gets
		return MySQLQuery::cast($query);
	}
}

class MySQLQuery extends SQLQuery {
	public static function cast($source) {
		if ($source instanceof SQLQuery) {
			$serialized = serialize($source);
			$serialized = str_replace('8:"SQLQuery"', '10:"MySQLQuery"', $serialized);
			$target = unserialize($serialized);
			foreach ($source as $prop => $value)
				$target->$prop = $value;
			return $target;
		}
		return $source;
	}

	public function canSortBy($fieldName) {
		if ($fieldName == 'Owner.Title') return true;
		return parent::canSortBy($fieldName);
	}

	public function execute() {
		if (substr($this->orderby, 0, 11) == 'Owner.Title') {
			$sort = trim(substr($this->orderby, -4));
			$this->orderby = "Member.FirstName $sort, Member.Surname $sort";
			$this->leftJoin('Member', 'MyModel.OwnerID = Member.ID');
		}
		return parent::execute();
	}
}

As you can see I'm trying to sort the table by the owners first- and surname. I got it working but I'm hoping someone might have a better way to accomplish this that is less of a hack.

/ John