SilverStripe 3.6.5 - 将上传的文件从前端SilverStripe表单关联到数据对象

时间:2018-04-06 18:35:25

标签: php forms upload silverstripe

我有一个名为'Project'的数据对象,它与另一个名为'ProjectExpenseForm'的数据对象有$ has_many关系。在网站的前端是SilverStripe表单,用于更新项目的某些字段。新文件和图像也可以以前端形式上传。

我正在使用名为SilverStripe Dropzone Master(https://github.com/unclecheese/silverstripe-dropzone)的模块在前端表单上创建上传字段。我设法让它工作,以便将所有上传保存到assets目录中的正确文件夹(每个Project都有一个上传文件的文件夹,设置是assets / projects / [project id] / files /)。但是我不确定如何将这些上传的文件附加/关联到项目。将它们上传到正确的文件夹是好的,但如果文件与项目没有关联,那就不好了。

以下是前端表单的代码:

public function UpdateMyProjectProfileForm()
{
    $fieldsArr = array();
    $member = Member::currentUser();

    if (!$member) {
        return "<div class='text-danger'>Error: must be logged in to view this page.</div>";
    }
    $request = $this->getRequest();
    $projectName = $request->param('ProjectName');
    $projectNameID = explode("-", $projectName);

    $projectNameID = $projectNameID[0];

    if ($member->inGroup('project-lead')) {
        $project = Project::get()
            ->filter(
                array(
                    "ProjectLeadID" => $member->ID,
                    "ID" => $projectNameID
                )
            )
            ->first();
        $name = ReadonlyField::create('Name', 'Name of Project', $project->Name);
        $firstName = ReadonlyField::create('FirstName', 'First Name of Project Manager', $project->FirstName);
        $lastName = ReadonlyField::create('LastName', 'Last Name of Project Manager', $project->LastName);
        $phone = ReadonlyField::create('Phone', "Phone Number", $project->Phone);
        $emailAddress = ReadonlyField::create('Email', "Manager Email", $project->Email);
        $notes = TextareaField::create('Notes', 'Notes', $project->Notes);
        $projectSummary = TextareaField::create('ProjectSummary', "Project Summary", $project->ProjectSummary);
        $imageUploader = FileAttachmentField::create('MyFile', 'Upload a file')
            ->setView('grid')
            ->setMultiple(true)
            ->setFolderName("projects/".$project->ID.'/expenses'); //THIS WORKS - Stores the file(s) uploaded to the proper directory

        array_push($fieldsArr, $name);
        array_push($fieldsArr, $firstName);
        array_push($fieldsArr, $lastName);
        array_push($fieldsArr, $phone);
        array_push($fieldsArr, $emailAddress);
        array_push($fieldsArr, $notes);
        array_push($fieldsArr, $projectSummary);
        array_push($fieldsArr, $imageUploader);
        $fields = new FieldList($fieldsArr);

        $updateButton = FormAction::create('update', 'Update')
            ->addExtraClass("btn btn-default commonBtn");

        $actions = new FieldList($updateButton);
        $required = new RequiredFields(
            array('Name', 'Notes', 'ProjectSummary')
        );

        $form = new Form($this, $projectName . '/UpdateMyProjectProfileForm', $fields, $actions, $required);

        $form->setFormMethod('POST', true);

        return $form;
    }
}

public function update($data, Form $form)
{
    $member = Member::currentUser();

    $request = $this->getRequest();
    $projectName = $request->param('ProjectName');
    $projectNameID = explode("-", $projectName);
    $projectNameID = $projectNameID[0];

    $project = Project::get()
        ->filter(
            array(
                "ProjectLeadID" => $member->ID,
                "ID" => $projectNameID
            )
        )
        ->first();

    if ($data['Name'] == "") {
        $form->addErrorMessage("Name", "Project Name is required.", "text-danger");
        return $this->redirectBack();
    }

    if ($data['Notes'] == "") {
        $form->addErrorMessage("Notes", "Notes is required.", "text-danger");
        return $this->redirectBack();
    }

    if ($data['ProjectSummary'] == "") {
        $form->addErrorMessage("ProjectSummary", "Project Summary is required.", "text-danger");
        return $this->redirectBack();
    }

    $member = Member::currentUser();

    if (!$member) {
        $form->addErrorMessage("FirstName", "Error: user profile not found.", "text-danger");
        return $this->redirectBack();
    }

    $project->Name = $data['Name'];
    $project->Notes = $data['Notes'];
    $project->ProjectSummary = $data['ProjectSummary'];
    $project->write();

    $form->sessionMessage("Project profile successfully updated.", 'text-success');

    return $this->redirectBack();
}

这是项目类:

public function UpdateMyProjectProfileForm()
{
    $fieldsArr = array();
    $member = Member::currentUser();

    if (!$member) {
        return "<div class='text-danger'>Error: must be logged in to view this page.</div>";
    }
    $request = $this->getRequest();
    $projectName = $request->param('ProjectName');
    $projectNameID = explode("-", $projectName);

    $projectNameID = $projectNameID[0];

    if ($member->inGroup('project-lead')) {
        $project = Project::get()
            ->filter(
                array(
                    "ProjectLeadID" => $member->ID,
                    "ID" => $projectNameID
                )
            )
            ->first();
        $name = ReadonlyField::create('Name', 'Name of Project', $project->Name);
        $firstName = ReadonlyField::create('FirstName', 'First Name of Project Manager', $project->FirstName);
        $lastName = ReadonlyField::create('LastName', 'Last Name of Project Manager', $project->LastName);
        $phone = ReadonlyField::create('Phone', "Phone Number", $project->Phone);
        $emailAddress = ReadonlyField::create('Email', "Manager Email", $project->Email);
        $notes = TextareaField::create('Notes', 'Notes', $project->Notes);
        $projectSummary = TextareaField::create('ProjectSummary', "Project Summary", $project->ProjectSummary);
        $imageUploader = FileAttachmentField::create('MyFile', 'Upload a file')
            ->setView('grid')
            ->setMultiple(true)
            ->setFolderName("projects/".$project->ID.'/expenses');

        array_push($fieldsArr, $name);
        array_push($fieldsArr, $firstName);
        array_push($fieldsArr, $lastName);
        array_push($fieldsArr, $phone);
        array_push($fieldsArr, $emailAddress);
        array_push($fieldsArr, $notes);
        array_push($fieldsArr, $projectSummary);
        array_push($fieldsArr, $imageUploader);
        $fields = new FieldList($fieldsArr);

        $updateButton = FormAction::create('update', 'Update')
            ->addExtraClass("btn btn-default commonBtn");

        $actions = new FieldList($updateButton);
        $required = new RequiredFields(
            array('Name', 'Notes', 'ProjectSummary')
        );

        $form = new Form($this, $projectName . '/UpdateMyProjectProfileForm', $fields, $actions, $required);

        $form->setFormMethod('POST', true);

        return $form;
    }
}

public function update($data, Form $form)

{
    $member = Member::currentUser();

    $request = $this->getRequest();
    $projectName = $request->param('ProjectName');
    $projectNameID = explode("-", $projectName);
    $projectNameID = $projectNameID[0];

    $project = Project::get()
        ->filter(
            array(
                "ProjectLeadID" => $member->ID,
                "ID" => $projectNameID
            )
        )
        ->first();

    if ($data['Name'] == "") {
        $form->addErrorMessage("Name", "Project Name is required.", "text-danger");
        return $this->redirectBack();
    }

    if ($data['Notes'] == "") {
        $form->addErrorMessage("Notes", "Notes is required.", "text-danger");
        return $this->redirectBack();
    }

    if ($data['ProjectSummary'] == "") {
        $form->addErrorMessage("ProjectSummary", "Project Summary is required.", "text-danger");
        return $this->redirectBack();
    }

    $member = Member::currentUser();

    if (!$member) {
        $form->addErrorMessage("FirstName", "Error: user profile not found.", "text-danger");
        return $this->redirectBack();
    }

    $project->Name = $data['Name'];
    $project->Notes = $data['Notes'];
    $project->ProjectSummary = $data['ProjectSummary'];
    $project->write();

    $form->sessionMessage("Project profile successfully updated.", 'text-success');

    return $this->redirectBack();
}

项目类(已删除了很多 - 我只保留了相关部分):

<?php

class Project extends DataObject
{

    private static $db = array(
        'Name'              => 'varchar(255)',,
        'FirstName'         => 'varchar(255)',
        'LastName'          => 'varchar(255)',
        'ProjectSlug'       => 'varchar(255)',
        'Email'             => 'varchar(255)',
        'Phone'             => 'varchar(255)',
        'Notes'             => 'Text',
        'ProjectSummary'     => 'Text',
    );

    // One-to-one relationship with gallery page
    private static $has_one = array(
        'MainImage' => 'Image',
        "Status" => 'ProjectStatus',
        'ProjectLead' => 'ProjectLead'
    );
    private static $has_many = array(
        'AdditionalProjectImages' => 'AdditionalProjectImage',
        'ProjectExpenseForms' => 'ProjectExpenseForm',
    );
    // Tell the datagrid what fields to show in the table
    private static $summary_fields = array(
        'ID' => 'ID',
        'Name' => 'Project',
    );

    // tidy up the CMS by not showing these fields

    public function getCMSFields()
    {
        $fields = parent::getCMSFields();
        $fields->removeByName("ProjectExpenseForms");
        $fields->removeByName("AdditionalProjectImages");

        $fields->addFieldToTab("Root.Main", new TextField("ProjectSlug", "Project Slug"));



        $projectMainImgUploadField = new UploadField("MainImage", "Project Main Image");
        $projectMainImgUploadField->setFolderName("projects/".$this->ID.'/images');
        $fields->addFieldToTab('Root.Main', $projectMainImgUploadField);
        $fields->addFieldToTab("Root.Main", new TextField("Name", "Project Name"));
        $fields->addFieldToTab("Root.Main", new TextField("FirstName", "First Name"));
        $fields->addFieldToTab("Root.Main", new TextField("LastName", "Last Name"));
        $fields->addFieldToTab("Root.Main", new TextField("Phone", "Phone Number"));
        $fields->addFieldToTab("Root.Main", new TextField("Email", "Email Address"));
        $fields->addFieldToTab("Root.Main", new TextareaField("Notes", "Notes"));
        $fields->addFieldToTab("Root.Main", new TextareaField("ProjectSummary", "Project Summary"));

        //EXPENSE FORMS
        $expensesGridFieldConfig = GridFieldConfig_RecordEditor::create();

        $expensesGridFieldConfig->addComponent(new GridFieldBulkUpload());
        $expensesGridFieldConfig->addComponent(new GridFieldSortableRows('SortOrder'));
        $expensesGridFieldConfig->getComponentByType('GridFieldBulkUpload')
            ->setUfSetup('setFolderName',"projects/" . $this->ID . "/expenses")
            ->setUfConfig('sequentialUploads', true);
        $expensesGridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
            // field from drawer class => label in UI
            'ID' => 'ID',
            'Title'=> 'Title'
        ));

        $expensesGridField = new GridField(
            "ProjectExpenseForms",
            "Project Expense Forms",
            $this->ProjectExpenseForms()->sort("SortOrder"),
            $expensesGridFieldConfig
        );

        $fields->addFieldToTab('Root.Project Expense Forms', $expensesGridField);

    public function getExpenses(){
        return $this->ProjectExpenseForms();
    }

    public function onBeforeWrite()
    {
        parent::onBeforeWrite();
        if ($this->StatusID == "" || $this->StatusID == 0 || is_null($this->StatusID)) {
            $siteConfig = SiteConfig::current_site_config();

            $this->StatusID = $siteConfig->DefaultProjectStatusID;
        }
        //email the assigned grantor
        if ($this->isChanged('ProjectGrantorID', DataObject::CHANGE_VALUE) && $this->ProjectGrantorID != 0) {
            $this->sendGrantorEmail();
        }
    }
    public function onAfterWrite()
    {
        parent::onAfterWrite();
        //If the project does not have the appropriate folders already created, it's time to create them.
        Folder::find_or_make("/projects/" . $this->ID . "/expenses");
        Folder::find_or_make("/projects/" . $this->ID . "/images");
    }
}

class ProjectAdmin extends ModelAdmin
{

    private static $managed_models = array('Project');
    private static $url_segment = 'Projects';
    private static $menu_title = 'Projects';

}

和ProjectExpenseForm类(已经删除了很多 - 我只是包含了相关部分):

<?php

class ProjectExpenseForm extends DataObject {

    private static $db = array(
        'SortOrder' => 'Int',
    );

    // One-to-one relationship with gallery page
    private static $has_one = array(
        'ProjectExpenseFile'   => 'File',
        'Project'              => 'Project'
    );

    // tidy up the CMS by not showing these fields
    public function getCMSFields() {
        $fields = parent::getCMSFields();
        $projectExpenseUploadField = new UploadField("ProjectExpenseFile", "Project Expense File");
        $projectExpenseUploadField->setFolderName("projects/".$this->ProjectID.'/expenses');
        $fields->addFieldToTab('Root.Main', $projectExpenseUploadField);
        $fields->removeFieldFromTab("Root.Main","SortOrder");

        return $fields;
    }

}

2 个答案:

答案 0 :(得分:1)

您需要将关系传递给File AttachmentField而不是'MyFile'

$imageUploader = FileAttachmentField::create('MyFile', 'Upload a file')

在您的情况下,它是AdditionalProjectImages,因为您在has_many中将其命名为。

 private static $has_many = array(
        'AdditionalProjectImages' => 'Image'
    )

他们应该指向图像类而不是AdditionalProjectImage。

所以你的FileAttachmentField应该是这样的:

$imageUploader = FileAttachmentField::create('AdditionalProjectImages', 'Upload a file')

由于每个$ has_many需要一个$ has_one,你需要在图像类上有一个。所以你需要一个扩展名:

ImageExtension extends Image
{
     public static $has_one = [
         'ProjectImages' => 'Project'
     ];
}

运行dev / build / flush如果你这样做,Silverstripe会将这些上传的文件附加/关联到你的Project。

万一你不知道有一个新的silverstripe论坛:SilverStripe Forum而且还有一个银色条纹用户的松散香奈儿。

答案 1 :(得分:0)

因为您知道将文件保存到assets/projects/[project id]/files/的文件夹,并且文件对于该项目是唯一的,所以您可以遍历文件并使用DB::query将它们与项目相关联。< / p>

update文件的UpdateMyProjectProfileForm方法中,我会做类似的事情。

$folderPath = 'assets/projects/' . $projectNameID . '/files/';
$folder = DataList::create('Folder')->filter('Filename', $folderPath)->first();
if ($folder) {
    $images = DataList::create('Image')->filter('ParentID', $folder->ID);
    foreach ($images as $image) {
        DB::query('INSERT INTO Project_AdditionalProjectImages (ProjectID, AdditionalProjectImagesID) VALUES (' . $projectNameID . ',' . $image->ID . ')');
    }
}

您可能还希望将ProjectLeadID添加到查询中以使其更安全。您必须检查您的表名称,因为Project_AdditionalProjectImages可能不正确。