Php Symfony2文件上载与自己的实体

Php Symfony2文件上载与自己的实体,php,symfony,file-upload,Php,Symfony,File Upload,我有一个实体“任务”和另一个实体“附件”。我想将所有附件存储在它们自己的表中,该表与它们的任务和用户关联。所以我创建了这个实体类: <?php namespace Seotool\MainBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Validator

我有一个实体“任务”和另一个实体“附件”。我想将所有附件存储在它们自己的表中,该表与它们的任务和用户关联。所以我创建了这个实体类:

<?php

namespace Seotool\MainBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="attachments")
 */
class Attachments {

/**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 */
public $name;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
public $path;

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="attachments")
 * @ORM\JoinColumn(name="user", referencedColumnName="id")
 */
protected $User;

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="attachments")
 * @ORM\JoinColumn(name="editor", referencedColumnName="id")
 */
protected $Editor;

/**
 * @ORM\ManyToOne(targetEntity="Task", inversedBy="attachments")
 * @ORM\JoinColumn(name="task", referencedColumnName="id")
 */
protected $Task;

/**
 * @Assert\File(maxSize="6000000")
 */
private $file;

/**
 * Sets file.
 *
 * @param UploadedFile $file
 */
public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
}

/**
 * Get file.
 *
 * @return UploadedFile
 */
public function getFile()
{
    return $this->file;
}

public function getAbsolutePath()
{
    return null === $this->path
        ? null
        : $this->getUploadRootDir().'/'.$this->path;
}

public function getWebPath()
{
    return null === $this->path
        ? null
        : $this->getUploadDir().'/'.$this->path;
}

protected function getUploadRootDir()
{
    // the absolute directory path where uploaded
    // documents should be saved
    return __DIR__.'/../../../../web/'.$this->getUploadDir();
}

protected function getUploadDir()
{
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'uploads/documents';
}

....

您应该将实体从
附件
重命名为
附件
,因为它只存储一个附件的数据

在您的情况下,您需要Symfony2表单集合类型以允许在任务表单(TaskType)中添加附件:

您还需要为单个附件实体创建AttachmentType表单类型

收款字段类型的单据: 有关嵌入表单集合的详细信息,请访问:

然后阅读以下章节:


我添加了一个新的表单类型:AttachmentsType.php

<?php
namespace Seotool\MainBundle\Form\Type;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AttachmentsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name', 'text');
    $builder->add('file', 'file');
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver
            ->setDefaults(array(
                'data_class' => 'Seotool\MainBundle\Entity\Attachments'
            ));
}

public function getName()
{
    return 'attachments';
}
}
但我的输出仅提供以下HTML:

 <div class="form-group"><label class="control-label required">Attachments</label><div id="task_attachments"></div></div><input id="task__token" name="task[_token]" class="form-control" value="brHk4Kk4xyuAhST3TrTHaqwlnA03pbJ5RE4NA0cmY-8" type="hidden"></form>
附件

好的,这是因为您必须在控制器中初始化TaskType的新实例-开始时没有分配给此任务的附件

public function newAction(Request $request)
{
    $task = new Task();

    $attachment1 = new Attachment();
    $task->getAttachments()->add($attachment1);
    $attachment2 = new Attachment();
    $task->getAttachments()->add($attachment2);
    // create form
    $form = $this->createForm(new TaskType(), $task);

    $form->handleRequest($request);
    ...
}

现在应该有2个新附件的文件输入。

如果遇到任何问题,请告诉我。我做了一个新的回答,希望您能看一下:)我收到此异常:FatalErrorException:错误:调用成员函数add()在/Applications/MAMP/htdocs/Seotool/src/Seotool/MainBundle/Controller/DashboardController.php第52行中的非对象上。第52行是:$task->getAttachments()->add($attachment);是否设置:$this->attachments=new ArrayCollection();在任务实体类的构造函数中?我现在就做了。异常已消失,但未输出任何内容…无文件上载:-/这里有解释:-尝试检查您的代码或给我更多代码:)例外您的意思是:“Symfony仅应在选择要上载的文件时添加附件条目?”我是的,您不应手动添加:$attachment->setTask($task)$附件->设置用户($userid);因为这将始终为您保存一个附件。
$builder->add('attachments', 'collection', array(
    'type' => new AttachmentsType(),
));
 <div class="form-group"><label class="control-label required">Attachments</label><div id="task_attachments"></div></div><input id="task__token" name="task[_token]" class="form-control" value="brHk4Kk4xyuAhST3TrTHaqwlnA03pbJ5RE4NA0cmY-8" type="hidden"></form>
public function newAction(Request $request)
{
    $task = new Task();

    $attachment1 = new Attachment();
    $task->getAttachments()->add($attachment1);
    $attachment2 = new Attachment();
    $task->getAttachments()->add($attachment2);
    // create form
    $form = $this->createForm(new TaskType(), $task);

    $form->handleRequest($request);
    ...
}