上传到manytomany关系symfony2

时间:2013-08-13 19:16:47

标签: php symfony

我有一个对象'content',它与图片有很多关系(图片模型)。一切正常,直到我坚持(图像上传,移动到适当的文件夹,工作正常)。 persist命令返回以下错误:

在关联Creator \ MainBundle \ Entity \ Content#pictures上找到Symfony \ Component \ HttpFoundation \ File \ UploadedFile类型的实体,但期待Creator \ MainBundle \ Entity \ Picture

我理解错误意味着什么,它期待Picture对象而不是上传的文件对象。我不明白从哪里开始,我读过的所有文档都只显示了如何将单个文件上传到单个列。

图片模型只有一个字段:file(string)。

非常感谢任何帮助。

内容控制器代码:

$form = $this->createFormBuilder($content, array('validation_groups'=>array('upload_'.$type)))
        ->add('picture')
        ->add('Upload '.ucfirst($type), 'submit')
        ->getForm();

$form->handleRequest($request);

if($request->getMethod()=='POST' && $form->isvalid())
{
    $content->uploadPicture();
    $em->persist($content);
    $em->flush();

    $session = $request->getSession();
    $session->getFlashBag()->add('success', 'Upload successful');                   
}

内容模型代码:

public function addPictures($picture)
{
    $this->pictures[] = $picture;
    return $this;
}

public function getPicture()
{
    return $this->picture;
}

public function setPicture($picture)
{
    $this->picture = $picture;
    return $this;
}

public function getPictures()
{
    return $this->pictures;
}

public function setPictures($pictures)
{
    $this->pictures = $pictures;
    return $this;
}

public function uploadPicture()
{       
    if (null === $this->getPicture()) {
        return;
    }

    $extension = $this->getPicture()->getExtension();
    if(!$extension) $extension = 'jpg';

    // unique file name
    $fname = uniqid().'.'.$extension;

    $this->getPicture()->move(
        $this->getUploadRootDir(),
        $fname
    );

    $this->makeThumbnail($fname, $extension);
    $this->addPictures($this->getPicture());
}

1 个答案:

答案 0 :(得分:1)

好的,我想出来了..

$picture = new Picture();

$form = $this->createFormBuilder($picture)
    ->add('file')
    ->add('Upload Picture', 'submit')
    ->getForm();

$form->handleRequest($request);

if($request->getMethod()=='POST' && $form->isvalid())
{
  $picture->uploadFile();
  $em->persist($picture);
  $content->addPicture($entity);
  $em->persist($content);
  $em->flush();
}

将上传功能移动到图片实体..还要重命名内容实体中的几个功能,但如果有人试图复制我所做的事情,那么任何事情都不应该是显而易见的..现在它很有用并插入关系。< / p>