答案 0 :(得分:7)
与评论中提到的@wmk一样,您可以将GridFieldPrintButton
的框架代码作为基础并从那里开始。 SilverStripe还有一个basic tutorial for creating a custom ActionProvider
。
我将为您提供一个非常基本的自定义操作提供程序,您可以复制和扩展以执行您需要的操作,而不是在此处重新编写教程。虽然你没有注意到按钮所需的确切结果,但我将只提供一个非常通用的类。
此代码是@wmk提及的GridFieldPrintButton
的精简版本。它支持按钮本身调用自定义代码以及URL。
我在代码中注意到我保留了一个“grid-print-button”的引用,这是为了让你的按钮很好地坐在打印旁边而不是可能坐在另一条线上(就像我在在我建立的旧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
构造函数中提供“左前按钮”作为GridFieldCustomButton
构造函数中的第一个参数来指定它应该在$gridFieldConfig->addComponent(new GridFieldCustomButton("buttons-before-left"))
中的位置。
例如。 GridField
有关ModelA(models.Model):
some_field_a = models.IntegerField()
ModelB(models.Model):
some_field_b = models.IntegerField()
a = models.ForeignKey(ModelA)
ModelC(models.Model):
some_field_c = models.IntegerField()
b = models.ForeignKey(ModelB)
片段的更多信息,请参阅SilverStripe developer documentation。