myk
myk

Reputation: 73

Use setQueriedColumns on GridField

I have a dataobject which I want to use on a GridField on a page but I want to limit the columns displayed. I used setQueriedColumns() to list the fields I wanted but it is still displaying the default $summary_fields from the dataobject.

MyActivity dataobject:

class MyActivity extends DataObject{
private static $db = array(
    'Title' => 'Varchar(255)',
    'URLSegment' => 'Varchar(512)',
    'IsPublished' => 'Boolean',
    'IsPublic' => 'Boolean',
    'IsBooked' => 'Boolean',
    'MaxDuration' => 'Int',
    'PricePoint' => 'Int',
    'Summary' => 'HTMLText',
    'Body' => 'HTMLText',
    'Sort' => 'Int'
);

private static $has_one = array(
    'FileAttachment'        =>  'File'
);

private static $summary_fields = array(
    'Title' => 'Name',
    'URLSegment' => 'URLSegment',
    'IsPublished' => 'Published',
    'IsBooked' => 'Booked',
    'Events.Count' => 'List of Events',
    'Categories.Count' => ' of Categories'
);
static $has_many = array(
    'Events' => 'MyEvent'
);

static $belongs_many_many = array(
    'Categories' => 'MyCategory'
);

...

}

MyActivityPage:

class MyActivityPage extends Page{
public function getCMSFields(){
    $fields = parent::getCMSFields();

    $GridFieldConfig = GridFieldConfig_RecordEditor::create();

    $fields->addFieldToTab('Root.Courses',
        GridField::create(
                'FileAttachment',
                'Activity List',
                MyActivity::get()->filter(['IsPublished'    =>  1])
                    ->setQueriedColumns([
                            'Title',
                            'URLSegment',
                            'IsPublished'
                        ]),
                $GridFieldConfig
        )
    );

    return $fields;
}
...
}

Upvotes: 1

Views: 60

Answers (1)

myk
myk

Reputation: 73

After thorough searching, I got what I'm looking for. Apparently, we can set the columns using GridFieldConfig then limit the fields by overriding the $summary_fields using the setDisplayFields() method in the GridFieldDataColumns object.

This could be handy to people who are looking for similar solution.

$gridField = GridField::create(
            'FileAttachment',
            'Activity List',
            MyActivity::get()->filter(['IsPublished' =>  1]),
            $GridFieldConfig
    )
$gridField->getConfig()
          ->getComponentByType('GridFieldDataColumns')
          ->setDisplayFields([
                'Title'         => 'Title',
                'URLSegment'    =>  'URLSegment',
                'IsPublished'   =>  'IsPublished'
             ]);

$fields->addFieldToTab('Root.Courses',$gridField);`

Upvotes: 1

Related Questions