sortablegridfield/docs/ModelAdminExample.md
Guy Sartorelli e374c93ae3 NEW Extend new AbstractGridFieldComponent class
This makes the `GridFieldSortableRows` component `Injectable`, and
allows any future enhancements in the new abstract class to
automatically apply without requiring additional changes in this module.

The class is introduced in silverstripe/framework 4.11.0 so the
dependency constraint needs to be updated.
2022-02-12 19:24:44 +13:00

1.4 KiB

ModelAdmin implementation Example

/**** MyModelAdmin.php ****/
use SilverStripe\Admin\ModelAdmin;
use SilverStripe\Forms\GridField\GridField;
use UndefinedOffset\SortableGridField\Forms\GridFieldSortableRows;

class MyModelAdmin extends ModelAdmin
{
    private static $menu_title = 'My Model Admin';

    private static $url_segment = 'my-model-admin';

    private static $managed_models = [
        MATestObject::class,
    ];

    public function getEditForm($id = null, $fields = null)
    {
        $form = parent::getEditForm($id, $fields);

        // This check is simply to ensure you are on the managed model you want adjust accordingly
        if ($this->modelClass === MATestObject::class) {
            $gridField = $form->Fields()->dataFieldByName($this->sanitiseClassName($this->modelClass));

            // This is just a precaution to ensure we got a GridField from dataFieldByName() which you should have
            if ($gridField instanceof GridField) {
                $gridField->getConfig()->addComponent(GridFieldSortableRows::create('SortOrder'));
            }
        }

        return $form;
    }
}

/**** MATestObject.php ****/
use SilverStripe\ORM\DataObject;

class MATestObject extends DataObject
{
    private static $db = [
        'Title' => 'Varchar',
        'SortOrder' => 'Int',
    ];

    private static $indexes = [
        'SortOrder' => true,
    ];

    private static $default_sort = 'SortOrder';
}