Silverstripe 3.1中嵌套的Dataobjects?

时间:2013-10-20 15:29:55

标签: silverstripe

是否可以在Silverstripe中创建嵌套的Dataobjects? 我用$ has_many关系尝试了它,但是第一个没有显示第二个数据对象。

这可能吗?如何?

1 个答案:

答案 0 :(得分:3)

在SilverStripe中始终可以使用嵌套的DataObjects。 在3.0之前的任何版本中,它只是界面不存在或非常糟糕 从3.0开始,您可以根据需要嵌套GridFields,不仅可以嵌套一次,还可以嵌套n次。

嵌套数据对象没什么特别之处,它与从页面到数据对象的关系一样。 关系可以是has_many,另一边是has_one,另一边是belogs_many_many的many_many。

这里有一个has_many的例子:

class TournamentPage extends Page {
    private static $has_many = array('Teams' => 'Team');
    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $fields->addFieldToTab('Root', Tab::create('TeamsTab', 'List of Teams'));
        $fields->addFieldToTab('Root.TeamsTab', GridField::create('Teams', 'The Teams', $this->Teams(), GridFieldConfig_RecordEditor::create());
        return $fields;
    }
}

class TournamentPage_Controller extends Page_Controller {}

class Team extends DataObject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('TournamentPage' => 'TournamentPage'); // to make has_many of TournamentPage work
    private static $has_many = array('Players' => 'Player');
    public function getCMSFields() {
        $fields = FieldList::create();
        $fields->push(TextField::create('Title', 'Team name');
        $fields->push(GridField::create('Players', 'The Players', $this->Players(), GridFieldConfig_RecordEditor::create());
        return $fields;
    }
}

class Player extends DataObject {
    private static $db = array('Title' => 'Varchar');
    private static $has_one = array('Team' => 'Team'); // to make has_many of Team work
    private static $has_many = array('DopingProblems' => 'DopingProblem');
    public function getCMSFields() {
        $fields = FieldList::create();
        $fields->push(TextField::create('Title', 'Player name');
        return $fields;
    }
}

及其模板:

// file: TournamentPage.ss
<% loop $Teams %>
    Team: $Title<br>
    Number of Players in this Team: $Players.Count<br>
    <ul>
        <% loop $Players %>
            <li>Player name: $Title</li>
        <% end_loop %>
    </ul>
<% end_loop %>