Symfony 2 - VichUploader can't handle file - php

I have very strange problem with VichUploader.
I have 2 entities where for one of them VichUploader works fine (Download Entity)- it saves file in directory and add record to database table. For second entity (Offer) it doesn't work- it displays Column 'file_name' cannot be null error. If I have added nullable parameter to fileName property it added record to database table but with NULL file_name (and it DIDN'T save file in directory).
My config.yml
vich_uploader:
db_driver: orm
mappings:
download_file:
uri_prefix: /files/download
upload_destination: %kernel.root_dir%/../web/files/download
offer_file:
uri_prefix: /files/offer
upload_destination: %kernel.root_dir%/../web/files/offer
inject_on_load: false
delete_on_update: false
delete_on_remove: true
Download entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Download
*
* #ORM\Table(name="izo_download")
* #ORM\Entity(repositoryClass="AppBundle\Entity\DownloadRepository")
* #Vich\Uploadable
*/
class Download
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="download_file", fileNameProperty="name")
*
* #var File $file
*/
private $file;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Download
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return Download
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $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->date = new \DateTime('now');
}
}
/**
* #return File
*/
public function getFile()
{
return $this->file;
}
}
Offer entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Offer
*
* #ORM\Table(name="izo_offer")
* #ORM\Entity(repositoryClass="AppBundle\Entity\OfferRepository")
* #Vich\Uploadable
* #ORM\HasLifecycleCallbacks()
*/
class Offer
{
/**
* #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)
* #Assert\NotBlank(message="To pole nie może być puste")
*/
private $name;
/**
* #Assert\Type(type="AppBundle\Entity\Client")
* #Assert\Valid
* #Assert\NotBlank(message="To pole nie może być puste")
* #ORM\ManyToOne(targetEntity="Client", inversedBy="offers",cascade={"persist"})
* #ORM\JoinColumn(name="client_id", referencedColumnName="id")
*/
private $clientBelongsTo;
/**
* #Assert\NotBlank(message="To pole nie może być puste")
* #ORM\ManyToOne(targetEntity="User", inversedBy="supportOffers")
* #ORM\JoinColumn(name="contact_person_id", referencedColumnName="id")
*/
private $contactPerson;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="createdOffers")
* #ORM\JoinColumn(name="creator_id", referencedColumnName="id")
*/
private $createdBy;
/**
* #ORM\OneToMany(targetEntity="Measurement", mappedBy="createdBy")
*/
private $createdMeasurements;
/**
* #ORM\OneToMany(targetEntity="Measurement", mappedBy="contactPerson")
*/
private $supportMeasurements;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="date")
*/
private $createdAt;
/**
* #var string
*
* #ORM\Column(name="note", type="text", nullable=true)
*/
private $note;
/**
* #Assert\NotBlank(message="To pole nie może być puste")
* #var integer
*
* #ORM\Column(name="comesFrom", type="integer")
*/
private $comesFrom;
/**
* #Assert\NotBlank(message="To pole nie może być puste", groups={"creation"})
* #var \DateTime
*
* #ORM\Column(name="notify", type="date")
*/
private $notify;
/**
* #var integer
*
* #ORM\Column(name="status", type="integer")
*/
private $status = 1;
/**
* #var integer
*
* #ORM\Column(name="whyNotSold", type="integer", nullable=true)
*/
private $whyNotSold;
/**
*
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="offer_file", fileNameProperty="fileName")
*
* #var File $file
*/
private $file;
/**
* #var string
*
* #ORM\Column(name="file_name", type="string", length=255)
*/
private $fileName;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime $updatedAt
*/
protected $updatedAt;
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $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;
}
/**
* #param string $fileName
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
}
/**
* #return string
*/
public function getFileName()
{
return $this->fileName;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Offer
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set createdAt
*
* #ORM\PrePersist
*
* #return Offer
*/
public function setCreatedAt()
{
$this->createdAt = new \DateTime();
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set note
*
* #param string $note
*
* #return Offer
*/
public function setNote($note)
{
$this->note = $note;
return $this;
}
/**
* Get note
*
* #return string
*/
public function getNote()
{
return $this->note;
}
/**
* Set notify
*
* #param \DateTime $notify
*
* #return Offer
*/
public function setNotify($notify)
{
$this->notify = $notify;
return $this;
}
/**
* Get notify
*
* #return \DateTime
*/
public function getNotify()
{
return $this->notify;
}
/**
* Set status
*
* #param integer $status
*
* #return Offer
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set whyNotSold
*
* #param integer $whyNotSold
*
* #return Offer
*/
public function setWhyNotSold($whyNotSold)
{
$this->whyNotSold = $whyNotSold;
return $this;
}
/**
* Get whyNotSold
*
* #return integer
*/
public function getWhyNotSold()
{
return $this->whyNotSold;
}
/**
* Set contactPerson
*
* #param \AppBundle\Entity\User $contactPerson
*
* #return Offer
*/
public function setContactPerson(\AppBundle\Entity\User $contactPerson = null)
{
$this->contactPerson = $contactPerson;
return $this;
}
/**
* Get contactPerson
*
* #return \AppBundle\Entity\User
*/
public function getContactPerson()
{
return $this->contactPerson;
}
/**
* Set createdBy
*
* #param \AppBundle\Entity\User $createdBy
*
* #return Offer
*/
public function setCreatedBy(\AppBundle\Entity\User $createdBy = null)
{
$this->createdBy = $createdBy;
return $this;
}
/**
* Get createdBy
*
* #return \AppBundle\Entity\User
*/
public function getCreatedBy()
{
return $this->createdBy;
}
/**
* Set comesFrom
*
* #param integer $comesFrom
*
* #return Offer
*/
public function setComesFrom($comesFrom)
{
$this->comesFrom = $comesFrom;
return $this;
}
/**
* Get comesFrom
*
* #return integer
*/
public function getComesFrom()
{
return $this->comesFrom;
}
/**
* Set clientBelongsTo
*
* #param \AppBundle\Entity\Client $clientBelongsTo
*
* #return Offer
*/
public function setClientBelongsTo(\AppBundle\Entity\Client $clientBelongsTo = null)
{
$this->clientBelongsTo = $clientBelongsTo;
return $this;
}
/**
* Get clientBelongsTo
*
* #return \AppBundle\Entity\Client
*/
public function getClientBelongsTo()
{
return $this->clientBelongsTo;
}
/**
* Constructor
*/
public function __construct()
{
$this->createdMeasurements = new \Doctrine\Common\Collections\ArrayCollection();
$this->supportMeasurements = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add createdMeasurement
*
* #param \AppBundle\Entity\Measurement $createdMeasurement
*
* #return Offer
*/
public function addCreatedMeasurement(\AppBundle\Entity\Measurement $createdMeasurement)
{
$this->createdMeasurements[] = $createdMeasurement;
return $this;
}
/**
* Remove createdMeasurement
*
* #param \AppBundle\Entity\Measurement $createdMeasurement
*/
public function removeCreatedMeasurement(\AppBundle\Entity\Measurement $createdMeasurement)
{
$this->createdMeasurements->removeElement($createdMeasurement);
}
/**
* Get createdMeasurements
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCreatedMeasurements()
{
return $this->createdMeasurements;
}
/**
* Add supportMeasurement
*
* #param \AppBundle\Entity\Measurement $supportMeasurement
*
* #return Offer
*/
public function addSupportMeasurement(\AppBundle\Entity\Measurement $supportMeasurement)
{
$this->supportMeasurements[] = $supportMeasurement;
return $this;
}
/**
* Remove supportMeasurement
*
* #param \AppBundle\Entity\Measurement $supportMeasurement
*/
public function removeSupportMeasurement(\AppBundle\Entity\Measurement $supportMeasurement)
{
$this->supportMeasurements->removeElement($supportMeasurement);
}
/**
* Get supportMeasurements
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSupportMeasurements()
{
return $this->supportMeasurements;
}
}

Probably this could be happening because the UploadableField annotation references the field database name, not the model name (eg: file_name, not fileName), but I test this in a working example and everything went fine. Also VichUploaderBundle listen to Doctrine events, this means that you need to update any other field of the entity to trigger the actual upload of the file, easiest way to "force" the upload its setting a field on the file field setter. Here's an example:
public function setFile($file)
{
$this->file= $file;
if ($this->file) {
$this->update_date = new \DateTime();
}
return $this;
}
This is very effective because you ensure that your file is uploaded and attached when the PrePersist or PreUpdate events are triggered. You could listen to the PreUpload and PostUpload events and check the data been handled (this is easily done whit the dump function provided by Symfony, Symfony >= 2.6). Hope this helps you

Related

Symfony 3 - VichUploader Serving files with a controller

I use Symfony 3.4 with PHP 5.6.
I want to use the vichuploader Bundle to download files. I managed to make it work normally. But now I want to be able to use the files directly from the controller to be able to use them in my database. After reading the documentation, I tried to do something.
I have on my index.html.twig the line :
<td><a href="{{ path('paquet_file', { 'id': uneInfo.id}) }}"</a>{{ uneInfo.urlPaquet }} </td>
On my controller :
namespace Site\PagesBundle\Controller;
use Site\PagesBundle\Entity\Paquet;
use Site\PagesBundle\Entity\TypeUser;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Vich\UploaderBundle\Handler\DownloadHandler;
//........
/**
* Serves an uploaded file.
*
* #Route("/{id}/file", name="paquet_file")
*/
public function fileAction(Paquet $paquet)
{
$downloadHandler = $this->get('vich_uploader.download_handler');
return $downloadHandler->downloadObject($paquet, $fileField = 'paquetFile', Paquet::class, true);
}
My entity :
<?php
namespace Site\PagesBundle\Entity;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Site\PagesBundle\Entity\Paquet;
use Site\PagesBundle\Entity\TypeUser;
use Symfony\Component\HttpFoundation\File\File;
use Doctrine\Common\Collections\ArrayCollection;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Paquet
*
* #ORM\Table(name="paquet")
* #ORM\Entity(repositoryClass="Site\PagesBundle\Repository\PaquetRepository")
* #Vich\Uploadable
*/
class Paquet
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="TypeUser")
* #ORM\JoinTable(name="Packages_des_TypesUser")
* #ORM\JoinColumn(nullable=false)
*/
private $typeUser;
public function __construct()
{
$this->typeUser = new ArrayCollection();
}
/**
* Get TypeUser
*
* #return Site\PagesBundle\Entity\TypeUser
*/
public function getTypeUser()
{
return $this->typeUser;
}
public function deleteTypeFromTypesUser(TypeUser $type)
{
$this->typeUser->removeElement($type);
}
/**
* Set typeUser
*
* #param Site\PagesBundle\Entity\TypeUser $typeUser
*
* #return Paquet
*/
public function setTypeUser(Site\PagesBundle\Entity\TypeUser $typeUser)
{
$this->typeUser = $typeUser;
return $this;
}
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="urlPaquet", type="string", length=255)
*/
private $urlPaquet;
/**
* #Vich\UploadableField(mapping="paquet", fileNameProperty="urlPaquet")
* #var File
*/
private $paquetFile;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
/**
* #param File|UploadedFile $unPaquetFile
*
* #return Paquet
*/
public function setPaquetFile(File $unPaquetFile = null)
{
$this->paquetFile = $unPaquetFile;
if ($unPaquetFile)
{
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return Paquet
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* #return File|null
*/
public function getPaquetFile()
{
return $this->paquetFile;
}
/**
* #var string
*
* #ORM\Column(name="urlNotice", type="string", length=255)
*/
private $urlNotice;
/**
* #Vich\UploadableField(mapping="notice", fileNameProperty="urlNotice")
* #var File
*/
private $noticeFile;
/**
* #var string
*
* #ORM\Column(name="commentaire", type="text")
*/
private $commentaire;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
*
* #return Paquet
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set urlPaquet
*
* #param string $urlPaquet
*
* #return Paquet
*/
public function setUrlPaquet($urlPaquet)
{
$this->urlPaquet = $urlPaquet;
return $this;
}
/**
* Get urlPaquet
*
* #return string|null
*/
public function getUrlPaquet()
{
return $this->urlPaquet;
}
/**
* #return File|null
*/
public function getNoticeFile()
{
return $this->noticeFile;
}
/**
* #param File|UploadedFile $uneNoticeFile
*
* #return Paquet
*/
public function setNoticeFile(File $uneNoticeFile = null)
{
$this->noticeFile = $uneNoticeFile;
if ($uneNoticeFile)
{
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* Set urlNotice
*
* #param string $urlNotice
*
* #return Paquet
*/
public function setUrlNotice($urlNotice)
{
$this->urlNotice = $urlNotice;
return $this;
}
/**
* Get urlNotice
*
* #return string
*/
public function getUrlNotice()
{
return $this->urlNotice;
}
/**
* Set commentaire
*
* #param string $commentaire
*
* #return Paquet
*/
public function setCommentaire($commentaire)
{
$this->commentaire = $commentaire;
return $this;
}
/**
* Get commentaire
*
* #return string
*/
public function getCommentaire()
{
return $this->commentaire;
}
}
But when I click on the URL file :
Screen - My page
I have this file :
Screen - Downloaded file
Thanks for your help !
I don't use this bundle yet (I plan to work with it soon though).
But from what I see in the doc page : https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/downloads/serving_files_with_a_controller.md the 4th argument is the filename while you set true to it.
So maybe it's just a filename issue ? You could try to set filename to null (I guess it will take the real filename by default) or set your own filename (with extension) as the 4th argument in the downloadObject() call.

Symfony3 - "Unrecognized field" exception when I want to pull entries based on the value of a Many-to-One relation property

I want to display records from an entity, but only records that have the loginID value equal to the current user's ID. In the Events entity, loginid is a many-to-one property.
I have the following Events entity:
namespace Vendor\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Events
*
* #ORM\Table(name="events")
* #ORM\Entity
*/
class Events
{
/**
* #var string
*
* #ORM\Column(name="EventName", type="string", length=255, nullable=false)
*/
private $eventname;
/**
* #var string
*
* #ORM\Column(name="Location", type="string", length=255, nullable=false)
*/
private $location;
/**
* #var \DateTime
*
* #ORM\Column(name="StartDate", type="datetime", nullable=false)
*/
private $startdate;
/**
* #var \DateTime
*
* #ORM\Column(name="EndDate", type="datetime", nullable=false)
*/
private $enddate;
/**
* #var boolean
*
* #ORM\Column(name="Status", type="boolean", nullable=false)
*/
private $status;
/**
* #var integer
*
* #ORM\Column(name="eventID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $eventid;
/**
* Set eventname
*
* #param string $eventname
*
* #return Events
*/
public function setEventname($eventname)
{
$this->eventname = $eventname;
return $this;
}
/**
* Get eventname
*
* #return string
*/
public function getEventname()
{
return $this->eventname;
}
/**
* Set location
*
* #param string $location
*
* #return Events
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set startdate
*
* #param \DateTime $startdate
*
* #return Events
*/
public function setStartdate($startdate)
{
$this->startdate = $startdate;
return $this;
}
/**
* Get startdate
*
* #return \DateTime
*/
public function getStartdate()
{
return $this->startdate;
}
/**
* Set enddate
*
* #param \DateTime $enddate
*
* #return Events
*/
public function setEnddate($enddate)
{
$this->enddate = $enddate;
return $this;
}
/**
* Get enddate
*
* #return \DateTime
*/
public function getEnddate()
{
return $this->enddate;
}
/**
* Set status
*
* #param boolean $status
*
* #return Events
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status=true;
}
/**
* Get eventid
*
* #return integer
*/
public function getEventid()
{
return $this->eventid;
}
/**
* Get web path to upload directory.
*
* #return string
* Relative path.
*/
protected function getUploadPath()
{
return 'uploads/eventCovers';
}
/**
* Get absolute Path.
*
* #return string
* Absolute path.
*/
protected function getUploadAbsolutePath()
{
return __DIR__ . '/../../../../web/' . $this->getUploadPath();
}
/**
* Get web path to a cover.
*
* #return null|string
* Relative path.
*/
public function getCoverWeb()
{
return NULL === $this->getCover()
? NULL
: $this->getUploadPath() . '/' . $this->getCover();
}
/**
* Get web path on disk to a cover.
*
* #return null|string
* Absolute path.
*/
public function getCoverAbsolute()
{
return NULL === $this->getCover()
? NULL
: $this->getUploadAbsolutePathPath() . '/' . $this->getCover();
}
/**
* Set validation for max file size of 2 MB.
*
* #Assert\File(maxSize="2M")
*/
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;
}
/**
*
* Upload a cover file.
*/
public function upload()
{
//file property can be empty
if (NULL === $this->getFile()){
return;
}
$filename=$this->getFile()->getClientOriginalName();
//move the uploaded file to the target directory using the original name
$this->getFile()->move(
$this->getUploadAbsolutePath(),
$filename);
//set the cover
$this->setCover($filename);
//cleanup
$this->setFile();
}
/**
* #var string
*
* #ORM\Column(name="Cover", type="string", length=255, nullable=true)
*/
private $cover;
/**
* Set cover
*
* #param string $cover
*
* #return Events
*/
public function setCover($cover)
{
$this->cover = $cover;
return $this;
}
/**
* Get cover
*
* #return string
*/
public function getCover()
{
return $this->cover;
}
/**
* #var \Vendor\MyBundle\Entity\Logins
*/
private $loginid;
/**
* #var \Vendor\MyBundle\Entity\WishList
*/
private $wishlistid;
/**
* Set loginid
*
* #param \Vendor\MyBundle\Entity\Logins $loginid
*
* #return Events
*/
public function setLoginid(\Vendor\MyBundle\Entity\Logins $loginid = null)
{
$this->loginid = $loginid;
return $this;
}
/**
* Get loginid
*
* #return \Vendor\MyBundle\Entity\Logins
*/
public function getLoginid()
{
return $this->loginid;
}
/**
* Set wishlistid
*
* #param \Vendor\MyBundle\Entity\WishList $wishlistid
*
* #return Events
*/
public function setWishlistid(\Vendor\MyBundle\Entity\WishList $wishlistid = null)
{
$this->wishlistid = $wishlistid;
return $this;
}
/**
* Get wishlistid
*
* #return \Vendor\MyBundle\Entity\WishList
*/
public function getWishlistid()
{
return $this->wishlistid;
}
}
and the following indexAction in my controller:
namespace Vendor\MyBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Vendor\MyBundle\Entity\Events;
use Vendor\MyBundle\Form\EventsType;
/**
* Events controller.
*
* #Route("/sec/events")
*/
class EventsController extends Controller
{
/**
* Lists all Events entities.
*
* #Route("/", name="sec_events_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$events = $em->getRepository('VendorMyBundle:Events')->findBy(array('loginid' => $user->getLoginid()));
return $this->render('events/index.html.twig', array(
'events' => $events,
));
}
}
However I am thrown the error: Unrecognized field: loginid even though that is the name of the field/property in the Events class.
I looked here and I do have the code used as it says in there.
What am I missing?
Any help would be greatly appreciated!
You are missing some ORM definition for $loginid and because of that there is no column loginid in your events table.
I assume you want to have OneToMany or ManyToMany association to ...\Entity\Logins, so you have to define that association according to this: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html

Doctrine Scheme update. Overlooking entities

I have created 2 new entities and when I run
app/console doctrine:schema:update --force
It says i am up to date and these two new entities do not get tables created.
Every other command i have found will detect entities in other bundles but none from the bundle i am working on. Example would be
app/console doctrine:mapping:info
It does not show there either.
Here is a example of one. This lives in the Entity Folder of my bundle
<?php
namespace test\OrganizationBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Department
* #ORM\Entity
* #ORM\Table(name="departments")
*/
class Department
{
/**
* #var integer
*
* #ORM\Column(name="id", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=50, nullable=false)
*/
private $name;
/**
* #var integer
* #ORM\Column(name="facilityId", type="int")
*
*/
private $facilityId;
/**
* #var \DateTime
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #var \DateTime
* #ORM\Column(name="updated", type="datetime")
*/
private $updated;
/**
* #var array
* #ORM\ManyToMany(targetEntity="DeptTag", mappedBy="departments")
*/
private $deptTags;
public function __construct()
{
$this->deptTags = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Department
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set facilityId
*
* #param string $facilityId
*
* #return Department
*/
public function setFacilityId($facilityId)
{
$this->facilityId = $facilityId;
return $this;
}
/**
* Get facilityId
*
* #return string
*/
public function getFacilityId()
{
return $this->facilityId;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return Department
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
/**
* Set updated
*
* #param \DateTime $updated
*
* #return Department
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set deptTags
*
* #param array $deptTags
*
* #return Department
*/
public function setDeptTags($deptTags)
{
$this->deptTags = $deptTags;
return $this;
}
/**
* Get deptTags
*
* #return array
*/
public function getDeptTags(DeptTag)
{
return $this->deptTags[] = $deptTag;
}
}

The target-entity cannot be found in - MappingException

I have Symfony project, in which there are 2 entities - Building and Building_type. They are connected with ManyToMany uni-directional association. So, when I try to access my controller, I have this error:
The target-entity Farpost\StoreBundle\Entity\Building_type cannot be found in 'Farpost\StoreBundle\Entity\Building#building_types'.
Farpost/StoreBundle/Entity/Building.php:
namespace Farpost\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
*
*/
class Building
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="alias", type="string", length=255)
*/
protected $alias;
/**
* #var string
*
* #ORM\Column(name="number", type="string", length=255)
*/
protected $number;
/**
* #ORM\ManyToMany(targetEntity="Building_type")
* #ORM\JoinTable(name="buildings_types",
* joinColumns={#ORM\JoinColumn(name="building_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="building_type_id", referencedColumnName="id")}
* )
*/
protected $building_types;
public function __construct()
{
$this->building_types = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set alias
*
* #param string $alias
* #return Building
*/
public function setAlias($alias)
{
$this->alias = $alias;
return $this;
}
/**
* Get alias
*
* #return string
*/
public function getAlias()
{
return $this->alias;
}
/**
* Set number
*
* #param string $number
* #return Building
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* Get number
*
* #return string
*/
public function getNumber()
{
return $this->number;
}
/**
* Add building_types
*
* #param \Farpost\StoreBundle\Entity\Building_type $buildingTypes
* #return Building
*/
public function addBuildingType(\Farpost\StoreBundle\Entity\Building_type $buildingTypes)
{
$this->building_types[] = $buildingTypes;
return $this;
}
/**
* Remove building_types
*
* #param \Farpost\StoreBundle\Entity\Building_type $buildingTypes
*/
public function removeBuildingType(\Farpost\StoreBundle\Entity\Building_type $buildingTypes)
{
$this->building_types->removeElement($buildingTypes);
}
/**
* Get building_types
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBuildingTypes()
{
return $this->building_types;
}
/**
* Add buildings_types
*
* #param \Farpost\StoreBundle\Entity\Buildings_types $buildingsTypes
* #return Building
*/
public function addBuildingsType(\Farpost\StoreBundle\Entity\Buildings_types $buildingsTypes)
{
$this->buildings_types[] = $buildingsTypes;
return $this;
}
/**
* Remove buildings_types
*
* #param \Farpost\StoreBundle\Entity\Buildings_types $buildingsTypes
*/
public function removeBuildingsType(\Farpost\StoreBundle\Entity\Buildings_types $buildingsTypes)
{
$this->buildings_types->removeElement($buildingsTypes);
}
/**
* Get buildings_types
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getBuildingsTypes()
{
return $this->buildings_types;
}
}
Farpost/StoreBundle/Entity/Building_type.php:
namespace Farpost\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Entity
*
*/
class Building_type
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="alias", type="string", length=255)
*/
protected $alias;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set alias
*
* #param string $alias
* #return Building_type
*/
public function setAlias($alias)
{
$this->alias = $alias;
return $this;
}
/**
* Get alias
*
* #return string
*/
public function getAlias()
{
return $this->alias;
}
}
Farpost/APIBundle/Controller/DefaultController.php:
public function listAction($name)
{
$repository = $this->getDoctrine()->getManager()
->getRepository('FarpostStoreBundle:Building');
$items = $repository->findAll();
$response = new Response(json_encode($items));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
Also, app/console doctrine:schema:validate output is:
[Mapping] OK - The mapping files are correct.
[Database] OK - The database schema is in sync with the mapping files.
Because the name of the entity contains an underscore _ and the PSR-0 autoloader will try to find it in Farpost/StoreBundle/Entity/Building/type.php.
You need to rename your class to BuildingType and put it in Farpost/StoreBundle/Entity/BuildingType.php
Also, make sure that your composer.json has proper entries pointing to proper namespace. Mine did not, causing this error.

Symfony2 - Doctrine exception: class used in the discriminator map does not exist

I am using Symfony2 with Doctrine and when I query from my controller the next error appears(it appears in the navigator when I call for the page):
Entity class 'Bdreamers\SuenoBundle\Entity\Sueno_video' used in the discriminator map of class 'Bdreamers\SuenoBundle\Entity\Sueno' does not exist.
I have one entity(superclass) called "Sueno" and two entities that extend from it(subclasses): Sueno_foto and Sueno_video.
When I load the fixtures, Doctrine works perfectly and fills the database without any issue, filling correctly the discriminator field "tipo" in the "Sueno" table. It also fills correctly the inherited entity table "Sueno_video" introducing the ID of "Sueno" and the exclusive fields of "Sueno_video"
This is the code of the entity file for "Sueno":
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="tipo", type="string")
* #ORM\DiscriminatorMap({"sueno" = "Sueno", "video" = "Sueno_video", "foto" = "Sueno_foto"})
*/
class Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario")
**/
private $usuario;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\SuenoBundle\Entity\Tag", inversedBy="suenos")
* #ORM\JoinTable(name="suenos_tags")
**/
private $tags;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_sigue")
* #ORM\JoinTable(name="usuarios_siguen")
**/
private $usuariosSeguidores;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_colabora")
* #ORM\JoinTable(name="usuarios_colaboran")
**/
private $usuariosColaboradores;
/**
* #var \DateTime
*
* #ORM\Column(name="fecha_subida", type="datetime")
*/
private $fechaSubida;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=40)
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="que_pido", type="string", length=140)
*/
private $quePido;
/**
* #var string
*
* #ORM\Column(name="texto", type="string", length=540)
*/
private $texto;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set usuario
*
* #param string $usuario
* #return Sueno
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
public function getTags()
{
return $this->tags;
}
/**
* Set usuariosSeguidores
*
* #param string $usuariosSeguidores
* #return Sueno
*/
public function setUsuariosSeguidores($usuariosSeguidores)
{
$this->usuariosSeguidores = $usuariosSeguidores;
return $this;
}
/**
* Get usuariosSeguidores
*
* #return string
*/
public function getUsuariosSeguidores()
{
return $this->usuariosSeguidores;
}
/**
* Set usuariosColaboradores
*
* #param string $usuariosColaboradores
* #return Sueno
*/
public function setUsuariosColaboradores($usuariosColaboradores)
{
$this->usuariosColaboradores = $usuariosColaboradores;
return $this;
}
/**
* Get usuariosColaboradores
*
* #return string
*/
public function getUsuariosColaboradores()
{
return $this->usuariosColaboradores;
}
/**
* Set fechaSubida
*
* #param \DateTime $fechaSubida
* #return Sueno
*/
public function setFechaSubida($fechaSubida)
{
$this->fechaSubida = $fechaSubida;
return $this;
}
/**
* Get fechaSubida
*
* #return \DateTime
*/
public function getFechaSubida()
{
return $this->fechaSubida;
}
/**
* Set titulo
*
* #param string $titulo
* #return Sueno
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set quePido
*
* #param string $quePido
* #return Sueno
*/
public function setQuePido($quePido)
{
$this->quePido = $quePido;
return $this;
}
/**
* Get quePido
*
* #return string
*/
public function getQuePido()
{
return $this->quePido;
}
/**
* Set texto
*
* #param string $texto
* #return Sueno
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
public function __construct() {
$this->usuariosColaboradores = new \Doctrine\Common\Collections\ArrayCollection();
$this->usuariosSeguidores = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->getTitulo();
}
}
And this is the code for the entity Sueno_video:
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
*/
class Sueno_video extends Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="link_video", type="string", length=255)
*/
private $linkVideo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set linkVideo
*
* #param string $linkVideo
* #return Sueno_video
*/
public function setLinkVideo($linkVideo)
{
$this->linkVideo = $linkVideo;
return $this;
}
/**
* Get linkVideo
*
* #return string
*/
public function getLinkVideo()
{
return $this->linkVideo;
}
}
And finally the code in the controller:
public function homeAction()
{
$em = $this->getDoctrine()->getManager();
$suenos = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array(
'fechaSubida' => new \DateTime('now -2 days')
));
return $this->render('EstructuraBundle:Home:home_registrado.html.twig');
}
The autoloader won't be able to resolve those class names to file paths, hence why it can't find your classes.
Changing the file and class names to SuenoVideo and SuenoFoto.

Categories