Symfony2 Doctrine2 getresult twig - symfony

i have an error :
Catchable Fatal Error: Object of class ParcAutoBundle\Entity\Car could not be converted to string
my class of maintenance is :
<?php
namespace AutoEcole\ParcAutoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Maintenance
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AutoEcole\ParcAutoBundle\Entity\MaintenanceRepository")
*/
class Maintenance {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="datemaintenance", type="string", length=255)
*/
private $datemaintenance;
/**
* #var integer
*
* #ORM\Column(name="mileage", type="bigint")
*/
private $mileage;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set datemaintenance
*
* #param string $datemaintenance
* #return Maintenance
*/
public function setDatemaintenance($datemaintenance) {
$this->datemaintenance = $datemaintenance;
return $this;
}
/**
* Get datemaintenance
*
* #return string
*/
public function getDatemaintenance() {
return $this->datemaintenance;
}
/**
* Set mileage
*
* #param integer $mileage
* #return Maintenance
*/
public function setMileage($mileage) {
$this->mileage = $mileage;
return $this;
}
/**
* Get mileage
*
* #return integer
*/
public function getMileage() {
return $this->mileage;
}
/**
* Set description
*
* #param string $description
* #return Maintenance
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* #ORM\ManyToOne(targetEntity="\AutoEcole\ParcAutoBundle\Entity\Car")
* #ORM\JoinColumn(nullable=false)
*/
private $car;
/**
* Set car
*
* #param \AutoEcole\ParcAutoBundle\Entity\Car $car
* #return Maintenance
*/
public function setCar(\AutoEcole\ParcAutoBundle\Entity\Car $car = null) {
$this->car = $car;
return $this;
}
/**
* Get car
*
* #return \AutoEcole\ParcAutoBundle\Entity\Car
*/
public function getCar() {
return $this->car;
}
}
my function in controller is :
if you want the MaintenanceType tell me
public function addcarmaintenanceAction($id, Request $request) {
//User connecté
$user = $this->getUser();
$maintenance = new Maintenance();
$car = $this->getDoctrine()->getManager()->getRepository('ParcAutoBundle:Car')->find($id);
//dump($car);
//die();
//Création du formulaire
$form = $this->createForm(new MaintenanceType());
$form->handleRequest($request);
if ($form->isValid()) {
//Récupération des données du formulaire de l'ajout du voiture
$datemaintenance = $form['datemaintenance']->getData();
$mileage = $form['mileage']->getData();
$description = $form['description']->getData();
//Préparation de l'objet pour le persister et faire flush() ensuite
$maintenance->setDatemaintenance($datemaintenance);
$maintenance->setMileage($mileage);
$maintenance->setDescription($description);
$maintenance->setCar($id);
//Entity Manager
$em = $this->getDoctrine()->getManager();
$em->persist($maintenance);
$em->flush();
$message = "style=display:block;";
return $this->render('ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig', array(
'form' => $form->createView(),
'user' => $user,
'message' => $message,
'car' => $car
));
}
$message = "style=display:none;";
return $this->render('ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig', array(
'user' => $user,
'form' => $form->createView(),
'message' => $message,
'car' => $car
));
}

the problem is solved , i putted the __toString() in the Car Class
public function __toString() {
return (string) $this->getRegistrationnumber();
}

In you ParcAutoBundle:ParcAuto:car_addmaintenance.html.twig template, try to display a property of car, not car directly:
{{ car.model }} // it's an exemple property
// instead of
{{ car }}

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).

Symfony2 stof doctrine uploadable with 1..1 or n..1 relations

i'm having trouble to use the uploadable extension of stofdoctrinebundle
i've a File entity :
<?php
namespace my\TestBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* File
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="my\TestBundle\Entity\FileRepository")
* #Gedmo\Uploadable(path="uploads", filenameGenerator="SHA1", allowOverwrite=true, appendNumber=true)
*/
class File
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\Column(name="path", type="string")
* #Gedmo\UploadableFilePath
*/
private $path;
/**
* #ORM\Column(name="name", type="string")
* #Gedmo\UploadableFileName
*/
private $name;
/**
* #ORM\Column(name="mime_type", type="string")
* #Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* #ORM\Column(name="size", type="decimal")
* #Gedmo\UploadableFileSize
*/
private $size;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return File
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set path
*
* #param string $path
* #return File
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set mimeType
*
* #param string $mimeType
* #return File
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
return $this;
}
/**
* Get mimeType
*
* #return string
*/
public function getMimeType()
{
return $this->mimeType;
}
/**
* Set size
*
* #param string $size
* #return File
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* Get size
*
* #return string
*/
public function getSize()
{
return $this->size;
}
}
in my controller, when i use a form directly on this entity :
$document = new File();
$form = $this->createFormBuilder($document)
->add('name')
->add('path','file',array(
'data_class' => null ))
->add('submit','submit')
->getForm()
if ($this->getRequest()->getMethod() === 'POST') {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($club);
$uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
$uploadableManager->markEntityToUpload($club, $club->getLogo()->getPath());
$em->flush();
}
}
my file is well uploaded and my entity correctly filled
But i want to use it in another entity :
class Company {
/**
* #ORM\ManyToOne(targetEntity="my\TestBundle\Entity\File", cascade={"persist"})
* #ORM\JoinColumn(name="logo", nullable=true)
*/
private $logo;
/**
* Get logo
*
* #return \my\TestBundle\Entity\File
*/
public function getLogo()
{
return $this->logo;
}
/**
* Set comments
*
* #param string $comments
* #return Club
*/
public function setComments($comments)
{
$this->comments = $comments;
return $this;
}
And in my controller :
$company = new Company();
$form = $this->createFormBuilder($company)
->add('name')
->add('logo', new \my\TestBundle\Form\FileType, array(
'data_class' => 'my\TestBundle\Entity\File' ))
->add('submit','submit')
->getForm()
;
if ($this->getRequest()->getMethod() === 'POST') {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($club);
$uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
$uploadableManager->markEntityToUpload($company, $company->getLogo()->getPath());
$em->flush();
}
}
My FileType :
/**
*
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('path', 'file', array(
'required' => false,
))
;
}
And when i submit, it tells me that all field of dile entity (mimetype, size, name) cannot be null.
But normally they are filled with the extension (like in 1st case)
How can i manage this?
Thanks
i think i solve my problem,
here what i've done :
$company = new Company();
$form = $this->createFormBuilder($company)
->add('name')
->add('logo', new \cM\ManagementBundle\Form\FileType, array(
'data_class' => 'cM\ManagementBundle\Entity\File' ))
->add('submit','submit')
->getForm()
;
if ($this->getRequest()->getMethod() === 'POST') {
$form->handleRequest($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($company);
$uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
$uploadableManager->markEntityToUpload($club->getLogo(), $club->getLogo()->getPath());
$em->flush();
}
}
I don't think the name is handled. Check documentation, name is asked in every demo form.

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 - embedded form won't display

I'm trying to create a form to insert "questions" that can have one or more "answers". So I want to add an embed form for the Answer entity.
It seems to work because I see the Question form, but only the string "Answers" is displayed at the bottom of my form, not the fields.
Here is my controller action :
public function addQuestionAction(Category $category)
{
$question = new Question();
$form = $this->createForm(new QuestionType(), $question);
$request = $this->get('request');
if ($request->getMethod() === 'POST') {
$form->bind($request);
$question->setCategory($category);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($question);
$em->flush();
return $this->redirect($this->generateUrl('mycategory_questiondisplay',
array('id' => $question->getId())));
}
}
return $this->render('MyCategoryBundle:Question:add.html.twig',
array(
'form' => $form->createView(),
));
}
My QuestionType form :
<?php
namespace My\CategoryBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class QuestionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('description')
->add('answers', 'collection', array(
'type' => new AnswerType(),
'allow_add' => true)
);
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Iel\CategoryBundle\Entity\Question'
));
}
/**
* #return string
*/
public function getName()
{
return 'my_categorybundle_question';
}
}
My Question Entity :
<?php
namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Question
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\CategoryBundle\Entity\QuestionRepository")
*/
class Question
{
/**
* #ORM\OneToMany(targetEntity="My\CategoryBundle\Entity\Answer",
mappedBy="question", cascade={"persist", "remove"})
*/
private $answers;
public function __construct()
{
$this->answers = new
\Doctrine\Common\Collections\ArrayCollection();
}
public function addAnswer(\My\CategoryBundle\Entity\Answer
$answer)
{
$this->answers[] = $answer;
$answers->setQuestion($this);
return $this;
}
public function removeAnswer(\My\CategoryBundle\Entity\Answer $answer)
{
$this->answers->removeElement($answer);
}
public function getAnswers()
{
return $this->answers;
}
public function setAnswers($answer)
{
$this->answer = $answer;
return $this;
}
/**
* #ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Category",
inversedBy="question")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* Set category
*
#param My\CategoryBundle\Entity\Category $category
*/
public function setCategory(\My\CategoryBundle\Entity\Category $category)
{
$this->category = $category;
}
/**
* Get category
*
#return My\CategoryBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Remove categories
**
#param My\CategoryBundle\Entity\Category $categories
*/
public function removeCategory(\My\CategoryBundle\Entity\Category $category)
{
$this->categories->removeElement($category);
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
* #return Question
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set description
*
* #param string $description
* #return Question
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
And finally, the Answer entity :
<?php
namespace My\CategoryBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Answer
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\CategoryBundle\Entity\AnswerRepository")
*/
class Answer
{
/**
* #ORM\ManyToOne(targetEntity="My\CategoryBundle\Entity\Question",
inversedBy="answer")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="question_id", referencedColumnName="id")
* })
*/
private $question;
/**
* Set question
*
#param My\CategoryBundle\Entity\Question $question
*/
public function setQuestion(\My\CategoryBundle\Entity\Question $question)
{
$this->question = $question;
}
/**
* Get question
*
#return My\CategoryBundle\Entity\Question
*/
public function getQuestion()
{
return $this->question;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="answer", type="text", nullable=true)
*/
private $answer;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set answer
*
* #param string $answer
* #return Answer
*/
public function setAnswer($answer)
{
$this->answer = $answer;
return $this;
}
/**
* Get answer
*
* #return string
*/
public function getAnswer()
{
return $this->answer;
}
}
I'm really not able to find what's wrong in my form...
The problem is that your question does not have any answers yet. Hence no forms. Try
$question = new Question();
$question->addAnswer(new Answer());
That will show an empty answer form.
Look in the cookbook to see how to use javascript to add answers dynamically from within the browser.

How I can persist an ArrayCollection to mysql?

the problem is the following:
When talking about radios I have programs, each program must have ads, so each program have one or many ads mentions.
Mi entity program:
<?php
namespace MediterraneoFM\MediterraneoFMBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* MediterraneoFM\MediterraneoFMBundle\Entity\Programas
*
* #ORM\Table()
* #ORM\Entity
*/
class Programas
{
/**
* #var integer $id_programa
*
* #ORM\Column(name="id_programa", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id_programa;
/**
* #var string $nombre
*
* #ORM\Column(name="nombre", type="string", length=40)
*/
private $nombre;
/**
* #var string $id_mencion_programa
*
* #ORM\Column(name="id_mencion_programa", type="string")
*
* #ORM\ManyToOne(targetEntity="MencionPrograma", inversedBy="Programas")
*
*/
private $id_mencion_programa;
/**
* #var \DateTime $duracion_desde
*
* #ORM\Column(name="duracion_desde", type="time")
*/
private $duracion_desde;
/**
* #var \DateTime $duracion_hasta
*
* #ORM\Column(name="duracion_hasta", type="time")
*/
private $duracion_hasta;
/**
* Get id_programa
*
* #return integer
*/
public function getIdPrograma()
{
return $this->id_programa;
}
/**
* Set nombre
*
* #param string $nombre
* #return Programas
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set id_mencion_programa
*
* #param MencionPrograma $idMencionPrograma
*
* #return Programas
*/
public function setIdMencionPrograma(MencionPrograma $idMencionPrograma)
{
$this->id_mencion_programa = $idMencionPrograma;
return $this;
}
/**
* Get id_mencion_programa
*
* #return string
*/
public function getIdMencionPrograma()
{
return $this->id_mencion_programa;
}
/**
* Set duracion_desde
*
* #param \DateTime $duracionDesde
* #return Programas
*/
public function setDuracionDesde($duracionDesde)
{
$this->duracion_desde = $duracionDesde;
return $this;
}
/**
* Get duracion_desde
*
* #return \DateTime
*/
public function getDuracionDesde()
{
return $this->duracion_desde;
}
/**
* Set duracion_hasta
*
* #param \DateTime $duracionHasta
* #return Programas
*/
public function setDuracionHasta($duracionHasta)
{
$this->duracion_hasta = $duracionHasta;
return $this;
}
/**
* Get duracion_hasta
*
* #return \DateTime
*/
public function getDuracionHasta()
{
return $this->duracion_hasta;
}
}
Mi entity mentions:
<?php
namespace MediterraneoFM\MediterraneoFMBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* MediterraneoFM\MediterraneoFMBundle\Entity\MencionPrograma
*
* #ORM\Table()
* #ORM\Entity
*/
class MencionPrograma
{
/**
* #var integer $id_mencion_programa
*
* #ORM\Column(name="id_mencion_programa", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\OneToMany(targetEntity="Programas", mappedBy="MencionPrograma")
*
*/
private $id_mencion_programa;
/**
* #var string $nombre
*
* #ORM\Column(name="nombre", type="string", length=33)
*/
private $nombre;
/**
* #var integer $id_emision_programa
*
* #ORM\Column(name="id_emision_programa", type="integer")
*/
private $id_emision_programa;
/**
* #var string $nro_menciones
*
* #ORM\Column(name="nro_menciones", type="string", length=11)
*/
private $nro_menciones;
public function __construct() {
$this->id_mencion_programa = new ArrayCollection();
}
/**
* Get id_mencion_programa
*
* #return integer
*/
public function getIdMencionPrograma()
{
return $this->id_mencion_programa;
}
/**
* Set id_emision_programa
*
* #param integer $idEmisionPrograma
* #return MencionPrograma
*/
public function setIdEmisionPrograma($idEmisionPrograma)
{
$this->id_emision_programa = $idEmisionPrograma;
return $this;
}
/**
* Get id_emision_programa
*
* #return integer
*/
public function getIdEmisionPrograma()
{
return $this->id_emision_programa;
}
/**
* Set nro_menciones
*
* #param string $nroMenciones
* #return MencionPrograma
*/
public function setNroMenciones($nroMenciones)
{
$this->nro_menciones = $nroMenciones;
return $this;
}
/**
* Get nro_menciones
*
* #return string
*/
public function getNroMenciones()
{
return $this->nro_menciones;
}
/**
* Set nombre
*
* #param string $nombre
* #return MencionPrograma
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
}
My controller:
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
namespace MediterraneoFM\MediterraneoFMBundle\Controller;
# Funciones del kernel de Symfony
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Doctrine\Common\Collections\ArrayCollection;
# Paginador
use MakerLabs\PagerBundle\Pager;
use MakerLabs\PagerBundle\Adapter\ArrayAdapter;
use MakerLabs\PagerBundle\Adapter\DoctrineOrmAdapter;
# Entities
use MediterraneoFM\MediterraneoFMBundle\Entity\Programas;
# Types
use MediterraneoFM\MediterraneoFMBundle\Form\InsertProgramasType;
class ProgramasController extends Controller {
# Alta de Clientes, insert en tabla Clientes.
public function insertAction() {
$programas = new Programas();
$formType = new InsertProgramasType();
$form = $this->createForm($formType, $programas);
return $this->render('MediterraneoFMBundle::insertProgramas.html.twig', array('form' => $form->createView()));
}
public function insertSuccessAction(Request $request) {
# Objeto que modifico
$programas = new Programas();
# Formulario que modifico
$formType = new InsertProgramasType();
$form = $this->createForm($formType, $programas);
if ($request->getMethod() == 'POST'):
$form->bind($request);
$data = $form->getData();
if ($form->isValid()):
$em = $this->getDoctrine()->getManager();
$em->persist($programas);
$em->flush();
return $this->redirect($this->generateUrl('insertProgramas'));
endif;
endif;
}
/**
*
* #Route("/programas/show/{limit}/{page}", defaults={"page"=1}, name="showProgramas")
*
*/
public function showAction($page, $limit) {
$programas = $this->getDoctrine()
->getRepository('MediterraneoFMBundle:Programas')
->findAll();
if (!$programas):
throw $this->createNotFoundException('No emisoras found for id ');
endif;
$adapter = new ArrayAdapter($programas);
$pager = new Pager($adapter, array('page' => $page, 'limit' => $limit));
return $this->render('MediterraneoFMBundle::showProgramas.html.twig', array('emisoras' => $programas, 'pager' => $pager));
}
}
?>
My formtype:
<?php
namespace MediterraneoFM\MediterraneoFMBundle\Form;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class InsertProgramasType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nombre')
->add('id_mencion_programa', 'entity', array(
'class' => 'MediterraneoFM\MediterraneoFMBundle\Entity\MencionPrograma',
'property' => 'nombre',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('c');
},
'label' => 'Mencion',
'multiple' => true,
'expanded' => true,
'required' => false,
))
->add('duracion_desde', 'time', array(
'with_seconds' => true
))
->add('duracion_hasta', 'time', array(
'with_seconds' => true
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MediterraneoFM\MediterraneoFMBundle\Entity\Programas',
'csrf_protection' => false,
'csrf_field_name' => '_token',
// a unique key to help generate the secret token
'intention' => 'task_item',
));
}
public function getName()
{
return 'mediterraneofm_mediterraneofmbundle_insertprogramastype';
}
}
So, when I save the data to de data base, it saves this:
O:58:"MediterraneoFM\MediterraneoFMBundle\Entity\MencionPrograma":4: {s:79:"�MediterraneoFM\MediterraneoFMBundle\Entity \MencionPrograma�id_mencion_programa";i:2;s:66:"�MediterraneoFM\MediterraneoFMBundle\Entity\MencionPrograma�nombre";s:3:"8-1";s:79:"�MediterraneoFM\MediterraneoFMBundle\Entity\MencionPrograma�id_emision_programa";i:2;s:73:"�MediterraneoFM\MediterraneoFMBundle\Entity\MencionPrograma�nro_menciones";s:1:"1";}
or like this:
Doctrine\Common\Collections\ArrayCollection#0000000037e77446000000008ebafd04
What Am I doing wrong? Sorry for my english!

Resources