Tutorials - Big bits of code to help you do more
Sorting on a related DataObject in ModelAdmin
Tweet2 August 2011 | | | Supports v2.4
Sometimes, in ModelAdmin, we want to be able to have a different default sort.
Specifically, like in cases where a has_one is the preferred sorting. For example, we have a warehouse. In our DataObjects, we have the object "Lanes", has_many Products. And we have Products, has_one "Lanes". When we're browsing our Products in the admin, we want to have them default sorted by their Lane, not their name.
Just saying default_sort = 'Lanes'; sadly does not do the job. It'll give you reddish-screens and stuff. Which is not what we like.
Here's a (quite simple actually) solution.
In the ModelAdmin we've made (ProductAdmin extends ModelAdmin),
class Products extends DataObject {
public static $db = array(
'Title' => 'Varchar(255)',
'Price' => 'Currency',
);
public static $has_one = array(
'Lane' => 'Lanes',
);
public static $default_sort = 'Price ASC';
public function getCMSFields(){
$fields->addFieldsToTab('Root.Main', array(
new TextField('Title', _t($this->class . '.TITLE', 'Title *NYT*')),
new CurrencyField('Price', _t($this->class . '.PRICE', 'Price *NYT*'))
)
);
return $fields;
}
}
And the same for our Lanes-object. Offcourse.
class Lanes extends DataObject {
public static $db = array(
'Title' => 'Varchar(255)',
'LaneNumber' => 'Int',
);
public static $has_many = array(
'Products' => 'Products',
);
public static $default_sort = 'Price ASC';
public function getCMSFields(){
$fields->addFieldsToTab('Root.Main', array(
new TextField('Title', _t($this->class . '.TITLE', 'Title *NYT*')),
new DropdownField('LaneNumber', _t($this->class . '.LANENUMBER', 'Lane *NYT*), array(1 => 1, 2 => 1))
);
return $fields;
}
}
Ok, that's all simple and obvious. Just DataObjects. (Ignore the example-values and such).
Now, in the ModelAdmin, where we manage the Products, it can't be sorted by Lane Number. It won't do that.
Unless...
class ProductAdmin_CollectionController extends ModelAdmin_CollectionController{
function getSearchQuery($searchCriteria) {
if(strpos($searchCriteria['url'],'Products')){
$query = parent::getSearchQuery($searchCriteria)->leftJoin( 'Lanes', 'Products.LaneID = Lanes.ID');
return $query->orderby('Lanes.LaneNumber ASC');
}
else{
return parent::getSearchQuery($searchCriteria);
}
}
}
This simple extension on the ModelAdmin sorts our products depending on which lane they're in.
Comments
RSS feed for comments on this page RSS feed for all comments
No one has commented on this page yet.
Post a comment ...
You cannot post comments until you have logged in. Login Here.