Adding a Button to CMS in SilverStripe

How to add a button to a CMS server that launches an action? I can display the button where I want to use:

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

    $fields->addFieldsToTab("Root.ButtonTest", array(
            FormAction::create('doAction', 'Action button')
        )
    );

    return $fields;
}

public function doAction() 
{
   //Do something
}

However, when a button is pressed, nothing is done.

I saw one example of how to put a button in the main action panel (next to save / publish), but this is not what I'm trying to do.

Having looked only on the documentation page , I can find, I need to do something inside:

public function getCMSActions()
{
    $actions = parent::getCMSActions();
    //Something here?
}

It is not clear how to create an action that triggers a button.

+4
source share
2 answers

/ LeftAndMain , . :

<?php
class MyExtension extends LeftAndMainExtension
{
    private static $allowed_actions = array(
        'doAction'  
    );

    public function doAction($data, $form){
        $className = $this->owner->stat('tree_class');
        $SQL_id = Convert::raw2sql($data['ID']);

        $record = DataObject::get_by_id($className, $SQL_id);

        if(!$record || !$record->ID){
            throw new SS_HTTPResponse_Exception(
                "Bad record ID #" . (int)$data['ID'], 404);
        }

        // at this point you have a $record, 
        // which is your page you can work with!

        // this generates a message that will show up in the CMS
        $this->owner->response->addHeader(
            'X-Status',
            rawurlencode('Success message!') 
        );

        return $this->owner->getResponseNegotiator()
               ->respond($this->owner->request);
    }
}

, , , LeftAndMain, mysite/_config/config.yml:

LeftAndMain:
  extensions:
    - MyExtension

. doAction - !

+8

, , , ModelAdmin.
( )

... admin:

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

    return $form;
}

MyGridFieldDetailForm_ItemRequest.php

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

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


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

    public function myAction(){ //do things } 

}
+2

Source: https://habr.com/ru/post/1538503/