Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

content management system - Adding a button to the CMS in SilverStripe

How do I add a button to the backend of the CMS that fires an action? I can display the button where I want using:

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

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

    return $fields;
}

public function doAction() 
{
   //Do something
}

However the button added does nothing when clicked.

I've seen one example of how to put a button on the main action bar (next to save/publish) but that's not what I'm trying to do.

Looking at the only page of documentation I can find, do I need to do something within:

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

It isn't very clear how to create the action that the button calls.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll have to extend/decorate LeftAndMain with your own extension and the action you want to call. Here's an example:

<?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);
    }
}

Once you have written an extension like this, you'll have to apply it to LeftAndMain by adding the following to your mysite/_config/config.yml:

LeftAndMain:
  extensions:
    - MyExtension

That's it. Your doAction button should now actually do something!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...