Jump to:

3430 Posts in 1057 Topics by 734 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: 554 Views
  • opex
    Avatar
    Community Member
    7 Posts

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

    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

    554 Views
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.