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
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);
}
}
}
I have a variable private $groupId; in entity. And there is a controller function public function settingsListAction(Request $request)
I want to access that groupId in controller function. How it can be achieved?
Edit
Controller function is
/**
* Get all settings content list
* #Route("settings", name="settings_list")
*/
public function settingsListAction(Request $request)
{
// Cannot edit at all.
//Fetch Current Financial Year target data to display that on "Road to paradise tab"
$entity = new J1Setting();
//do smthing
$groupIdValue = $entity->getGroup();
$settingsGroup = $this->getDoctrine()->getRepository('AppBundle:J1SettingGroup')->findAll();
$settingsList = $this->getDoctrine()->getRepository('AppBundle:J1Setting')->findBy(array('groupId' => groupIdValue));
return $this->render('default/settingsList.html.twig', array('settingsGroup' => $settingsGroup, 'settingsList' => $settingsList));
}
And entity is:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Component\Annotation\J1Entity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* J1Setting
*
* #ORM\Table(name="j1_settings", indexes={#ORM\Index(name="IDX_SName", columns={"name"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\J1SettingRepository")
* #J1Entity(auditClass="AppBundle\Component\Audit\J1AuditSetting")
*/
class J1Setting
{
/**
* #var integer
*
* #ORM\Column(name="setting_id", type="integer")
*
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $settingid;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="value", type="string", length=250, nullable=true)
*/
private $value;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="group_id", type="integer")
* #ORM\Id
*/
private $groupId;
/**
* #var J1SettingGroup
*
* #ORM\ManyToOne(targetEntity="J1SettingGroup", inversedBy="settings")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="group_id", referencedColumnName="id")
* })
*/
private $group;
/**
* #var string
*
* #ORM\Column(name="setting_type", type="string", length=100)
*/
private $settingType;
/**
* Get settingid
*
* #return integer
*/
public function getSettingId()
{
return $this->settingid;
}
/**
* Set name
*
* #param string $name
* #return J1Setting
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set value
*
* #param string $value
* #return J1Setting
*/
public function setValue($value)
{
$this->value = serialize($value);
return $this;
}
/**
* Get value
*
* #return string
*/
public function getValue()
{
return unserialize($this->value);
}
/**
* Return name replacing underscores with spaces
*
* #return mixed
*/
public function getFriendlyName(){
return str_replace('_', ' ', $this->getName());
}
/**
* Set description
*
* #param string $description
* #return J1Setting
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set groupId
*
* #param integer $groupId
* #return J1Setting
*/
public function setGroupId($groupId)
{
$this->groupId = $groupId;
return $this;
}
/**
* Get groupId
*
* #return integer
*/
public function getGroupId()
{
return $this->groupId;
}
/**
* Set settingType
*
* #param string $settingType
* #return J1Setting
*/
public function setSettingType($settingType)
{
$this->settingType = $settingType;
return $this;
}
/**
* Get settingType
*
* #return string
*/
public function getSettingType()
{
return $this->settingType;
}
/**
* Set group
*
* #param $group
* #return J1Setting
*/
public function setGroup($group = null)
{
$this->group = $group;
return $this;
}
/**
* Get group
*
* #return integer
*/
public function getGroup()
{
return $this->group;
}
}
you need to create a getter in your entity
public function getGroupId(){
return $this->groupId;
}
public function setGroupId($groupId){
$this->groupId = $groupId;
}
and in your controller:
$entity = new J1Setting();
$entity->setGroupId(123);
$groupIdValue = $entity->getGroupId();
var_dump($goupIdValue) //outputs 123
When using Doctrine, you shouldn't put foreign keys into an entity.
This means, groupId should not be part of your J1Setting entity. If you want to access the id of the associated group, then you have to use $entity->getGroup()->getId(). Obviously, this only works, if the entity actually has a group!
I'm lost in a complexe relation (for me). I've a entity project for an entity client and you can attach users to a project. When i try to add a project without users, no problem. But, when i try to add a project and users Sf2 display this error :
Entity of type Intranet\IntranetBundle\Entity\ProjectUser is missing an assigned ID for field 'project'. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.
I'm understand it's angry because the project_id is null. But i don't know why it's null.
My Project.php
namespace Intranet\IntranetBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Project
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Intranet\IntranetBundle\Entity\ProjectRepository")
*/
class Project
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotBlank(
* message = "The field cannot be empty"
* )
*/
private $name;
/**
* #Gedmo\Slug(fields={"name"})
* #ORM\Column(length=255, unique=true)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="contact_client", type="text", nullable=true)
*/
private $contactClient;
/**
* #var string
*
* #ORM\Column(name="technologies", type="string", length=255, nullable=true)
*/
private $technologies;
/**
* #var string
*
* #ORM\Column(name="languages", type="string", length=255, nullable=true)
*/
private $languages;
/**
* #var string
*
* #ORM\Column(name="extern", type="text", nullable=true)
*/
private $extern;
/**
* #var string
*
* #ORM\Column(name="url_prod", type="string", length=255, nullable=true)
*/
private $urlProd;
/**
* #var string
*
* #ORM\Column(name="url_staging", type="text", nullable=true)
*/
private $urlStaging;
/**
* #var string
*
* #ORM\Column(name="url_dev", type="text", nullable=true)
*/
private $urlDev;
/**
* #var string
*
* #ORM\Column(name="hosting_company", type="string", length=255, nullable=true)
*/
private $hostingCompany;
/**
* #var string
*
* #ORM\Column(name="hosting_type", type="string", length=255, nullable=true)
*/
private $hostingType;
/**
* #var string
*
* #ORM\Column(name="hosting_manager", type="text", nullable=true)
*/
private $hostingManager;
/**
* #var string
*
* #ORM\Column(name="ssh", type="text", nullable=true)
*/
private $ssh;
/**
* #var string
*
* #ORM\Column(name="ftp", type="text", nullable=true)
*/
private $ftp;
/**
* #var string
*
* #ORM\Column(name="db", type="text", nullable=true)
*/
private $db;
/**
* #var string
*
* #ORM\Column(name="emails", type="text", nullable=true)
*/
private $emails;
/**
* #var string
*
* #ORM\Column(name="cms", type="text", nullable=true)
*/
private $cms;
/**
* #var string
*
* #ORM\Column(name="web_services", type="text", nullable=true)
*/
private $webServices;
/**
* #var string
*
* #ORM\Column(name="comment", type="text", nullable=true)
*/
private $comment;
/**
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\Client", inversedBy="projects")
* #ORM\JoinColumn(nullable=false)
*/
private $client;
/**
* #ORM\OneToMany(targetEntity="Intranet\IntranetBundle\Entity\ProjectUser", mappedBy="project", cascade={"persist"})
*/
private $projectUsers;
public function __construct()
{
$this->projectUsers = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Project
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set slug
*
* #param string $slug
* #return Client
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set contactClient
*
* #param string $contactClient
* #return Project
*/
public function setContactClient($contactClient)
{
$this->contactClient = $contactClient;
return $this;
}
/**
* Get contactClient
*
* #return string
*/
public function getContactClient()
{
return $this->contactClient;
}
/**
* Set technologies
*
* #param string $technologies
* #return Project
*/
public function setTechnologies($technologies)
{
$this->technologies = $technologies;
return $this;
}
/**
* Get technologies
*
* #return string
*/
public function getTechnologies()
{
return $this->technologies;
}
/**
* Set languages
*
* #param string $languages
* #return Project
*/
public function setLanguages($languages)
{
$this->languages = $languages;
return $this;
}
/**
* Get languages
*
* #return string
*/
public function getLanguages()
{
return $this->languages;
}
/**
* Set extern
*
* #param string $extern
* #return Project
*/
public function setExtern($extern)
{
$this->extern = $extern;
return $this;
}
/**
* Get extern
*
* #return string
*/
public function getExtern()
{
return $this->extern;
}
/**
* Set urlProd
*
* #param string $urlProd
* #return Project
*/
public function setUrlProd($urlProd)
{
$this->urlProd = $urlProd;
return $this;
}
/**
* Get urlProd
*
* #return string
*/
public function getUrlProd()
{
return $this->urlProd;
}
/**
* Set urlStaging
*
* #param string $urlStaging
* #return Project
*/
public function setUrlStaging($urlStaging)
{
$this->urlStaging = $urlStaging;
return $this;
}
/**
* Get urlStaging
*
* #return string
*/
public function getUrlStaging()
{
return $this->urlStaging;
}
/**
* Set urlDev
*
* #param string $urlDev
* #return Project
*/
public function setUrlDev($urlDev)
{
$this->urlDev = $urlDev;
return $this;
}
/**
* Get urlDev
*
* #return string
*/
public function getUrlDev()
{
return $this->urlDev;
}
/**
* Set hostingCompany
*
* #param string $hostingCompany
* #return Project
*/
public function setHostingCompany($hostingCompany)
{
$this->hostingCompany = $hostingCompany;
return $this;
}
/**
* Get hostingCompany
*
* #return string
*/
public function getHostingCompany()
{
return $this->hostingCompany;
}
/**
* Set hostingType
*
* #param string $hostingType
* #return Project
*/
public function setHostingType($hostingType)
{
$this->hostingType = $hostingType;
return $this;
}
/**
* Get hostingType
*
* #return string
*/
public function getHostingType()
{
return $this->hostingType;
}
/**
* Set hostingManager
*
* #param string $hostingManager
* #return Project
*/
public function setHostingManager($hostingManager)
{
$this->hostingManager = $hostingManager;
return $this;
}
/**
* Get hostingManager
*
* #return string
*/
public function getHostingManager()
{
return $this->hostingManager;
}
/**
* Set ssh
*
* #param string $ssh
* #return Project
*/
public function setSsh($ssh)
{
$this->ssh = $ssh;
return $this;
}
/**
* Get ssh
*
* #return string
*/
public function getSsh()
{
return $this->ssh;
}
/**
* Set ftp
*
* #param string $ftp
* #return Project
*/
public function setFtp($ftp)
{
$this->ftp = $ftp;
return $this;
}
/**
* Get ftp
*
* #return string
*/
public function getFtp()
{
return $this->ftp;
}
/**
* Set db
*
* #param string $db
* #return Project
*/
public function setDb($db)
{
$this->db = $db;
return $this;
}
/**
* Get db
*
* #return string
*/
public function getDb()
{
return $this->db;
}
/**
* Set emails
*
* #param string $emails
* #return Project
*/
public function setEmails($emails)
{
$this->emails = $emails;
return $this;
}
/**
* Get emails
*
* #return string
*/
public function getEmails()
{
return $this->emails;
}
/**
* Set cms
*
* #param string $cms
* #return Project
*/
public function setCms($cms)
{
$this->cms = $cms;
return $this;
}
/**
* Get cms
*
* #return string
*/
public function getCms()
{
return $this->cms;
}
/**
* Set webServices
*
* #param string $webServices
* #return Project
*/
public function setWebServices($webServices)
{
$this->webServices = $webServices;
return $this;
}
/**
* Get webServices
*
* #return string
*/
public function getWebServices()
{
return $this->webServices;
}
/**
* Set comment
*
* #param string $comment
* #return Project
*/
public function setComment($comment)
{
$this->comment = $comment;
return $this;
}
/**
* Get comment
*
* #return string
*/
public function getComment()
{
return $this->comment;
}
/**
* Set client
*
* #param \Intranet\IntranetBundle\Entity\Client $client
* #return Project
*/
public function setClient(\Intranet\IntranetBundle\Entity\Client $client)
{
$this->client = $client;
return $this;
}
/**
* Get client
*
* #return \Intranet\IntranetBundle\Entity\Client
*/
public function getClient()
{
return $this->client;
}
public function addProjectUser(\Intranet\IntranetBundle\Entity\ProjectUser $projectUser)
{
$this->projectUsers[] = $projectUser;
}
public function removeProjectUser(\Intranet\IntranetBundle\Entity\ProjectUser $projectUser)
{
$this->projectUsers->removeElement($projectUser);
}
public function getProjectUsers()
{
return $this->projectUsers;
}
}
My ProjectUser.php
namespace Intranet\IntranetBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class ProjectUser
{
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\Project", inversedBy="projectUsers")
*/
private $project;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Intranet\UserBundle\Entity\User")
*/
private $user;
/**
* #ORM\Column(name="profil", type="smallint")
*/
private $profil;
public function setProject(\Intranet\IntranetBundle\Entity\Project $project)
{
$project->addProjectUser($this);
$this->project = $project;
}
public function getProject()
{
return $this->project;
}
public function setUser(\Intranet\UserBundle\Entity\User $user)
{
$this->user = $user;
}
public function getUser()
{
return $this->user;
}
public function setProfil($profil)
{
$this->profil = $profil;
}
public function getProfil()
{
return $this->profil;
}
}
profil = smallint for the job of the user (1=manager, 2=designer, ...)
My ProjectController (addAction)
public function addAction()
{
$project = new Project;
$form = $this->createForm(new ProjectType, $project);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($project);
$em->flush();
foreach ($form->get('projectUsers')->getData() as $u) {
$u->setProject($project);
$em->persist($u);
}
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'The project : '. $project->getName() .' has been added');
return $this->redirect($this->generateUrl('clients_list'));
}
}
return $this->render('IntranetIntranetBundle:Project:add_project.html.twig', array(
'form' => $form->createView()
));
}
Thanks for your help
Well, first of all, you shouldn't specify #ORM\Id annotation on every foreign key in your ProjectUser entity - it is for primary keys.
Then you should declare column join on foreign key fields:
/**
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\Project", inversedBy="projectUsers")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $project;
/**
* #ORM\ManyToOne(targetEntity="Intranet\IntranetBundle\Entity\User", inversedBy="projects")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
You also should have a field like
class User
{
// ...
/**
* #ORM\OneToMany(targetEntity="Intranet\IntranetBundle\Entity\ProjectUser", mappedBy="user")
*/
private $projects;
// ...
}
Finally, to add user to project, I suggest you embed a ProjectUserType form with user selection into ProjectType form. In your controller, you can have something like
public function addAction()
{
$project = new Project;
$projectUser = new ProjectUser();
$projectUser->setProject($project);
$project->addProjectUser($projectUser);
$form = $this->createForm(new ProjectType, $project);
// ...
And in form ProjectUserType
class ProjectUserType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('user', 'entity', array(
'class' => 'Intranet:IntranetBundle:User'
));
// ...
Hope this helps at least a little bit.
When you code : $em->persist($project);
$project is equal to $project = new Project; (don't you have forget '()' ?)
Actually the $projet is empty... To do this, I think you forget to code :
$project = $form->getData();
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.
I have a form with 4 realtionships but have a problem with 2 of them.
Here is code for my form:
<?php
namespace Psw\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class MeatType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name_pl')
->add('name_en')
->add('jm')
->add('vat')
->add('net_price')
->add('min')
->add('new')
->add('promotion', 'entity', array(
'class' => 'PswAdminBundle:Promotions',
'empty_value' => 'No promotion',
'required' => false
))
->add('promotion_price')
->add('producer', 'entity', array(
'class' => 'PswAdminBundle:MeatProducers'
))
->add('animals')
->add('categories')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Psw\AdminBundle\Entity\Meat'
));
}
public function getName()
{
return 'psw_adminbundle_meattype';
}
}
And entities
Meat:
<?php
namespace Psw\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Meat
*
* #ORM\Table()
* #ORM\Entity
*/
class Meat
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name_pl", type="string", length=255)
*/
private $name_pl;
/**
* #var string
*
* #ORM\Column(name="name_en", type="string", length=255)
*/
private $name_en;
/**
* #var string
*
* #ORM\Column(name="jm", type="string", length=10)
*/
private $jm;
/**
* #var integer
*
* #ORM\Column(name="vat", type="integer")
*/
private $vat;
/**
* #var float
*
* #ORM\Column(name="net_price", type="float")
*/
private $net_price;
/**
* #var float
*
* #ORM\Column(name="min", type="float")
*/
private $min;
/**
* #var boolean
*
* #ORM\Column(name="new", type="boolean")
*/
private $new;
/**
* #var integer
*
* #ORM\Column(name="promotion", type="integer", nullable=true)
* #ORM\ManyToOne(targetEntity="Promotions")
*/
private $promotion;
/**
* #var float
*
* #ORM\Column(name="promotion_price", type="float")
*
*/
private $promotion_price;
/**
* #ORM\ManyToMany(targetEntity="Animals")
* #ORM\JoinTable(name="meat_animals",
* joinColumns={#ORM\JoinColumn(name="meat_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="animal_id", referencedColumnName="id")}
* )
**/
private $animals;
/**
* #ORM\ManyToMany(targetEntity="MeatCategories")
* #ORM\JoinTable(name="meat_meat_categories",
* joinColumns={#ORM\JoinColumn(name="meat_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
**/
private $categories;
/**
* #ORM\Column(name="producer", type="integer")
*
* #ORM\ManyToOne(targetEntity="MeatProducers", inversedBy="products")
* #ORM\JoinColumn(name="producer", referencedColumnName="id")
**/
private $producer;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name_pl
*
* #param string $namePl
* #return Meat
*/
public function setNamePl($namePl)
{
$this->name_pl = $namePl;
return $this;
}
/**
* Get name_pl
*
* #return string
*/
public function getNamePl()
{
return $this->name_pl;
}
/**
* Set name_en
*
* #param string $nameEn
* #return Meat
*/
public function setNameEn($nameEn)
{
$this->name_en = $nameEn;
return $this;
}
/**
* Get name_en
*
* #return string
*/
public function getNameEn()
{
return $this->name_en;
}
/**
* Set jm
*
* #param string $jm
* #return Meat
*/
public function setJm($jm)
{
$this->jm = $jm;
return $this;
}
/**
* Get jm
*
* #return string
*/
public function getJm()
{
return $this->jm;
}
/**
* Set vat
*
* #param integer $vat
* #return Meat
*/
public function setVat($vat)
{
$this->vat = $vat;
return $this;
}
/**
* Get vat
*
* #return integer
*/
public function getVat()
{
return $this->vat;
}
/**
* Set net_price
*
* #param float $netPrice
* #return Meat
*/
public function setNetPrice($netPrice)
{
$this->net_price = $netPrice;
return $this;
}
/**
* Get net_price
*
* #return float
*/
public function getNetPrice()
{
return $this->net_price;
}
/**
* Set min
*
* #param float $min
* #return Meat
*/
public function setMin($min)
{
$this->min = $min;
return $this;
}
/**
* Get min
*
* #return float
*/
public function getMin()
{
return $this->min;
}
/**
* Set new
*
* #param boolean $new
* #return Meat
*/
public function setNew($new)
{
$this->new = $new;
return $this;
}
/**
* Get new
*
* #return boolean
*/
public function getNew()
{
return $this->new;
}
/**
* Set promotion
*
* #param integer $promotion
* #return Meat
*/
public function setPromotion($promotion)
{
$this->promotion = $promotion;
return $this;
}
/**
* Get promotion
*
* #return integer
*/
public function getPromotion()
{
return $this->promotion;
}
/**
* Constructor
*/
public function __construct()
{
$this->animals = new ArrayCollection();
$this->categories = new ArrayCollection();
}
/**
* Add animals
*
* #param \Psw\AdminBundle\Entity\Animals $animals
* #return Meat
*/
public function addAnimal(\Psw\AdminBundle\Entity\Animals $animals)
{
$this->animals[] = $animals;
return $this;
}
/**
* Remove animals
*
* #param \Psw\AdminBundle\Entity\Animals $animals
*/
public function removeAnimal(\Psw\AdminBundle\Entity\Animals $animals)
{
$this->animals->removeElement($animals);
}
/**
* Get animals
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAnimals()
{
return $this->animals;
}
/**
* Add categories
*
* #param \Psw\AdminBundle\Entity\Meat_categories $categories
* #return Meat
*/
public function addCategorie(\Psw\AdminBundle\Entity\Meat_categories $categories)
{
$this->categories[] = $categories;
return $this;
}
/**
* Remove categories
*
* #param \Psw\AdminBundle\Entity\Meat_categories $categories
*/
public function removeCategorie(\Psw\AdminBundle\Entity\Meat_categories $categories)
{
$this->categories->removeElement($categories);
}
/**
* Get categories
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
/**
* Set producer
*
* #param \Psw\AdminBundle\Entity\MeatProducers $producer
* #return Meat
*/
public function setProducer(\Psw\AdminBundle\Entity\MeatProducers $producer = null)
{
$this->producer = $producer;
return $this;
}
/**
* Get producer
*
* #return \Psw\AdminBundle\Entity\MeatProducers
*/
public function getProducer()
{
return $this->producer;
}
/**
* Set promotion_price
*
* #param float $promotionPrice
* #return Meat
*/
public function setPromotionPrice($promotionPrice)
{
$this->promotion_price = $promotionPrice;
return $this;
}
/**
* Get promotion_price
*
* #return float
*/
public function getPromotionPrice()
{
return $this->promotion_price;
}
}
MeatProducers:
<?php
namespace Psw\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* MeatProducers
*
* #ORM\Table()
* #ORM\Entity
*/
class MeatProducers
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\OneToMany(targetEntity="Meat", mappedBy="producer")
**/
private $products;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return MeatProducers
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
public function __toString()
{
return $this->name;
}
/**
* Constructor
*/
public function __construct()
{
$this->products = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add products
*
* #param \Psw\AdminBundle\Entity\Meat $products
* #return MeatProducers
*/
public function addProduct(\Psw\AdminBundle\Entity\Meat $products)
{
$this->products[] = $products;
return $this;
}
/**
* Remove products
*
* #param \Psw\AdminBundle\Entity\Meat $products
*/
public function removeProduct(\Psw\AdminBundle\Entity\Meat $products)
{
$this->products->removeElement($products);
}
/**
* Get products
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProducts()
{
return $this->products;
}
}
There are no problems with many to many raltions on Animals and Categories.
But Promotions and Producers where i have many to one cause some issues.
Problem is that when trying to insert/update record doctrine calls __toString method instead of getId to obtain value to put into database.
I have working example like this with other entities, they are almost the same but in this case it just does not want to work.
Controller code is from crud generator, I didn't change anything there if necessary I may post it.
Question is how to make it use getId method?
The issue here is not with the __toString, it lies in your mapping annotation. You should not use #Column for association mappings. Instead, use #JoinColumn:
/**
* #ORM\ManyToOne(targetEntity="Promotions")
* #ORM\JoinColumn(name="promotion_id", referencedColumnName="id")
*/
private $promotion;