Jump to:

3461 Posts in 1065 Topics by 740 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Make ModelAdmin sort relation attributes in result table

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

Page: 1
Go to End
Author Topic: 575 Views
  • opex
    Community Member
    7 Posts

    Make ModelAdmin sort relation attributes in result table Link to this post


    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

Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.