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

Make ModelAdmin sort relation attributes in result table

Go to End



Community Member, 7 Posts

7 October 2011 at 10:07am

Edited: 07/10/2011 10:10am


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