就像评论中提到的@wmk一样,您可以直接获取框架代码GridFieldPrintButton
作为基地并从那里出发。 SilverStripe 还有一个创建自定义的基本教程ActionProvider https://docs.silverstripe.org/en/3.1/developer_guides/forms/how_tos/create_a_gridfield_actionprovider/.
我不会在这里重复教程,而是为您提供一个非常基本的自定义操作提供程序,您可以复制和扩展它来执行您需要的操作。虽然您没有注意到您想要从按钮获得的确切结果,但我将提供一个非常通用的类。
该代码是以下代码的精简版本GridFieldPrintButton
@wmk 提到的。它支持按钮本身调用自定义代码以及 URL。
我在代码中注意到我保留了“网格打印按钮”的引用,这是为了使您的按钮很好地位于打印旁边,而不是可能位于另一行(就像我在测试中所做的那样)我建立的较旧的 3.1 网站)。
class GridFieldCustomButton implements GridField_HTMLProvider, GridField_ActionProvider, GridField_URLHandler {
protected $targetFragment;
protected $someCustomConstructData;
//TargetFragment is just for positioning control of the HTML fragment
//SomeCustomConstructData is just an example of providing some default options into your butotn
public function __construct($targetFragment = "after", $someCustomConstructData = null) {
$this->targetFragment = $targetFragment;
$this->someCustomConstructData = $someCustomConstructData;
}
//Generate the HTML fragment for the GridField
public function getHTMLFragments($gridField) {
$button = new GridField_FormAction(
$gridField,
'custom',
'Custom Action',
'custom',
null
);
return array(
//Note: "grid-print-button" is used here to match the styling of the buttons in ModelAdmin
$this->targetFragment => '<p class="grid-print-button">' . $button->Field() . '</p>',
);
}
public function getActions($gridField) {
return array('myCustomAction');
}
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if($actionName == 'myCustomAction') {
return $this->handleMyCustomAction();
}
}
//For accessing the custom action from the URL
public function getURLHandlers($gridField) {
return array(
'myCustomAction' => 'handleMyCustomAction',
);
}
//Handle the custom action, for both the action button and the URL
public function handleMyCustomAction($gridField, $request = null) {
//Do your stuff here!
}
}
继续评论中的讨论,您将需要修改您的自定义ModelAdmin
向其添加新组件GridField
.
class MyCustomAdmin extends ModelAdmin
{
private static $managed_models = array(
'MyCustomObject'
);
private static $url_segment = 'custom-admin';
private static $menu_title = 'All Custom Objects';
public function getEditForm($ID = null, $Fields = null)
{
$form = parent::getEditForm($ID, $Fields);
$fields = $form->Fields();
$gridField = $fields->fieldByName('MyCustomObject');
$gridFieldConfig = $gridField->getConfig();
$gridFieldConfig->addComponent(new GridFieldCustomButton());
return $form;
}
}
具体来说,该行$gridFieldConfig->addComponent(new GridFieldCustomButton())
完成这项工作,将您的自定义按钮如我上面所示并将其添加到ModelAdmin
。您还可以指定它应该放在哪里GridField
也通过提供“buttons-before-left”作为第一个参数GridFieldCustomButton
构造函数。
eg. $gridFieldConfig->addComponent(new GridFieldCustomButton("buttons-before-left"))
有关更多信息GridField
片段可以在SilverStripe 开发人员文档 https://docs.silverstripe.org/en/3.1/developer_guides/forms/field_types/gridfield/#flexible-area-assignment-through-fragments.