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!
Related
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).
I have this issues "Warning: spl_object_hash() expects parameter 1 to be object, string given" when I try to save the onetomay entity side of my relationship, the code below may be give you some ideas:
<?php
namespace BackendBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* BulletinSalaire
*
* #ORM\Table(name="bulletin_salaire")
* #ORM\Entity(repositoryClass="BackendBundle\Repository\BulletinSalaireRepository")
*/
class BulletinSalaire
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="periode", type="date")
*/
private $periode;
/**
* #var string
*
* #ORM\Column(name="mode_reglement", type="string", length=255)
*/
private $modeReglement;
/**
*
* #ORM\ManyToOne(targetEntity="Employee", inversedBy="employees", cascade={"persist"})
* #ORM\JoinColumn(name="id_employee", referencedColumnName="id")
*/
private $employee;
/**
*
* #ORM\OneToMany(targetEntity="LibelleBulletin", mappedBy="bulletinsalaire", cascade={"persist"})
* #ORM\JoinColumn(name="id_libelleBulltin", referencedColumnName="id")
*/
private $libelleBulletins;
public function __construct()
{
$this->libelleBulletins= new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set libelle
*
* #param string $libelle
*
* #return BulletinSalaire
*/
public function setLibelle($libelle)
{
$this->libelle = $libelle;
return $this;
}
/**
* Get libelle
*
* #return string
*/
public function getLibelle()
{
return $this->libelle;
}
/**
* Set base
*
* #param integer $base
*
* #return BulletinSalaire
*/
public function setBase($base)
{
$this->base = $base;
return $this;
}
/**
* Get base
*
* #return int
*/
public function getBase()
{
return $this->base;
}
/**
* Set retenues
*
* #param float $retenues
*
* #return BulletinSalaire
*/
public function setRetenues($retenues)
{
$this->retenues = $retenues;
return $this;
}
/**
* Get retenues
*
* #return float
*/
public function getRetenues()
{
return $this->retenues;
}
/**
* Set periode
*
* #param \DateTime $periode
*
* #return BulletinSalaire
*/
public function setPeriode($periode)
{
$this->periode = $periode;
return $this;
}
/**
* Get periode
*
* #return \DateTime
*/
public function getPeriode()
{
return $this->periode;
}
/**
* Set modeReglement
*
* #param string $modeReglement
*
* #return BulletinSalaire
*/
public function setModeReglement($modeReglement)
{
$this->modeReglement = $modeReglement;
return $this;
}
/**
* Get modeReglement
*
* #return string
*/
public function getModeReglement()
{
return $this->modeReglement;
}
/**
* #return mixed
*/
public function getEmployee()
{
return $this->employee;
}
/**
* #param mixed $employee
*/
public function setEmployee($employee)
{
$this->employee = $employee;
}
/**
* #param LibelleBulletin $libellebulletin
* #return $this
*/
public function addLibelleBulletin(LibelleBulletin $libellebulletin)
{
$this->libelleBulletins[] = $libellebulletin;
$libellebulletin->setBulletinSalaire($this);
return $this;
}
/**
* #param LibelleBulletin $libellebulletin
*/
public function removeLibelleBulletin(LibelleBulletin $libellebulletin)
{
$this->libelleBulletins->removeElement($libellebulletin);
}
public function getLibelleBulletins()
{
return $this->libelleBulletins;
}
}
/---------------------Entity Many libelle to one bulletin de salaire ----------------/
<?php
/**
* Created by PhpStorm.
* User: achouri
* Date: 17/11/2016
* Time: 4:05 PM
*/
namespace BackendBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BulletinSalaire
*
* #ORM\Table(name="libelle_bulletins")
* #ORM\Entity()
*/
class LibelleBulletin
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="BulletinSalaire", inversedBy="libellebulletins")
* #ORM\JoinColumn(nullable=false)
*/
private $bulletinSalaire;
/**
* #var string
*
* #ORM\Column(name="libelle", type="string", length=255)
*
*/
private $libelle;
/**
* #var int
*
* #ORM\Column(name="base", type="integer")
*/
private $base;
/**
* #var float
*
* #ORM\Column(name="retenues", type="float")
*/
private $retenues;
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return string
*/
public function getLibelle()
{
return $this->libelle;
}
/**
* #param string $libelle
*/
public function setLibelle($libelle)
{
$this->libelle = $libelle;
}
/**
* #return int
*/
public function getBase()
{
return $this->base;
}
/**
* #param int $base
*/
public function setBase($base)
{
$this->base = $base;
}
/**
* #return float
*/
public function getRetenues()
{
return $this->retenues;
}
/**
* #param float $retenues
*/
public function setRetenues($retenues)
{
$this->retenues = $retenues;
}
/**
* #return mixed
*/
public function getBulletinSalaire()
{
return $this->bulletinSalaire;
}
/**
* #param mixed $bulletinSalaire
*/
public function setBulletinSalaire($bulletinSalaire)
{
$this->bulletinSalaire = $bulletinSalaire;
}
}
/---------------------bulletinsallaireType---------------------------/
<?php
namespace BackendBundle\Form;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use BackendBundle\Form\LibelleBulletinType;
class BulletinSalaireType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('libelleBulletins',LibelleBulletinType::class,array('label' => '','data_class' => null))
->add('periode')->add('modeReglement')
->add('employee',EntityType::class,array('attr' => array(
'class' => 'form-control'),
'class' => 'BackendBundle:Employee',
'choice_label' => function ($employee) {
return $employee->getNom()." ".$employee->getPrenom();
}));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BackendBundle\Entity\BulletinSalaire'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'backendbundle_bulletinsalaire';
}
}
/------------------------libelleBultinType-----------------------/
<?php
namespace BackendBundle\Form;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use BackendBundle\Form\EmployeeType;
class LibelleBulletinType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('libelle')->add('base')->add('retenues');
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'BackendBundle\Entity\LibelleBulletin'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'backendbundle_libellebulletin';
}
}
/----------------------Action du save-----------------/
/**
* Creates a new bulletinSalaire entity.
*
* #Route("/new", name="bulletinsalaire_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$bulletinSalaire = new Bulletinsalaire();
$libellebulletin= new LibelleBulletin();
$form = $this->createForm('BackendBundle\Form\BulletinSalaireType', $bulletinSalaire);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$bulletinSalaire->addLibelleBulletin($libellebulletin);
$em->persist($bulletinSalaire);
$em->flush($bulletinSalaire);
return $this->redirectToRoute('bulletinsalaire_show', array('id' => $bulletinSalaire->getId()));
}
return $this->render('BackendBundle:bulletinsalaire:new.html.twig', array(
'bulletinSalaire' => $bulletinSalaire,
'form' => $form->createView(),
));
}
As #xabbuh pointed, we need to see how do you create the object. Looks like you are trying to set $employee or $libelleBulletins with a string instead of an object.
This is wrong.
$bulletin->setEmployee('some value');
This is right.
$employee = $dm->getRepository('BackendBundle:Employee')->findOneById('employeeId');
$bulletin->setEmployee($employee);
I am a beginner learning Symfony. I have an entity called sale for which I a form for inserting sales data.
The problem is each attempt to insert data results in the following error:
Neither the property "selectedstock" nor one of the methods
"addSelectedstock()"/"removeSelectedstock()", "setSelectedstock()",
"selectedstock()", "__set()" or "__call()" exist and have public
access in class "iCerge\Salesdeck\SalesBundle\Entity\Sale".
My Sale class is as follows:
<?php
namespace iCerge\Salesdeck\SalesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Sales
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="iCerge\Salesdeck\SalesBundle\Entity\SalesRepository")
*/
class Sale
{
private $selectedstock;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var float
*
* #ORM\Column(name="cost", type="float")
*/
private $cost;
/**
* #var float
*
* #ORM\Column(name="profitloss", type="float")
*/
private $profitloss;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="datetime")
*/
private $date;
/**
* #ORM\ManyToOne(targetEntity="iCerge\Salesdeck\StockBundle\Entity\Stock", inversedBy="sales")
* #ORM\JoinColumn(name="sid", referencedColumnName="id")
*/
protected $stock;
/**
* #var integer
*
* #ORM\Column(name="number_of_purchases", type="integer")
*/
private $number_of_purchases;
/**
* #var float
*
* #ORM\Column(name="active_buy_price", type="float")
*/
private $active_buy_price;
/**
* #var integer
*
* #ORM\Column(name="sid", type="integer")
*/
private $sid;
/**
* Get sid
*
* #return integer
*/
public function getSid()
{
return $this->sid ? $this->sid : 0;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set cost
*
* #param float $cost
* #return Sales
*/
public function setCost($cost)
{
$this->cost = $cost;
return $this;
}
/**
* Get cost
*
* #return float
*/
public function getCost()
{
return $this->cost;
}
/**
* Set date
*
* #param \DateTime $date
* #return Sales
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set profitloss
*
* #param float $profitloss
* #return Sales
*/
public function setProfitloss($profitloss)
{
$this->profitloss = $profitloss;
return $this;
}
/**
* Get profitloss
*
* #return float
*/
public function getProfitloss()
{
return $this->profitloss;
}
/**
* Set stock
*
* #param \iCerge\Salesdeck\StockBundle\Entity\Stock $stock
* #return Sale
*/
public function setStock(\iCerge\Salesdeck\StockBundle\Entity\Stock $stock = null)
{
$this->stock = $stock;
return $this;
}
/**
* Get stock
*
* #return \iCerge\Salesdeck\StockBundle\Entity\Stock
*/
public function getStock()
{
return $this->stock;
}
/********************/
/**
* Set number_of_purchases
*
* #return integer
*/
public function setNumberOfPurchases($purchases)
{
$this->number_of_purchases = $purchases;
return $this;
}
/**
* Get number_of_purchases
*
* #return integer
*/
public function getNumberOfPurchases()
{
return $this->number_of_purchases;
}
/**
* Set active_buy_price
*
* #return integer
*/
public function setActiveBuyPrice($price)
{
$this->active_buy_price = $price;
return $this;
}
/**
* Get active_buy_price
*
* #return integer
*/
public function getActiveBuyPrice()
{
return $this->active_buy_price;
}
public function getselectedstock()
{
return $this->selectedstock;
}
}
And the following is my Form class:
<?php
namespace iCerge\Salesdeck\SalesBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class SalesType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('selectedstock', 'choice', array(
'choices' => $options['allow_extra_fields'],
'required' => true,
'empty_value' => 'Choose a Product',
'empty_data' => null,
'label' => 'Select Item',
// 'mapped'=>false
))
/*->add('test', 'choice', array(
'choices' => $options['allow_extra_fields'],
'required' => false,
'empty_value' => 'Choose your gender',
'empty_data' => null,
'mapped'=>false
))*/
->add('number_of_purchases', 'integer', array('label'=>'Number of purchases'))
->add('cost')
->add('profitloss', 'text', array('label'=>'Profit/Loss'))
->add('date', 'datetime', array('data'=>new \DateTime('now')))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
// 'data_class' => 'iCerge\Salesdeck\SalesBundle\Entity\Sales'
'data_class' => 'iCerge\Salesdeck\SalesBundle\Entity\Sale'
));
}
/**
* #return string
*/
public function getName()
{
return 'icerge_salesdeck_salesbundle_sales';
}
}
What am I doing wrong here?
Update
Screenshot shows dropdown list of available stock.
The form is the sales/add form which requires an item of available stock from the list to be selected.
You don't have a setter for selectedstock, and not related to the error you don't have annotation to mark selectedstock as an orm column, so it won't be persisted.
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.
I have this entity (Registro):
<?php
namespace Gitek\RegistroBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Gitek\RegistroBundle\Entity\Registro
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Gitek\RegistroBundle\Entity\RegistroRepository"))
*/
class Registro
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var datetime $fecha
*
* #ORM\Column(name="fecha", type="datetime")
*/
private $fecha;
/**
* #var smallint $comenzado
*
* #ORM\Column(name="comenzado", type="smallint", nullable=true)
*/
private $comenzado;
/**
* #var smallint $completado
*
* #ORM\Column(name="completado", type="smallint", nullable=true)
*/
private $completado;
/**
* #var datetime $created_at
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var datetime $updated_at
*
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updated_at;
/** #ORM\ManyToOne(targetEntity="Gitek\UsuarioBundle\Entity\Usuario") */
protected $usuario;
/** #ORM\ManyToOne(targetEntity="Gitek\HotelBundle\Entity\Tipotarea") */
protected $tipotarea;
/** #ORM\ManyToOne(targetEntity="Gitek\HotelBundle\Entity\Habitacion") */
protected $habitacion;
/** #ORM\ManyToOne(targetEntity="Gitek\RegistroBundle\Entity\Master") */
protected $master;
/**
* #ORM\ManyToMany(targetEntity="Gitek\HotelBundle\Entity\Incidencia", inversedBy="registros")
* #ORM\JoinTable(name="incidencia_registro",
* joinColumns={#ORM\JoinColumn(name="registro_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="incidencia_id", referencedColumnName="id")}
* )
*/
protected $incidencias;
public function __construct()
{
$this->created_at = new \DateTime();
$this->updated_at = new \DateTime();
}
// public function __toString()
// {
// return $this->getNombre();
// }
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fecha
*
* #param datetime $fecha
*/
public function setFecha($fecha)
{
$this->fecha = $fecha;
}
/**
* Get fecha
*
* #return datetime
*/
public function getFecha()
{
return $this->fecha;
}
/**
* Set comenzado
*
* #param smallint $comenzado
*/
public function setComenzado($comenzado)
{
$this->comenzado = $comenzado;
}
/**
* Get comenzado
*
* #return smallint
*/
public function getComenzado()
{
return $this->comenzado;
}
/**
* Set completado
*
* #param smallint $completado
*/
public function setCompletado($completado)
{
$this->completado = $completado;
}
/**
* Get completado
*
* #return smallint
*/
public function getCompletado()
{
return $this->completado;
}
/**
* Set created_at
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
}
/**
* Get created_at
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set updated_at
*
* #param datetime $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updated_at = $updatedAt;
}
/**
* Get updated_at
*
* #return datetime
*/
public function getUpdatedAt()
{
return $this->updated_at;
}
/**
* Set usuario
*
* #param Gitek\UsuarioBundle\Entity\Usuario $usuario
*/
public function setUsuario(\Gitek\UsuarioBundle\Entity\Usuario $usuario)
{
$this->usuario = $usuario;
}
/**
* Get usuario
*
* #return Gitek\UsuarioBundle\Entity\Usuario
*/
public function getUsuario()
{
return $this->usuario;
}
/**
* Set tipotarea
*
* #param Gitek\HotelBundle\Entity\Tipotarea $tipotarea
*/
public function setTipotarea(\Gitek\HotelBundle\Entity\Tipotarea $tipotarea)
{
$this->tipotarea = $tipotarea;
}
/**
* Get tipotarea
*
* #return Gitek\HotelBundle\Entity\Tipotarea
*/
public function getTipotarea()
{
return $this->tipotarea;
}
/**
* Set habitacion
*
* #param Gitek\HotelBundle\Entity\Habitacion $habitacion
*/
public function setHabitacion(\Gitek\HotelBundle\Entity\Habitacion $habitacion)
{
$this->habitacion = $habitacion;
}
/**
* Get habitacion
*
* #return Gitek\HotelBundle\Entity\Habitacion
*/
public function getHabitacion()
{
return $this->habitacion;
}
/**
* Add incidencias
*
* #param Gitek\HotelBundle\Entity\Incidencia $incidencias
*/
public function addIncidencia(\Gitek\HotelBundle\Entity\Incidencia $incidencias)
{
$this->incidencias[] = $incidencias;
}
/**
* Get incidencias
*
* #return Doctrine\Common\Collections\Collection
*/
public function getIncidencias()
{
return $this->incidencias;
}
}
I wanted to save multiple data on a row, so I created a new Entity with only an array propery like this (Master):
<?php
namespace Gitek\RegistroBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
class Master
{
/** #ORM\OneToMany(targetEntity="Gitek\HotelBundle\Entity\Habitacion", mappedBy="master") */
protected $registros;
public function __construct()
{
$this->registros = new ArrayCollection();
}
public function getRegistros()
{
return $this->registros;
}
public function setRegistros(ArrayCollection $registros)
{
$this->registros = $registros;
}
}
I created my MasterType like this:
<?php
namespace Gitek\RegistroBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;
class MasterType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('registros', 'collection', array(
'type' => new RegistroType(),
'allow_add' => true,
'by_reference' => true,
));
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Gitek\RegistroBundle\Entity\Master'
);
}
public function getName()
{
return 'master';
}
}
And this is my controller:
public function asignarAction()
{
$master = new Master();
$request = $this->getRequest();
$form = $this->createForm(new MasterType(), $master);
if ('POST' === $request->getMethod()) {
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($master);
$em->flush();
return $this->redirect($this->generateUrl('recepcion_asignar'));
}else {
print_r("ezez");
print_r($form->getErrors());
}
} else {
}
return $this->render('RegistroBundle:Recepcion:asignar.html.twig', array(
'registro' => $master,
'form' => $form->createView()
));
}
The form works ok, and I see the data is submited correctly but it is not persisted, I´m getting this error all the time:
Class Gitek\RegistroBundle\Entity\Master is not a valid entity or mapped super class.
I think that the problem is within de Master entity.
Any help or clue?
You missed the #Entity annotation on your Master class, you will also need a master table on your database for this to work.
If you don't want to create the master table, then you can skip the #Entity annotation, but you can not persist master. Instead you would have to iterate through the collection and persist only the entities in the array.