hello guys following the doc to make a file uploader but i cant find out why its not workin when i hit submit its gives an error Unable to create the "uploads/cv" directory although these folders exist already in project/src/My/UserBundle/Resources/public/images
my document entity
namespace My\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* My\UserBundle\Entity\Document
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\UserBundle\Entity\DocumentRepository")
*/
class Document
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $path
*
* #ORM\Column(name= "name",type="string", length=255)
*/
private $name;
/**
* #var string $path
*
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $path;
/**
* #Assert\File(maxSize="6000000")
*/
private $file ;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set path
*
* #param string $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
function getFile()
{
return $this->file;
}
function setFile($file)
{
$this->file =$file;
}
function preUpload()
{
if(null !== $this->file )
{
$this->path = uniqid() . '.' . $this->file->guessExtension();
}
}
function upload()
{
if(null === $this->file)
{
return ;
}
$this->file->move( $this->getUploadDir() ,$this->getPath );
unset($this->file);
}
function removeUpload()
{
if($file = $this->getAbsolutePath() )
{
unlink($file);
}
}
function getWebPath()
{
return $this->getUploadDir() . $this->getPath() ;
}
function getUploadDir()
{
return 'uploads/cv' ;
}
function getAbsolutePath()
{
return $this->getRootDir() . $this->getPath() ;
}
function getRootDir()
{
return __DIR__ . '../../../../src/' .$this->getUploadDir() ;
}
function setName($n)
{
$this->name =$n ;
}
function getName()
{
return $this->name ;
}
}
and my controller action
function uploadAction()
{
$document = new Document();
$form = $this->createFormBuilder($document)
->add('name')
->add('file')
->getForm();
$request = $this->getRequest() ;
if( $request->getMethod() == 'POST' )
{
$form->bindRequest($request);
if($form->isValid() )
{
$em = $this->getDoctrine()->getEntityManager() ;
$document->upload();
$em->persist($document);
$em->flush();
return
$this->render('MyUserBundle:Document:upload.html.twig');
}
}
else
{
return
$this->render('MyUserBundle:Document:upload.html.twig' ,array('form'=>$form->createView() );
}
thanks in advance
I think you created your uploads/cv folder in the wrong path.
It should be project/web/uploads/cv, not project/src/My/UserBundle/Resources/public/images.
Then give Symfony the write permissions to that folder with chmod.
Related
I have a problem in the registration process when using FOSUserBundle. Instead of the real path of the image I'm trying to upload, in the database, it always saves initial value under the path column and the image is not uploaded in the directory I have defined.
namespace Session\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Security\Core\Util\SecureRandom;
/**
* User
*
* #ORM\Table(name="User")
* #ORM\Entity(repositoryClass="Session\UserBundle\Entity\UserRepository")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
public $path;
/**
* #Assert\File(maxSize="6000000")
*/
public $file;
/* * *************************************************************** */
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if ($this->file == $this->getAbsolutePath()) {
unlink($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->id . '/' . $this->path;
}
protected function getUploadRootDir()
{
return __DIR__ . '/../../../../web/' . $this->getUploadDir() . '/' . $this->id;
}
protected function getUploadDir()
{
return 'uploads/users';
}
/**
* Set path
*
* #param string $path
* #return User
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* #param UploadedFile $file
* #return object
*/
public function setFile(UploadedFile $file = null)
{
$this->upload();
return $this;
}
/**
* Get the file used for profile picture uploads
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
// a file was uploaded
// generate a unique filename
$filename = $this->generateRandomProfilePictureFilename();
$this->setPath($filename . '.' . $this->getFile()->guessExtension());
}
}
/**
* Generates a 32 char long random filename
*
* #return string
*/
public function generateRandomProfilePictureFilename()
{
$count = 0;
do {
$generator = new SecureRandom();
$random = $generator->nextBytes(16);
$randomString = bin2hex($random);
$count++;
} while (file_exists($this->getUploadRootDir() . '/' . $randomString . '.' . $this->getFile()->guessExtension()) && $count < 50);
return $randomString;
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
$this->getFile()->move($this->getUploadRootDir(), $this->getPath());
if (isset($this->tempPath) && file_exists($this->getUploadRootDir() . '/' . $this->tempPath)) {
unlink($this->getUploadRootDir() . '/' . $this->tempPath);
$this->tempPath = null;
}
$this->file = null;
}
}
Database row preview:
What is the problem?
I use DoctrineBehaviors to apply translation of my entity, and JordiLlonchCrudGenerator to generate my crud, and LexikFormFilterBundle to generate my form filters type.
My form type
class PageFilterType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'filter_text')
->add('content', 'filter_text')
;
$listener = function(FormEvent $event)
{
// Is data empty?
foreach ($event->getData() as $data) {
if(is_array($data)) {
foreach ($data as $subData) {
if(!empty($subData)) return;
}
}
else {
if(!empty($data)) return;
}
}
$event->getForm()->addError(new FormError('Filter empty'));
};
$builder->addEventListener(FormEvents::POST_BIND, $listener);
}
When i try to filters my entities, the error said hat no field called title in Class Entity\Page.
I understand this problem but i have no idea how to resolve this error, because the field title is into the entity PageTranslation, here my function filters :
protected function filter()
{
$request = $this->getRequest();
$session = $request->getSession();
$filterForm = $this->createForm(new PageFilterType());
$em = $this->getDoctrine()->getManager();
$queryBuilder = $em->getRepository('PageBundle:Page')
->createQueryBuilder('e')
->select('e')
->where('e.deletedAt IS NULL')
;
// Reset filter
if ($request->get('filter_action') == 'reset') {
$session->remove('PageControllerFilter');
}
// Filter action
if ($request->get('filter_action') == 'filter') {
// Bind values from the request
$filterForm->bind($request);
if ($filterForm->isValid()) {
// Build the query from the given form object
$this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
// Save filter to session
$filterData = $filterForm->getData();
$session->set('PageControllerFilter', $filterData);
}
} else {
// Get filter from session
if ($session->has('PageControllerFilter')) {
$filterData = $session->get('PageControllerFilter');
$filterForm = $this->createForm(new PageFilterType(), $filterData);
$this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
}
}
return array($filterForm, $queryBuilder);
}
I think that i should customize this line but i don't know how
$queryBuilder = $em->getRepository('PageBundle:Page')
->createQueryBuilder('e')
->select('e')
->where('e.deletedAt IS NULL')
;
Any solution for that ?
Also, i have created a trash for each entity, for exemple if one page is deleted the user can find it on trash,
Exemple : http://snapplr.com/snap/xxmk
So i have no problem with the action restore all, but remove all is not functional
This is my action
public function emptyTrashAction(){
$em = $this->getDoctrine()->getEntityManager();
$entities=$em->getRepository('PageBundle:Page')->findByRemoved();
if($entities){
foreach ($entities as $entity) {
$em->remove($entity);
$em->flush();
}
$this->get('session')->getFlashBag()->add('success', 'La corbeille est vide !!');
return $this->redirect($this->generateUrl('pa_trash'));
}else{
$this->get('session')->getFlashBag()->add('error', 'La corbeille est déjà vide !! ');
return $this->redirect($this->generateUrl('pa'));
}
}
What i wanna do, is to delete all entities where the feild DeletedAt is not empty, how can i do this ?
Thanks //
This is my entity Page Class
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* Page
* #ORM\Table(name="page")
* #ORM\Entity(repositoryClass="Core\PageBundle\Entity\PageRepository")
*
*/
class Page
{
use ORMBehaviors\Translatable\Translatable;
use ORMBehaviors\Timestampable\Timestampable;
use ORMBehaviors\SoftDeletable\SoftDeletable;
use ORMBehaviors\Blameable\Blameable;
public function __call($method, $arguments)
{
return \Symfony\Component\PropertyAccess\PropertyAccess::createPropertyAccessor()->getValue($this->translate(), $method);
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="nbview", type="integer", nullable=true)
*/
private $nbview;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nbview
*
* #param integer $nbview
* #return Page
*/
public function setNbview($nbview)
{
$this->nbview = $nbview;
return $this;
}
/**
* Get nbview
*
* #return integer
*/
public function getNbview()
{
return $this->nbview;
}
public function getUpdateLogMessage(array $changeSets = [])
{
return 'Changed: '.print_r($changeSets, true);
}
public function getRemoveLogMessage()
{
return 'removed!';
}
And this is the translation page class
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* #ORM\Table(name="page_lang")
* #ORM\Entity()
*/
class PageTranslation
{
use ORMBehaviors\Translatable\Translation;
use ORMBehaviors\Sluggable\Sluggable;
/**
* #inheritdoc
*/
public function getSluggableFields()
{
return ['title'];
}
/**
* #inheritdoc
*/
public function getSlug()
{
if (!$this->slug) {
$this->generateSlug();
}
return $this->slug;
}
/**
* #var string $title
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string $content
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var string $meta
*
* #ORM\Column(name="meta", type="text", nullable=true)
*/
private $meta;
public function getId(){
return $ths->id;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set title
*
* #param string $title
* #return Page
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Set content
*
* #param string $content
* #return Page
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* #param $method
* #param $args
*
* #return mixed
*/
/**
* Set meta
*
* #param string $meta
* #return PageTranslation
*/
public function setMeta($meta)
{
$this->meta = $meta;
return $this;
}
/**
* Get meta
*
* #return string
*/
public function getMeta()
{
return $this->meta;
}
}
I am having problem with LifecycleCallbacks in symfony2 not being executed even though I have #ORM\HasLifecycleCallbacks annotation. I am trying to follow example provided in http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html#using-the-id-as-the-filename. My goal is to save file under the document id.
The below provided code does not result in an error, other than the
The file could not be found. information in reloaded page.
To check what is going on I added die("TEST"); command to upload() function but it seems that it is never executed as the result was only the form page being reloaded with the above mentioned error.
I would like to ask you for advice what may be the reason that the upload() function is not executed?
Controller:
/**
* #Route("app/documents/add/", name="app_documents_add")
*/
public function addAction(Request $request)
{
/**
* This code is aimed at checking if the book is choseen and therefore whether any further works may be carried out
*/
$session = new Session();
if(!$session->get("App_Books_Chosen_Lp")) return new RedirectResponse($this->generateUrl('app_listbooks'));
// Authorization goes here
$documents = new Documents();
$form = $this->createForm(new DocumentsType(), $documents);
$form->add('save', 'submit', array('label' => 'Dodaj dokument'));
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
//$documents->upload();
$book = $em->getReference('AppBundle:Books', $session->get("App_Books_Chosen_Lp"));
if( $book ) $documents->setBook($book);
else die ("CRITICAL ERROR: addAction - Bad book id");
$em->persist($documents);
$em->flush();
}
return $this->render('AppBundle:Documents:adddocuments.html.twig', array('form' => $form->createView()));
}
Documents class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="Documents")
*/
class Documents
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Books", inversedBy="documents")
* #ORM\JoinColumn(name="book_id", referencedColumnName="id")
*/
protected $book;
/**
* #ORM\Column(type="string", length=220)
*/
protected $marker;
/**
* #ORM\Column(type="date", length=220)
*/
protected $document_date;
/**
* #ORM\Column(type="string", length=220)
* #Assert\File(maxSize="6000000")
*/
protected $link;
/**
* #ORM\Column(type="text")
*/
protected $notes;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set marker
*
* #param string $marker
* #return Documents
*/
public function setMarker($marker)
{
$this->marker = $marker;
return $this;
}
/**
* Get marker
*
* #return string
*/
public function getMarker()
{
return $this->marker;
}
/**
* Set document_date
*
* #param \DateTime $documentDate
* #return Documents
*/
public function setDocumentDate($documentDate)
{
$this->document_date = $documentDate;
return $this;
}
/**
* Get document_date
*
* #return \DateTime
*/
public function getDocumentDate()
{
return $this->document_date;
}
/**
* Set link
*
* #param string $link
* #return Documents
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set notes
*
* #param string $notes
* #return Documents
*/
public function setNotes($notes)
{
$this->notes = $notes;
return $this;
}
/**
* Get notes
*
* #return string
*/
public function getNotes()
{
return $this->notes;
}
/**
* Set book
*
* #param \AppBundle\Entity\Books $book
* #return Documents
*/
public function setBook(\AppBundle\Entity\Books $book = null)
{
$this->book = $book;
return $this;
}
/**
* Get book
*
* #return \AppBundle\Entity\Books
*/
public function getBook()
{
return $this->book;
}
/*
* ### FILE UPLOAD PROCESS ###
*/
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
public function getWebPath()
{
return null === $this->link
? null
: $this->getUploadDir().'/'.$this->link;
}
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';
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/*
* Temp fila path
*/
private $temp;
/**
* 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->link = 'initial';
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
$this->link = $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);
}
}
public function getAbsolutePath()
{
return null === $this->link
? null
: $this->getUploadRootDir().'/'.$this->id.'.'.$this->link;
}
}
`
The answer why the upload() function was not executed was quite easy - the form is marked as invalid. Now I am looking for help why this happens (The file could not be found while using LifecycleCallbacks)
I've a problem with 'HasLifecycleCallbacks'. When I try to update only my image in my entity it's doesn't work (It doesn't display form error or php error). But if I update my image and a field (title or text) it's working !
There are no others bugs, all work except this feature.
namespace Acme\NewsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* News
*
* #ORM\Table(name="news")
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="Acme\NewsBundle\Entity\NewsRepository")
*/
class News
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(length=255, unique=true)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255, nullable=true)
*/
private $image;
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
private $oldFile;
/**
* #var string
*
* #ORM\Column(name="text", type="text")
*/
private $text;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct()
{
$this->created = new \Datetime;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return News
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set slug
*
* #param string $slug
* #return News
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set image
*
* #param string $image
* #return News
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set file
*
* #param string $file
* #return News
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
/**
* Set text
*
* #param string $text
* #return News
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set created
*
* #param \DateTime $created
* #return News
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
// upload img
public function getFullFilePath()
{
return null === $this->file ? null : $this->getUploadRootDir(). $this->file;
}
public function getUploadRootDir()
{
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir()."news/";
}
protected function getTmpUploadRootDir()
{
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/up/';
}
public function getFilePath()
{
return null === $this->file ? null : "/web/up/news/". $this->file;
}
/**
* #ORM\PreUpdate()
*/
public function delOldFile()
{
if (null === $this->file) {
return;
}
if(file_exists($this->getUploadRootDir().$this->image)){
$oldDir = $this->getUploadRootDir().$this->image;
if(file_exists($oldDir)) {
unlink($oldDir);
}
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadFile()
{
var_dump(true); die();
// the file property can be empty if the field is not required
if (null === $this->file) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
$extension = pathinfo($this->file->getClientOriginalName(), PATHINFO_EXTENSION);
$name = uniqid().'.'.$extension;
$this->file->move($this->getUploadRootDir().'/', $name);
// resize 145*145
$cropImg = $this->getUploadRootDir().'/'.$name;
$cropDest = $this->getUploadRootDir().'/'.$name;
$largeur = 145;
$hauteur = 145;
$dimension = getimagesize($cropImg);
$ratio = $dimension[0] / $dimension[1];
if($largeur == 0 && $hauteur == 0){ $largeur = $dimension[0]; $hauteur = $dimension[1]; }
else if($hauteur == 0){ $hauteur = round($largeur / $ratio); }
else if($largeur == 0){ $largeur = round($hauteur * $ratio); }
if($dimension[0] > ($largeur/$hauteur)*$dimension[1] ){ $dimY = $hauteur; $dimX = round($hauteur*$dimension[0]/$dimension[1]); $decalX=($dimX-$largeur)/2; $decalY=0;}
if($dimension[0] < ($largeur/$hauteur)*$dimension[1]){ $dimX = $largeur; $dimY = round($largeur*$dimension[1]/$dimension[0]); $decalY=($dimY-$hauteur)/2; $decalX=0;}
if($dimension[0] == ($largeur/$hauteur)*$dimension[1]){ $dimX = $largeur; $dimY = $hauteur; $decalX=0; $decalY=0;}
$miniature = imagecreatetruecolor ($largeur,$hauteur);
if(in_array($extension,array('jpeg','jpg','JPG','JPEG'))){$file = imagecreatefromjpeg($cropImg); }
elseif(in_array($extension,array('png','PNG'))){$file = imagecreatefrompng($cropImg); }
elseif(in_array($extension,array('gif','GIF'))){$file = imagecreatefromgif($cropImg); }
else{ return false; }
imagecopyresampled($miniature,$file,-$decalX,-$decalY,0,0,$dimX,$dimY,$dimension[0],$dimension[1]);
imagejpeg($miniature,$cropDest,90);
$this->setImage($name);
}
/**
* #ORM\PostPersist()
*/
public function moveFile()
{
if (null === $this->file) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
}
/**
* #ORM\PreRemove()
*/
public function removeFile()
{
if ($this->getFullFilePath()) {
unlink($this->getFullFilePath());
}
}
}
This issue is a known bug, check out the doc: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html#using-lifecycle-callbacks
To resolve this, the doc suggest you to use a "updatedAt" field that will be updated each time you persist your entity, even if only the file field changed.
Check that your entity form type has a mapped (mapped option set to true) image field.,
$builder->add('createdDateTime',null,
array("mapped" => true,
"required" => false,
"description" => "Thedatetime of creation")
);
i used the following code in the controller inorder to get the filenames of the uploaded files
My controller is
class uploadController extends Controller
{
public function uploadAction(Request $request)
{
$id= $_GET['id'];
$user = new attachments();
$form = $this->createFormBuilder($user)->add('files','file',array("data_class" => null,"attr"=>array("multiple" =>"multiple",)))->getForm();
$formView = $form->createView();
$formView->getChild('files')->set('full_name','files[]');
if ($request->getMethod() == 'POST')
{
$em = $this->getDoctrine()->getManager();
$data = $form["files"]->getData();
}
}
when i print the $data it is not giving the filenames of uploaded files it is returning the null values
my entity is:
use Symfony\Component\HttpFoundation\File\UploadedFile;
class attachments
{
private $id;
/**
* #var integer
* #ORM\Column(name="user", type="integer", nullable=false)
* #ORM\ManyToOne(targetEntity="users", inversedBy="annotations")
*/
protected $userId;
/**
* #var string
*
* #Assert\File(maxSize="6000000")
* #ORM\Column(name="files", type="array", length=255, nullable=true)
*/
public $files=array();
public function __construct()
{
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userId
*
* #param integer $userId
* #return attachments
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* Set files
* #param object $files
*
* #return attachments
*/
public function setFiles($files)
{
$this->files = $files;
}
/**
* Get files
*
* #return object
*/
public function getFiles()
{
return $this->files;
}
public function uploadFiles()
{
// the files property can be empty if the field is not required
if (null === $this->files)
{
return;
}
else
{
$this->files->move($this->getUploadRootDir(), $this->files->getClientOriginalName());
}
$this->setFiles($this->files->getClientOriginalName());
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir() . DIRECTORY_SEPARATOR . $this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir() . DIRECTORY_SEPARATOR . $this->path;
}
protected function getUploadRootDir()
{
return __DIR__ . '/../../../../web/'. $this->getUploadDir();
}
protected function getUploadDir()
{
return 'uploads/';
}
}
Uploaded Files in Symfony2 are of type Symfony/Component/HttpFoundation/File/UploadedFile.
You can get the original client name ( php will rename files when putting them into php_upload_tmp_dir ) with:
$file->getClientOriginalName();
... move the file to a new location with:
$file->move('path/to/your_file', 'new_name.jpg');
You can not use the assert File Constraint for an array.
* #Assert\File(maxSize="6000000")
*/
protected $files = array();
Therefore you need the All constraint.
Furthermore you can't just call the move method on an array or collection... you will have to loop over the collection/array.
$this->files->move('..') // this is never going to work...
Use an array collection and create a property for your uploaded files if thats what you want.
protected $files;
protected $uploadedFiles;
public function __construct()
{
$this->files = new ArrayCollection;
$this->uploadedFiles = new Array();
}
If you want to transform your Doctrine Collection of UploadedFile entities into an Array do the following:
$collection = $entity->getFiles();
$array = $collection->toArray();
But whatever you're trying to do ... better use OOP instead of arrays like you're attempting here.