具有 has_many 关系的 ModelAdmin

ModelAdmin with a has_many relationship

我正在扩展 ModelAdmin 来管理一个 DataObject,并且我有一个 $has_many 关系由另一个 DataObject 管理。我想在另一个选项卡上管理此对象,但不知道如何添加它。我的基本代码:

ApplicationAdmin.php:

class Applications extends ModelAdmin {
    private static $menu_title = 'Applications';

    private static $url_segment = 'apps';

    private static $managed_models = array (
        'Application'
    );
}

Application.php

class Application extends DataObject {
    private static $db = array(
        'Name' => "varchar"
    );

    private static $has_many = array(
        'Documents' => 'Document',
    );

    public function getCMSFields() {
        $fields = FieldList::create(
            TextField::create('Name'),
        );

        return $fields;
    }
}

Document.php

class Document extends DataObject {
    private static $db = array(
        'Title' => "varchar",
    );

    private static $has_one = array(
        "Document" => "File",
        "Application" => "Application"
    );

    public function getCMSFields () {
        $fields = FieldList::create(
            TextField::create('Title'),
            $doc = new UploadField('Document')
        );
        $doc->getValidator()->setAllowedExtensions(array('pdf', 'docx'));

        return $fields;
    }   
}

基本上我想在 Root.Documents 选项卡下管理此条目的文档。

您可以使用 GridField 来处理 ApplicationDocument 之间的关系,并根据需要将该字段放在其自己的选项卡上。示例:

# Application.php
public function getCMSFields() {

    $fields         = parent::getCMSFields();
    $nameField      = TextField::create('Name');
    $documentsField = GridField::create(
        'Documents',
        'Documents',
        $this->Documents(),
        GridFieldConfig_RelationEditor::create()
    );

    $fields->addFieldToTab(
        'Root.Main',
        $nameField
    );

    $fields->addFieldToTab(
        'Root.Documents',
        $documentsField
    );

    return $fields;

}

您的代码在 Document class 中包含一些拼写错误(class 名称中有 .php,getValidator 应该是 getValidator()),并且 class 还需要一个 $has_one = ['Application' => 'Application']; 才能起作用。