SilverStripe - 限制数据对象可以拥有的许多关系的数量

时间:2013-09-25 12:58:36

标签: silverstripe

如果我想在cms中使用$has_many建立GridField关系,那么我如何限制一个对象可以拥有的关系数量?这可能吗?

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

我正在考虑实施GridField_SaveHandler来制作自定义GridFieldComponent但不确定如果我发现某些内容错误,我将如何使用它来中止保存。

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分: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);

答案 2 :(得分:0)

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

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