Reputation: 5371
I have an object 'content' which has a manyToMany relationship with pictures (Picture model). Everything works until I persist (the images are uploaded, moved to appropriate folder, work fine). The persist command returns the following error:
Found entity of type Symfony\Component\HttpFoundation\File\UploadedFile on association Creator\MainBundle\Entity\Content#pictures, but expecting Creator\MainBundle\Entity\Picture
I understand what the error means, it's expecting the Picture object instead of the uploaded file object. I don't understand where to go from here though, all the documentation I've read only shows how to upload a single file to a single column.
The picture model has only one field: file (string).
Any help would be much appreciated.
Content Controller code:
$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');
}
Content Model Code:
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());
}
Upvotes: 1
Views: 630
Reputation: 5371
Okay I figured it out..
$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();
}
Moved upload functions to Picture entity.. Had to also rename a couple functions in Content entity but nothing that shouldn't be obvious if someone is trying to replicate what I did.. Now it works great and inserts the relationship.
Upvotes: 1