Fraser
Fraser

Reputation: 14246

Silverstripe. Modifying gridfieldconfig in modeladmin to add sortable headers

I'm using modeladmin to display a number of event DataObjects.

I've added a number of columns to the summary fields which the client wishes to be able to sort by. Currently, only title is sortable by default. Is it possible to modify gridfieldconfig in modeladmin? In particular to add fields to GridFieldSortableHeader?

Here is my Event dataobject with the summary fields that I need to be able to sort by in modeladmin:

......
static $summary_fields = array('Title', 'DescriptionSummary', 'EventStartDate', 'EventEndDate', 'EventVenue');

static $field_labels = array('DescriptionSummary' => 'Description', 'EventStartDate' => 'Start Date', 'EventEndDate' => 'End Date', 'EventVenue' => 'Venue');

private $widget;
//TO GET THE SUMMARY FIELD VALUES
public function getEventVenue(){
    if ($eventVenue = $this->Venue()->Title) return $eventVenue;
    return "No Venue specified";
}

public function getEventStartDate(){
    if ($startDate = DataObject::get_one('CalendarDateTime', 'EventID = '.$this->ID)) return $startDate->StartDate;
    return "No start dates specified";
}

public function getEventEndDate(){
    if ($startDate = DataObject::get_one('CalendarDateTime', 'EventID = '.$this->ID)) return $startDate->EndDate;
    return "No end dates specified";
}
....

and my event admin:

class EventAdmin extends ModelAdmin {

    public static $managed_models = array('CalendarEvent', 'Venue', 'EventCategory');
    static $url_segment = 'events';
    static $menu_title = 'Events';

}

Upvotes: 1

Views: 3938

Answers (1)

Ingo Schommer
Ingo Schommer

Reputation: 716

I've just added some info to doc.silverstripe.org on how to override the edit form and access the GridField within (link). The relevant bits (adapted to your use case):

class EventAdmin extends ModelAdmin {
  // ...

  public function getEditForm($id = null, $fields = null) {
    $form = parent::getEditForm($id, $fields);
    $gridField = $form->Fields()->fieldByName($this->sanitiseClassName($this->modelClass));
    $gridField->getConfig()->getComponentByType('GridFieldSortableHeader')
      ->setFieldSorting(array(...));
    return $form;
  }

}


In case you're trying to sort by the CalendarDate relationship and the EventStartDate field, you'll generally have to override the results list in ModelAdmin, see docs. While you can add the necessary join there (DataQuery->leftJoin), its not possible to select additional columns in the query. So that would just allow you to sort by EventStartDate by default, but not to re-sort the GridField via the UI. Its a missing feature, we should really support "dot notations" in DataList->sort() out of the box.

Upvotes: 10

Related Questions