[英]upload to manytomany relationship symfony2
我有一个与图片具有多对多关系的对象“内容”(图片模型)。 一切正常,直到我坚持(将图像上传,移动到适当的文件夹后,一切正常)。 persist命令返回以下错误:
在关联Creator \\ MainBundle \\ Entity \\ Content#pictures上找到类型为Symfony \\ Component \\ HttpFoundation \\ File \\ UploadedFile的实体,但是期望Creator \\ MainBundle \\ Entity \\ Picture
我了解错误的含义,它期望的是Picture对象而不是上载的文件对象。 不过,我不知道从哪里去,我只读的所有文档都显示了如何将单个文件上传到单个列。
图片模型只有一个字段:文件(字符串)。
任何帮助将非常感激。
内容控制器代码:
$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());
}
好吧,我知道了。
$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();
}
将上载函数移到了Picture实体。.还必须在Content实体中重命名几个函数,但是如果有人尝试复制我所做的事情,这应该是不显而易见的。.现在它很好用并插入了关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.