Skip to content

Commit

Permalink
FIX Respect searchable_fields
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Mar 22, 2023
1 parent 0d041e7 commit 66a2bb5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 11 deletions.
30 changes: 19 additions & 11 deletions src/Forms/GridField/GridFieldFilterHeader.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,21 +254,29 @@ public function getManipulatedData(GridField $gridField, SS_List $dataList)
public function canFilterAnyColumns($gridField)
{
$list = $gridField->getList();

if (!$this->checkDataType($list)) {
if (!($list instanceof Filterable) || !$this->checkDataType($list)) {
return false;
}

$columns = $gridField->getColumns();
foreach ($columns as $columnField) {
$metadata = $gridField->getColumnMetadata($columnField);
$title = $metadata['title'];

if ($title && $list->canFilterBy($columnField)) {
return true;
$modelClass = $gridField->getModelClass();
$searchableFields = Config::inst()->get($modelClass, 'searchable_fields');
if (!empty($searchableFields)) {
// Scenario #1 - searchable_fields is defined on model class
foreach ($searchableFields as $searchableField) {
if ($list->canFilterBy($searchableField)) {
return true;
}
}
} else {
// Scenario #2 - searchable_fields is not defined, use what's inside the gridfield
$columns = $gridField->getColumns();
foreach ($columns as $columnField) {
$metadata = $gridField->getColumnMetadata($columnField);
$title = $metadata['title'];
if ($title && $list->canFilterBy($columnField)) {
return true;
}
}
}

return false;
}

Expand Down
20 changes: 20 additions & 0 deletions tests/php/Forms/GridField/GridFieldFilterHeaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,24 @@ public function testCustomSearchField()

$this->assertEquals('ReallyCustomSearch', $this->component->getSearchField());
}

public function testCanFilterAnyColumns()
{
$gridField = $this->gridField;
$filterHeader = $gridField->getConfig()->getComponentByType(GridFieldFilterHeader::class);

// test that you can filter by something if searchable_fields is not defined
// silverstripe will scaffold db columns that are in the gridfield to be
// searchable by default
Config::modify()->remove(Team::class, 'searchable_fields');
$this->assertTrue($filterHeader->canFilterAnyColumns($gridField));

// test that you can filterBy if searchable_fields is defined
Config::modify()->set(Team::class, 'searchable_fields', ['Name']);
$this->assertTrue($filterHeader->canFilterAnyColumns($gridField));

// test that you can not filterBy if searchable_fields is not defined and not legit
Config::modify()->set(Team::class, 'searchable_fields', ['WhatIsThis']);
$this->assertFalse($filterHeader->canFilterAnyColumns($gridField));
}
}

0 comments on commit 66a2bb5

Please sign in to comment.