Skip to content

Instantly share code, notes, and snippets.

@GuySartorelli
Last active June 25, 2024 00:04
Show Gist options
  • Save GuySartorelli/1d3516714308685b3dfa84e8f9322de3 to your computer and use it in GitHub Desktop.
Save GuySartorelli/1d3516714308685b3dfa84e8f9322de3 to your computer and use it in GitHub Desktop.
A really basic example of adding an action to a gridfield in Silverstripe CMS 4's SecurityAdmin
<?php
namespace App\GridField;
use SilverStripe\Forms\GridField\AbstractGridFieldComponent;
use SilverStripe\Forms\GridField\GridField_HTMLProvider;
class Button extends AbstractGridFieldComponent implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler
{
protected $targetFragment;
public function __construct($targetFragment = 'before')
{
$this->targetFragment = $targetFragment;
}
public function getHTMLFragments($gridField)
{
// Build action button
$button = new GridField_FormAction(
$gridField,
'sendfile',
'Download The File',
'sendfile',
null
);
// "no-ajax" here is important!
$button
->addExtraClass('btn btn-dark no-ajax font-icon-down-circled btn--icon-large')
->setForm($gridField->getForm());
return [
$this->targetFragment => $button->Field()
];
}
public function getActions($gridField)
{
return ['sendfile'];
}
public function getURLHandlers($gridField)
{
return [
'sendfile' => 'sendFile',
];
}
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
{
// notice the lowercase action name. Even if you have uppercase for the action name everywhere else,
// the action name passed in here will *always* be fully lowercase.
if ($actionName == 'sendfile') {
return $this->sendFile($gridField);
}
return null;
}
public function sendFile()
{
return HTTPRequest::send_file('Some file content', 'file.txt', 'text/plain');
}
}
SilverStripe\Admin\SecurityAdmin:
extensions:
- App\Extensions\MyExtension
<?php
namespace App\Extensions;
use App\GridField\Button;
use SilverStripe\Core\Extension;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\GridField\GridField;
class MyExtension extends Extension
{
public function updateEditForm(Form $form)
{
/** @var GridField $membersGridField */
$membersGridField = $form->Fields()->dataFieldByName('Members');
$membersGridField->getConfig()->addComponent(new Button());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment