I'm using easyadmin and fosuserbundle.
The problém that everytime i try to update(change) the user password , nothing is happen , the same old password still the same. I think maybe i miss some config .
Config.yml
easyadmin:
Admin:
class: AppBundle\Entity\User
form:
fields:
- username
- email
- { property: 'plainPassword' , type: 'text'}
User.php:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Security\Core\Util\SecureRandom;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
/**
* #Vich\Uploadable
* #ORM\Entity()
* #ORM\HasLifecycleCallbacks()
* #ORM\Table(name="user")
*
* #UniqueEntity("email")
*
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255,nullable=true)
*
*/
public $nom;
/**
* #ORM\Column(type="string",nullable=true,length=255,nullable=true)
*/
public $prenom;
/**
* #ORM\Column(type="string",nullable=true,length=255,nullable=true)
*/
public $adresse;
/**
* #ORM\Column(type="string", length=255,nullable=true)
*
* #Assert\Range(
* min = 00000000,
* max = 99999999,minMessage="Entrer un numero de cin correct svp",maxMessage="Entrer un numero tel correct svp"
* )
*/
protected $phone;
/**
* #var Devise[]
*
* #ORM\OneToMany(targetEntity="Devise", mappedBy="buyer")
*/
private $purchases;
/**
* The creation date of the product.
*
* #var \DateTime
* #ORM\Column(type="datetime", name="created_at")
*/
private $createdAt = null;
public function __construct()
{
parent::__construct();
// your own logic
$this->purchases = new ArrayCollection();
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set referance
*
* #param string $referance
*
*/
public function setReferance($referance )
{if($this->referance==NULL) $referance ='2';
$this->referance = $referance ;
return $this;
}
/**
* Get referance
*
* #return string
*/
public function getReferance ()
{
return $this->referance ;
}
/**
* Set forename
*
* #param string $forname
* #return User
*/
public function setForename($forename)
{
$this->forname = $forename;
return $this;
}
/**
* Get forename
*
* #return string
*/
public function getForename()
{
return $this->forname;
}
/**
* Asks whether the user is granted a particular role
*
* #return boolean
*/
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
/**
* Set nickname
*
* #param string $nickname
* #return User
*/
public function setNickname($nickname)
{
$this->nickname = $nickname;
return $this;
}
/**
* Get nickname
*
* #return string
*/
public function getNickname()
{
return $this->nickname;
}
/**
* Set lastEdited
*
* #param \DateTime $lastEdited
* #return User
*/
public function setLastEdited($lastEdited)
{
$this->lastEdited = $lastEdited;
return $this;
}
/**
* Get lastEdited
*
* #return \DateTime
*/
public function getLastEdited()
{
return $this->lastEdited;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function setLastEditedValueAsNow() {
$this->setLastEdited(new \DateTime());
}
/**
* Set surname
*
* #param string $surname
* #return User
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return Utilisateurs
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
public function __toString()
{if ($this->prenom != null && $this->nom!= null && $this->phone != null) {
return 'prenom&nom :'.$this->prenom.' '.$this->nom.' | phone : '.$this->phone ;
}
else return 'id :'.$this->id.' | username : '.$this->username ; }
/**
* Set nom
*
* #param string $nom
*
* #return Utilisateurs
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
*
* #return Utilisateurs
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set ville
*
* #param string $ville
*
* #return Utilisateurs
*/
public function setVille($ville)
{
$this->ville = $ville;
return $this;
}
/**
* Get ville
*
* #return string
*/
public function getVille()
{
return $this->ville;
}
/**
* Set class
*
* #param string $class
*
* #return Utilisateurs
*/
public function setClass($class)
{
$this->class = $class;
return $this;
}
/**
* Get class
*
* #return string
*/
public function getClass()
{
return $this->class;
}
/**
* Set phone
*
* #param string $phone
*
* #return Utilisateurs
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* Add purchase
*
* #param \AppBundle\Entity\Devise $purchase
*
* #return User
*/
public function addPurchase(\AppBundle\Entity\Devise $purchase)
{
$this->purchases[] = $purchase;
return $this;
}
/**
* Remove purchase
*
* #param \AppBundle\Entity\Devise $purchase
*/
public function removePurchase(\AppBundle\Entity\Devise $purchase)
{
$this->purchases->removeElement($purchase);
}
/**
* Get purchases
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPurchases()
{
return $this->purchases;
}
/**
* Set adresse
*
* #param string $adresse
*
* #return User
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
));
}
public function unserialize($serialized)
{
list(
$this->id,
$this->username,
$this->password) = unserialize($serialized);
}
}
Related
I need to find a single row from the database and I am using findOneBy().
findBy() and findOneBy() and any other symfony functions always return an empty array collection for my ManyToOne related entities when I loop through the collection.
But when using findAll() function and I loop through the collection, it returns the expected data.
You will find the controller function at the end of the question with the different find functions I have used and do not work.
Entities listed below:
The news entity is related to the newsBlocks entity and newsBlocks is related to the legalNotices entity.
They all are related by ManyToOne/OneToMany relationship.
News Entity
<?php
namespace Honda\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* News
*
* #ORM\Table(name="news")
* #ORM\Entity(repositoryClass="Honda\MainBundle\Repository\NewsRepository")
*/
class News
{
use Traits\DistributorTrait,
Traits\StartDateEndDateTrait,
Traits\HomeActivationTrait,
Traits\ActivationTrait,
Traits\RedirectionTrait;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #Assert\NotBlank()
* #ORM\Column(name="title", type="string", length=255, nullable=true)
*/
private $title;
/**
* #var string
*
* #Assert\NotBlank()
* #ORM\Column(name="description1", type="text", nullable=true)
*/
private $description1;
/**
* #var integer
*
* #ORM\Column(name="type", type="integer", nullable=true)
*/
private $type;
/**
* #Gedmo\Slug(fields={"title"})
* #ORM\Column(unique=true)
*/
private $slug;
/**
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"all"}, fetch="LAZY")
* #ORM\JoinColumn(name="image", referencedColumnName="id", onDelete="SET NULL", nullable=true)
*/
protected $image;
/**
*
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"all"}, fetch="LAZY")
* #ORM\JoinColumn(name="image_mobile", referencedColumnName="id", onDelete="SET NULL", nullable=true)
*/
protected $image_mobile;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=true)
*/
protected $createdAt;
/**
* #Gedmo\SortablePosition
* #ORM\Column(name="position", type="integer")
*/
private $position;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\NewsBlocks", mappedBy="news", cascade={"persist"})
*/
private $newsBlocks;
/**
* Constructor.
*/
public function __construct()
{
$this->createdAt = new \DateTime('NOW', new \DateTimeZone('Europe/Paris'));
$this->slides = new ArrayCollection();
$this->newsBlocks = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #return string
*/
public function __toString()
{
if ($this->getId()) {
return $this->getTitle();
}
return '';
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return News
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description1
*
* #param string $description1
*
* #return News
*/
public function setDescription1($description1)
{
$this->description1 = $description1;
return $this;
}
/**
* Get description1
*
* #return string
*/
public function getDescription1()
{
return $this->description1;
}
/**
* Set type
*
* #param integer $type
*
* #return News
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return integer
*/
public function getType()
{
return $this->type;
}
/**
* Set image
*
* #param \Application\Sonata\MediaBundle\Entity\Media $image
*
* #return News
*/
public function setImage(\Application\Sonata\MediaBundle\Entity\Media $image = null)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return \Application\Sonata\MediaBundle\Entity\Media
*/
public function getImage()
{
return $this->image;
}
/**
* Set slug
*
* #param string $slug
*
* #return News
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return News
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set position
*
* #param integer $position
*
* #return ALaUne
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position
*
* #return integer
*/
public function getPosition()
{
return $this->position;
}
/**
* Set imageMobile.
*
* #param \Application\Sonata\MediaBundle\Entity\Media|null $imageMobile
*
* #return News
*/
public function setImageMobile(\Application\Sonata\MediaBundle\Entity\Media $imageMobile = null)
{
$this->image_mobile = $imageMobile;
return $this;
}
/**
* Get imageMobile.
*
* #return \Application\Sonata\MediaBundle\Entity\Media|null
*/
public function getImageMobile()
{
return $this->image_mobile;
}
/**
* Add newsBlock.
*
* #param \Honda\MainBundle\Entity\NewsBlocks $newsBlock
*
* #return NewNews
*/
public function addNewsBlock(\Honda\MainBundle\Entity\NewsBlocks $newsBlock)
{
if (!$this->newsBlocks->contains($newsBlock)) {
$this->newsBlocks[] = $newsBlock;
$newsBlock->setNews($this);
}
return $this;
}
/**
* Remove newsBlock.
*
* #param \Honda\MainBundle\Entity\NewsBlocks $newsBlock
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeNewsBlock(\Honda\MainBundle\Entity\NewsBlocks $newsBlock)
{
if (!$this->newsBlocks->contains($newsBlock)) {
return;
}
$this->newsBlocks->removeElement($newsBlock);
$newsBlock->setNews(null);
return $this;
}
/**
* Get newsBlocks.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNewsBlocks()
{
return $this->newsBlocks;
}
}
NewsBlocks
<?php
namespace Honda\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Honda\MainBundle\Entity\Traits;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* NewsBlocks
*
* #ORM\Table(name="news_blocks")
* #ORM\Entity(repositoryClass="Honda\MainBundle\Repository\NewsBlocksRepository")
*/
class NewsBlocks
{
use Traits\DistributorTrait;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="block_name", type="string", length=255)
*/
private $blockName;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\Offer", mappedBy="newsBlockOffer", cascade={"all"})
*/
private $offers;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\Video", mappedBy="newsBlockVideo", cascade={"persist"})
*/
private $videos;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\LegalNotices", mappedBy="newsBlockLegalNotices", cascade={"persist"})
*/
private $legalNotices;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\OfferCarousel", mappedBy="newsOfferBlocks", cascade={"persist"})
*/
private $offerCarousels;
/**
* #ORM\ManyToOne(targetEntity="Honda\MainBundle\Entity\News", inversedBy="newsBlocks", cascade={"persist"})
*/
private $news;
/**
* #ORM\OneToMany(targetEntity="Honda\MainBundle\Entity\News\PhotoSlider", mappedBy="newsPhotoSliderBlock", cascade={"persist"})
*/
private $photoSliders;
/**
* #ORM\Column(name="position", type="integer")
*/
private $position;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Constructor
*/
public function __construct()
{
$this->offers = new \Doctrine\Common\Collections\ArrayCollection();
$this->videos = new \Doctrine\Common\Collections\ArrayCollection();
$this->legalNotices = new \Doctrine\Common\Collections\ArrayCollection();
$this->offerCarousels = new \Doctrine\Common\Collections\ArrayCollection();
$this->photoSliders = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add offer.
*
* #param \Honda\MainBundle\Entity\News\Offer $offer
*
* #return NewsBlocks
*/
public function addOffer(\Honda\MainBundle\Entity\News\Offer $offer)
{
if (!$this->offers->contains($offer)) {
$this->offers[] = $offer;
$offer->setNewsBlockOffer($this);
}
return $this;
}
/**
* Remove offer.
*
* #param \Honda\MainBundle\Entity\News\Offer $offer
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeOffer(\Honda\MainBundle\Entity\News\Offer $offer)
{
if (!$this->offers->contains($offer)) {
return;
}
$this->offers->removeElement($offer);
$offer->setNewsBlockOffers(null);
return $this;
}
/**
* Get offers.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getOffers()
{
return $this->offers;
}
/**
* Add video.
*
* #param \Honda\MainBundle\Entity\News\Video $video
*
* #return NewsBlocks
*/
public function addVideo(\Honda\MainBundle\Entity\News\Video $video)
{
if (!$this->videos->contains($video)) {
$this->videos[] = $video;
$video->setNewsBlockVideo($this);
}
return $this;
}
/**
* Remove video.
*
* #param \Honda\MainBundle\Entity\News\Video $video
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeVideo(\Honda\MainBundle\Entity\News\Video $video)
{
if (!$this->videos->contains($video)) {
return;
}
$this->videos->removeElement($video);
$video->setNewsBlockVideo(null);
return $this;
}
/**
* Get videos.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVideos()
{
return $this->videos;
}
/**
* Set blockName.
*
* #param string $blockName
*
* #return NewsBlocks
*/
public function setBlockName($blockName)
{
$this->blockName = $blockName;
return $this;
}
/**
* Get blockName.
*
* #return string
*/
public function getBlockName()
{
return $this->blockName;
}
/**
* Add legalNotice.
*
* #param \Honda\MainBundle\Entity\News\LegalNotices $legalNotice
*
* #return NewsBlocks
*/
public function addLegalNotice(\Honda\MainBundle\Entity\News\LegalNotices $legalNotice)
{
if (!$this->legalNotices->contains($legalNotice)) {
$this->legalNotices[] = $legalNotice;
$legalNotice->setNewsBlockLegalNotices($this);
}
return $this;
}
/**
* Remove legalNotice.
*
* #param \Honda\MainBundle\Entity\News\LegalNotices $legalNotice
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeLegalNotice(\Honda\MainBundle\Entity\News\LegalNotices $legalNotice)
{
if (!$this->legalNotices->contains($legalNotice)) {
return;
}
$this->legalNotices->removeElement($legalNotice);
$legalNotice->setUniqueLook(null);
return $this;
}
/**
* Get legalNotices.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLegalNotices()
{
return $this->legalNotices;
}
/**
* Add offerCarousel.
*
* #param \Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel
*
* #return NewsBlocks
*/
public function addOfferCarousel(\Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel)
{
if (!$this->offerCarousels->contains($offerCarousel)) {
$this->offerCarousels[] = $offerCarousel;
$offerCarousel->setNewsOfferBlocks($this);
}
return $this;
}
/**
* Remove offerCarousel.
*
* #param \Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeOfferCarousel(\Honda\MainBundle\Entity\News\OfferCarousel $offerCarousel)
{
if (!$this->offerCarousels->contains($offerCarousel)) {
return;
}
$this->offerCarousels->removeElement($offerCarousel);
$offerCarousel->setNewsOfferBlocks(null);
return $this;
}
/**
* Get offerCarousels.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getOfferCarousels()
{
return $this->offerCarousels;
}
/**
* Set news.
*
* #param \Honda\MainBundle\Entity\News|null $news
*
* #return NewsBlocks
*/
public function setNews(\Honda\MainBundle\Entity\News $news = null)
{
$this->news = $news;
return $this;
}
/**
* Get news.
*
* #return \Honda\MainBundle\Entity\News|null
*/
public function getNews()
{
return $this->news;
}
/**
* Add photoSlider.
*
* #param \Honda\MainBundle\Entity\News\PhotoSlider $photoSlider
*
* #return NewsBlocks
*/
public function addPhotoSlider(\Honda\MainBundle\Entity\News\PhotoSlider $photoSlider)
{
if (!$this->photoSliders->contains($photoSlider)) {
$this->photoSliders[] = $photoSlider;
$photoSlider->setNewsPhotoSliderBlock($this);
}
return $this;
}
/**
* Remove photoSlider.
*
* #param \Honda\MainBundle\Entity\News\PhotoSlider $photoSlider
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removePhotoSlider(\Honda\MainBundle\Entity\News\PhotoSlider $photoSlider)
{
if (!$this->photoSliders->contains($photoSlider)) {
return;
}
$this->photoSliders->removeElement($photoSlider);
$photoSlider->setNewsPhotoSliderBlock(null);
}
/**
* Get slides.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPhotoSliders()
{
return $this->photoSliders;
}
/**
* Set position.
*
* #param int $position
*
* #return NewsBlocks
*/
public function setPosition($position)
{
$this->position = $position;
return $this;
}
/**
* Get position.
*
* #return int
*/
public function getPosition()
{
return $this->position;
}
}
Legal Notices
<?php
namespace Honda\MainBundle\Entity\News;
use Doctrine\ORM\Mapping as ORM;
use Honda\MainBundle\Entity\Traits;
/**
* LegalNotices
*
* #ORM\Table(name="news_legal_notices")
* #ORM\Entity(repositoryClass="Honda\MainBundle\Repository\News\LegalNoticesRepository")
*/
class LegalNotices
{
use Traits\DistributorTrait,
Traits\ActivationTrait;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="Honda\MainBundle\Entity\NewsBlocks", inversedBy="legalNotices", cascade={"persist"})
*/
private $newsBlockLegalNotices;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set description.
*
* #param string $description
*
* #return LegalNotices
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description.
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set newsBlockLegalNotices.
*
* #param \Honda\MainBundle\Entity\NewsBlocks|null $newsBlockLegalNotices
*
* #return LegalNotices
*/
public function setNewsBlockLegalNotices(\Honda\MainBundle\Entity\NewsBlocks $newsBlockLegalNotices = null)
{
$this->newsBlockLegalNotices = $newsBlockLegalNotices;
return $this;
}
/**
* Get newsBlockLegalNotices.
*
* #return \Honda\MainBundle\Entity\NewsBlocks|null
*/
public function getNewsBlockLegalNotices()
{
return $this->newsBlockLegalNotices;
}
}
Here is my function in the controller:
/**
* #Route("/actualites/{slug}", name="news_show_article", requirements={"slug": "[a-zA-Z0-9\-]+"})
*/
public function articleAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
$news = $em->getRepository(News::class)->findBy(['slug' => $slug]); // Return specific row but collection emtpy
$news = $em->getRepository(News::class)->findOneBy(['slug' => $slug]); // Return specific row but collection emtpy
$news = $em->getRepository(News::class)->findBy([], ['createdAt' => 'DESC']); // Return all but collection empty
$r = $news[16]->getNewsBlocks();
foreach ($r as $item) {
dump($item);
}
$news = $em->getRepository(News::class)->findAll(); // Return all and collection is not emtpy
$r = $news[16]->getNewsBlocks();
foreach ($r as $item) {
foreach($item->getOffers() as $offer) {
dump($offer);
}
}
}
//Events.php
<?php
namespace erp\GenerateBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Events
* #ORM\Entity
* #UniqueEntity(fields="description", message="Already Exists")
*/
class Events
{
/**
* #var string
* #Column(type = "string", unique = true)
* #Assert/Description()
*/
private $description;
/**
* #var \DateTime
*/
private $eventdate;
/**
* #var integer
*/
private $duration;
/**
* #var integer
*/
private $createdby;
/**
* #var \DateTime
*/
private $added;
/**
* #var \DateTime
*/
private $updated;
/**
* #var integer
*/
private $id;
/**
* #var \erp\GenerateBundle\Entity\User
*/
private $userid;
/**
* #var \erp\GenerateBundle\Entity\EventType
*/
private $eventtype;
/**
* Set description
*
* #param string $description
* #return Events
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set eventdate
*
* #param \DateTime $eventdate
* #return Events
*/
public function setEventdate($eventdate)
{
$this->eventdate = $eventdate;
return $this;
}
/**
* Get eventdate
*
* #return \DateTime
*/
public function getEventdate()
{
return $this->eventdate;
}
/**
* Set duration
*
* #param integer $duration
* #return Events
*/
public function setDuration($duration)
{
$this->duration = $duration;
return $this;
}
/**
* Get duration
*
* #return integer
*/
public function getDuration()
{
return $this->duration;
}
/**
* Set createdby
*
* #param integer $createdby
* #return Events
*/
public function setCreatedby($createdby)
{
$this->createdby = $createdby;
return $this;
}
/**
* Get createdby
*
* #return integer
*/
public function getCreatedby()
{
return $this->createdby;
}
/**
* Set added
*
* #param \DateTime $added
* #return Events
*/
public function setAdded($added)
{
$this->added = $added;
return $this;
}
/**
* Get added
*
* #return \DateTime
*/
public function getAdded()
{
return $this->added;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Events
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userid
*
* #param \erp\GenerateBundle\Entity\User $userid
* #return Events
*/
public function setUserid(\erp\GenerateBundle\Entity\User $userid = null)
{
$this->userid = $userid;
return $this;
}
/**
* Get userid
*
* #return \erp\GenerateBundle\Entity\User
*/
public function getUserid()
{
return $this->userid;
}
/**
* Set eventtype
*
* #param \erp\GenerateBundle\Entity\EventType $eventtype
* #return Events
*/
public function setEventtype(\erp\GenerateBundle\Entity\EventType $eventtype = null)
{
$this->eventtype = $eventtype;
return $this;
}
/**
* Get eventtype
*
* #return \erp\GenerateBundle\Entity\EventType
*/
public function getEventtype()
{
return $this->eventtype;
}
}
Check Config.yml
framework:
validation: { enabled: true, enable_annotations: true}
In Controller
check isValid()
If it is not there then add. isValid() before submission of form .
I can hardly decipher your problem. Are there any error messages? Where is the problem in persisting to the db or submitting a form?
But I see some problems in the code you post it.
Annotation #Assert/Description() doesn't exist.
In the example you're missing use Doctrine\ORM\Mapping as ORM;
You should use #ORM\Column(type = "string", unique = true) if you use ORM alias instead of #Column
I created an entity that has an image/file field in it. The insert and the render of the records in this entity works perfectly, but the update function, to modify some or all the fields of the entity, return this error:
Error: Call to a member function move() on a non-object
So I suppose that the error is in the function moveImage() in entity itself, that is:
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->image)
{
return;
}
if (!is_dir($this->getUploadRootDir()))
{
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir() . $this->image, $this->getFullImagePath());
unlink($this->getTmpUploadRootDir() . $this->image);
}
I don't know what is the problem, and if I'm guessing right. Any suggest?
This is the entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Ricette
*
* #ORM\Table()
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="AppBundle\Repository\RicetteRepository")
*/
class Ricette
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titolo", type="string", length=255)
*/
private $titolo;
/**
* #var string
*
* #ORM\Column(name="ingredienti", type="text")
*/
private $ingredienti;
/**
* #var string
*
* #ORM\Column(name="procedimento", type="text")
*/
private $procedimento;
/**
* #var integer
*
* #ORM\Column(name="quantita", type="integer")
*/
private $quantita;
/**
* #var integer
*
* #ORM\Column(name="difficolta", type="integer")
*/
private $difficolta;
/**
* #var string
*
* #ORM\Column(name="tempo", type="string", length=50)
*/
private $tempo;
/**
* #var string $image
* #Assert\File( maxSize = "60000000", mimeTypesMessage = "Perfavore inserisci un'immagine valida!")
* #ORM\Column(name="image", type="string", length=255, nullable=true)
*/
private $image;
/**
* #ORM\ManyToOne(targetEntity="Tipologia", inversedBy="ricette")
* #ORM\JoinColumn(name="tipologia_id", referencedColumnName="id")
*/
protected $tipologia;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titolo
*
* #param string $titolo
*
* #return Ricette
*/
public function setTitolo($titolo)
{
$this->titolo = $titolo;
return $this;
}
/**
* Get titolo
*
* #return string
*/
public function getTitolo()
{
return $this->titolo;
}
/**
* Set ingredienti
*
* #param string $ingredienti
*
* #return Ricette
*/
public function setIngredienti($ingredienti)
{
$this->ingredienti = $ingredienti;
return $this;
}
/**
* Get ingredienti
*
* #return string
*/
public function getIngredienti()
{
return $this->ingredienti;
}
/**
* Set procedimento
*
* #param string $procedimento
*
* #return Ricette
*/
public function setProcedimento($procedimento)
{
$this->procedimento = $procedimento;
return $this;
}
/**
* Get procedimento
*
* #return string
*/
public function getProcedimento()
{
return $this->procedimento;
}
/**
* Set quantita
*
* #param integer $quantita
*
* #return Ricette
*/
public function setQuantita($quantita)
{
$this->quantita = $quantita;
return $this;
}
/**
* Get quantita
*
* #return integer
*/
public function getQuantita()
{
return $this->quantita;
}
/**
* Set difficolta
*
* #param integer $difficolta
*
* #return Ricette
*/
public function setDifficolta($difficolta)
{
$this->difficolta = $difficolta;
return $this;
}
/**
* Get difficolta
*
* #return int
*/
public function getDifficolta()
{
return $this->difficolta;
}
/**
* Set tempo
*
* #param string $tempo
*
* #return Ricette
*/
public function setTempo($tempo)
{
$this->tempo = $tempo;
return $this;
}
/**
* Get tempo
*
* #return string
*/
public function getTempo()
{
return $this->tempo;
}
/**
* Set image
*
* #param string $image
*/
public function setImage($image)
{
$this->image = $image;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
public function getFullImagePath()
{
return null === $this->image ? null : $this->getUploadRootDir() . $this->image;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir() . $this->getId() . "/";
}
protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../web/immaginiRicette/';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage()
{
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
if(!$this->id){
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
}
$this->setImage($this->image->getClientOriginalName());
}
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->image)
{
return;
}
if (!is_dir($this->getUploadRootDir()))
{
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir() . $this->image, $this->getFullImagePath());
unlink($this->getTmpUploadRootDir() . $this->image);
}
/**
* #ORM\PreRemove()
*/
public function removeImage()
{
$file=$this->image;
if($file = $this->getFullImagePath() && file_exists($file)) {
unlink($file);
rmdir($this->getUploadRootDir());
}
}
/**
* Set tipologia
*
* #param \AppBundle\Entity\Tipologia $tipologia
*
* #return Ricette
*/
public function setTipologia(\AppBundle\Entity\Tipologia $tipologia = null)
{
$this->tipologia = $tipologia;
return $this;
}
/**
* Get tipologia
*
* #return \AppBundle\Entity\Tipologia
*/
public function getTipologia()
{
return $this->tipologia;
}
}
I have a Form for Product with relation oneToMany with entity ProductLocale and the user can add many ProductLocale as he want.
The rendered form in html seems correct but when I receive the POST array and perform bind() the server response this error:
"ERROR: This value should be of type Wearplay\WearBundle\Entity\ProductLocale.
But I send two ProductLocale entities and validator doesn't recognize them.
It is obvious that the POST request contains a multi-dimensional array that contains the various entities ProductLocale, but the question is why
$form->bindRequest($request)
doesn't work correctly?
Edit #1:
Product Entity
<?php
namespace Wearplay\WearBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*#ORM\Column(type="string")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="BrandOwner", cascade="persist")
*/
private $owner;
/**
* #ORM\Column(name="creation_date", type="datetime", nullable=false)
*/
private $creationDate;
/**
* #Assert\Type(type="Wearplay\WearBundle\Entity\ProductLocale")
*/
protected $productLocales;
/**
* #Assert\Type(type="Wearplay\WearBundle\Entity\ProductPic")
*/
protected $productPic;
public function __construct()
{
$this->productLocales = new ArrayCollection();
}
/**
* #ORM\PrePersist
*/
public function createTimestamps()
{
$this->creationDate = new \DateTime(date('Y-m-d H:i:s'));
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Product
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Set owner
*
* #param \Wearplay\WearBundle\Entity\BrandOwner $owner
* #return Product
*/
public function setOwner(\Wearplay\WearBundle\Entity\BrandOwner $owner = null)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return \Wearplay\WearBundle\Entity\BrandOwner
*/
public function getOwner()
{
return $this->owner;
}
/**
* Get ProductLocales
*
* #return \Wearplay\WearBundle\Entity\ProductLocale
*/
public function getProductLocales()
{
return $this->productLocales;
}
/**
* Set ProductLocale
*
* #param \Wearplay\WearBundle\Entity\ProductLocale $productLocale
* #return Product
*/
public function setProductLocales(ArrayCollection $productLocales = null)
{
$this->productLocales = $productLocales;
//return $this->productLocale;
}
/**
* Add ProductLocale
*
* #param ProductLocale $productLocale
*/
/*
public function addProductLocale(ProductLocale $productLocale)
{
$this->productLocales[] = $productLocale;
}
public function removeProductLocale(ProductLocale $productLocale)
{
$this->productLocale->removeElement($productLocale);
}*/
/**
* Get ProductPic
*
* #return \Wearplay\WearBundle\Entity\ProductPic
*/
public function getProductPic()
{
return $this->productPic;
}
/**
* Set ProductPic
*
* #param \Wearplay\WearBundle\Entity\ProductPic $productPic
* #return Product
*/
public function setProductPic(ProductPic $productPic = null)
{
$this->productPic = $productPic;
}
/**
* Add ProductPic
*
* #param ProductPic $productPic
*/
public function addProductPic(ProductPic $productPic)
{
$this->productPic[] = $productPic;
}
}
ProductLocale Entity
<?php
namespace Wearplay\WearBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
* #ORM\Table(name="product_locale")
*/
class ProductLocale
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Product", cascade="persist")
*/
private $product;
/**
*#ORM\Column(name="market_nation", type="string")
*/
private $marketNation;
/**
* #ORM\Column(type="string")
*/
private $link;
/**
* #ORM\Column(type="decimal", precision=9, scale=2)
*/
private $price;
/**
* #ORM\Column(type="string", length=3)
*/
private $currency;
/**
* #ORM\Column(name="creation_date", type="datetime", nullable=false)
*/
private $creationDate;
/**
* #ORM\PrePersist
*/
/*
public function addProduct(Product $product)
{
if (!$this->product->contains($product)) {
$this->product->add($product);
}
}
*/
public function createTimestamps()
{
$this->creationDate = new \DateTime(date('Y-m-d H:i:s'));
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set marketNation
*
* #param string $marketNation
* #return ProductLocale
*/
public function setMarketNation($marketNation)
{
$this->marketNation = $marketNation;
return $this;
}
/**
* Get marketNation
*
* #return string
*/
public function getMarketNation()
{
return $this->marketNation;
}
/**
* Set link
*
* #param string $link
* #return ProductLocale
*/
public function setLink($link)
{
$this->link = $link;
return $this;
}
/**
* Get link
*
* #return string
*/
public function getLink()
{
return $this->link;
}
/**
* Set price
*
* #param float $price
* #return ProductLocale
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return float
*/
public function getPrice()
{
return $this->price;
}
/**
* Set currency
*
* #param string $currency
* #return ProductLocale
*/
public function setCurrency($currency)
{
$this->currency = $currency;
return $this;
}
/**
* Get currency
*
* #return string
*/
public function getCurrency()
{
return $this->currency;
}
/**
* Set creationDate
*
* #param \DateTime $creationDate
* #return ProductLocale
*/
public function setCreationDate($creationDate)
{
$this->creationDate = $creationDate;
return $this;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Set product
*
* #param \Wearplay\WearBundle\Entity\Product $product
* #return ProductLocale
*/
public function setProduct(\Wearplay\WearBundle\Entity\Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return \Wearplay\WearBundle\Entity\Product
*/
public function getProduct()
{
return $this->product;
}
}
Solved
Yes #ihsan and #snyx, you're absolutely right, I removed this line:
#Assert\Type(type="Wearplay\WearBundle\Entity\ProductLocale and everything worked perfectly.
I'm sorry for the trivial question but I'm pretty new in Symfony2.
Reading this page I've setup a form to handle PATCH requests.
I've a Player entity:
<?php
namespace Acme\PlayerBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\PlayerBundle\Entity\Player
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\PlayerBundle\Entity\PlayerRepository")
*/
class Player
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotBlank()
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="players")
* #ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* #ORM\ManyToOne(targetEntity="Acme\TeamBundle\Entity\Team", inversedBy="players")
* #ORM\JoinColumn(nullable=false)
* #Assert\NotBlank()
*/
private $team;
/**
* #var integer $shirtNumber
*
* #ORM\Column(name="shirtNumber", type="smallint")
* #Assert\NotBlank()
*/
private $shirtNumber;
/**
* #var integer $vsid
*
* #ORM\Column(name="vsid", type="integer", nullable=true)
*/
private $vsid;
/**
* #var string $firstname
*
* #ORM\Column(name="firstname", type="string", length=255, nullable=true)
*/
private $firstname;
/**
* #var string $lastname
*
* #ORM\Column(name="lastname", type="string", length=255, nullable=true)
*/
private $lastname;
/**
* #var boolean $deleted
*
* #ORM\Column(name="deleted", type="boolean")
*/
private $deleted = false;
/**
* #var integer $role
*
* #ORM\Column(type="integer", nullable=true)
*/
private $role;
/**
* Create the user salt
*/
public function __construct()
{
//TODO: just for test
$this->uniqueId = substr(uniqid(), 0, 14);
}
/* MANAGED BY DOCTRINE, DON'T EDIT */
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Player
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set shirtNumber
*
* #param integer $shirtNumber
* #return Player
*/
public function setShirtNumber($shirtNumber)
{
$this->shirtNumber = $shirtNumber;
return $this;
}
/**
* Get shirtNumber
*
* #return integer
*/
public function getShirtNumber()
{
return $this->shirtNumber;
}
/**
* Set vsid
*
* #param integer $vsid
* #return Player
*/
public function setVsid($vsid)
{
$this->vsid = $vsid;
return $this;
}
/**
* Get vsid
*
* #return integer
*/
public function getVsid()
{
return $this->vsid;
}
/**
* Set firstname
*
* #param string $firstname
* #return Player
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return Player
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Player
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Set role
*
* #param integer $role
* #return Player
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* Get role
*
* #return integer
*/
public function getRole()
{
return $this->role;
}
/**
* Set owner
*
* #param Acme\UserBundle\Entity\User $owner
* #return Player
*/
public function setOwner(\Acme\UserBundle\Entity\User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return Acme\UserBundle\Entity\User
*/
public function getOwner()
{
return $this->owner;
}
/**
* Set team
*
* #param Acme\TeamBundle\Entity\Team $team
* #return Player
*/
public function setTeam(\Acme\TeamBundle\Entity\Team $team)
{
$this->team = $team;
return $this;
}
/**
* Get team
*
* #return Acme\TeamBundle\Entity\Team
*/
public function getTeam()
{
return $this->team;
}
}
and a Team entity:
<?php
namespace Acme\TeamBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Acme\TeamBundle\Entity\Team
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\TeamBundle\Entity\TeamRepository")
*/
class Team
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $uniqueId
*
* #ORM\Column(name="uniqueId", type="string", length=15)
*/
private $uniqueId;
/**
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="teams")
* #ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=50)
* #Assert\NotBlank()
*/
private $name;
/**
* #var string $homeColor
*
* #ORM\Column(name="homeColor", type="string", length=7, nullable=true)
*/
private $homeColor;
/**
* #var string $awayColor
*
* #ORM\Column(name="awayColor", type="string", length=7, nullable=true)
*/
private $awayColor;
/**
* #var string $homeShirt
*
* #ORM\Column(name="homeShirt", type="string", length=50, nullable=true)
*/
private $homeShirt;
/**
* #var string $awayShirt
*
* #ORM\Column(name="awayShirt", type="string", length=50, nullable=true)
*/
private $awayShirt;
/**
* #var string $teamLogo
*
* #ORM\Column(name="teamLogo", type="string", length=50, nullable=true)
*/
private $teamLogo;
/**
* #var boolean $deleted
*
* #ORM\Column(name="deleted", type="boolean")
*/
private $deleted = false;
/**
* #ORM\OneToMany(targetEntity="Acme\PlayerBundle\Entity\Player", mappedBy="team", cascade={"persist", "remove"})
*/
private $players;
/**
* #ORM\OneToMany(targetEntity="Acme\MatchBundle\Entity\Match", mappedBy="homeTeam")
*/
private $homeMatches;
/**
* #ORM\OneToMany(targetEntity="Acme\MatchBundle\Entity\Match", mappedBy="awayTeam")
*/
private $awayMatches;
/**
* Create the user salt
*/
public function __construct()
{
$this->players = new ArrayCollection();
$this->homeMatches = new ArrayCollection();
$this->awayMatches = new ArrayCollection();
//TODO: just for test
$this->uniqueId = substr(uniqid(), 0, 14);
}
public function getMatches()
{
return array_merge($this->awayMatches->toArray(), $this->homeMatches->toArray());
}
/* MANAGED BY DOCTRINE, DON'T EDIT */
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set uniqueId
*
* #param string $uniqueId
* #return Team
*/
public function setUniqueId($uniqueId)
{
$this->uniqueId = $uniqueId;
return $this;
}
/**
* Get uniqueId
*
* #return string
*/
public function getUniqueId()
{
return $this->uniqueId;
}
/**
* Set name
*
* #param string $name
* #return Team
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set homeColor
*
* #param string $homeColor
* #return Team
*/
public function setHomeColor($homeColor)
{
$this->homeColor = $homeColor;
return $this;
}
/**
* Get homeColor
*
* #return string
*/
public function getHomeColor()
{
return $this->homeColor;
}
/**
* Set awayColor
*
* #param string $awayColor
* #return Team
*/
public function setAwayColor($awayColor)
{
$this->awayColor = $awayColor;
return $this;
}
/**
* Get awayColor
*
* #return string
*/
public function getAwayColor()
{
return $this->awayColor;
}
/**
* Set homeShirt
*
* #param string $homeShirt
* #return Team
*/
public function setHomeShirt($homeShirt)
{
$this->homeShirt = $homeShirt;
return $this;
}
/**
* Get homeShirt
*
* #return string
*/
public function getHomeShirt()
{
return $this->homeShirt;
}
/**
* Set awayShirt
*
* #param string $awayShirt
* #return Team
*/
public function setAwayShirt($awayShirt)
{
$this->awayShirt = $awayShirt;
return $this;
}
/**
* Get awayShirt
*
* #return string
*/
public function getAwayShirt()
{
return $this->awayShirt;
}
/**
* Set teamLogo
*
* #param string $teamLogo
* #return Team
*/
public function setTeamLogo($teamLogo)
{
$this->teamLogo = $teamLogo;
return $this;
}
/**
* Get teamLogo
*
* #return string
*/
public function getTeamLogo()
{
return $this->teamLogo;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Team
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Add players
*
* #param Acme\PlayerBundle\Entity\Player $players
* #return Team
*/
public function addPlayer(\Acme\PlayerBundle\Entity\Player $players)
{
$this->players[] = $players;
return $this;
}
/**
* Remove players
*
* #param Acme\PlayerBundle\Entity\Player $players
*/
public function removePlayer(\Acme\PlayerBundle\Entity\Player $players)
{
$this->players->removeElement($players);
}
/**
* Get players
*
* #return Doctrine\Common\Collections\Collection
*/
public function getPlayers()
{
return $this->players;
}
/**
* Add homeMatches
*
* #param Acme\MatchBundle\Entity\Match $homeMatches
* #return Team
*/
public function addHomeMatche(\Acme\MatchBundle\Entity\Match $homeMatches)
{
$this->homeMatches[] = $homeMatches;
return $this;
}
/**
* Remove homeMatches
*
* #param Acme\MatchBundle\Entity\Match $homeMatches
*/
public function removeHomeMatche(\Acme\MatchBundle\Entity\Match $homeMatches)
{
$this->homeMatches->removeElement($homeMatches);
}
/**
* Get homeMatches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getHomeMatches()
{
return $this->homeMatches;
}
/**
* Add awayMatches
*
* #param Acme\MatchBundle\Entity\Match $awayMatches
* #return Team
*/
public function addAwayMatche(\Acme\MatchBundle\Entity\Match $awayMatches)
{
$this->awayMatches[] = $awayMatches;
return $this;
}
/**
* Remove awayMatches
*
* #param Acme\MatchBundle\Entity\Match $awayMatches
*/
public function removeAwayMatche(\Acme\MatchBundle\Entity\Match $awayMatches)
{
$this->awayMatches->removeElement($awayMatches);
}
/**
* Get awayMatches
*
* #return Doctrine\Common\Collections\Collection
*/
public function getAwayMatches()
{
return $this->awayMatches;
}
/**
* Set owner
*
* #param Acme\UserBundle\Entity\User $owner
* #return Team
*/
public function setOwner(\Acme\UserBundle\Entity\User $owner)
{
$this->owner = $owner;
return $this;
}
/**
* Get owner
*
* #return Acme\UserBundle\Entity\User
*/
public function getOwner()
{
return $this->owner;
}
}
Now I've created a player form class with the app/console and I've edited the team field to be an instance of the Team entity, this way:
<?php
namespace Acme\PlayerBundle\Form;
use Acme\TeamBundle\Entity\TeamRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class PlayerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('shirtNumber')
->add('firstname')
->add('lastname')
->add('role')
->add('team', 'entity', array(
'class' => 'AcmeTeamBundle:Team',
'query_builder' => function(TeamRepository $er) {
$query = $er->createQueryBuilder('t');
return $query;
}
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\PlayerBundle\Entity\Player',
'csrf_protection' => false
));
}
public function getName()
{
return 'player';
}
}
And this is the relevant part of my controller:
/**
* Create a new player
*
* #Route(".{_format}", name="api_player_create")
* #Method("POST")
* #ApiDoc(
* description="Create a new player",
* statusCodes={
* 201="Player created and informations are returned",
* 400="Missing informations",
* 403="The user isn't authorized"
* },
* input="Acme\PlayerBundle\Form\PlayerType",
* return="Acme\PlayerBundle\Entity\Player"
* )
*
* #return Renders the player just created
*/
public function createPlayerAction()
{
return $this->processForm(new Player());
}
/**
* Edit a player
*
* #param integer $id The id of the player to be created
*
* #Route("/{id}.{_format}", name="api_player_patch", requirements={ "id": "\d+" })
* #Method("PATCH")
* #ApiDoc(
* description="Edit a player",
* statusCodes={
* 200="Player is updated",
* 400="Missing informations",
* 403="The user isn't authorized"
* },
* input="Acme\PlayerBundle\Form\PlayerType",
* return="Acme\PlayerBundle\Entity\Player"
* )
*
* #return Renders the player just edited
*/
public function editPlayerAction(Player $player)
{
if ($player->getOwner() != $this->getUser()) {
throw new ApiException\PermissionDeniedException;
}
return $this->processForm($player);
}
/**
* Function to handle a form to create/edit a player
*
* #param Player $player The player to be created or edited
*
* #return Api Response
*/
private function processForm(Player $player)
{
/**
* Check if the player is new (to be created) or we're editing a player
*/
$statusCode = is_null($player->getId()) ? 201 : 200;
$form = $this->createForm(new PlayerType(), $player);
$form->bind($this->getRequest());
if ($form->isValid()) {
if($player->getTeam()->getOwner() != $this->getUser()) {
throw new ApiException\PermissionDeniedException;
}
$player->setOwner($this->getUser());
$this->entityManager->persist($player);
$this->entityManager->flush();
return $this->apiResponse->getResponse($player, $statusCode);
}
return $this->apiResponse->getResponse($form, 400, 'Missing arguments');
}
The player creation works fine, the player edit doesn't, when the user makes the api request, passing the ID in the url and the name of the player I get:
Catchable Fatal Error: Argument 1 passed to Acme\PlayerBundle\Entity\Player::setTeam() must be an instance of Acme\TeamBundle\Entity\Team, null given, called in /Volumes/Dati/Users/alessandro/Sites/acme-api/vendor/symfony/symfony/src/Symfony/Component/Form/Util/PropertyPath.php on line 538 and defined in /Volumes/Dati/Users/alessandro/Sites/acme-api/src/Acme/PlayerBundle/Entity/Player.php line 278
Seems that form is trying to set the Team to null, why?
I've tried both sending and not the team as the form parameters but it doesn't work.
Any clue?
Figured it out that null unsent fields in the form is the default behaviour in symfony.
There is an open request for partial form binding in symfony. For now a guy created a form event subscriber that adds the missing fields with the actual values:
https://gist.github.com/3720535
This is his code:
<?php
namespace Foo;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
/**
* Changes Form->bind() behavior so that it treats not set values as if they
* were sent unchanged.
*
* Use when you don't want fields to be set to NULL when they are not displayed
* on the page (or to implement PUT/PATCH requests).
*/
class PatchSubscriber implements EventSubscriberInterface
{
public function onPreBind(FormEvent $event)
{
$form = $event->getForm();
$clientData = $event->getData();
$clientData = array_replace($this->unbind($form), $clientData ?: array());
$event->setData($clientData);
}
/**
* Returns the form's data like $form->bind() expects it
*/
protected function unbind($form)
{
if ($form->hasChildren()) {
$ary = array();
foreach ($form->getChildren() as $name => $child) {
$ary[$name] = $this->unbind($child);
}
return $ary;
} else {
return $form->getClientData();
}
}
static public function getSubscribedEvents()
{
return array(
FormEvents::PRE_BIND => 'onPreBind',
);
}
}
to add to the form you have to edit the buildForm method in the form class:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$subscriber = new PatchSubscriber();
$builder->addEventSubscriber($subscriber);
$builder->add('name');
....
}
In this case you're ok to use the PATCH REST requests to edit an entity just by the sent fields