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