i'm trying to upload a file in my database with symfony, I modified my entity, and my form. But when i click on upload a document, i have no error but nothing append (I have no new doc in C:\wamp64\www\myproject\web\upload, and my database field, here support, is null). Here is the code of my entities :
<?php
namespace Main\ConfigBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Invoice
*/
class InvoiceCoach
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $reference_invoice;
/**
* #var string
*/
private $status;
/**
* #var string
*/
private $total = 0;
/**
* #var string
*/
private $tva;
/**
* #var string
*/
private $link;
/**
* #var string
*/
private $paiement_method;
/**
* #var \DateTime
*/
private $date_billing;
/**
* #var \DateTime
*/
private $date_submission;
/**
* #var \DateTime
*/
private $date_creation;
/**
* #var \DateTime
*/
private $date_updated;
/**
* #var string
*/
private $commentaire;
/**
* #var boolean
*/
private $valid_paul = 0;
/**
* #var boolean
*/
private $valid_corinne = 0;
/**
* #var boolean
*/
private $valid_lise = 0;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $invoice;
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $element;
/**
* #var \Main\ConfigBundle\Entity\Coach
*/
private $coachs;
/**
* #var File
*/
private $file;
/**
* Constructor
*/
public function __construct()
{
$this->invoice = new \Doctrine\Common\Collections\ArrayCollection();
$this->element = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set referenceInvoice
*
* #param string $referenceInvoice
*
* #return InvoiceCoach
*/
public function setReferenceInvoice($referenceInvoice)
{
$this->reference_invoice = $referenceInvoice;
return $this;
}
/**
* Get referenceInvoice
*
* #return string
*/
public function getReferenceInvoice()
{
return $this->reference_invoice;
}
/**
* Set status
*
* #param string $status
*
* #return InvoiceCoach
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Set total
*
* #param string $total
*
* #return InvoiceCoach
*/
public function setTotal($total)
{
$this->total = $total;
return $this;
}
/**
* Get total
*
* #return string
*/
public function getTotal()
{
return $this->total;
}
/**
* Set tva
*
* #param string $tva
*
* #return InvoiceCoach
*/
public function setTva($tva)
{
$this->tva = $tva;
return $this;
}
/**
* Get tva
*
* #return string
*/
public function getTva()
{
return $this->tva;
}
/**
* Set link
*
* #param string $link
*
* #return InvoiceCoach
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set paiementMethod
*
* #param string $paiementMethod
*
* #return InvoiceCoach
*/
public function setPaiementMethod($paiementMethod)
{
$this->paiement_method = $paiementMethod;
return $this;
}
/**
* Get paiementMethod
*
* #return string
*/
public function getPaiementMethod()
{
return $this->paiement_method;
}
/**
* Set dateBilling
*
* #param \DateTime $dateBilling
*
* #return InvoiceCoach
*/
public function setDateBilling($dateBilling)
{
$this->date_billing = $dateBilling;
return $this;
}
/**
* Get dateBilling
*
* #return \DateTime
*/
public function getDateBilling()
{
return $this->date_billing;
}
/**
* Set dateSubmission
*
* #param \DateTime $dateSubmission
*
* #return InvoiceCoach
*/
public function setDateSubmission($dateSubmission)
{
$this->date_submission = $dateSubmission;
return $this;
}
/**
* Get dateSubmission
*
* #return \DateTime
*/
public function getDateSubmission()
{
return $this->date_submission;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
*
* #return InvoiceCoach
*/
public function setDateCreation($dateCreation)
{
$this->date_creation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->date_creation;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
*
* #return InvoiceCoach
*/
public function setDateUpdated($dateUpdated)
{
$this->date_updated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated()
{
return $this->date_updated;
}
/**
* Set commentaire
*
* #param string $commentaire
*
* #return InvoiceCoach
*/
public function setCommentaire($commentaire)
{
$this->commentaire = $commentaire;
return $this;
}
/**
* Get commentaire
*
* #return string
*/
public function getCommentaire()
{
return $this->commentaire;
}
/**
* Set validPaul
*
* #param boolean $validPaul
*
* #return InvoiceCoach
*/
public function setValidPaul($validPaul)
{
$this->valid_paul = $validPaul;
return $this;
}
/**
* Get validPaul
*
* #return boolean
*/
public function getValidPaul()
{
return $this->valid_paul;
}
/**
* Set validCorinne
*
* #param boolean $validCorinne
*
* #return InvoiceCoach
*/
public function setValidCorinne($validCorinne)
{
$this->valid_corinne = $validCorinne;
return $this;
}
/**
* Get validCorinne
*
* #return boolean
*/
public function getValidCorinne()
{
return $this->valid_corinne;
}
/**
* Set validLise
*
* #param boolean $validLise
*
* #return InvoiceCoach
*/
public function setValidLise($validLise)
{
$this->valid_lise = $validLise;
return $this;
}
/**
* Get validLise
*
* #return boolean
*/
public function getValidLise()
{
return $this->valid_lise;
}
/**
* Add invoice
*
* #param \Main\ConfigBundle\Entity\InvoiceBox $invoice
*
* #return InvoiceCoach
*/
public function addInvoice(\Main\ConfigBundle\Entity\InvoiceBox $invoice)
{
$this->invoice[] = $invoice;
return $this;
}
/**
* Remove invoice
*
* #param \Main\ConfigBundle\Entity\InvoiceBox $invoice
*/
public function removeInvoice(\Main\ConfigBundle\Entity\InvoiceBox $invoice)
{
$this->invoice->removeElement($invoice);
}
/**
* Get invoice
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getInvoice()
{
return $this->invoice;
}
/**
* Add element
*
* #param \Main\ConfigBundle\Entity\InvoiceElement $element
*
* #return InvoiceCoach
*/
public function addElement(\Main\ConfigBundle\Entity\InvoiceElement $element)
{
$this->element[] = $element;
return $this;
}
/**
* Remove element
*
* #param \Main\ConfigBundle\Entity\InvoiceElement $element
*/
public function removeElement(\Main\ConfigBundle\Entity\InvoiceElement $element)
{
$this->element->removeElement($element);
}
/**
* Get element
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getElement()
{
return $this->element;
}
/**
* Set coachs
*
* #param \Main\ConfigBundle\Entity\Coach $coachs
*
* #return InvoiceCoach
*/
public function setCoachs(\Main\ConfigBundle\Entity\Coach $coachs = null)
{
$this->coachs = $coachs;
return $this;
}
/**
* Get coachs
*
* #return \Main\ConfigBundle\Entity\Coach
*/
public function getCoachs()
{
return $this->coachs;
}
/**
* #var string
*/
private $support;
/**
* Set support
*
* #param string $support
*
* #return InvoiceCoach
*/
public function setSupport($support)
{
$this->support = $support;
return $this;
}
/**
* Get support
*
* #return string
*/
public function getSupport()
{
return $this->support;
}
/**
* Set file
*
* #param File $file
* #return InvoiceCoach
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return File
*/
public function getFile()
{
return $this->file;
}
// File Upload Method
public function getAbsolutePath()
{
return null === $this->support ? null : $this->getUploadRootDir().'/'.$this->support;
}
public function getPath()
{
return null === $this->support ? null : $this->getUploadDir().'/'.$this->support;
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
return 'upload';
}
// Doctrine Specific Method
public function __persist()
{
if($this->file !== null)
$this->support = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
}
public function __postPersist()
{
if($this->file === null)
return;
$this->file->move($this->getUploadRootDir(), $this->support);
unset($this->file);
$this->file = null;
}
public function __flush()
{
if($this->file === null)
return;
$this->__remove();
$this->__persist();
$this->__postPersist();
}
public function __remove()
{
if($file = $this->getAbsolutePath())
if(file_exists($file))
unlink($file);
}
}
THX a lot
edit : here is the code of my controller (when the form is created) and where I call it on twig :
$em = $this->getDoctrine()->getManager();
$invoice = $em->getRepository("MainConfigBundle:InvoiceCoach")->find($id);
$formUpload = $this->createForm('invoicesupport', $invoice)
->add('save', 'submit', array('label' => 'Enregistrer') );
if($request->getMethod() == "POST"){
$formUpload->handleRequest($request);
if($formUpload->isValid()){
$em->persist($invoice);
$em->flush();
}
return $this->redirect($this->generateUrl('coach_paid_edit', array('id' => $id) ));
}
twig :
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Upload facture</h5>
</div>
<div class="modal-body">
{{ form_start(form, {'attr': {'novalidate': 'novalidate', 'data-parsley-validate':'data-parsley-validate'}}) }}
{{ form_row(formUpload.file) }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
{{ form_row(formUpload.save) }}
{{ form_end(form) }}
</div>
</div>
First and most important - did you test that "Doctrine Specific Method" are firing up ?. My guess is that they not firing up (honestly i see first time approach like this - and i don't know why should it work)
Even if - i think that approach is bad , this code should be moved to event listeners/subscribed . It shouldn't be in entity file.
Look at http://symfony.com/doc/current/doctrine/event_listeners_subscribers.html
Here you have link to my old upload solution with Trait connected to entity
https://gist.github.com/poznet/e3955a48fea01d8640dafbd966c53a83
Related
In my backoffice (made with Sonata Admin) I have an overview of registrations.
My Registration Model looks like this:
<?php
namespace MyProject\Domain\Model;
use MyProject\Domain\Model\Interfaces\HostInterface;
use MyProject\Domain\Model\Interfaces\VisitReasonInterface;
use MyProject\Domain\Model\Interfaces\CustomerInterface;
use MyProject\Domain\Model\Interfaces\EntryPointInterface;
use MyProject\Domain\Model\Interfaces\LanguageInterface;
use MyProject\Domain\Model\Interfaces\RegistrationInterface;
use MyProject\Domain\Model\Interfaces\SiteInterface;
use MyProject\Domain\Model\Traits\HasFileTrait;
use MyProject\Infrastructure\Model\GenderType;
use Knp\DoctrineBehaviors\Model\Timestampable\Timestampable;
use Symfony\Component\Intl\Intl;
/**
* Class Registration.
*/
class Registration implements RegistrationInterface
{
use HasFileTrait;
use Timestampable;
public const UPLOADS_FOLDER = 'uploads/registrations';
/**
* #var string|null
*/
protected $companyName;
/**
* #var string|null
*/
protected $firstname;
/**
* #var string|null
*/
protected $lastname;
/**
* #var string|null
*/
protected $email;
/**
* #var string|null
*/
protected $addressFirstLine;
/**
* #var string|null
*/
protected $addressSecondLine;
/**
* #var string|null
*/
protected $zipCode;
/**
* #var string|null
*/
protected $city;
/**
* #var string|null
*/
protected $countryCode = 'BE';
/**
* #var string|null
*/
protected $gender;
/**
* #var \DateTime|null
*/
protected $birthDate;
/**
* #var string|null
*/
protected $country = 'BE';
/**
* #var string|null
*/
protected $website;
/**
* #var string|null
*/
protected $workPermit;
/**
* #var string|null
*/
protected $licensePlate;
/**
* #var bool
*/
protected $incognito = false;
/**
* #var bool
*/
protected $refused = false;
/**
* #var \DateTime
*/
protected $eta;
/**
* #var \DateTime
*/
protected $etd;
/**
* #var \DateTime
*/
protected $rta;
/**
* #var \DateTime
*/
protected $rtd;
/**
* #var bool
*/
protected $preRegistration = false;
/**
* #var int
*/
protected $id;
/**
* #var LanguageInterface
*/
protected $language;
/**
* #var CustomerInterface
*/
protected $customer;
/**
* #var SiteInterface
*/
protected $site;
/**
* #var EntryPointInterface
*/
protected $entryPoint;
/**
* #var HostInterface|null
*/
protected $host;
/**
* #var VisitReasonInterface|null
*/
protected $visitReason;
/**
* #var string|null
*/
protected $licenseNumber;
/**
* #var string|null
*/
protected $mobileNumber;
/**
* #var string|null
*/
protected $salutation;
/**
* #var int
*/
protected $customerUniqueId;
/**
* #var string
*/
protected $occupation;
/**
* #var string
*/
protected $status;
/**
* #var boolean
*/
protected $hasLightPlan;
/**
* #var string
*/
protected $referredBy;
/**
* #var boolean
*/
protected $subscribedToNewsletter;
/**
* #var string
*/
protected $uniqueId;
/**
* #var int
*/
protected $numberOfPassengers;
/**
* #var int
*/
protected $mtow;
/**
* #var float
*/
protected $avgaz;
/**
* #var string
*/
protected $arrivalFrom;
/**
* #var string
*/
protected $departureTo;
/**
* Set companyName.
*
* #param string|null $companyName
*
* #return RegistrationInterface
*/
public function setCompanyName($companyName)
{
$this->companyName = $companyName;
return $this;
}
/**
* Get companyName.
*
* #return string|null
*/
public function getCompanyName()
{
return $this->companyName;
}
/**
* Set firstname.
*
* #param string|null $firstname
*
* #return RegistrationInterface
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname.
*
* #return string|null
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname.
*
* #param string|null $lastname
*
* #return RegistrationInterface
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get full name (first + last name)
*
* #return string
*/
public function getName()
{
return $this->getFirstname() . ' ' . $this->getLastname();
}
/**
* Get lastname.
*
* #return string|null
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set email.
*
* #param string|null $email
*
* #return RegistrationInterface
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email.
*
* #return string|null
*/
public function getEmail()
{
return $this->email;
}
/**
* Set addressFirstLine.
*
* #param string|null $addressFirstLine
*
* #return RegistrationInterface
*/
public function setAddressFirstLine($addressFirstLine)
{
$this->addressFirstLine = $addressFirstLine;
return $this;
}
/**
* Get addressFirstLine.
*
* #return string|null
*/
public function getAddressFirstLine()
{
return $this->addressFirstLine;
}
/**
* Set addressSecondLine.
*
* #param string|null $addressSecondLine
*
* #return RegistrationInterface
*/
public function setAddressSecondLine($addressSecondLine)
{
$this->addressSecondLine = $addressSecondLine;
return $this;
}
/**
* Get addressSecondLine.
*
* #return string|null
*/
public function getAddressSecondLine()
{
return $this->addressSecondLine;
}
/**
* Set zipCode.
*
* #param string|null $zipCode
*
* #return RegistrationInterface
*/
public function setZipCode($zipCode)
{
$this->zipCode = $zipCode;
return $this;
}
/**
* Get zipCode.
*
* #return string|null
*/
public function getZipCode()
{
return $this->zipCode;
}
/**
* Set city.
*
* #param string|null $city
*
* #return RegistrationInterface
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city.
*
* #return string|null
*/
public function getCity()
{
return $this->city;
}
/**
* Set gender.
*
* #param string|null $gender
*
* #return RegistrationInterface
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender.
*
* #return string|null
*/
public function getGender()
{
return $this->gender;
}
/**
* Set birthDate.
*
* #param \DateTime|null $birthDate
*
* #return RegistrationInterface
*/
public function setBirthDate($birthDate)
{
$this->birthDate = $birthDate;
return $this;
}
/**
* Get birthDate.
*
* #return \DateTime|null
*/
public function getBirthDate()
{
return $this->birthDate;
}
/**
* Set country.
*
* #param string|null $country
*
* #return RegistrationInterface
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country.
*
* #return string|null
*/
public function getCountry()
{
return $this->country;
}
/**
* Set website.
*
* #param string|null $website
*
* #return RegistrationInterface
*/
public function setWebsite($website)
{
$this->website = $website;
return $this;
}
/**
* Get website.
*
* #return string|null
*/
public function getWebsite()
{
return $this->website;
}
/**
* Set workPermit.
*
* #param string|null $workPermit
*
* #return RegistrationInterface
*/
public function setWorkPermit($workPermit)
{
$this->workPermit = $workPermit;
return $this;
}
/**
* #return string|null
*/
public function getWorkPermit()
{
return $this->workPermit;
}
/**
* #param $licensePlate
*
* #return RegistrationInterface
*/
public function setLicensePlate($licensePlate)
{
$this->licensePlate = $licensePlate;
return $this;
}
/**
* #return string|null
*/
public function getLicensePlate()
{
return $this->licensePlate;
}
/**
* #param bool $incognito
*
* #return RegistrationInterface
*/
public function setIncognito($incognito)
{
$this->incognito = $incognito;
return $this;
}
/**
* #return bool
*/
public function getIncognito()
{
return $this->incognito;
}
/**
* #param bool $refused
*
* #return RegistrationInterface
*/
public function setRefused($refused)
{
$this->refused = $refused;
return $this;
}
/**
* #return bool
*/
public function getRefused()
{
return $this->refused;
}
/**
* Set eta.
*
* #param \DateTime $eta
*
* #return RegistrationInterface
*/
public function setEta(\DateTime $eta)
{
$this->eta = $eta;
return $this;
}
/**
* Get eta.
*
* #return \DateTime
*/
public function getEta()
{
return $this->eta;
}
/**
* Set etd.
*
* #param \DateTime $etd
*
* #return RegistrationInterface
*/
public function setEtd(?\DateTime $etd)
{
$this->etd = $etd;
return $this;
}
/**
* Get etd.
*
* #return \DateTime
*/
public function getEtd()
{
return $this->etd;
}
/**
* Set rta.
*
* #param \DateTime $rta
*
* #return RegistrationInterface
*/
public function setRta(?\DateTime $rta)
{
$this->rta = $rta;
return $this;
}
/**
* Get rta.
*
* #return \DateTime
*/
public function getRta()
{
return $this->rta;
}
/**
* Set rtd.
*
* #param \DateTime $rtd
*
* #return RegistrationInterface
*/
public function setRtd(\DateTime $rtd)
{
$this->rtd = $rtd;
return $this;
}
/**
* Get rtd.
*
* #return \DateTime
*/
public function getRtd()
{
return $this->rtd;
}
/**
* Set preRegistration.
*
* #param bool $preRegistration
*
* #return RegistrationInterface
*/
public function setPreRegistration($preRegistration)
{
$this->preRegistration = $preRegistration;
return $this;
}
/**
* Get preRegistration.
*
* #return bool
*/
public function getPreRegistration()
{
return $this->preRegistration;
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param LanguageInterface|null $language
*
* #return $this
*/
public function setLanguage(LanguageInterface $language = null)
{
$this->language = $language;
return $this;
}
/**
* #return LanguageInterface
*/
public function getLanguage()
{
return $this->language;
}
/**
* #param CustomerInterface|null $customer
*
* #return $this
*/
public function setCustomer(CustomerInterface $customer = null)
{
$this->customer = $customer;
return $this;
}
/**
* #return CustomerInterface
*/
public function getCustomer()
{
return $this->customer;
}
/**
* #param SiteInterface|null $site
*
* #return $this
*/
public function setSite(SiteInterface $site = null)
{
$this->site = $site;
if ($site) {
$this->setCustomer($site->getCustomer());
}
return $this;
}
/**
* #return SiteInterface
*/
public function getSite()
{
return $this->site;
}
/**
* #param EntryPointInterface|null $entryPoint
*
* #return $this
*/
public function setEntryPoint(EntryPointInterface $entryPoint = null)
{
$this->entryPoint = $entryPoint;
$this->setSite($entryPoint->getSite());
return $this;
}
/**
* #return EntryPointInterface
*/
public function getEntryPoint()
{
return $this->entryPoint;
}
/**
* #param HostInterface|null $host
* #return $this
*/
public function setHost(?HostInterface $host = null)
{
$this->host = $host;
return $this;
}
/**
* #return HostInterface|null
*/
public function getHost()
{
return $this->host;
}
/**
* #return string|null
*/
public function getLicenseNumber()
{
return $this->licenseNumber;
}
/**
* #param string|null $licenseNumber
* #return RegistrationInterface
*/
public function setLicenseNumber($licenseNumber)
{
$this->licenseNumber = $licenseNumber;
return $this;
}
/**
* #return string|null
*/
public function getMobileNumber()
{
return $this->mobileNumber;
}
/**
* #param string|null $mobileNumber
* #return RegistrationInterface $this
*/
public function setMobileNumber($mobileNumber)
{
$this->mobileNumber = $mobileNumber;
return $this;
}
/**
* #return VisitReasonInterface|null
*/
public function getVisitReason()
{
return $this->visitReason;
}
/**
* #param VisitReasonInterface|null $visitReason
* #return RegistrationInterface $this
*/
public function setVisitReason(VisitReasonInterface $visitReason = null)
{
$this->visitReason = $visitReason;
return $this;
}
/**
* Get the 2-letter country abbreviation
*
* #return string|null
*/
public function getCountryCode()
{
return $this->countryCode;
}
/**
* Set the 2-letter country abbreviation
*
* #param string|null $countryCode
* #return Registration
*/
public function setCountryCode($countryCode)
{
$this->countryCode = $countryCode;
return $this;
}
/**
* Get the full translated country name
*
* #return null|string
*/
public function getAddressCountry()
{
return Intl::getRegionBundle()->getCountryName($this->countryCode);
}
/**
* #param string|null $salutation
* #return Registration
*/
public function setSalutation($salutation)
{
$this->salutation = $salutation;
return $this;
}
/**
* #return string|null
*/
public function getSalutation()
{
return $this->salutation;
}
/**
* getUploadsFolder.
*
* #return string
*/
public function getUploadsFolder()
{
return $this::UPLOADS_FOLDER;
}
/**
* getAllowedFileExtensions.
*
* #return array
*/
public function getAllowedFileExtensions()
{
return ['jpg', 'jpeg', 'png'];
}
/**
* getAllowedFileMimeTypes.
*
* #return array
*/
public function getAllowedFileMimeTypes()
{
return ['image/jpeg', 'image/pjpeg', 'image/png'];
}
/**
* Get the gender name
*
* #return string
*/
public function getGenderName()
{
$genders = array_flip(GenderType::toArray());
return $genders[$this->gender] ?? '';
}
/**
* #return int
*/
public function getCustomerUniqueId()
{
return $this->customerUniqueId;
}
/**
* #param int $customerUniqueId
* #return RegistrationInterface
*/
public function setCustomerUniqueId($customerUniqueId)
{
$this->customerUniqueId = $customerUniqueId;
return $this;
}
/**
* #return string
*/
public function getOccupation()
{
return $this->occupation;
}
/**
* #param string $occupation
* #return RegistrationInterface
*/
public function setOccupation($occupation)
{
$this->occupation = $occupation;
return $this;
}
/**
* #return string
*/
public function getStatus()
{
return $this->status;
}
/**
* #param string $status
* #return RegistrationInterface
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* #return bool
*/
public function hasLightPlan()
{
return $this->hasLightPlan;
}
/**
* #param bool $hasLightPlan
* #return RegistrationInterface
*/
public function setHasLightPlan($hasLightPlan)
{
$this->hasLightPlan = $hasLightPlan;
return $this;
}
/**
* #return string
*/
public function getReferredBy()
{
return $this->referredBy;
}
/**
* #param string $referredBy
* #return RegistrationInterface
*/
public function setReferredBy($referredBy)
{
$this->referredBy = $referredBy;
return $this;
}
/**
* #return bool
*/
public function isSubscribedToNewsletter()
{
return $this->subscribedToNewsletter;
}
/**
* #param bool $subscribedToNewsletter
* #return RegistrationInterface
*/
public function setSubscribedToNewsletter($subscribedToNewsletter)
{
$this->subscribedToNewsletter = $subscribedToNewsletter;
return $this;
}
/**
* #return int
*/
public function getNumberOfPassengers()
{
return $this->numberOfPassengers;
}
/**
* #param int $numberOfPassengers
* #return RegistrationInterface
*/
public function setNumberOfPassengers($numberOfPassengers)
{
$this->numberOfPassengers = $numberOfPassengers;
return $this;
}
/**
* #return int
*/
public function getMtow()
{
return $this->mtow;
}
/**
* #param int $mtow
* #return RegistrationInterface
*/
public function setMtow($mtow)
{
$this->mtow = $mtow;
return $this;
}
/**
* #return float
*/
public function getAvgaz()
{
return $this->avgaz;
}
/**
* #param float $avgaz
* #return RegistrationInterface
*/
public function setAvgaz($avgaz)
{
$this->avgaz = $avgaz;
return $this;
}
/**
* #return string
*/
public function getArrivalFrom()
{
return $this->arrivalFrom;
}
/**
* #param string $arrivalFrom
* #return RegistrationInterface
*/
public function setArrivalFrom($arrivalFrom)
{
$this->arrivalFrom = $arrivalFrom;
return $this;
}
/**
* #return string
*/
public function getDepartureTo()
{
return $this->departureTo;
}
/**
* #param string $departureTo
* #return RegistrationInterface
*/
public function setDepartureTo($departureTo)
{
$this->departureTo = $departureTo;
return $this;
}
/**
* #return string
*/
public function getUniqueId()
{
return $this->uniqueId ?? $this->getCustomerUniqueId();
}
/**
* #param string $id
* #return RegistrationInterface
*/
public function setUniqueId($id)
{
$this->uniqueId = $id;
return $this;
}
}
In my RegistrationAdmin class I have:
/**
* #param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('companyName', null, [
'label' => 'label.company_name',
])
->add('firstname', null, [
'label' => 'label.firstname',
])
->add('lastname', null, [
'label' => 'label.lastname',
])
->add('language', null, [
'label' => 'label.language',
])
->add('allowedFrom', 'doctrine_orm_date', [
'label' => 'label.allowed_from',
])
->add('visitReason', null, [
'label' => 'label.visit_reason',
])
;
}
The problem is that the visit reasons (last filter) is showing all the visit reasons in the application.
A visit reason is linked (relation) to a customer. And a customer is linked (relation) to a user in the application.
So I would like to show all the visit reasons in autocomplete dropdown that are linked to the logged in user.
But how could I do this?
Check documentation in http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/filter_field_definition.html. Parameters to add the new filter are the field name, the filter type, the filter configuration, form field type and form field configuration.
//set visitReason from your user $visitsReasonUser
->add('my_filter', null, array(), 'entity', array(
'class' => 'MyBundle:Registration',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.visitReason in :vistsUser')
->setParameters(':visitUser',$visitsReasonUser');
}
))
In editAction method of controller I tried to edit existed entities in class table inheritance.
But after form submit I get error:
Neither the property "id" nor one of the methods
"addId()"/"removeId()", "setId()", "id()", "__set()" or "__call()"
exist and have public access in class "AdBundle\Entity\AdFlat".
Why AdFlat entity not extended of AdBase entity?
Base entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdBase
*
* #ORM\Table(name="ad_base")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdBaseRepository")
* #ORM\HasLifecycleCallbacks()
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="discr", type="string")
* #ORM\DiscriminatorMap({
"flat" = "AdFlat"
* })
*/
abstract class AdBase
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="author", type="string", length=255)
*/
private $author;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdCategory")
*/
private $category;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(message="Field Location should not be blank")
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
* #Assert\NotBlank(message="Not specified Title")
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=true)
* #Assert\NotBlank(message="Not specified Description")
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="AdBundle\Entity\AdPhoto", mappedBy="ad")
*/
private $photos;
/**
* #ORM\Column(type="float")
* #Assert\NotBlank()
*/
private $price;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdPriceType")
*/
private $priceType;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var string
*
* #ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
/**
* #var bool
*
* #ORM\Column(name="visible", type="boolean")
*/
private $visible = false;
/**
* #ORM\Column(type="boolean")
*/
private $active = true;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set author
*
* #param string $author
*
* #return AdBase
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* #return mixed
*/
public function getCategory()
{
return $this->category;
}
/**
* #param mixed $category
*/
public function setCategory($category)
{
$this->category = $category;
}
/**
* #return mixed
*/
public function getLocation()
{
return $this->location;
}
/**
* #param mixed $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* Set title
*
* #param string $title
*
* #return AdBase
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*
* #return AdBase
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set photos
*
* #param string $photos
*
* #return AdBase
*/
public function setPhotos($photos)
{
$this->photos = $photos;
return $this;
}
/**
* Get photos
*
* #return string
*/
public function getPhotos()
{
return $this->photos;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getPriceType()
{
return $this->priceType;
}
/**
* #param mixed $priceType
*/
public function setPriceType($priceType)
{
$this->priceType = $priceType;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return AdBase
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param string $updatedAt
*
* #return AdBase
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return string
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set visible
*
* #param boolean $visible
*
* #return AdBase
*/
public function setVisible($visible)
{
$this->visible = $visible;
return $this;
}
/**
* Get visible
*
* #return bool
*/
public function getVisible()
{
return $this->visible;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #ORM\PrePersist()
*/
public function prePersist()
{
$this->author = 'voodoo';
$this->createdAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
$this->location = 'Donetsk';
}
/**
* #ORM\PreUpdate()
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime('now', new \DateTimeZone('UTC'));
}
}
Extended entity:
<?php
namespace AdBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* AdFlat
*
* #ORM\Table(name="ad_flat")
* #ORM\Entity(repositoryClass="AdBundle\Repository\AdFlatRepository")
*/
class AdFlat extends AdBase
{
/**
* #var integer
*
* #ORM\Column(type="integer")
* #Assert\NotBlank(message="ad_flat.rooms.not_blank")
*/
private $rooms;
/**
* #var float
*
* #ORM\Column(name="square", type="float", nullable=true)
*/
private $square;
/**
* #var float
*
* #ORM\Column(name="liveSquare", type="float", nullable=true)
*/
private $liveSquare;
/**
* #var float
*
* #ORM\Column(type="float", nullable=true)
*/
private $kitchenSquare;
/**
* #var int
*
* #ORM\Column(name="floor", type="integer")
*/
private $floor;
/**
* #var int
*
* #ORM\Column(name="floors", type="integer")
*/
private $floors;
/**
* #var string
*
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWallType")
*/
private $wallType;
/**
* #ORM\ManyToOne(targetEntity="AdBundle\Entity\AdWCType")
*/
private $wcType;
/**
* #return mixed
*/
public function getRooms()
{
return $this->rooms;
}
/**
* #param mixed $rooms
*/
public function setRooms($rooms)
{
$this->rooms = $rooms;
}
/**
* Set square
*
* #param float $square
*
* #return AdFlat
*/
public function setSquare($square)
{
$this->square = $square;
return $this;
}
/**
* Get square
*
* #return float
*/
public function getSquare()
{
return $this->square;
}
/**
* Set liveSquare
*
* #param float $liveSquare
*
* #return AdFlat
*/
public function setLiveSquare($liveSquare)
{
$this->liveSquare = $liveSquare;
return $this;
}
/**
* Get liveSquare
*
* #return float
*/
public function getLiveSquare()
{
return $this->liveSquare;
}
/**
* #return float
*/
public function getKitchenSquare()
{
return $this->kitchenSquare;
}
/**
* #param float $kitchenSquare
*/
public function setKitchenSquare($kitchenSquare)
{
$this->kitchenSquare = $kitchenSquare;
}
/**
* Set floor
*
* #param integer $floor
*
* #return AdFlat
*/
public function setFloor($floor)
{
$this->floor = $floor;
return $this;
}
/**
* Get floor
*
* #return int
*/
public function getFloor()
{
return $this->floor;
}
/**
* Set floors
*
* #param integer $floors
*
* #return AdFlat
*/
public function setFloors($floors)
{
$this->floors = $floors;
return $this;
}
/**
* Get floors
*
* #return int
*/
public function getFloors()
{
return $this->floors;
}
/**
* Set wallType
*
* #param string $wallType
*
* #return AdFlat
*/
public function setWallType($wallType)
{
$this->wallType = $wallType;
return $this;
}
/**
* Get wallType
*
* #return string
*/
public function getWallType()
{
return $this->wallType;
}
/**
* Set wcType
*
* #param string $wcType
*
* #return AdFlat
*/
public function setWcType($wcType)
{
$this->wcType = $wcType;
return $this;
}
/**
* Get wcType
*
* #return string
*/
public function getWcType()
{
return $this->wcType;
}
}
In controller:
public function editAction(Request $request)
{
$adId = $request->get('id');
if (!$adId) {
return $this->renderError('Unknown Ad');
}
$adEntity = $this->getDoctrine()->getRepository('AdBundle:AdBase')->find($adId);
if (null === $adEntity) {
return $this->renderError('Unknown Ad');
}
$reflection = new \ReflectionClass($adEntity);
$adForm = $this->getForm($reflection->getShortName());
$form = $this->createForm($adForm, $adEntity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($adEntity);
$em->flush();
return $this->redirectToRoute('ad_bundle_ad_view', array(
'id' => $adEntity->getId()
));
}
return $this->render('AdBundle:Ad:edit-ad-flat.html.twig', array(
'form' => $form->createView()
));
}
private function renderError($message = '')
{
return $this->render('::error.html.twig', array(
'error' => $message
));
}
private function getEntity($className)
{
$entityName = 'AdBundle\Entity\\' . $className;
return new $entityName();
}
private function getForm($className)
{
$formName = 'AdBundle\Form\Type\\' . $className . 'Type';
return new $formName();
}
The error message simply states that you are missing a way to set the entity's $id property. It doesn't tell you anything about the class not extending the base class. However, your base class only defines a getter method for the $id property but no setter method.
Doctrine Entities work as POPOs (Plain Old PHP Objects). To achieve extending correctly you need to work with the MappedSuperClass here is an example
I have Order documents that are embedded in my Table document and I cannot figure out how to update them. For example how can I change the value of "pizza" to "pollo"
My MongoDB is like this:
Tables Document
<?php
namespace Acme\StoreBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/** #MongoDB\Document */
class Tables
{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\Int
*/
protected $number;
/**
* #MongoDB\Int
*/
protected $numordini;
/**
* #MongoDB\String
*/
protected $state;
/**
* #MongoDB\String
*/
protected $left;
/**
* #MongoDB\String
*/
protected $top;
/**
* #MongoDB\String
*/
protected $qrcode;
/**
* #MongoDB\String
*/
protected $idristorante;
/**
* #MongoDB\String
*/
protected $idadmin;
/**
* #MongoDB\EmbedMany(targetDocument="Order")
*/
private $order;
public function __construct()
{
$this->order = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return id $id
*/
public function getId()
{
return $this->id;
}
/**
* Set number
*
* #param int $number
* #return self
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* Get number
*
* #return int $number
*/
public function getNumber()
{
return $this->number;
}
/**
* Set state
*
* #param string $state
* #return self
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get state
*
* #return string $state
*/
public function getState()
{
return $this->state;
}
/**
* Set qrcode
*
* #param string $qrcode
* #return self
*/
public function setQrcode($qrcode)
{
$this->qrcode = $qrcode;
return $this;
}
/**
* Get qrcode
*
* #return string $qrcode
*/
public function getQrcode()
{
return $this->qrcode;
}
/**
* Set idristorante
*
* #param string $idristorante
* #return self
*/
public function setIdristorante($idristorante)
{
$this->idristorante = $idristorante;
return $this;
}
/**
* Get idristorante
*
* #return string $idristorante
*/
public function getIdristorante()
{
return $this->idristorante;
}
/**
* Set idadmin
*
* #param string $idadmin
* #return self
*/
public function setIdadmin($idadmin)
{
$this->idadmin = $idadmin;
return $this;
}
/**
* Get idadmin
*
* #return string $idadmin
*/
public function getIdadmin()
{
return $this->idadmin;
}
/**
* Add order
*
* #param Acme\StoreBundle\Document\Order $order
*/
public function addOrder(\Acme\StoreBundle\Document\Order $order)
{
$this->order[] = $order;
}
/**
* Remove order
*
* #param Acme\StoreBundle\Document\Order $order
*/
public function removeOrder(\Acme\StoreBundle\Document\Order $order)
{
$this->order->removeElement($order);
}
/**
* Get order
*
* #return Doctrine\Common\Collections\Collection $order
*/
public function getOrder()
{
return $this->order;
}
/**
* Set left
*
* #param string $left
* #return self
*/
public function setLeft($left)
{
$this->left = $left;
return $this;
}
/**
* Get left
*
* #return string $left
*/
public function getLeft()
{
return $this->left;
}
/**
* Set top
*
* #param string $top
* #return self
*/
public function setTop($top)
{
$this->top = $top;
return $this;
}
/**
* Get top
*
* #return string $top
*/
public function getTop()
{
return $this->top;
}
/**
* Set numordini
*
* #param int $numordini
* #return self
*/
public function setNumordini($numordini)
{
$this->numordini = $numordini;
return $this;
}
/**
* Get numordini
*
* #return int $numordini
*/
public function getNumordini()
{
return $this->numordini;
}
}
Order Document
<?php
namespace Acme\StoreBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/** #MongoDB\EmbeddedDocument */
class Order
{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\String
*/
protected $nomepiatto;
/**
* #MongoDB\String
*/
protected $variazione;
/**
* #MongoDB\String
*/
protected $prezzo;
/**
* #MongoDB\String
*/
protected $riferimento;
/**
* #MongoDB\String
*/
protected $status;
/**
* Get id
*
* #return id $id
*/
public function getId()
{
return $this->id;
}
/**
* Set nomepiatto
*
* #param string $nomepiatto
* #return self
*/
public function setNomepiatto($nomepiatto)
{
$this->nomepiatto = $nomepiatto;
return $this;
}
/**
* Get nomepiatto
*
* #return string $nomepiatto
*/
public function getNomepiatto()
{
return $this->nomepiatto;
}
/**
* Set variazione
*
* #param string $variazione
* #return self
*/
public function setVariazione($variazione)
{
$this->variazione = $variazione;
return $this;
}
/**
* Get variazione
*
* #return string $variazione
*/
public function getVariazione()
{
return $this->variazione;
}
/**
* Set prezzo
*
* #param string $prezzo
* #return self
*/
public function setPrezzo($prezzo)
{
$this->prezzo = $prezzo;
return $this;
}
/**
* Get prezzo
*
* #return string $prezzo
*/
public function getPrezzo()
{
return $this->prezzo;
}
/**
* Set riferimento
*
* #param string $riferimento
* #return self
*/
public function setRiferimento($riferimento)
{
$this->riferimento = $riferimento;
return $this;
}
/**
* Get riferimento
*
* #return string $riferimento
*/
public function getRiferimento()
{
return $this->riferimento;
}
/**
* Set status
*
* #param string $status
* #return self
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return string $status
*/
public function getStatus()
{
return $this->status;
}
}
databases tables output:
{
"_id" : ObjectId("54ad1e08622ef2b6541fc775"),
"number" : NumberLong(1),
"state" : "ciao",
"idristorante" : "54a8834f622ef2e8688b4572",
"idadmin" : "luca",
"order" : [
{
"_id" : ObjectId("54f71508622ef2df618b4567"),
"nomepiatto" : "opopop",
"prezzo" : "12"
},
{
"_id" : ObjectId("54f71ffb622ef2f47f8b4567"),
"nomepiatto" : "pizza",
"prezzo" : "12"
}
],
"left" : "476px",
"top" : "420px"
}
This will set all Table.order.nomepiatta fields with the value pizza to pollo. Not tested but it should work.
$repo = $odm->getRepository("Table");
$repo->createQueryBuilder()->findAndUpdate()->field('order.nomepiatto')
->set('pollo')->field("order.nomepiatto")->equals('pizza')->getQuery()->execute();
I have an api in symfony2, in which adding and deleting items is not issue, however, updating doesn't throw me any errors however the relevent row in my database does not get updated!
My Controller method:
/*
* #Route("/complete/uid/{storeUid}",
* name = "media_complete"
* )
*
* #Method({"GET"})
*
* #param String $storeUid - the uid for the store that has completed downloading
*
* #return Response
*/
public function downloadCompleteAction($storeUid)
{
$response = $this->getNewJsonResponse();
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository("SimplySmartUHDProBundle:Machine");
try {
//get the machine from the db
$machine = $repo->findOneBy(array(
"uid" => $storeUid
));
//set it as download completed
$machine->setStatus(Machine::STATUS_DOWNLOAD_COMPLETE);
$em->persist($machine);
$em->flush();
$response->setStatusCode(200);
} catch (\Exception $e) {
//if there is an error, catch the exception set the status to 500 and return json with the exception error
$error = array("message" => $e->getMessage());
$response->setContent(json_encode($error));
$response->setStatusCode(500);
}
return $response;
}
My Entity:
namespace SimplySmart\UHDProBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use SimplySmart\UHDProBundle\Entity\Store;
/**
* Machine
*
* #ORM\Table(name="Machines", uniqueConstraints={#ORM\UniqueConstraint(name="UID", columns={"UID"})})
* #ORM\Entity
*/
class Machine
{
const STATUS_NO_FEED = 0;
const STATUS_REQUIRES_DOWNLOAD = 1;
const STATUS_DOWNLOAD_IN_PROGRESS = 2;
const STATUS_DOWNLOAD_COMPLETE = 3;
/**
* Array of available statuses
*
* #var array
*/
static public $statuses = array(
self::STATUS_NO_FEED,
self::STATUS_REQUIRES_DOWNLOAD,
self::STATUS_DOWNLOAD_IN_PROGRESS,
self::STATUS_DOWNLOAD_COMPLETE
);
/**
* #var string
*
* #ORM\Column(name="UID", type="string", length=50, nullable=false)
*/
private $uid;
/**
* #var string
*
* #ORM\Column(name="StoreCode", type="string", length=10, nullable=false)
*/
private $storecode;
/**
* #var string
*
* #ORM\Column(name="Description", type="string", length=100, nullable=true)
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="Status", type="boolean", nullable=false)
*/
private $status;
/**
* #var boolean
*
* #ORM\Column(name="OnlineStatus", type="boolean", nullable=false)
*/
private $onlinestatus;
/**
* #var string
*
* #ORM\Column(name="Version", type="string", length=10, nullable=false)
*/
private $version;
/**
* #var \DateTime
*
* #ORM\Column(name="Timestamp", type="datetime", nullable=false)
*/
private $timestamp;
/**
* #ORM\ManyToOne(targetEntity="SimplySmart\UHDProBundle\Entity\Store", inversedBy="machines")
* #ORM\JoinColumn(name="StoreCode", referencedColumnName="Code")
*/
protected $store;
/**
* #ORM\ManyToMany(targetEntity="SimplySmart\UHDProBundle\Entity\Feed", inversedBy="machines")
* #ORM\JoinTable(joinColumns={#ORM\JoinColumn(name="machine_id", referencedColumnName="MachID")},
* inverseJoinColumns={#ORM\JoinColumn(name="feed_id", referencedColumnName="FeedID")}
* )
*
*/
protected $feeds;
/**
* #var integer
*
* #ORM\Column(name="MachID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $machid;
/**
*
*/
public function __construct()
{
$this->feeds = new ArrayCollection();
}
/**
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #param string $description
*
* #return $this
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getFeedtype()
{
return $this->feedtype;
}
/**
* #param string $feedtype
*
* #return $this
*/
public function setFeedtype($feedtype)
{
$this->feedtype = $feedtype;
return $this;
}
/**
* #return int
*/
public function getMachid()
{
return $this->machid;
}
/**
* #param int $machid
*
* #return $this
*/
public function setMachid($machid)
{
$this->machid = $machid;
return $this;
}
/**
* #return boolean
*/
public function isOnlinestatus()
{
return $this->onlinestatus;
}
/**
* #param boolean $onlinestatus
*
* #return $this
*/
public function setOnlinestatus($onlinestatus)
{
$this->onlinestatus = $onlinestatus;
return $this;
}
/**
* #return boolean
*/
public function isStatus()
{
return $this->status;
}
/**
* #param boolean $status
*
* #throws \Exception if invalid status is given
*
* #return $this
*/
public function setStatus($status)
{
if (in_array($status, self::$statuses)) {
$this->status = $status;
} else {
throw new \Exception("invalid status given");
}
return $this;
}
/**
* #return string
*/
public function getStorecode()
{
return $this->storecode;
}
/**
* #param string $storecode
*
* #return $this
*/
public function setStorecode($storecode)
{
$this->storecode = $storecode;
return $this;
}
/**
* #return \DateTime
*/
public function getTimestamp()
{
return $this->timestamp;
}
/**
* #param \DateTime $timestamp
*
* #return $this
*/
public function setTimestamp($timestamp)
{
$this->timestamp = $timestamp;
return $this;
}
/**
* #return string
*/
public function getUid()
{
return $this->uid;
}
/**
* #param string $uid
*
* #return $this
*/
public function setUid($uid)
{
$this->uid = $uid;
return $this;
}
/**
* #return string
*/
public function getVersion()
{
return $this->version;
}
/**
* #param string $version
*
* #return $this
*/
public function setVersion($version)
{
$this->version = $version;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
/**
* Get onlinestatus
*
* #return boolean
*/
public function getOnlinestatus()
{
return $this->onlinestatus;
}
/**
* Set store
*
* #param \SimplySmart\UHDProBundle\Entity\Store $store
* #return Machine
*/
public function setStore(\SimplySmart\UHDProBundle\Entity\Store $store = null)
{
$this->store = $store;
return $this;
}
/**
* Get store
*
* #return \SimplySmart\UHDProBundle\Entity\Store
*/
public function getStore()
{
return $this->store;
}
/**
* Method to generate and set a new UID
*
* #return $this
*/
public function generateNewUid()
{
$date = new \DateTime("UTC");
$uid = "U";
$uid .= $date->format("U");
$uid .= 'R'.rand(0,100);
$this->setUid($uid);
return $this;
}
/**
* Add feeds
*
* #param \SimplySmart\UHDProBundle\Entity\Feed $feeds
* #return Machine
*/
public function addFeed(\SimplySmart\UHDProBundle\Entity\Feed $feeds)
{
$this->feeds[] = $feeds;
return $this;
}
/**
* Remove feeds
*
* #param \SimplySmart\UHDProBundle\Entity\Feed $feeds
*/
public function removeFeed(\SimplySmart\UHDProBundle\Entity\Feed $feeds)
{
$this->feeds->removeElement($feeds);
}
/**
* Get feeds
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFeeds()
{
return $this->feeds;
}
}
I am fully aware that when updating an entity I shouldn't need to use $em->persist($machine), however removing this doesn't seem to make any difference.
The part that is really grinding my gears, is that when I go on the profiler, it appears as it is ran all the queries as expected!
Just realised that I've been a complete idiot and my issue is that status is set as a boolean field in my entity, so it was updating, but always setting it as 1!
What I'm trying to do is to get an Post(Post Entity) form where I can select a featured picture from another entity(File Entity).
At the end I would like to display only the files of type "featured Image" but even if I remove my query_builder I've got a exception that says:
Class "Site\Backend\Adminbundle\Entity\File" seems not to be a managed Doctrine entity. Did you forget to map it?
Here is my PostType form
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('title')
->add('thumb', 'entity', array(
'class' => 'Site\Backend\Adminbundle\Entity\File',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('f')
//->where('f.state = :state')
//->setParameter('state', $prms['state'])
->orderBy('f.dateUpdated', 'DESC');
}
))
}
In the other hand I have my two entities:
Here is my File entity
<?php
namespace Site\Backend\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Site\Backend\AdminBundle\Entity\File
*
* #ORM\Table()
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class File {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreated", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="dateUpdated", type="datetime")
*/
private $dateUpdated;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
/**
* #ORM\Column(type="string", length=255)
*/
public $path;
/**
* #ORM\ManyToOne(targetEntity="TypeFile", inversedBy="files")
*/
private $type;
/**
* #var string
*
* #ORM\OneToMany(targetEntity="Site\Backend\BlogBundle\Entity\Post", mappedBy="thumb")
*/
private $posts;
public function __construct() {
$this->setDateCreated(new \DateTime());
$this->setDateUpdated(new \DateTime());
$this->type = new ArrayCollection();
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload() {
$this->setDateUpdated(new \DateTime());
if (null !== $this->file) {
// do whatever you want to generate a unique name
$this->path = sha1(uniqid(mt_rand(), true)) . '.' . $this->file->guessExtension();
} else {
//throwException($e);
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload() {
if (null === $this->file) {
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->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
/**
* #ORM\PostRemove()
*/
public function removeUpload() {
if ($file = $this->getAbsolutePath()) {
if (file_exists($file)) {
unlink($file);
}
}
}
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 when displaying uploaded doc/image in the view.
return 'uploads/' . $this->type;
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return File
*/
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 File
*/
public function setPath($path) {
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath() {
return $this->path;
}
public function __toString() {
return $this->name;
}
/**
* Add type
*
* #param Site\Backend\AdminBundle\Entity\TypeFile $type
* #return File
*/
public function addType(\Site\Backend\AdminBundle\Entity\TypeFile $type) {
$this->type[] = $type;
return $this;
}
/**
* Remove type
*
* #param Site\Backend\AdminBundle\Entity\TypeFile $type
*/
public function removeType(\Site\Backend\AdminBundle\Entity\TypeFile $type) {
$this->type->removeElement($type);
}
/**
* Get type
*
* #return Doctrine\Common\Collections\Collection
*/
public function getType() {
return $this->type;
}
/**
* Set type
*
* #param Site\Backend\AdminBundle\Entity\TypeFile $type
* #return File
*/
public function setType(\Site\Backend\AdminBundle\Entity\TypeFile $type = null) {
$this->type = $type;
return $this;
}
public function getFile() {
return $this->file;
}
public function setFile($file) {
$this->file = $file;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
* #return File
*/
public function setDateCreated($dateCreated) {
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated() {
return $this->dateCreated;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
* #return File
*/
public function setDateUpdated($dateUpdated) {
$this->dateUpdated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated() {
return $this->dateUpdated;
}
/**
* Add posts
*
* #param \Site\Backend\BlogBundle\Entity\Post $posts
* #return File
*/
public function addPost(\Site\Backend\BlogBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* Remove posts
*
* #param \Site\Backend\BlogBundle\Entity\Post $posts
*/
public function removePost(\Site\Backend\BlogBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
And Here is my Post entity
<?php
namespace Site\Backend\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Post
*
* #ORM\Table()
* #ORM\Entity
*/
class Post
{
/**
* #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;
/**
* #var \DateTime
*
* #ORM\Column(name="dateCreated", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="dateUpdated", type="datetime")
*/
private $dateUpdated;
/**
* #var \DateTime
*
* #ORM\Column(name="datePublished", type="datetime", nullable=true)
*/
private $datePublished;
/**
* #var string
*
* #ORM\Column(name="state", type="string", length=255)
*/
private $state;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var Author
* #ORM\ManyToOne(targetEntity="Site\Backend\AdminBundle\Entity\User", inversedBy="posts")
*/
private $author;
/**
* #var Thumb
* #ORM\ManyToOne(targetEntity="Site\Backend\AdminBundle\Entity\File", inversedBy="posts")
*/
private $thumb;
/**
* #var Comments
* #ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
private $comments;
/**
* #var Categories
* #ORM\ManyToMany(targetEntity="Category", cascade={"persist"})
*/
private $categories;
/**
* #var Tags
* #ORM\ManyToMany(targetEntity="Tag", cascade={"persist"})
*/
private $tags;
/**
* Constructeur
*/
public function __construct()
{
$this->setDateCreated(new \DateTime());
$this->setDateUpdated(new \DateTime());
$this->comments = new ArrayCollection();
$this->Categories = new ArrayCollection();
$this->tags = new ArrayCollection();
}
public function __toString(){
return $this->title;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Post
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set dateCreated
*
* #param \DateTime $dateCreated
* #return Comment
*/
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
* Get dateCreated
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
* #return Comment
*/
public function setDateUpdated($dateUpdated)
{
$this->dateUpdated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated()
{
return $this->dateUpdated;
}
/**
* Get datePublished
*
* #return \DateTime
*/
public function getDatePublished()
{
return $this->datePublished;
}
/**
* Set datePublished
*
* #param \DateTime $datePublished
* #return Comment
*/
public function setDatePublished($datePublished)
{
$this->datePublished = $datePublished;
return $this;
}
/**
* Set state
*
* #param string $state
* #return Post
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get state
*
* #return string
*/
public function getState()
{
return $this->state;
}
/**
* Set content
*
* #param string $content
* #return Post
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set author
*
* #param \Site\Backend\AdminBundle\Entity\User $author
* #return Post
*/
public function setAuthor(\Site\Backend\AdminBundle\Entity\User $author = null)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return \Site\Backend\AdminBundle\Entity\User
*/
public function getAuthor()
{
return $this->author;
}
/**
* Add comments
*
* #param \Site\Backend\BlogBundle\Entity\Comment $comments
* #return Post
*/
public function addComment(\Site\Backend\BlogBundle\Entity\Comment $comments)
{
$this->comments[] = $comments;
return $this;
}
/**
* Remove comments
*
* #param \Site\Backend\BlogBundle\Entity\Comment $comments
*/
public function removeComment(\Site\Backend\BlogBundle\Entity\Comment $comments)
{
$this->comments->removeElement($comments);
}
/**
* Get comments
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}
/**
* Add Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
* #return Post
*/
public function addCategory(\Site\Backend\BlogBundle\Entity\Category $category)
{
$this->categories[] = $category;
return $this;
}
/**
* Add Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
* #return Post
*/
public function addCategoriesNew(\Site\Backend\BlogBundle\Entity\Category $category)
{
$this->categories[] = $category;
return $this;
}
/**
* Remove Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
*/
public function removeCategory(\Site\Backend\BlogBundle\Entity\Category $category)
{
$this->categories->removeElement($category);
}
/**
* Remove Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
*/
public function removeCategoriesNew(\Site\Backend\BlogBundle\Entity\Category $category)
{
}
/**
* Get Categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
/**
* Get Categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategoriesNew()
{
//return $this->categories;
}
/**
* Add tags
*
* #param \Site\Backend\BlogBundle\Entity\tag $tags
* #return Post
*/
public function addTag(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Add tags
*
* #param \Site\Backend\BlogBundle\Entity\tag $tags
* #return Post
*/
public function addTagsNew(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
$this->tags[] = $tags;
return $this;
}
/**
* Remove tags
*
* #param \Site\Backend\BlogBundle\Entity\Tag $tags
*/
public function removeTag(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
$this->tags->removeElement($tags);
}
/**
* Remove Tags
*
* #param \Site\Backend\BlogBundle\Entity\tag $tags
*/
public function removeTagsNew(\Site\Backend\BlogBundle\Entity\Tag $tags)
{
//$this->tags->removeElement($tags);
}
/**
* Get Tags
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
/**
* Get Tags
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTagsNew()
{
//return $this->Tags;
}
/**
* Add Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
* #return Post
*/
public function addCategorie(\Site\Backend\BlogBundle\Entity\Category $categories)
{
$this->categories[] = $categories;
return $this;
}
/**
* Remove Categories
*
* #param \Site\Backend\BlogBundle\Entity\Category $categories
*/
public function removeCategorie(\Site\Backend\BlogBundle\Entity\Category $categories)
{
$this->categories->removeElement($categories);
}
/**
* #ORM\preUpdate
*/
public function setUpdateValue(){
$this->setDateUpdated(new \DateTime());
}
/**
* Set thumb
*
* #param \Site\Backend\AdminBundle\Entity\File $thumb
* #return Post
*/
public function setThumb(\Site\Backend\AdminBundle\Entity\File $thumb = null)
{
$this->thumb = $thumb;
return $this;
}
/**
* Get thumb
*
* #return \Site\Backend\AdminBundle\Entity\File
*/
public function getThumb()
{
return $this->thumb;
}
}
Thanks in advance
I hope I was clear, if It is not the case please tell me.
Try changing:
Site\Backend\Adminbundle\Entity\File
to
Site\Backend\AdminBundle\Entity\File
An other way to resolve the case :
->add('thumb', null, array(
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('f')
->select('f')
->leftJoin('f.type', 't')
->where('t.name = :type')
->setParameter('type', 'Featured Images')
->orderBy('f.dateUpdated', 'DESC');
}
))
In case you are working with multiple connections, you might have forgotten to map your bundle. Make sure it's the case in app/config/config.yml:
orm:
entity_managers:
default:
mappings:
AppBundle: ~
SiteBackendAdminBundle: ~
Or if you want to split in several entity managers:
orm:
entity_managers:
default:
mappings:
AppBundle: ~
admin:
mappings:
SiteBackendAdminBundle: ~
Documentation Symfony/Doctrine: Multiple Entity Managers.