3

如果我有一个$has_many想要GridField在 cms 中管理的关系,我将如何限制一个对象可以拥有的关系数量?这可能吗?

我可以在模型中执行此操作,还是必须将其添加到GridField我用来添加和删除关系的检查中?

我正在考虑实施GridField_SaveHandler以进行自定义GridFieldComponent,但不确定如果我检测到有问题,如何使用它来中止保存。

4

3 回答 3

2

以下2个解决方案不是解决这个问题的最干净的方法,而是最实用和最容易实施的方法。

基本上,我建议做的就是对对象进行计数,并在计数超过一定数量后取消添加新记录的能力。

如果您想限制单个关系/网格上的记录数(假设每支球队最多 5 名球员):

class Player extends Dataobject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('TeamPage' => 'TeamPage');
}
class TeamPage extends Page {
    private static $has_one = array('Players' => 'Player');
    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $config = GridFieldConfig_RecordEditor::create();
        if ($this->Players()->count > 5) {
            // remove the buttons if we don't want to allow more records to be added/created
            $config->removeComponentsByType('GridFieldAddNewButton');
            $config->removeComponentsByType('GridFieldAddExistingAutocompleter');
        }
        $grid = GridField::create('Players', 'Players on this Team', $this->Players(), $config);
        $fields->addFieldToTab('Root.Main', $grid);
        return $fields;
    }
}

如果您想限制全局记录总数(如果我们将这种方式限制为 5,这意味着如果 1 个团队已经有 3 个玩家,那么第 2 个团队只能有 2 个):

class Player extends Dataobject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('TeamPage' => 'TeamPage');
    public function canCreate($member = null) {
        if (Player::get()->count() > 5) {
           return false;
        }
        return parent::canCreate($member);
    }
}
class TeamPage extends Page {
    private static $has_one = array('Players' => 'Player');
    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $config = GridFieldConfig_RecordEditor::create();
        $grid = GridField::create('Players', 'Players on this Team', $this->Players(), $config);
        $fields->addFieldToTab('Root.Main', $grid);
        return $fields;
    }
}
于 2013-10-28T13:22:05.197 回答
1

我写了一个快速的 jQuery 插件来限制 GridField 可以拥有的项目数量: -

在此处下载插件:- gridfieldlimit.js

https://letscrate.com/f/monkeyben/silverstripe/gridfieldlimit.js

在 getCMSFields 函数中设置插件:-

// Pass GridField configs, each one containing field name and item limit
$vars = array(
    "GridFieldLimits" => "[['GRIDFIELD_NAME_1', 3], ['GRIDFIELD_NAME_2', 6]]",
);

// Load the jquery gridfield plugin
Requirements::javascriptTemplate("themes/YOUR_THEME_NAME/javascript/gridfieldlimit.js", $vars);
于 2014-01-27T13:08:55.730 回答
0

对我有用:canCreate让 GridField 管理的 DataObject 的方法检查现有对象。

当然,这不允许您实现自定义 GridFieldComponent,因为您需要修改 DataObject 代码。

于 2013-09-26T07:20:19.253 回答