phpcontent-management-systemsilverstripe

How to change order of items in SilverStripe GridField


I use a GridField in SilverStripe to create HTML section items that are rendered on a page. This works so far but it always displays the sections in the order that I added them to the CMS or rather by the ID it gets when it's created.

So my question is: How can i change that order. I don't want to manually change the IDs but would rather do a simple drag and drop.

Edit: Could the use of Elemental be a solution to this problem?

Screenshot of the CMS view

The Page:

class HomePage extends Page
{
    private static $has_many = [
        'SectionObjects' => SectionObject::class
    ];

    public function getCMSFields()
    {
        $fields = parent::getCMSFields();

        $fields->addFieldToTab('Root.Sections',
            $grid = GridField::create('SectionObjects', 'Sections', $this->SectionObjects(), GridFieldConfig_RecordEditor::create())
        );

        $config = $grid->getConfig();

        $dataColumns = $config->getComponentByType(GridFieldDataColumns::class);

        $dataColumns->setDisplayFields([
            'ID' => 'ID',
            'LastEdited' => 'Changed'
        ]);

        return $fields;
    }
}

The Section object

class SectionObject extends DataObject{

    private static $db = [
        'Content' => 'Text',
        'BgColor' => Color::class
    ];

    private static $has_one = [
        'HomePage' => HomePage::class
    ];

    public function getCMSFields(){
        return new FieldList(
            TextareaField::create('Content','SectionContent'),
            ColorField::create('BgColor', 'Hintergrundfarbe')
        );
    }
}

Solution

  • Definitely using the elemental module would allow you to have the kind of behaviour you want - but if you don't want to go to the effort of refactoring your code to comply with that module, you could use either the gridfieldextensions or sortablegridfield module to allow you to sort the gridfield (with drag and drop) to your heart's content.