1

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

这可能吗?如何?

4

1 回答 1

3

在 SilverStripe 中,嵌套 DataObjects 的层次结构始终是可能的。它只是在 3.0 之前的任何版本中都不存在或非常糟糕的接口,从 3.0 开始,您可以尽可能多地嵌套 GridFields,不仅可以嵌套一次,还可以嵌套n多次。

嵌套数据对象没什么特别的,它就像从页面到数据对象的关系一样。关系可以是 has_many 和 has_one 在另一边,或者是 many_many 和 belogs_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 %>
于 2013-10-21T01:52:30.027 回答