Custom Actions on DataObject/ModelAdmin


#1

Silverstripe Version: 4.2.1

Question: How can I add custom actions when looking at a DataObject in the cms?

Hello,

I am trying to find a way to add a dropdown or button with custom actions when viewing a dataobject in the cms (e.g. I would like to click a button that would trigger an email or similar).
I did see there is a way to do this on the SiteTree object (e.g. the Archive action). but I couldn’t quite find a way to do this on simple dataobjects. How would you advice I should approach this?

To clarify I am talking about this section of the cms when looking at a dataobject:

Thanks in advance!


#2

You must set ItemRequestClass in getEditForm do something like this:

            public function getEditForm($id = null, $fields = null) {
        		$form = parent::getEditForm($id, $fields);
        		if($this->modelClass == "Competition") {
        			$form
        			->Fields()
        			->fieldByName($this->sanitiseClassName($this->modelClass))
        			->getConfig()
        			->getComponentByType(GridFieldDetailForm::class)
        			->setItemRequestClass(CompetitionModelGridFieldDetailForm_ItemRequest::class);
        		}
        		return $form;
        	}

and then:

class CompetitionModelGridFieldDetailForm_ItemRequest extends GridFieldDetailForm_ItemRequest{
private static $allowed_actions = array("ItemEditForm");

function ItemEditForm() {
	$form = parent::ItemEditForm();
	$formActions = $form->Actions();

	$button = FormAction::create('generateTable');
	$button->setTitle('Tabelle berechnen');
	$button->addExtraClass('ss-ui-action-constructive');
	$formActions->push($button);
	
	$form->setActions($formActions);
	return $form;
}


function generateTable($data, $form) {

	//do things
	$form->sessionMessage('Tabelle wurde berechnet.', '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);
	}
}

}


#3

thank you very much!