Add buttons for custom action to ModelAdmin
Asked Answered
R

1

6

When managing Dataobjects with ModelAdmin in Silverstripe 3, i was wondering how you can add buttons for custom action to the list view as well as to the edit-page.

I've managed to add a button for a action to the edit-page by setting the ItemRequest on the ModelAdmins GridField class with the code below:

class MyModelAdmin extends ModelAdmin
{
    //...

    public function getEditForm($id = null, $fields = null)
    {
        $form = parent::getEditForm($id, $fields);
        $form
            ->Fields()
            ->fieldByName($this->sanitiseClassName($this->modelClass))
            ->getConfig()
            ->getComponentByType('GridFieldDetailForm')
            ->setItemRequestClass('MyModelGridFieldDetailForm_ItemRequest');

        return $form;
    }

}

MyModelGridFieldDetailForm_ItemRequest.php

class MyModelGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest
{
    function ItemEditForm()
    {
        $form = parent::ItemEditForm();
        $formActions = $form->Actions();

        $button = FormAction::create('myAction');
        $button->setTitle('My Custom Action');
        $button->addExtraClass('ss-ui-action-constructive');
        $formActions->push($button);

        $form->setActions($formActions);
        return $form;
    }


    function myAction($data, $form)
    {

        //do things

        $form->sessionMessage('My Action has been successful', 'good');

        if ($this->gridField->getList()->byId($this->record->ID)) {
            return $this->edit(Controller::curr()->getRequest());
        } else {
            $noActionURL = Controller::curr()->removeAction($data['url']);
            Controller::curr()->getRequest()->addHeader('X-Pjax', 'Content');
            return Controller::curr()->redirect($noActionURL, 302);
        }
    }

}

So the question is:

Can i have a button for the same action in the ModelAdmin GridField Listview? So that it appears next to the edit and delete button:

ModelAdmin GridField actions

Rhadamanthus answered 21/8, 2013 at 5:21 Comment(0)
K
6

You can do this by creating your own GridFieldComponent implementing GridField_ColumnProvider and GridField_ActionProvider.

In your case you can pretty much copy the GridFieldDeleteAction class and edit getColumnContent() with your own GridField_FormAction and edit handleAction() to do your magic.

Krum answered 21/8, 2013 at 11:50 Comment(1)
that'll do - thanks :) i was kind of hoping for some magic method like getCMSActions() i'd just have to override to change both areas...Rhadamanthus

© 2022 - 2024 — McMap. All rights reserved.