ModelAdmin: filter by $many_many with a dropdown

When you have a DataObject with a $many_many "Tags" => "Tag" you can add a filter dropdown in ModelAdmin by overwriting the scaffoldSearchFields() method:

private static $many_many = [
    'Tags' => 'Tag'
];

private static $searchable_fields = [
    'Title',
    'Description',
    'Tags.Title' => [
        "field" => "DropdownField",
        "filter" => "ExactMatchFilter",
        "title" => 'Tag'
    ]
];

/*
...
*/

public function scaffoldSearchFields($_params = null) {
    $fields = parent::scaffoldSearchFields($_params);

    $tagDropdown = DropdownField::create(
        'Tags.Title', 
        'Tag', 
        Tag::get()->map('Title', 'Title')->toArray()
    );

    $fields->replaceField('Tags__Title', $tagDropdown);

    return $fields;
}
Rate this post (3 rating(s))

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments