How to get uploadedFile array from PHP form - php

I am new to PHP. I succeeded in uploading single image to a form and saving it in the database. But when I modify that to upload multiple images, I get an error saying
The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) array.
class SatelliteImages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var array
*/
private $files= array();
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
*Set files
*
* #param UploadedFile[] $files
*/
public function setFiles($files)
{
$this->files = $files;
//return $this;
}
/**
* Get files
*
* #return UploadedFile[]
*/
public function getFiles()
{
return $this->files;
}
/**
* #param satelliteImage[] $images
*
* #return satelliteImage[]
*
*/
public function upload($images){
foreach ($this->getFiles() as $key => $file) {
$images[$key]->setImage(file_get_contents($file));
}
return $images;
}
}
This is the SatelliteImage entity(single image)
class satelliteImage
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var float
*
* #ORM\Column(name="latitude", type="float")
*/
private $latitude;
/**
* #var float
*
* #ORM\Column(name="longitude", type="float")
*/
private $longitude;
/**
* #var string
*
* #ORM\Column(name="image", type="blob", nullable=true))
*/
private $image;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set latitude
*
* #param float $latitude
*
* #return satelliteImage
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
return $this;
}
/**
* Get latitude
*
* #return float
*/
public function getLatitude()
{
return $this->latitude;
}
/**
* Set longitude
*
* #param float $longitude
*
* #return satelliteImage
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
return $this;
}
/**
* Get longitude
*
* #return float
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Set image
*
* #param string $image
*
* #return satelliteImage
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
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';
}
/**
* #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 upload()
{
// the file property can be empty if the field is not required
if (null === $this->getFile()) {
return;
}
$imgFile=$this->getFile();
$this->setImage(file_get_contents($imgFile));
// clean up the file property as you won't need it anymore
$this->file = null;
}
}
In my controller, how can I create an array of images and pass it to the above function?
/**
* #Route("/uploads", name="upload_images")
*
*/
public function uploadImages(Request $request)
{
$images=new Images();
$form = $this->createForm(ImageFile::class, $images);
$form->handleRequest($request);
$em=$this->getDoctrine()->getManager();
$images->upload(????);
}
ImageFile class:
class ImageFile extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('files', FileType::class, array(
'attr' => array(
'accept' => 'image/*',
'multiple' => 'multiple'
)
))
->add('save',SubmitType::class,array('label'=>'Insert Image','attr'=>array('class'=>'btn btn-primary','style'=>'margin-bottom:15px')))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => SatelliteImages::class
));
}
}

This code right here is a problem:
/**
* #Assert\File(maxSize="60000000")
*/
private $files= array();
You need to fix that. You are asserting it's a file, but then you specify that it's an array!
EDIT #2
Your upload function has a problem too. You are returning the same parameter that you are passing in ($images). So you need to change it like so:
/**
* #param satelliteImage[] $images
*
* #return satelliteImage[]
*
*/
public function upload($images){
foreach ($this->getFiles() as $key => $file) {
$img[$key]->setImage(file_get_contents($file));
}
return $img;
}
EDIT #3
The buildForm function seems ok. In your Controller, I think you need to create the class and load the form like this:
$images = new SatelliteImages();
$form = $this->createFormBuilder($images);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$images = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($images);
$em->flush();
return $this->redirectToRoute('some_path');
}
Can you try it? Not sure if that's the problem or not.

SOLUTION
I managed to resolve previous issue by changing 'FileType' to 'CollectionType' in imageFile class's buildForm() function
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('files', CollectionType::class, array(
'attr' => array(
'accept' => 'image/*',
'multiple' => 'multiple'
)
))
->add('save',SubmitType::class,array('label'=>'Insert Image','attr'=>array('class'=>'btn btn-primary','style'=>'margin-bottom:15px')))
;
}
I also changed the 'files' like this
/**
* #var array
*/
private $files;
public function __construct()
{
$this->files = new ArrayCollection();
}
However, when I do that, the 'browse images' button disappears from the view. Any suggestions to fix that?
I also tried removing the construct() function. When I do that, it gives me an error in the controller saying "invalid argument supplied for foreach"

Related

How to correctly render a form?

Symfony makes it all so easy. It sets out the big lines for your project and nothing ever goes wrong. Until something does go wrong. You'll be looking for the right solution for days. At least that's what I'm doing right now.
I'm working on a little test project in which you can add urls as bookmarks and give each url a variety of tags to categorize the urls.
I have used the generate:doctrine:crud command to build my forms. But I am getting a weird error.
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Bla\LinkBundle\Entity\Url could not be converted to string") in form_div_layout.html.twig at line 13.
I can solve this issue by adding a __toString() method in my Url entity but I wanna know why.
The problem is with the name property being null. If I return this value as '' using __toString() it works fine. But I do not like this solution. All other values are null as well when I am in the "create url" form, so why is it complaining about the name property?
Form
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('url')
->add('flags')
->add('tags', EntityType::class, array(
'class' => 'Bla\LinkBundle\Entity\Tag',
'choice_label' => 'name',
'multiple' => true,
))
;
}
Controller
public function newAction(Request $request)
{
$url = new Url();
$form = $this->createForm('Bla\LinkBundle\Form\UrlType', $url);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($url);
$em->flush();
return $this->redirectToRoute('url_show', array('id' => $url->getId()));
}
return $this->render('url/new.html.twig', array(
'url' => $url,
'form' => $form->createView(),
));
}
Entity
namespace Bla\LinkBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Bla\LinkBundle\Entity\Tag;
/**
* URL
*
* #ORM\Table(name="urls")
* #ORM\Entity
*/
class Url
{
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="url", type="text", length=65535, nullable=false)
*/
private $url;
/**
* #var integer
*
* #ORM\Column(name="flags", type="integer", nullable=false)
*/
private $flags;
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity="\Bla\LinkBundle\Entity\Tag", cascade={"persist"})
* #ORM\JoinTable(name="url_tag",
* joinColumns={#ORM\JoinColumn(name="url_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="tag_id", referencedColumnName="id", unique=true)}
* )
*/
protected $tags;
public function __construct()
{
$this->tags = new ArrayCollection();
}
/**
* Set name
*
* #param string $name
*
* #return Urls
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set url
*
* #param string $url
*
* #return Urls
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set flags
*
* #param integer $flags
*
* #return Urls
*/
public function setFlags($flags)
{
$this->flags = $flags;
return $this;
}
/**
* Get flags
*
* #return integer
*/
public function getFlags()
{
return $this->flags;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #param \Doctrine\Common\Collections\ArrayCollection $tags
* #return Urls
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getTags()
{
return $this->tags;
}
/**
* Add tag
*
* #param Tag $tag
* #return Urls
*/
public function addTag(Tag $tag)
{
$this->tags->add($tag);
return $this;
}
/**
* Remove tag
*
* #param Tags $tag
*/
public function removeTag(Tag $tag)
{
$this->tags->removeElement($tag);
}
}
try to implements this into form class :
public function getName()
{
return 'filter_type_url';
}
public function getParent()
{
return 'multiselectentity';
}

symfony2 image multiple upload

I'm trying to figure out how to do multiple file uploads but without luck. I have not been able to get too much info on this.. Maybe someone here will help me out? :D
Criteria:
I know that in my form type I'm supposed to use multiples for fields; but when I add it, it gives me the this error.
Catchable Fatal Error: Argument 1 passed to
PhotoGalleryBundle\Entity\Image::setFile() must be an instance of
Symfony\Component\HttpFoundation\File\UploadedFile, array given,
called in
/home/action/workspace/www/DecorInterior/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php
on line 442 and defined
Image Entity
Here is my code in PHP:
<?php
namespace PhotoGalleryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Image
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="PhotoGalleryBundle\Entity\ImageRepository")
* #ORM\HasLifecycleCallbacks
*/
class Image
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="imageCaptation", type="string", length=255)
* #Assert\NotBlank
*/
private $imageCaptation;
/**
* #var string
*
* #ORM\Column(name="imageName", type="string", length=255)
*/
private $imageName;
/**
* #var string
*
* #ORM\Column(name="imageFilePath", type="string", length=255, nullable=true)
*/
private $imageFilePath;
/**
* #var \DateTime
*
* #ORM\Column(name="imageUploadedDate", type="datetime")
* #Gedmo\Timestampable(on="create")
*/
private $imageUploadedDate;
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
/**
* #ORM\ManyToOne(targetEntity="Album", inversedBy="images")
* #ORM\JoinColumn(name="album", referencedColumnName="id")
*/
private $album;
private $temp;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set imageCaptation
*
* #param string $imageCaptation
* #return Image
*/
public function setImageCaptation($imageCaptation)
{
$this->imageCaptation = $imageCaptation;
return $this;
}
/**
* Get imageCaptation
*
* #return string
*/
public function getImageCaptation()
{
return $this->imageCaptation;
}
/**
* Set imageName
*
* #param string $imageName
* #return Image
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* Get imageName
*
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
/**
* Set imageFilePath
*
* #param string $imageFilePath
* #return Image
*/
public function setImageFilePath($imageFilePath)
{
$this->imageFilePath = $imageFilePath;
return $this;
}
/**
* Get imageFilePath
*
* #return string
*/
public function getImageFilePath()
{
return $this->imageFilePath;
}
/**
* Get imageUploadedDate
*
* #return \DateTime
*/
public function getImageUploadedDate()
{
return $this->imageUploadedDate;
}
/**
* Set file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null) {
$this->file = $file;
// check if we have an old image path
if (isset($this->imageFilePath)) {
// store the old name to delete after the update
$this->temp = $this->imageFilePath;
$this->imageFilePath = null;
} else {
$this->imageFilePath = 'initial';
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate
*/
public function preUpload() {
if (null !== $this->getFile()) {
// do whatever you want to generate a unique name
$fileName = sha1(uniqid(mt_rand(), true));
$this->imageFilePath = $fileName . '.' . $this->getFile()->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate
*/
public function upload() {
if (null === $this->getFile()) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getFile()->move($this->getUploadRootDir(), $this->imageFilePath);
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->getUploadRootDir() . '/' . $this->temp);
// clear the temp image path
$this->temp = null;
}
$this->imageFilePath = null;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload() {
$file = $this->getAbsolutePath();
if ($file) {
unlink($file);
}
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile() {
return $this->file;
}
public function getAbsolutePath() {
return null === $this->imageFilePath
? null
: $this->getUploadRootDir() . '/' . $this->imageFilePath;
}
public function getWebPath() {
return null === $this->imageFilePath
? null
: $this->getUploadDir() . '/' . $this->imageFilePath;
}
public function getUploadRootDir() {
// the absolute path where uploaded
// documents should be saved
return __DIR__.'/../../../web/' . $this->getUploadDir();
}
public function getUploadDir() {
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view
return 'uploads/images';
}
/**
* Set album
*
* #param \PhotoGalleryBundle\Entity\Album $album
* #return Image
*/
public function setAlbum(\PhotoGalleryBundle\Entity\Album $album = null)
{
$this->album = $album;
return $this;
}
/**
* Get album
*
* #return \PhotoGalleryBundle\Entity\Album
*/
public function getAlbum()
{
return $this->album;
}
}
ImageType:
<?php
namespace PhotoGalleryBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ImageType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imageCaptation')
->add('imageName')
->add('file', 'file', array('multiple' => TRUE))
->add('album')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'PhotoGalleryBundle\Entity\Image'
));
}
/**
* #return string
*/
public function getName()
{
return 'photogallerybundle_image';
}
}
In this case the value will be an array of UploadedFile objects. Given that you have a type with multiple files yet only one caption, name, etc I assume you will want to refactor Image to support multiple image files. In this case the file property would be better known as files and setFiles should accept an array.
If however you want have one Image entity per file uploaded, consider implementing a collection instead.
Alternatively you could manually process the form in your action. For example:
public function uploadAction(Request $request)
{
foreach ($request->files as $uploadedFile) {
$uploadedFile = current($uploadedFile['file']);
// Build Image using each uploaded file
}
...

Embed Symfony file form

I want to embed a form (ImageType) into another (VideoFileType) in Symfony. My first form contains a file input. Basically, it's an image that will uploaded and then resized according to many presets already defined.
My second form will embed the ImageType form. The second form is a VideoFileType form which contains the ImageType form. Basically, the ImageType will act as a thumbnail for the video file. The VideoFileType will also contain a second file input to upload the videoFile and finally a select box to select the corresponding VideoPreset.
So to recap, the VideoFileType will embed an ImageType.
My class structure is similar. I have a VideoFile which has a Thumbnail attribute that is an Image class
When I show only the ImageType and upload an image, everything works perfectly fine.
ImageType:
class ImageType extends AbstractType
{
private $imageManager;
public function __construct(ImageManager $imageManager) {
$this->imageManager = $imageManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', 'file');
$builder->addEventListener(
FormEvents::POST_SUBMIT,
array($this, 'onPostSetData')
);
}
public function getDefaultOptions(array $options) {
return array('data_class' => 'OSC\MediaBundle\Entity\Image');
}
public function onPostSetData(FormEvent $event) {
$image = $event->getData();
$form = $event->getForm();
//We need here to update the video file with the new content
$image = $this->imageManager->uploadImage($image);
$event->setData($image);
}
public function getName()
{
return 'image';
}
}
VideoFileType
class VideoFileType extends AbstractType
{
public $container;
public $videoPresets = [];
public function __construct(Container $container) {
$this->container = $container;
$videoPresets = $container->getParameter('osc_media.video.presets');
foreach ($videoPresets as $key => $videoPreset) {
array_push($this->videoPresets, $key);
}
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('thumbnail', new ImageType($this->container->get('osc_media.manager.image')));
$builder->add('file', 'file');
$builder->add('videoPreset', 'choice', array(
'choices' => $this->videoPresets,
'multiple' => false,
'required' => true
));
$builder->addEventListener(
FormEvents::POST_SUBMIT,
array($this, 'onPostSetData')
);
$builder->add('save', 'submit');
}
public function onPostSetData(FormEvent $event) {
$videoFile = $event->getData();
$form = $event->getForm();
}
public function getDefaultOptions(array $options) {
return array('data_class' => 'OSC\MediaBundle\Entity\VideoFile');
}
public function getName()
{
return 'video_file';
}
}
VideoFile
class VideoFile
{
protected $file;
public function setfile(File $file = null)
{
$this->file = $file;
if ($file) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTime('now');
}
}
/**
* #return File
*/
public function getFile()
{
return $this->file;
}
public function __construct() {
$this->thumbnail = new Image();
}
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #var string
*/
private $filename;
/**
* #var integer
*/
private $position;
/**
* #var string
*/
private $extension;
/**
* #var integer
*/
private $size;
/**
* #var string
*/
private $videoPreset;
/**
* #var integer
*/
private $duration;
/**
* #var \DateTime
*/
private $createdAt;
/**
* #var \DateTime
*/
private $updatedAt;
/**
* #var string
*/
private $height;
/**
* #var string
*/
private $width;
/**
* #var \OSC\MediaBundle\Entity\Image
*/
private $thumbnail;
/**
* #var \OSC\MediaBundle\Entity\Video
*/
private $video;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return VideoFile
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set filename
*
* #param string $filename
* #return VideoFile
*/
public function setFilename($filename)
{
$this->filename = $filename;
return $this;
}
/**
* Get filename
*
* #return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* Set position
*
* #param integer $position
* #return VideoFile
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position
*
* #return integer
*/
public function getPosition()
{
return $this->position;
}
/**
* Set extension
*
* #param string $extension
* #return VideoFile
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* #return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* Set size
*
* #param integer $size
* #return VideoFile
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* Get size
*
* #return integer
*/
public function getSize()
{
return $this->size;
}
/**
* Set videoPreset
*
* #param string $videoPreset
* #return VideoFile
*/
public function setVideoPreset($videoPreset)
{
$this->videoPreset = $videoPreset;
return $this;
}
/**
* Get videoPreset
*
* #return string
*/
public function getVideoPreset()
{
return $this->videoPreset;
}
/**
* Set duration
*
* #param integer $duration
* #return VideoFile
*/
public function setDuration($duration)
{
$this->duration = $duration;
return $this;
}
/**
* Get duration
*
* #return integer
*/
public function getDuration()
{
return $this->duration;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return VideoFile
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return VideoFile
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set height
*
* #param string $height
* #return VideoFile
*/
public function setHeight($height)
{
$this->height = $height;
return $this;
}
/**
* Get height
*
* #return string
*/
public function getHeight()
{
return $this->height;
}
/**
* Set width
*
* #param string $width
* #return VideoFile
*/
public function setWidth($width)
{
$this->width = $width;
return $this;
}
/**
* Get width
*
* #return string
*/
public function getWidth()
{
return $this->width;
}
/**
* Set thumbnail
*
* #param \OSC\MediaBundle\Entity\Image $thumbnail
* #return VideoFile
*/
public function setThumbnail(\OSC\MediaBundle\Entity\Image $thumbnail = null)
{
$this->thumbnail = $thumbnail;
return $this;
}
/**
* Get thumbnail
*
* #return \OSC\MediaBundle\Entity\Image
*/
public function getThumbnail()
{
return $this->thumbnail;
}
/**
* Set video
*
* #param \OSC\MediaBundle\Entity\Video $video
* #return VideoFile
*/
public function setVideo(\OSC\MediaBundle\Entity\Video $video = null)
{
$this->video = $video;
return $this;
}
/**
* Get video
*
* #return \OSC\MediaBundle\Entity\Video
*/
public function getVideo()
{
return $this->video;
}
}
Image Class
class Image
{
protected $file;
public function setfile(File $file = null)
{
$this->file = $file;
if ($file) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTime('now');
}
}
/**
* #return File
*/
public function getFile()
{
return $this->file;
}
/**
* #var integer
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $imageFiles;
/**
* Constructor
*/
public function __construct()
{
$this->imageFiles = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add imageFiles
*
* #param \OSC\MediaBundle\Entity\ImageFile $imageFiles
* #return Image
*/
public function addImageFile(\OSC\MediaBundle\Entity\ImageFile $imageFiles)
{
$this->imageFiles[] = $imageFiles;
return $this;
}
/**
* Remove imageFiles
*
* #param \OSC\MediaBundle\Entity\ImageFile $imageFiles
*/
public function removeImageFile(\OSC\MediaBundle\Entity\ImageFile $imageFiles)
{
$this->imageFiles->removeElement($imageFiles);
}
/**
* Get imageFiles
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getImageFiles()
{
return $this->imageFiles;
}
}
ImageFile
class ImageFile
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #var string
*/
private $filename;
/**
* #var string
*/
private $extension;
/**
* #var string
*/
private $size;
/**
* #var string
*/
private $imagePreset;
/**
* #var \DateTime
*/
private $createdAt;
/**
* #var \DateTime
*/
private $updatedAt;
/**
* #var string
*/
private $height;
/**
* #var string
*/
private $width;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return ImageFile
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set filename
*
* #param string $filename
* #return ImageFile
*/
public function setFilename($filename)
{
$this->filename = $filename;
return $this;
}
/**
* Get filename
*
* #return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* Set extension
*
* #param string $extension
* #return ImageFile
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* #return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* Set size
*
* #param string $size
* #return ImageFile
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* Get size
*
* #return string
*/
public function getSize()
{
return $this->size;
}
/**
* Set imagePreset
*
* #param string $imagePreset
* #return ImageFile
*/
public function setImagePreset($imagePreset)
{
$this->imagePreset = $imagePreset;
return $this;
}
/**
* Get imagePreset
*
* #return string
*/
public function getImagePreset()
{
return $this->imagePreset;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return ImageFile
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return ImageFile
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set height
*
* #param string $height
* #return ImageFile
*/
public function setHeight($height)
{
$this->height = $height;
return $this;
}
/**
* Get height
*
* #return string
*/
public function getHeight()
{
return $this->height;
}
/**
* Set width
*
* #param string $width
* #return ImageFile
*/
public function setWidth($width)
{
$this->width = $width;
return $this;
}
/**
* Get width
*
* #return string
*/
public function getWidth()
{
return $this->width;
}
}
However, when I try to create a VideoFileType form, I get the following error:
The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class OSC\MediaBundle\Entity\Image. You can avoid this error by setting the "data_class" option to "OSC\MediaBundle\Entity\Image" or by adding a view transformer that transforms an instance of class OSC\MediaBundle\Entity\Image to scalar, array or an instance of \ArrayAccess.
So, what I want, is the treatment of the ImageFileType (OnPostSetData) to be executed with the same success when embedded in VideoFileType as when used alone.
Then, after completion, I want the Image object to be inserted in the VideoFile as the thumbnail attribute. Afterwards, it should finish the treatment inside VideoFileType's OnPostSetData method.
If it's not feasible, I'll simply recreate ImageType's logic inside the VideoFileType and that is not a big deal. However, I feel that it could be nice if I could reuse the ImageFileType.
I'm not a 100% sure but try adding this function to your ImageTypeclass.
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
....
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'OSC\MediaBundle\Entity\Image'
));
}
And change the configuration for the thumbnail property inside buildForm in class VideoFileType.
$builder->add('thumbnail',
new ImageType($this->container->get('osc_media.manager.image')),
array(
'data_class' => 'OSC\MediaBundle\Entity\Image'
));
This is verry easy if you want to extend formtype,
just do like this:
Define your first form as a service
Extend your second form using getParent method
public function getParent()
{
return 'image';
}
doing like this you have the same fields in ur second form as in first
and you can add some more.

Symfony2 Form collection foreign key

Hoping that my explanation is clear(!), i will do my best:
I am working with the Symfony framework and untill now i got it all worked out. So whats my problem?
I use a form collection (ProjectType and DocumentType):
One project can have many documents.
To get the forms i used the generate:crud command and then adjusted the entities, types, etc. like on this page: http://symfony.com/doc/current/cookbook/form/form_collections.html
This all went succesfull: I can create new projects and in the same form i can add many documents. When the submit button is pressed the data gets persisted in the MySQL database.
In my doctrines i created a foreign key in the document entity, called: project_id. The association of these are correct because when i add the id to the form the dropdown appears with existing projects.
BUT I would like that the form also persist the foreign key in my documents table (which is off course the new created project PK). So that when i creat a new project with documents, the foreign key of the documents is the PK from the new project.
Edit: When i add the foreign key manually in the database and then delete the project the documents with the foreign key alse gets deleted (just to point out that the association is correct..!)
Please help me out, thank you!
-----------------ProjectController.php:
/**
* Displays a form to create a new Project entity.
*
* #Route("/new", name="project_new")
* #Method("GET")
* #Template()
*/
public function newAction() {
$entity = new Project();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a Project entity.
*
* #param Project $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Project $entity) {
$form = $this->createForm(new ProjectType(), $entity, array(
'action' => $this->generateUrl('project_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create project'));
return $form;
}
/**
* Creates a new Project entity.
*
* #Route("/", name="project_create")
* #Method("POST")
* #Template("AcmeDemoBundle:Project:new.html.twig")
*/
public function createAction(Request $request) {
$entity = new Project();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
$entity->setDateCreated(new \DateTime());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('project_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
-----------------ProjectType.php:
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name')
->add('date_executed')
->add('imageprojects', 'collection', array(
'type' => new DocumentType(),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Project',
'cascade_validation' => false,
));
}
/**
* #return string
*/
public function getName() {
return 'project';
}
---------------Project.php (Entity):
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
*
* #ORM\Column(type="string")
*/
protected $name;
/**
*
* #ORM\Column(type="date")
*/
protected $date_executed;
/**
*
* #ORM\Column(type="date")
*/
protected $date_created;
/**
* #ORM\OneToMany(targetEntity="Document", mappedBy="project_id", cascade={"persist", "remove"})
*/
protected $imageprojects;
public function __construct() {
$this->imageprojects = new ArrayCollection();
}
function __toString() {
return $this->getName();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Project
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set date_executed
*
* #param \DateTime $dateExecuted
* #return Project
*/
public function setDateExecuted($dateExecuted)
{
$this->date_executed = $dateExecuted;
return $this;
}
/**
* Get date_executed
*
* #return \DateTime
*/
public function getDateExecuted()
{
return $this->date_executed;
}
/**
* Set date_created
*
* #param \DateTime $dateCreated
* #return Project
*/
public function setDateCreated($dateCreated)
{
$this->date_created = $dateCreated;
return $this;
}
/**
* Get date_created
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->date_created;
}
/**
* Add projectimages
*
* #param \Acme\DemoBundle\Entity\Document $projectimages
* #return Project
*/
public function addImageproject(Document $projectimages)
{
//$this->imageprojects[] = $imageprojects;
$projectimages->addProjectimage($this);
$this->imageprojects->add($projectimages);
return $this;
}
/**
* Remove projectimages
*
* #param \Acme\DemoBundle\Entity\Document $projectimages
*/
public function removeImageproject(Document $projectimages)
{
$this->imageprojects->removeElement($projectimages);
}
/**
* Get imageprojects
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getImageprojects()
{
return $this->imageprojects;
}
------------------Document.php (Entity)
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* #ORM\ManyToOne(targetEntity="Project", inversedBy="imageprojects")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $project_id;
/**
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank
*/
public $name;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
public function getAbsolutePath() {
return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->id . '.' . $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 'imgupload';
}
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null) {
$this->file = $file;
// check if we have an old image path
if (is_file($this->getAbsolutePath())) {
// store the old name to delete after the update
$this->temp = $this->getAbsolutePath();
} else {
$this->path = 'initial';
}
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile() {
return $this->file;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload() {
if (null !== $this->getFile()) {
$this->path = $this->getFile()->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload() {
if (null === $this->getFile()) {
return;
}
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->temp);
// clear the temp image path
$this->temp = null;
}
// you must throw an exception here if the file cannot be moved
// so that the entity is not persisted to the database
// which the UploadedFile move() method does
$this->getFile()->move(
$this->getUploadRootDir(), $this->id . '.' . $this->getFile()->guessExtension()
);
$this->setFile(null);
}
/**
* #ORM\PreRemove()
*/
public function storeFilenameForRemove() {
$this->temp = $this->getAbsolutePath();
}
/**
* #ORM\PostRemove()
*/
public function removeUpload() {
if (isset($this->temp)) {
unlink($this->temp);
}
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Document
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set path
*
* #param string $path
* #return Document
*/
public function setPath($path) {
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath() {
return $this->path;
}
/**
* Add projectimages
*
* #param \Acme\DemoBundle\Entity\Project $projectimages
* #return Document
*/
public function addProjectimage(Project $projectimages) {
$this->projectimages[] = $projectimages;
/*
if (!$this->projectimages->contains($projectimages)) {
$this->projectimages->add($projectimages);
}
*/
return $this;
}
/**
* Remove projectimages
*
* #param \Acme\DemoBundle\Entity\Project $projectimages
*/
public function removeProjectimage(Project $projectimages) {
$this->projectimages->removeElement($projectimages);
}
/**
* Get projectimages
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProjectimages() {
return $this->projectimages;
}
/**
* Set project_id
*
* #param \Acme\DemoBundle\Entity\Project $projectId
* #return Document
*/
public function setProjectId(\Acme\DemoBundle\Entity\Project $projectId = null) {
$this->project_id = $projectId;
return $this;
}
/**
* Get project_id
*
* #return \Acme\DemoBundle\Entity\Project
*/
public function getProjectId() {
return $this->project_id;
}
OK, it was a matter of 'bad reading'...! The solution was already posted for this question: [Persistence with embedded forms

How to update particular image related data using doctrine entity with one to many relationship in Symfony 2

I have two entities (namely Book, Image) having OneToMany relationship between them, i.e. One book can have more than one images.
Now when I am trying to edit the details of the book, how can I do edit for any particular image for that particular book?
More clearly if I say, I want to alter only one particular image out of all the images previously uploaded. Can anyone help me on this please?
Below are my entities and forms.
/**
* #ORM\Table(name="books")
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="Library\MainBundle\Entity\BookRepository")
*/
class Book
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="subject", type="string", length=255)
*/
private $subject;
/**
* #var string
*
* #ORM\Column(name="isbn", type="string", length=255)
*/
private $isbn;
/**
* #var string
*
* #ORM\Column(name="Description", type="text")
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="books")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
**/
private $category;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="bookpublishers")
* #ORM\JoinColumn(name="publisher_id", referencedColumnName="id")
**/
private $publisher;
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="bookauthors")
* #ORM\JoinTable(name="book_author")
**/
private $author;
/**
* #ORM\OneToMany(targetEntity="BookReview", mappedBy="bookreview", cascade={"all"})
**/
private $reviews;
/**
* #var string $image
* #Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
* #ORM\Column(name="image", type="string", length=255)
*/
private $image;
/**
* #ORM\OneToMany(targetEntity="Image", mappedBy="book", cascade={"all"})
**/
private $pictures;
/**
* #var string
*/
private $imageName;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Book
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set subject
*
* #param string $subject
* #return Book
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* Get subject
*
* #return string
*/
public function getSubject()
{
return $this->subject;
}
/**
* Set isbn
*
* #param string $isbn
* #return Book
*/
public function setIsbn($isbn)
{
$this->isbn = $isbn;
return $this;
}
/**
* Get isbn
*
* #return string
*/
public function getIsbn()
{
return $this->isbn;
}
/**
* Set description
*
* #param string $description
* #return Book
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set category
*
* #param \Library\MainBundle\Entity\Category $category
* #return Book
*/
public function setCategory(Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \Library\MainBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set publisher
*
* #param \Library\MainBundle\Entity\User $publisher
* #return Book
*/
public function setPublisher(User $publisher = null)
{
$this->publisher = $publisher;
return $this;
}
/**
* Get publisher
*
* #return \Library\MainBundle\Entity\User
*/
public function getPublisher()
{
return $this->publisher;
}
/**
* Add author
*
* #param \Library\MainBundle\Entity\User $author
* #return Book
*/
public function addAuthor(User $author)
{
$this->author[] = $author;
return $this;
}
/**
* Remove author
*
* #param \Library\MainBundle\Entity\User $author
*/
public function removeAuthor(User $author)
{
$this->author->removeElement($author);
}
/**
* Get author
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set author
*
* #return User
*/
public function setAuthor(User $author)
{
$this->author[] = $author;
}
/**
* Add reviews
*
* #param \Library\MainBundle\Entity\BookReview $reviews
* #return Book
*/
public function addReview(BookReview $reviews)
{
$this->reviews[] = $reviews;
return $this;
}
/**
* Remove reviews
*
* #param \Library\MainBundle\Entity\BookReview $reviews
*/
public function removeReview(BookReview $reviews)
{
$this->reviews->removeElement($reviews);
}
/**
* Get reviews
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getReviews()
{
return $this->reviews;
}
public function getFullImagePath() {
return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir().$this->getId()."/";
}
protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/upload/books/';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
$tempImageName = time() . '_' .$this->image->getClientOriginalName();
if(!$this->id){
$this->setImageName($this->image->getClientOriginalName());
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $tempImageName);
unlink($this->getUploadRootDir().$this->getImageName());
}
$this->setImage($tempImageName);
}
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->image) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir().$this->getImageName(), $this->getFullImagePath());
unlink($this->getTmpUploadRootDir().$this->getImageName());
}
/**
* #ORM\PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
/**
* Set image
*
* #param string $image
* #return Book
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set image
*
* #param string $image
* #return Book
*/
public function setImageName($image)
{
$this->imageName = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
/**
* Constructor
*/
public function __construct()
{
$this->author = new ArrayCollection();
$this->reviews = new ArrayCollection();
$this->pictures = new ArrayCollection();
}
/**
* Add pictures
*
* #param \Library\MainBundle\Entity\Image $pictures
* #return Book
*/
public function addPicture(Image $pictures)
{
$this->pictures[] = $pictures;
$pictures->setBook($this);
return $this;
}
/**
* Remove pictures
*
* #param \Library\MainBundle\Entity\Image $pictures
*/
public function removePicture(Image $pictures)
{
$this->pictures->removeElement($pictures);
}
/**
* Get pictures
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPictures()
{
return $this->pictures;
}
}
Image Entity (Image.php)
/**
* Image
*
* #ORM\Table(name="book_images")
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="Library\MainBundle\Entity\ImageRepository")
*/
class Image
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="Book", inversedBy="pictures")
* #ORM\JoinColumn(name="book_id", referencedColumnName="id")
**/
private $book;
/**
* #var string
*/
private $imageName;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Image
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set book
*
* #param \Library\MainBundle\Entity\Book $book
* #return Image
*/
public function setBook(Book $book)
{
$this->book = $book;
return $this;
}
/**
* Get book
*
* #return \Library\MainBundle\Entity\Book
*/
public function getBook()
{
return $this->book;
}
/**
* Set image
*
* #param string $image
* #return Book
*/
public function setImageName($image)
{
$this->imageName = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
public function getFullImagePath() {
return null === $this->name ? null : $this->getUploadRootDir(). $this->name;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir().$this->getBook()->getId()."/";
}
protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/upload/books/';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->name) {
return;
}
$tempImageName = time() . '_' .$this->name->getClientOriginalName();
if(!$this->getBook()->getId()){
$this->setImageName($this->name->getClientOriginalName());
$this->name->move($this->getTmpUploadRootDir(), $this->name->getClientOriginalName());
}else{
$this->name->move($this->getUploadRootDir(), $tempImageName);
unlink($this->getUploadRootDir().$this->getImageName());
}
$this->setName($tempImageName);
}
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->name) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir().$this->getImageName(), $this->getFullImagePath());
unlink($this->getTmpUploadRootDir().$this->getImageName());
}
/**
* #ORM\PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
}
My Forms :
BookType.php
namespace Library\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Library\MainBundle\Entity\Role;
use Library\MainBundle\Entity\Image;
class BookType extends AbstractType
{
/**
* #var \Library\MainBundle\Entity\Role
*/
protected $publisherrole;
/**
* #var \Library\MainBundle\Entity\Role
*/
protected $authorrole;
public function __construct (Role $publisherRole, Role $authorRole)
{
$this->publisherrole = $publisherRole;
$this->authorrole = $authorRole;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('label' => 'book.label.name',
'attr' => array('class' => 'element text medium')))
->add('subject', 'text', array('label' => 'book.label.subject',
'attr' => array('class' => 'element text medium')))
->add('isbn', 'text', array('label'=> 'book.label.isbn',
'attr' => array('class' => 'element text medium')))
->add('description', 'textarea', array('label' => 'book.label.description',
'attr' => array('class' => 'element textarea medium')))
->add('category', 'entity', array(
'class' => 'LibraryMainBundle:Category',
'property' => 'name',
"label" => 'book.label.category',
"attr" => array('class' => 'element select medium')))
->add('publisher', 'entity', array(
'class' => 'LibraryMainBundle:User',
'property' => 'name',
'label' => 'book.label.publisher',
'choices' => $this->publisherrole->getUser(),
'attr' => array('class' => 'element select medium')
))
->add('author', 'entity', array(
'class' => 'LibraryMainBundle:User',
'property' => 'name',
'label' => 'book.label.author',
'choices' => $this->authorrole->getUser(),
'multiple' => 'true',
'attr' => array('class' => 'element select medium')
))
->add('image', 'file', array('label' => 'book.label.coverpic',
'attr' => array('class' => 'element textarea medium'),
'data_class' => null
))
->add("pictures", 'collection', array(
'type'=>new FileType(),
'allow_add'=>true,
'by_reference' => true,
'data'=>array(new Image(),
new Image()
)
))
->add("save", "submit", array('label' => 'book.button.save'));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Library\MainBundle\Entity\Book'
));
}
/**
* #return string
*/
public function getName()
{
return 'library_mainbundle_book';
}
}
FileType.php
namespace Library\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class FileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
return $builder->add("name", "file");
}
public function getName()
{
return "filetype";
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class'=>'Library\MainBundle\Entity\Image',
'csrf_protection'=>true,
'csrf_field_name'=>'_token',
'intention'=>'file'
));
}
}
Please let me know if anything more required from my end.

Categories