Custom Actions on DataObject/ModelAdmin

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!

1 Like

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

}

1 Like

thank you very much!

@theTigerDuck is it possible to add actions to a different part of the edit form eg. the top right corner of the page or to have a drop menu of actions instead? If I add multiple buttons for different actions it starts to get quite cluttered.

Also - I keep getting a “forbidden” error when I click on the button, despite having ItemEditForm listed as an allowed action (as per example code above). Any ideas?

you could put them to “MoreOptions” or group them like described here (didn’t tested):

$fields->addFieldToTab('ActionMenus.MoreOptions', FormAction::create('minor', 'Minor action'));
1 Like