Best approach to retrieve entity field form from database - symfony

I have that Entity TwitterPost.php
<?php
namespace FEB\TwitterBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Twitterpost
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="FEB\TwitterBundle\Entity\TwitterpostRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Twitterpost
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=50)
* #Assert\NotNull(message="Debe escribir un titulo")
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="tweet", type="string", length=145)
* #Assert\NotNull(message="Debe escribir un tweet")
*/
private $tweet;
/**
* Many-To-Many, Unidirectional
*
* #var ArrayCollection $tags
*
* #ORM\ManyToMany(targetEntity="\FEB\TagsBundle\Entity\Tag")
* #ORM\JoinTable(name="twitterpost_tags",
* joinColumns={#ORM\JoinColumn(name="twitterpost_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="tag", referencedColumnName="id")}
* )
*/
private $tags;
/**
* #var string
*
* #ORM\Column(name="photo", type="string", length=255, nullable=true)
*/
private $photo;
/**
* #var string
*
* #ORM\Column(name="idpost", type="string", length=100)
*/
private $idpost;
/**
* #var string
*
* #ORM\Column(name="autor", type="string", length=50)
*/
private $autor;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct()
{
$this->setCreated(new \DateTime());
$this->tags = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titulo
*
* #param string $titulo
* #return Twitterpost
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set tweet
*
* #param string $tweet
* #return Twitterpost
*/
public function setTweet($tweet)
{
$this->tweet = $tweet;
return $this;
}
/**
* Get tweet
*
* #return string
*/
public function getTweet()
{
return $this->tweet;
}
/**
* Set tags
*
* #param string $tags
* #return Twitterpost
*/
public function setTags($tags)
{
$this->tags = $tags;
return $this;
}
/**
* Get tags
*
* #return string
*/
public function getTags()
{
return $this->tags;
}
/**
* Set photo
*
* #param string $photo
* #return Twitterpost
*/
public function setPhoto($photo)
{
$this->photo = $photo;
return $this;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
/**
* Set idpost
*
* #param string $idpost
* #return Twitterpost
*/
public function setIdPost($idpost)
{
$this->idpost = $idpost;
return $this;
}
/**
* Get idpost
*
* #return string
*/
public function getIdPost()
{
return $this->idpost;
}
/**
* Set autor
*
* #param string $autor
* #return Twitterpost
*/
public function setAutor($autor)
{
$this->autor = $autor;
return $this;
}
/**
* Get autor
*
* #return string
*/
public function getAutor()
{
return $this->autor;
}
/**
* Set created
*
* #param \DateTime $created
* #return Tag
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
And this one
/**
* Tag
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="FEB\TagsBundle\Entity\TagRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Tag
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="tag", type="string", length=255)
*/
private $tag;
/**
* #var string
*
* #ORM\Column(name="autor", type="string", length=50)
*/
private $autor;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct()
{
$this->setCreated(new \DateTime());
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set tag
*
* #param string $tag
* #return Tag
*/
public function setTag($tag)
{
$this->tag = $tag;
return $this;
}
/**
* Get tag
*
* #return string
*/
public function getTag()
{
return $this->tag;
}
/**
* Set autor
*
* #param string $autor
* #return Tag
*/
public function setAutor($autor)
{
$this->autor = $autor;
return $this;
}
/**
* Get autor
*
* #return string
*/
public function getAutor()
{
return $this->autor;
}
/**
* Set created
*
* #param \DateTime $created
* #return Tag
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
It's a Manytomany relationship between TwitterPost and Tags. And in my form has a select field which is a Entity class Tag.
<?php
namespace FEB\TwitterBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class TwitterpostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('titulo')
->add('tweet', 'textarea')
->add('photo', 'file', array('required' => false))
->add('tags', 'entity', array(
'class' => 'FEBTagsBundle:tag',
'property' => 'tag',
'empty_value' => 'Selecciona tags',
'multiple' => true));
}
public function getName()
{
return 'twitter_form';
}
}
When I submit the data form, in the "twitterpost" table the data is saved correctly and in the aux table "twitterpost_tags" too.
For example:
twitterpost_id tag_id
1-----------1
1-----------2
2-----------1
2-----------3
The tag table:
id---------tag
1----------tagA
2----------tagB
3----------tagC
When I want show all data of Twitterpost, what is the best approached to show the tag name and not the tag id?
Than you in advanced.

I'm not sure if I get you right. To show All tags in the twitterpost form you are already doing the right thing:
->add('tags', 'entity', array(
'class' => 'FEBTagsBundle:tag',
'property' => 'tag',
'empty_value' => 'Selecciona tags',
'multiple' => true
));
This will create a multiple select box where you can select from all the tags. From the docs:
property
type: string
This is the property that should be used for displaying the entities as text in the HTML element. If left blank, the entity object will be cast into a string and so must have a __toString() method.
If you don't want a multi-select but checkboxes or radiobuttons instead, checkout this part of the documentation.
In case you are asking on how to output the data when not inside the TwitterpostType, you can just treat them as objects in a Controller:
$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findOne($id);
// to get all _tags_ of a post just call the getter:
$tags = $post->getTags();
The same goes for twig templates:
{# imagine you have all posts in a variable called 'posts' #}
{% for post in posts %}
<h1>{{ post.titulo }}</h1>
<div class="tags">
{% for tag in posts.tags %}
{{ tag.tag }}
{% endfor %}
</div>
{% endfor %}
Edit:
For a native SQL / DQL query you need a custom repository class. There you can store your own queries:
class TwitterpostRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery(
'SELECT p FROM TwitterBundle:Twitterpost p ORDER BY p.name ASC'
)
->getResult();
}
}
Then you can use it like this in the controller:
$repository = $this->getDoctrine()->getRepository('TwitterBundle:Twitterpost');
$post = $repository->findAllOrderedByName();

Related

Symfony relation OneToMany

I'm stuck with this problem. I try to upload one or more picture for one entity with a collection but when I submit my form I've got this error :
Symfony\Component\Validator\ConstraintViolation
Object(Symfony\Component\Form\Form).data.imagearticle[0].Article = null
It's because in my entity ImageArticle I put this :
namespace AD\PlatformBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use AD\PlatformBundle\Entity\Article;
/**
* ImageArticle
*
* #ORM\Table()
* #ORM\Entity()
* #ORM\HasLifecycleCallbacks
*/
class ImageArticle
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #var File
*
* #Assert\File(
* maxSize = "1M",
* mimeTypes = {
* "image/jpeg",
* "image/gif",
* "image/png",
* },
* maxSizeMessage = "La taille maximum du fichier doit etre inférieur ou égale à 1MB. Pour reduire sa taille vous pouvez utiliser le site : compressjpeg.com",
* mimeTypesMessage = "Seulement les fichiers .jpeg / .gif /.png sont acceptés"
* )
*/
private $file;
private $tempFileName;
/**
* #var Article
* #ORM\ManyToOne(targetEntity="AD\PlatformBundle\Entity\Article", inversedBy="imagearticle")
* #ORM\JoinColumn(nullable=false)
* #Assert\NotNull()
*/
private $Article;
public function getFile()
{
return $this->file;
}
public function setFile(UploadedFile $file)
{
$this->file = $file;
if (null !== $this->url)
{
$this->tempFileName = $this->url;
$this->url=null;
$this->alt=null;
}
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set url
*
* #param string $url
*
* #return ImageArticle
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set alt
*
* #param string $alt
*
* #return ImageArticle
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null === $this->file)
{
return;
}
//On add un extension pour le fichier.
$this->url = $this->file->guessExtension();
//Le alt est le nom du fichier du client.
$this->alt= $this->file->getClientOriginalName();
}
/**
*
* #ORM\PostPersist()
* #ORM\PostUpdate()
*
*/
public function upload()
{
if(null=== $this->file)
{
return;
}
//Si ancien fichier on supprime
if(null !== $this->tempFileName)
{
$oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this->tempFileName;
if (file_exists($oldFile))
{
unlink($oldFile);
}
}
//On deplace
$this->file->move
(
$this->getUploadRootDir(),
$this->id.'.'.$this->url
);
// chmod($this->getUploadRootDir().'/'.$this->id.'.'.$this->url,644);
}
/**
*#ORM\PreRemove()
*/
public function preRemoveUpload()
{
$this->tempFileName = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}
/**
*
* #ORM\PostRemove()
*/
public function removeUpload()
{
if(file_exists($this->tempFileName))
{
unlink($this->tempFileName);
}
}
public function getUploadDir()
{
return 'upload/img/blog/';
}
protected function getUploadRootDir()
{
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function __toString()
{
return $this->getUploadDir().$this->id.'.'.$this->getUrl();
}
/**
* Set source
*
* #param string $source
*
* #return Image
*/
/**
* Set article
*
* #param \AD\PlatformBundle\Entity\Article $article
*
* #return ImageArticle
*/
public function setArticle(\AD\PlatformBundle\Entity\Article $article = null)
{
$this->article = $article;
return $this;
}
/**
* Get article
*
* #return \AD\PlatformBundle\Entity\Article
*/
public function getArticle()
{
dump($this->article);
return $this->article;
}
But when I remove this Assert\NotNull my error is "Column article_id cannot be null"
This is my Article entity :
<?php
namespace AD\PlatformBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Article
*
* #ORM\Table()
* #ORM\Entity
*/
class Article
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titre1", type="string", length=255)
*/
private $titre1;
/**
* #var string
*
* #ORM\Column(name="titre2", type="string", length=255)
*/
private $titre2;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #ORM\ManyToMany(targetEntity="AD\UserBundle\Entity\User")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
*
* #ORM\OneToMany(targetEntity="AD\PlatformBundle\Entity\ImageArticle", mappedBy="article", cascade="all", orphanRemoval=true)
* #Assert\Valid()
* #ORM\OrderBy({"position" = "ASC"})
*
*/
private $imagearticle;
/**
* #Gedmo\Slug(fields={"titre1"})
* #ORM\Column(length=128, unique=true)
*/
private $slugurl;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titre1
*
* #param string $titre1
*
* #return Article
*/
public function setTitre1($titre1)
{
$this->titre1 = $titre1;
return $this;
}
/**
* Get titre1
*
* #return string
*/
public function getTitre1()
{
return $this->titre1;
}
/**
* Set titre2
*
* #param string $titre2
*
* #return Article
*/
public function setTitre2($titre2)
{
$this->titre2 = $titre2;
return $this;
}
/**
* Get titre2
*
* #return string
*/
public function getTitre2()
{
return $this->titre2;
}
/**
* Set description
*
* #param string $description
*
* #return Article
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set user
*
* #param \AD\UserBundle\Entity\User $user
*
* #return Article
*/
public function setUser(\AD\UserBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \AD\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set imagearticle
*
* #param \AD\PlatformBundle\Entity\ImageArticle $imagearticle
*
* #return Article
*/
public function setImagearticle(\AD\PlatformBundle\Entity\ImageArticle $imagearticle = null)
{
$this->imagearticle = $imagearticle;
return $this;
}
/**
* Get imagearticle
*
* #return \AD\PlatformBundle\Entity\ImageArticle
*/
public function getImagearticle()
{
return $this->imagearticle;
}
/**
* Constructor
*/
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set slugurl
*
* #param string $slugurl
*
* #return Article
*/
public function setSlugurl($slugurl)
{
$this->slugurl = $slugurl;
return $this;
}
/**
* Get slugurl
*
* #return string
*/
public function getSlugurl()
{
return $this->slugurl;
}
/**
* Add user
*
* #param \AD\UserBundle\Entity\User $user
*
* #return Article
*/
public function addUser(\AD\UserBundle\Entity\User $user)
{
$this->user[] = $user;
return $this;
}
/**
* Remove user
*
* #param \AD\UserBundle\Entity\User $user
*/
public function removeUser(\AD\UserBundle\Entity\User $user)
{
$this->user->removeElement($user);
}
/**
* Add imagearticle
*
* #param \AD\PlatformBundle\Entity\ImageArticle $imagearticle
*
* #return Article
*/
public function addImagearticle(\AD\PlatformBundle\Entity\ImageArticle $imagearticle)
{
$this->imagearticle[] = $imagearticle;
return $this;
}
/**
* Remove imagearticle
*
* #param \AD\PlatformBundle\Entity\ImageArticle $imagearticle
*/
public function removeImagearticle(\AD\PlatformBundle\Entity\ImageArticle $imagearticle)
{
$this->imagearticle->removeElement($imagearticle);
}
}
Thx for your help!
My controller :
public function newArticleAction(Request $request)
{
$article= new Article();
$form = $this->get('form.factory')->create(new \AD\PlatformBundle\Form\ArticleType(), $article);
if($form->handleRequest($request)->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
$request->getSession()->getFlashBag()->add('notice', 'Annonce enregistrée ! :)');
return $this->redirect($this->generateUrl('va_platform_blog'));
}
return $this->render('ADPlatformBundle:Cars:newarticle.html.twig', array(
'form' =>$form->createView(),
));
}
And my form ArticleType :
class ArticleType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('titre1')
->add('titre2')
->add('description', 'textarea', array('required' => false))
->add('imagearticle', 'collection', array(
'type' => new ImageArticleType(),
'allow_add' => true,
'allow_delete' => true,
'required' => true,
'by_reference' => false,
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AD\PlatformBundle\Entity\Article'
));
}
/**
* #return string
*/
public function getName()
{
return 'ad_platformbundle_article';
}
}
ImageArticleType
namespace AD\PlatformBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ImageArticleType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', 'file', array('label' => 'Choisir mon images'))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AD\PlatformBundle\Entity\ImageArticle'
));
}
/**
* #return string
*/
public function getName()
{
return 'ad_platformbundle_imagearticle';
}
Here is the solution.
In ImageArticle.php:
/**
* #var Article
* #ORM\ManyToOne(targetEntity="AD\PlatformBundle\Entity\Article", inversedBy="imagearticle")
* #ORM\JoinColumn(nullable=false)
* #Assert\NotNull()
*/
private $article; //previously $Article
In Article.php:
/**
*
* #ORM\OneToMany(targetEntity="AD\PlatformBundle\Entity\ImageArticle", mappedBy="article", cascade="all", orphanRemoval=true)
* #Assert\Valid()
*
*/
private $imagearticle; // remove #ORM\OrderBy({"position" = "ASC"}) since there is no position property
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
$this->imagearticle = new \Doctrine\Common\Collections\ArrayCollection(); //instanciate as an ArrayCollection when a new instance of Article is created
}
/**
* Add imagearticle
*
* #param \AD\PlatformBundle\Entity\ImageArticle $imagearticle
*
* #return Article
*/
public function addImagearticle(\AD\PlatformBundle\Entity\ImageArticle $imagearticle)
{
$imagearticle->setArticle($this); //since doctrine only checks owning side you need to do this to keep data in sync
$this->imagearticle[] = $imagearticle;
return $this;
}
/**
* Remove imagearticle
*
* #param \AD\PlatformBundle\Entity\ImageArticle $imagearticle
*/
public function removeImagearticle(\AD\PlatformBundle\Entity\ImageArticle $imagearticle)
{
$imagearticle->setArticle(); //same reason than above
$this->imagearticle->removeElement($imagearticle);
return $this;
}
I also recommend you to remove method setImagearticle() since image article is a collection and not an object, you should not have to use it.
Use camelCase to name your variable and method (so it should be $imageArticle and not imagearticle) this is a good practice to make your code more readable by others.
Finally use plural when you are working with collections (i.e. users instead of user) so you immediatly know what you are working with (another good practice).

How to customise form rendering when based on entity field in symfony 2?

I have created a form based on an entity field. This form is composed of checkboxes that allow user to choose an entity (here 'car').
This works fine but I need to customize the rendering to get extra informations. Currently, the only information that is displayed is the 'id' attribute.
In my case, I would like to display extra entity informations in the form such as color, brand etc ...
Does anyone know how to proceed ?
The controller :
public function chooserAction() {
//symfony.com/doc/current/reference/forms/types/entity.html
$cars = $this->getDoctrine()
->getRepository('CarBundle:Car')
->find(1);
$formBuilder = $this->createFormBuilder();
/*
foreach ($cars as $car) {
$formBuilder->add($car->getId() ,'checkbox')->getForm();
}
*/
$formBuilder->add('cars', 'entity', array(
'class' => 'CarBundle:Car',
'property' => 'id',
'expanded' => 'true',
'multiple' => 'true',
));
$formBuilder->add('save', 'submit');
$form = $formBuilder->getForm();
$request = $this->get('request');
$form->handleRequest($request);
if ($form->isValid()) {
echo "ok";
// return $this->redirect($this->generateUrl('car_show', array('id' => $car->getId())));
}
return $this->render('CarBundle:Car:chooser.html.twig', array('form' => $form->createView()));
}
The entity :
<?php
namespace Foobar\CarBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Car
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Foobar\CarBundle\Entity\CarRepository")
*/
class Car
{
/**
* #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;
/**
* #var string
*
* #ORM\Column(name="brand", type="string", length=255)
*/
private $brand;
/**
* #var string
*
* #ORM\Column(name="color", type="string", length=255)
*/
private $color;
/**
* #var integer
*
* #ORM\Column(name="power", type="integer")
*/
private $power;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Car
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set brand
*
* #param string $brand
* #return Car
*/
public function setBrand($brand)
{
$this->brand = $brand;
return $this;
}
/**
* Get brand
*
* #return string
*/
public function getBrand()
{
return $this->brand;
}
/**
* Set color
*
* #param string $color
* #return Car
*/
public function setColor($color)
{
$this->color = $color;
return $this;
}
/**
* Get color
*
* #return string
*/
public function getColor()
{
return $this->color;
}
/**
* Set power
*
* #param integer $power
* #return Car
*/
public function setPower($power)
{
$this->power = $power;
return $this;
}
/**
* Get power
*
* #return integer
*/
public function getPower()
{
return $this->power;
}
}
The view :
car chooser
{{ form(form) }}
You could create a toString() method in your Car entity.
public function __toString()
{
return '' . $this->getName();
}
If you want more thinks like pictures you could follow that http://symfony.com/doc/current/cookbook/form/form_customization.html

Symfony persists fail with relation cascade

Hello i have this error when i try to persist my entity :
An exception occurred while executing 'INSERT INTO item_details (item_id, item_type, name, start_date, end_date, description, pre_requisites, picture, acquired_knowledges, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params [null, null, "ertret", "09\/01\/2014", "17\/01\/2014", "ter", "trtre", {}, "trtre", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'item_id' cannot be null
Course entity code :
<?php
namespace Mooc\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Course
*
* #ORM\Table(name="course")
* #ORM\Entity
*/
class Course
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="language_id", type="integer", nullable=false)
*/
private $languageId;
/**
* #var integer
*
* #ORM\Column(name="category_id", type="integer", nullable=false)
*/
private $categoryId;
/**
* #ORM\OneToMany(targetEntity="ItemDetails", mappedBy="course",cascade={"all"})
**/
private $details;
/**
* Constructor
*/
public function __construct()
{
$this->details = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set languageId
*
* #param integer $languageId
* #return Course
*/
public function setLanguageId($languageId)
{
$this->languageId = $languageId;
return $this;
}
/**
* Get languageId
*
* #return integer
*/
public function getLanguageId()
{
return $this->languageId;
}
/**
* Set categoryId
*
* #param integer $categoryId
* #return Course
*/
public function setCategoryId($categoryId)
{
$this->categoryId = $categoryId;
return $this;
}
/**
* Get categoryId
*
* #return integer
*/
public function getCategoryId()
{
return $this->categoryId;
}
/**
* Add details
*
* #param \Mooc\TeacherBundle\Entity\ItemDetails $details
* #return Course
*/
public function addDetail(\Mooc\AdminBundle\Entity\ItemDetails $details)
{
$this->details[] = $details;
return $this;
}
/**
* Add details
*
* #param \Mooc\TeacherBundle\Entity\ItemDetails $details
* #return Course
*/
public function setDetails(\Mooc\AdminBundle\Entity\ItemDetails $details)
{
$this->details[] = $details;
return $this;
}
/**
* Remove details
*
* #param \Mooc\TeacherBundle\Entity\ItemDetails $details
*/
public function removeDetail(\Mooc\AdminBundle\Entity\ItemDetails $details)
{
$this->details->removeElement($details);
}
/**
* Get details
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDetails()
{
return $this->details;
}
}
Item details entity code :
namespace Mooc\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ItemDetails
*
* #ORM\Table(name="item_details")
* #ORM\Entity
*/
class ItemDetails
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="item_id", type="integer", nullable=false)
*/
private $itemId;
/**
* #var integer
*
* #ORM\Column(name="item_type", type="integer", nullable=false)
*/
private $itemType;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="start_date", type="string", length=60, nullable=false)
*/
private $startDate;
/**
* #var string
*
* #ORM\Column(name="end_date", type="string", length=60, nullable=false)
*/
private $endDate;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=false)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="pre_requisites", type="text", nullable=false)
*/
private $preRequisites;
/**
* #var string
*
* #ORM\Column(name="picture", type="string", length=255, nullable=false)
*/
private $picture;
/**
* #var string
*
* #ORM\Column(name="acquired_knowledges", type="text", nullable=false)
*/
private $acquiredKnowledges;
/**
* #var integer
*
* #ORM\Column(name="status", type="integer", nullable=false)
*/
private $status;
/**
* #ORM\ManyToOne(targetEntity="Course", inversedBy="details")
* #ORM\JoinColumn(name="item_id", referencedColumnName="id")
**/
private $course;
/**
* #ORM\OneToMany(targetEntity="Video", mappedBy="itemDetails",cascade={"all"})
**/
private $video;
/**
* Constructor
*/
public function __construct()
{
$this->video = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set itemId
*
* #param integer $itemId
* #return ItemDetails
*/
public function setItemId($itemId)
{
$this->itemId = $itemId;
return $this;
}
/**
* Get itemId
*
* #return integer
*/
public function getItemId()
{
return $this->itemId;
}
/**
* Set itemType
*
* #param integer $itemType
* #return ItemDetails
*/
public function setItemType($itemType)
{
$this->itemType = $itemType;
return $this;
}
/**
* Get itemType
*
* #return integer
*/
public function getItemType()
{
return $this->itemType;
}
/**
* Set name
*
* #param string $name
* #return ItemDetails
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set startDate
*
* #param string $startDate
* #return ItemDetails
*/
public function setStartDate($startDate)
{
$this->startDate = $startDate;
return $this;
}
/**
* Get startDate
*
* #return string
*/
public function getStartDate()
{
return $this->startDate;
}
/**
* Set endDate
*
* #param string $endDate
* #return ItemDetails
*/
public function setEndDate($endDate)
{
$this->endDate = $endDate;
return $this;
}
/**
* Get endDate
*
* #return string
*/
public function getEndDate()
{
return $this->endDate;
}
/**
* Set description
*
* #param string $description
* #return ItemDetails
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set preRequisites
*
* #param string $preRequisites
* #return ItemDetails
*/
public function setPreRequisites($preRequisites)
{
$this->preRequisites = $preRequisites;
return $this;
}
/**
* Get preRequisites
*
* #return string
*/
public function getPreRequisites()
{
return $this->preRequisites;
}
/**
* Set picture
*
* #param string $picture
* #return ItemDetails
*/
public function setPicture($picture)
{
$this->picture = $picture;
return $this;
}
/**
* Get picture
*
* #return string
*/
public function getPicture()
{
return $this->picture;
}
/**
* Set acquiredKnowledges
*
* #param string $acquiredKnowledges
* #return ItemDetails
*/
public function setAcquiredKnowledges($acquiredKnowledges)
{
$this->acquiredKnowledges = $acquiredKnowledges;
return $this;
}
/**
* Get acquiredKnowledges
*
* #return string
*/
public function getAcquiredKnowledges()
{
return $this->acquiredKnowledges;
}
/**
* Set status
*
* #param integer $status
* #return ItemDetails
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Set course
*
* #param \Mooc\AdminBundle\Entity\Course $course
* #return ItemDetails
*/
public function setCourse(\Mooc\AdminBundle\Entity\Course $course = null)
{
$this->course = $course;
return $this;
}
/**
* Get course
*
* #return \Mooc\AdminBundle\Entity\Course
*/
public function getCourse()
{
return $this->course;
}
/**
* Add details
*
* #param \Mooc\TeacherBundle\Entity\ItemDetails $video
* #return Course
*/
public function addVideo(\Mooc\AdminBundle\Entity\Video $video)
{
$this->details[] = $video;
return $this;
}
/**
* Add details
*
* #param \Mooc\TeacherBundle\Entity\ItemDetails $video
* #return Course
*/
public function setVideo(\Mooc\AdminBundle\Entity\Video $video)
{
$this->video[] = $video;
return $this;
}
/**
* Remove details
*
* #param \Mooc\TeacherBundle\Entity\ItemDetails $video
*/
public function removeVideo(\Mooc\AdminBundle\Entity\Video $video)
{
$this->video->removeElement($video);
}
/**
* Get details
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVideo()
{
return $this->video;
}
}
Video entity code :
namespace Mooc\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Video
*
* #ORM\Table(name="video")
* #ORM\Entity
*/
class Video
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="course_id", type="integer", nullable=false)
*/
private $courseId;
/**
* #var string
*
* #ORM\Column(name="video", type="string", length=255, nullable=false)
*/
private $video;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=false)
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="ItemDetails")
* #ORM\JoinColumn(name="course_id", referencedColumnName="id")
**/
private $itemDetails;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set courseId
*
* #param integer $courseId
* #return Video
*/
public function setCourseId($courseId)
{
$this->courseId = $courseId;
return $this;
}
/**
* Get courseId
*
* #return integer
*/
public function getCourseId()
{
return $this->courseId;
}
/**
* Set video
*
* #param string $video
* #return Video
*/
public function setVideo($video)
{
$this->video = $video;
return $this;
}
/**
* Get video
*
* #return string
*/
public function getVideo()
{
return $this->video;
}
/**
* Set description
*
* #param string $description
* #return Video
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set itemDetails
*
* #param \Mooc\AdminBundle\Entity\ItemDetails $itemDetails
* #return Video
*/
public function setItemDetails(\Mooc\AdminBundle\Entity\ItemDetails $itemDetails = null)
{
$this->itemDetails = $itemDetails;
return $this;
}
/**
* Get itemDetails
*
* #return \Mooc\AdminBundle\Entity\ItemDetails
*/
public function getItemDetails()
{
return $this->itemDetails;
}
}
Course form code :
namespace Mooc\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Doctrine\ORM\EntityRepository;
class CourseType extends AbstractType
{
private $languageId;
public function __construct($languageId) {
$this->languageId=$languageId;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$session = new Session();
$languageId=$session->get('languageId');
$builder
->add('languageId', 'entity', array(
'class' => 'MoocAdminBundle:Language',
'property' => 'name',
'preferred_choices' => array((object)$languageId),
))
->add('categoryId', 'entity', array(
'class' => 'MoocAdminBundle:CourseCategory',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.languageId ='.$this->languageId);
},
))
->add('details', new ItemDetailsType())
->add('submit', 'submit', array('attr' => array('class' => 'btn btn-success btn-large')));
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Mooc\AdminBundle\Entity\Course'
));
}
/**
* #return string
*/
public function getName()
{
return 'mooc_adminbundle_course';
}
}
ItemDetails form :
namespace Mooc\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ItemDetailsType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('startDate')
->add('endDate')
->add('description')
->add('preRequisites')
->add('picture','file')
->add('acquiredKnowledges')
->add('status')
->add('video', new VideoType())
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Mooc\AdminBundle\Entity\ItemDetails'
));
}
/**
* #return string
*/
public function getName()
{
return 'mooc_adminbundle_itemdetails';
}
}
video Form :
<?php
namespace Mooc\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class VideoType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('courseId')
->add('video','file')
->add('description','textarea')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Mooc\AdminBundle\Entity\Video'
));
}
/**
* #return string
*/
public function getName()
{
return 'mooc_adminbundle_video';
}
}
Code in controller :
public function courseaddAction() {
$locale=$this->get('session')->get('_locale');
$language=$this->get('doctrine.orm.entity_manager')->getRepository('MoocAdminBundle:Language')->findBy(array('locale'=>$locale));
$languageId=$language[0]->getId();
$form=$this->createForm(new CourseType($languageId));
if ($this->getRequest()->isMethod("POST")) {
$form->HandleRequest($this->getRequest());
//if ($form->isValid()) {
$course = $form->getData();
$this->get('mooc.course')->addCourse($course);
//}
}
return $this->render('MoocTeacherBundle:Default:courseadd.html.twig', array('form'=>$form->createView(),'languageId'=>$languageId));
}
Code in service :
public function addCourse($course) {
$details=$course->getDetails();
$this->em->persist($course);
/*
foreach($course->getDetails() as $details) {
$details->setItemType('course');
$this->em->persist($details);
foreach($details->getVideo() as $video) {
$this->em->persist($video);
}
}
*/
$this->em->flush();
}
You need to set ItemId, in example from form:
$builder
->add('name')
->add('startDate')
->add('itemId') //add this line
->add('endDate')
->add('description')
->add('preRequisites')
->add('picture','file')
->add('acquiredKnowledges')
->add('status')
->add('video', new VideoType())
;
or change nullable value to true
/**
* #var integer
*
* #ORM\Column(name="item_id", type="integer", nullable=true) //here nullable to true
*/
private $itemId;

Why Symfony and Doctrine uses __toString instead of getId when inserting/updateing record

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;

Query result found but not displayed in Symfony

Well, I don't really see this one.
This is a simple page where I try to display results of a joined query.
Here is the controller code :
public function pageApproachUpdateAction($pageId)
{
$em=$this->getDoctrine()->getEntityManager();
$pageWithMapItems = $em->getRepository('bndmyBundle:Page')->getPageWithMapItems($pageId);
return $this->render('bndmyBundle:test.html.twig', array(
'pageWithMapItems' => $pageWithMapItems
));
Here is the query :
public function getPageWithMapItems($pageId) {
$qb = $this->createQueryBuilder('p')
->leftJoin('p.mapItems', 'm')
->where('p.id = :pageId')
->setParameter('pageId', $pageId)
->addSelect('m');
return $qb->getQuery()
->getSingleResult();
}
Here is the twig code :
<body>
{% for mapitem in pageWithMapItems %}
item {{mapitem.id}}<br/>
{% else %}
No result
{% endfor %}
</body>
Here is the Page entity :
<?php
namespace bnd\myBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* bnd\myBundle\Entity\Page
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="bnd\myBundle\Entity\PageRepository")
*/
class Page
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="bnd\myBundle\Entity\Route", mappedBy="page")
*/
private $routes;
/**
* #ORM\OneToMany(targetEntity="bnd\myBundle\Entity\MapItem", mappedBy="page")
*/
private $mapItems;
/**
* #var smallint $number
*
* #ORM\Column(name="number", type="smallint")
*/
private $number;
/**
* #var string $background
*
* #ORM\Column(name="background", type="string", length=255, nullable="true")
*/
private $background;
/**
* #var string $type
*
* #ORM\Column(name="type", type="string", length=30)
*/
private $type;
/**
* #var string $description
*
* #ORM\Column(name="description", type="text", nullable="true")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set background
*
* #param string $background
*/
public function setBackground($background)
{
$this->background = $background;
}
/**
* Get background
*
* #return string
*/
public function getBackground()
{
return $this->background;
}
/**
* Set type
*
* #param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
public function __construct()
{
$this->routes = new \Doctrine\Common\Collections\ArrayCollection();
$this->mapItems = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add routes
*
* #param bnd\myBundle\Entity\Route $routes
*/
public function addRoute(\bnd\myBundle\Entity\Route $routes)
{
$this->routes[] = $routes;
}
/**
* Get routes
*
* #return Doctrine\Common\Collections\Collection
*/
public function getRoutes()
{
return $this->routes;
}
/**
* Set number
*
* #param smallint $number
*/
public function setNumber($number)
{
$this->number = $number;
}
/**
* Get number
*
* #return smallint
*/
public function getNumber()
{
return $this->number;
}
/**
* Add mapItems
*
* #param bnd\myBundle\Entity\MapItem $mapItems
*/
public function addMapItem(\bnd\myBundle\Entity\MapItem $mapItems)
{
$this->mapItems[] = $mapItems;
}
/**
* Get mapItems
*
* #return Doctrine\Common\Collections\Collection
*/
public function getMapItems()
{
return $this->mapItems;
}
/**
* Set description
*
* #param text $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return text
*/
public function getDescription()
{
return $this->description;
}
}
And the MapItem entity :
namespace bnd\myBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* bnd\myBundle\Entity\MapItem
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="bnd\myBundle\Entity\MapItemRepository")
*/
class MapItem
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="bnd\myBundle\Entity\Page", inversedBy="mapItems")
* #ORM\JoinColumn(nullable=false)
*/
private $page;
/**
* #var string $type
*
* #ORM\Column(name="type", type="string", length=255)
*/
private $type;
/**
* #var string $latlng
*
* #ORM\Column(name="latlng", type="text")
*/
private $latlng;
/**
* #var string $description
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set type
*
* #param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set latlng
*
* #param string $latlng
*/
public function setLatlng($latlng)
{
$this->latlng = $latlng;
}
/**
* Get latlng
*
* #return string
*/
public function getLatlng()
{
return $this->latlng;
}
/**
* Set description
*
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set page
*
* #param bnd\myBundle\Entity\Page $page
*/
public function setPage(\bnd\myBundle\Entity\Page $page)
{
$this->page = $page;
}
/**
* Get page
*
* #return bnd\myBundle\Entity\Page
*/
public function getPage()
{
return $this->page;
}
}
No result is displayed, but there should be one!
I don't have any exception, no typo mistakes I guess
I checked the profiler to read the actual queries performed ; I tested them with PhpMyAdmin, and none of them have no result.
It's a very simple and basic case. So, what did I did wrong ?
Thanks :)
So the thing is you've a one-to-many on your mapItems, so doctrine will return you an arrayCollection.
Your mapItems wasn't displayed in twig because you have to make your for loop on pageWithMapItems.mapItems, if you do it directly on pageWithMapItems it'll not work because your pageWithMapItems variable contain un object of page and not an array.
So this should work:
<body>
{% for mapitem in pageWithMapItems.mapItems %}
item {{mapitem.id}}<br/>
{% else %}
No result
{% endfor %}
</body>
Hope i'm clear !

Resources