silverstripesilverstripe-4

Silverstripe GridField set search result format


I've got a class which has the below structure.

class TheTeam extends BaseElement { private static $table_name = 'theTeam';

private static $inline_editable = false;

private static $belongs_many_many = [
    'People' => Person::class,
];
.......

The people object results are displayed in another tab and I can add/remove people and it all works fine. However, the result when I search for a person only displays the title field. It doesn't show the name.

Below is the structure for the Person class.

class Person extends DataObject
{
    private static $table_name = 'Person';
....
    private static $db = [
        'Sort' => 'Int',
        'Title' => 'Text',
        'Name' => 'Varchar(255)',
        'Role' => 'Text',
        'About' => 'Text',
        'Phone' => 'Text',
        'Email' => 'Text'
    ];

    private static $many_many = [
        'Teams' => Team::class,
        'Departments' => Department::class,
        'TheTeams' => TheTeam::class,
    ];
    private static $summary_fields = [
        'Name' => 'Name',
        'Created.Nice' => 'Created'
    ];

    private static $searchable_fields = [
        'Name',
        'Role',
        'Teams.ID' => ['field' => DropdownField::class, 'title' => 'Teams', 'filter' => ExactMatchFilter::class],
        'Departments.Title'
    ];
     .....

Appreciate any help.

enter image description here My issue is when I search for a person, only the title is displayed in the search results. How can I expand the results to display the person's name as well?


Solution

  • In Silverstripe CMS the "Title" field is a fallback for components such as the GridFieldAddExistingAutocompleter (which is the component you're interacting with there) use if they haven't been given a specific field to display.

    Given that you're using the "Title" field for something other than the display name of the record, you'll need to tell the component specifically which field to use instead.

    To do this, you'll need to fetch it from the gridfield config (whether it's a gridfield in a ModelAdmin or on some other record) and then call setResultsFormat() on it.

    e.g. if the gridfield is in a ModelAdmin:

    protected function getGridFieldConfig(): GridFieldConfig
    {
        $config = parent::getGridFieldConfig();
        $config->getComponentByType(GridFieldAddExistingAutocompleter::class)->setResultsFormat('$FullName');
        return $config;
    }
    

    Note that in the above example the new display field to use is called FullName (which could also be a getFullName() method) on the record. The single quotes are intentional - we're passing a string to be interpreted by the templating handler in this case.