I have a many-to-many relationship between two tables in my database (1 artikel has more than 1 bestelling and vice versa), so I made a link table(bestelregel).
But now I want to make a form so that I can add a new order with multiple products, but as I am new to this, I am not sure how to do it. I've tried to make a form for the entity Bestelling so that I can make a new order. And tried adding products to the order with another form(form based on the link table), but I recieved the following error:
Expected value of type "AppBundle\Entity\Artikel" for association field "AppBundle\Entity\Bestelregel#$bestelordernummer", got "AppBundle\Entity\Bestelling" instead.
I hope you guys can help me. Maybe with another way?
My code:
Entity Artikel
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Artikel
*
* #ORM\Table(name="artikel")
* #ORM\Entity(repositoryClass="AppBundle\Repository\ArtikelRepository")
*/
class Artikel
{
//Mapping naar de database
/**
* #var string
*
* #ORM\Column(name="artikelnummer", type="integer", length=20, unique=true)
* #ORM\Id
* #Assert\Length(
* min = 10,
* max = 10,
* minMessage = "Minimaal 10 karakters",
* maxMessage = "Maximaal 10 karakters"
*)
*/
private $artikelnummer;
/**
* #var string
*
* #ORM\Column(name="omschrijving", type="string", length=255, nullable=true)
*/
private $omschrijving;
/**
* #var string
*
* #ORM\Column(name="specificaties", type="string", length=255, nullable=true)
*/
private $specificaties;
/**
* #var string
*
* #ORM\Column(name="Magazijnlocatie", type="string", length=6)
* #Assert\Regex(
* pattern = "/^20|[0-1]{1}[0-9]{1}\/[A-Z][0]{1}[0-9]{1}|10$/i",
* match=true,
* message="Ongeldige locatie [ERROR1]")
* #Assert\Regex(
* pattern = "/^[2]{1}[1-9]{1}\/[A-Z]{1}[0-9]{1}$/i",
* match=false,
* message="Ongeldige locatie [ERROR2]")
* #Assert\Regex(
* pattern = "/^[3-9]{1}[0-9]{1}\/[A-Z][0-9]{1}$/i",
* match=false,
* message="Ongeldige locatie [ERROR3]")
* #Assert\Regex(
* pattern = "/^[0-1]{1}[0-9]{1}\/[A-Z][1]{1}[1-9]{1}$/i",
* match=false,
* message="Ongeldige locatie [ERROR4]")
* #Assert\Regex(
* pattern = "/^[0-1]{1}[0-9]{1}\/[A-Z][2-9]{1}[0-9]{1}$/i",
* match=false,
* message="Ongeldige locatie [ERROR5]")
* #Assert\Regex(
* pattern = "/^[0-9A-Za-z]+$/i",
* match=false,
* message="Ongeldige locatie [ERROR6]")
* #Assert\Length(
* max = 6,
* maxMessage = "Mag niet meer zijn dan {{ limit }} karakters"
* )
*/
private $magazijnlocatie;
/**
* #var decimal
*
* assert
* #ORM\Column#Column(type="decimal", precision= 10, scale=2, nullable=true)
*/
private $inkoopprijs;
/**
* #var string
*
* #ORM\Column(name="vervangendArtikel", type="string", length=255, nullable=true)
*/
private $vervangendArtikel;
/**
* #var integer
*
* #ORM\Column(name="minimumVoorraad", type="integer", length=20, nullable=true)
*/
private $minimumVoorraad;
/**
* #var integer
*
* #ORM\Column(name="voorraadaantal", type="integer", length=20, nullable=true)
*/
private $voorraadaantal;
/**
* #var integer
*
* #ORM\Column(name="bestelserie", type="integer", length=20, nullable=true)
*/
private $bestelserie;
/**
* #var integer
*
* #ORM\Column(name="verkopen", type="integer", length=20, nullable=true)
*/
private $verkopen;
/**
* #var integer
*
* #ORM\Column(name="gereserveerdeVoorraad", type="integer", length=10, nullable=true)
*/
private $gereserveerdeVoorraad;
/**
* #var integer
*
* #ORM\Column(name="vrijeVoorraad", type="integer", length=10, nullable=true)
*/
private $vrijeVoorraad;
/**
* #var bool
*
* #ORM\Column(name="in_voorraad", type="boolean")
*/
private $inVoorraad;
/**
* #var int
*
* #ORM\OneToMany(targetEntity="Bestelregel", mappedBy="artikelnummer")
*/
private $bestelregels;
public function __construct() {
$this->bestelregels = new ArrayCollection();
}
//**************************************************Set/Get Functies hieronder!*********************************
/**
* Set artikelnummer
*
* #param string $artikelnummer
*
* #return Artikel
*/
public function setArtikelnummer($artikelnummer)
{
$this->artikelnummer = $artikelnummer;
return $this;
}
/**
* Get artikelnummer
*
* #return string
*/
public function getArtikelnummer()
{
return $this->artikelnummer;
}
/**
* Set omschrijving
*
* #param string $omschrijving
*
* #return Artikel
*/
public function setOmschrijving($omschrijving)
{
$this->omschrijving = $omschrijving;
return $this;
}
/**
* Get omschrijving
*
* #return string
*/
public function getOmschrijving()
{
return $this->omschrijving;
}
/**
* Set specificaties
*
* #param string $specificaties
*
* #return Artikel
*/
public function setSpecificaties($specificaties)
{
$this->specificaties = $specificaties;
return $this;
}
/**
* Get specificaties
*
* #return string
*/
public function getSpecificaties()
{
return $this->specificaties;
}
/**
* Set magazijnlocatie
*
* #param string $magazijnlocatie
*
* #return Artikel
*/
public function setMagazijnlocatie($magazijnlocatie)
{
$this->magazijnlocatie = $magazijnlocatie;
return $this;
}
/**
* Get magazijnlocatie
*
* #return string
*/
public function getMagazijnlocatie()
{
return $this->magazijnlocatie;
}
/**
* Set inkoopprijs
*
* #param decimal $inkoopprijs
*
* #return Artikel
*/
public function setInkoopprijs($inkoopprijs)
{
$this->inkoopprijs = $inkoopprijs;
return $this;
}
/**
* Get inkoopprijs
*
* #return decimal
*/
public function getInkoopprijs()
{
return $this->inkoopprijs;
}
/**
* Set vervangendArtikel
*
* #param string $vervangendArtikel
*
* #return Artikel
*/
public function setVervangendartikel($vervangendeArtikel)
{
$this->vervangendArtikel = $vervangendArtikel;
return $this;
}
/**
* Get vervangendArtikel
*
* #return string
*/
public function getVervangendartikel()
{
return $this->vervangendArtikel;
}
/**
* Set minimumVoorraad
*
* #param integer $minimumVoorraad
*
* #return Artikel
*/
public function setMinimumvoorraad($minimumVoorraad)
{
$this->minimumVoorraad = $minimumVoorraad;
return $this;
}
/**
* Get minimumVoorraad
*
* #return integer
*/
public function getMinimumvoorraad()
{
return $this->minimumVoorraad;
}
/**
* Set voorraadaantal
*
* #param integer $voorraadaantal
*
* #return Artikel
*/
public function setVoorraadaantal($voorraadaantal)
{
$this->voorraadaantal = $voorraadaantal;
return $this;
}
/**
* Get voorraadaantal
*
* #return integer
*/
public function getVoorraadaantal()
{
return $this->voorraadaantal;
}
/**
* Set bestelserie
*
* #param integer $bestelserie
*
* #return Artikel
*/
public function setBestelserie($bestelserie)
{
$this->bestelserie = $bestelserie;
}
/**
* Get bestelserie
*
* #return integer
*/
public function getBestelserie()
{
return $this->bestelserie;
}
/**
* Set verkopen
*
* #param integer $verkopen
*
* #return Verkopen
*/
public function setVerkopen($verkopen)
{
$this->verkopen= $verkopen;
return $this;
}
/**
* Get verkopen
*
* #return integer
*/
public function getVerkopen()
{
return $this->verkopen;
}
/**
* Set gereserveerdeVoorraad
*
* #param integer $gereserveerdeVoorraad
*
*/
public function setGereserveerdevoorraad($gereserveerdeVoorraad)
{
$this->gereserveerdeVoorraad= $gereserveerdeVoorraad;
return $this;
}
/**
* Get gereserveerdeVoorraad
*
* #return integer
*/
public function getGereserveerdevoorraad()
{
return $this->gereserveerdeVoorraad;
}
/**
* Set vrijeVoorraad
*
* #param integer $vrijeVoorraad
*
* #return Artikel
*/
public function setVrijevoorraad($vrijeVoorraad)
{
$this->vrijeVoorraad= $vrijeVoorraad;
return $this;
}
/**
* Get vrijeVoorraad
*
* #return integer
*/
public function getVrijevoorraad()
{
return $this->vrijeVoorraad;
}
/**
* #return bool
*/
public function getInVoorraad()
{
return $this->inVoorraad;
}
/**
* #param bool $inVoorraad
*/
public function setInVoorraad($inVoorraad)
{
$this->inVoorraad = $inVoorraad;ity
}
}
Entity Bestelling
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Bestelling
*
* #ORM\Table(name="bestelling")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BestellingRepository")
*/
class Bestelling
{
/**
* #var int
*
* #ORM\Column(name="bestelordernummer", type="integer", unique=true)
* #ORM\Id
*/
private $bestelordernummer;
/**
* #var string
*
* #ORM\Column(name="leverancier", type="string", length=100, nullable=true)
*/
private $leverancier;
/**
* #var int
*
* #ORM\Column(name="keuringseisen", type="integer", length=4, nullable=true)
*/
private $keuringseisen;
/**
* #var int
*
* #ORM\OneToMany(targetEntity="Bestelregel", mappedBy="bestelordernummer")
*/
private $bestelregels;
public function __construct() {
$this->bestelregels = new ArrayCollection();
}
/**
* Set bestelordernummer
*
* #param integer $bestelordernummer
*
* #return Bestelling
*/
public function setBestelordernummer($bestelordernummer)
{
$this->bestelordernummer = $bestelordernummer;
return $this;
}
/**
* Get bestelordernummer
*
* #return integer
*/
public function getBestelordernummer()
{
return $this->bestelordernummer;
}
/**
* Set leverancier
*
* #param string $leverancier
*
* #return Bestelling
*/
public function setLeverancier($leverancier)
{
$this->leverancier = $leverancier;
return $this;
}
/**
* Get leverancier
*
* #return string
*/
public function getLeverancier()
{
return $this->leverancier;
}
/**
* Set keuringseisen
*
* #param integer $keuringseisen
*
* #return Bestelling
*/
public function setKeuringseisen($keuringseisen)
{
$this->keuringseisen = $keuringseisen;
return $this;
}
/**
* Get keuringseisen
*
* #return integer
*/
public function getKeuringseisen()
{
return $this->keuringseisen;
}
}
Entity Bestelregel (Link table)
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Bestelregel
*
* #ORM\Table(name="bestelregel")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BestelregelRepository")
*/
class Bestelregel
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\ManyToOne(targetEntity="Artikel", inversedBy="bestelregels")
* #ORM\JoinColumn(name="artikelnummer", referencedColumnName="artikelnummer")
*/
private $artikelnummer;
/**
* #var int
*
* #ORM\ManyToOne(targetEntity="Artikel", inversedBy="bestelregels")
* #ORM\JoinColumn(name="bestelordernummer", referencedColumnName="bestelordernummer")
*/
private $bestelordernummer;
/**
* Set id
*
* #param integer $id
*
* #return Bestelregel
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set artikelnummer
*
* #param integer $artikelnummer
*
* #return Bestelregel
*/
public function setArtikelnummer($artikelnummer)
{
$this->artikelnummer = $artikelnummer;
return $this;
}
/**
* Get artikelnummer
*
* #return integer
*/
public function getArtikelnummer()
{
return $this->artikelnummer;
}
/**
* Set bestelordernummer
*
* #param integer $bestelordernummer
*
* #return Bestelregel
*/
public function setBestelordernummer($bestelordernummer)
{
$this->bestelordernummer = $bestelordernummer;
return $this;
}
/**
* Get bestelordernummer
*
* #return integer
*/
public function getBestelordernummer()
{
return $this->bestelordernummer;
}
}
Form Bestelling
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class BestellingType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
//gebruiken wat je nodig hebt, de id hoeft er niet bij als deze auto increment is
$builder
->add('bestelordernummer', IntegerType::class) //naam is b.v. een attribuut of variabele van klant
;
$builder
->add('leverancier', TextType::class) //naam is b.v. een attribuut of variabele van klant
;
$builder
->add('keuringseisen', TextType::class) //naam is b.v. een attribuut of variabele van klant
;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Bestelling'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_bestelregel';
}
}
Form Bestelregel (Link table)
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class BestelregelType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
//gebruiken wat je nodig hebt, de id hoeft er niet bij als deze auto increment is
$builder
->add('artikelnummer', EntityType::class, array(
'class' => 'AppBundle:Artikel',
'choice_label' => 'artikelnummer'))
;
$builder
->add('bestelordernummer', EntityType::class, array(
'class' => 'AppBundle:Bestelling',
'choice_label' => 'bestelordernummer'))
;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Bestelregel'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_bestelregel';
}
}
Picture Database
You don'e need to add an intermediate entity (bestelregel here), unless it has to have its own unique properties (like the timestamp for which the relation stablished, or the user who stablished the relation or anything else).
In other words, if your bestelregel entity has ONLY this list of properties:
id
artikle
bestelling (or bestelorder or whatever you call it in Dutch)
forget about creating it. you only need these two entity classes:
Beselling
Artikel
Taking advantage of Doctrine ORM relations, the relation database table would be created and manipulated automatically behind the scene.
Also, keep your code in English, as you have the opportunity of a World get in touch in case you need a hand, instead of using Dutch or any other language. You may use translation tools to translate the interface, but use English for your code base as it is a best practice all over the world.
Article entity:
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="`article`")
*/
class Article
{
/**
* #ORM\ManyToMany(targetEntity="Order", mappedBy="articles")
*/
private $orders;
public function __construct() {
$this->orders = new ArrayCollection();
}
public function addOrder(Order $order)
{
if ($this->orders->contains($order)) {
return;
}
$this->orders->add($order);
$order->addArticle($this);
}
public function removeOrder(Order $order)
{
if (!$this->orders->contains($order)) {
return;
}
$this->orders->removeElement($order);
$order->removeArticle($this);
}
}
Order entity:
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="`order`")
*/
class Order
{
/**
* #ORM\ManyToMany(targetEntity="Article", inversedBy="orders")
*/
private $articles;
public function __construct() {
$this->articles = new ArrayCollection();
}
public function addArticle(Article $article)
{
if ($this->articles->contains($article)) {
return;
}
$this->articles->add($article);
$article->addOrder($this);
}
public function removeArticle(Article $article)
{
if (!$this->articles->contains($article)) {
return;
}
$this->articles->removeElement($article);
$article->removeOrder($this);
}
}
OrderType form:
namespace AppBundle\Form;
use AppBundle\Entity\Article;
use AppBundle\Entity\Order;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class OrderType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('articles', EntityType::class, array(
'class' => Article::class,
'expanded' => true,
'multiple' => true,
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Order::class
));
}
}
I had the same exact problem and worked it on the same way as the first answer of this question. The problem was that when the form was rendered as html the checkboxes were rendered as
<input type="checkbox" name="form_name[field_name][]" value ="entityid"/> <input type="checkbox" name ="form_name[field_name][]" value="otherentityid"/>
When the form was submitted only one of the checked checkboxes is submitted
Related
I use the Symfony version 3.4.0 and I try to use this bundle to translate entities : https://github.com/webfactory/WebfactoryPolyglotBundle
So I created two entities ( Film and FilmTranslation ) for the test
Here my Film.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Webfactory\Bundle\PolyglotBundle\Annotation as Polyglot;
use Webfactory\Bundle\PolyglotBundle\TranslatableInterface;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Film
*
* #ORM\Table(name="film")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FilmRepository")
* #Polyglot\Locale(primary="fr_FR")
*/
class Film
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #Polyglot\TranslationCollection
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="Titre", type="string", length=255, unique=true)
* #Polyglot\Translatable
* #var string|TranslatableInterface
*/
private $titre;
/**
* #ORM\OneToMany(targetEntity="FilmTranslation", mappedBy="entity")
* #Polyglot\TranslationCollection
* #var Collection
*/
private $translations;
public function __construct()
{
$this->translations = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
*
* #return Film
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Add translation
*
* #param \AppBundle\Entity\FilmTranslation $translation
*
* #return Film
*/
public function addTranslation(\AppBundle\Entity\FilmTranslation $translation)
{
$this->translations[] = $translation;
return $this;
}
/**
* Remove translation
*
* #param \AppBundle\Entity\FilmTranslation $translation
*/
public function removeTranslation(\AppBundle\Entity\FilmTranslation $translation)
{
$this->translations->removeElement($translation);
}
/**
* Get translations
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTranslations()
{
return $this->translations;
}
}
And here my FilmTranslation.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Webfactory\Bundle\PolyglotBundle\Entity\BaseTranslation;
/**
* FilmTranslation
*
* #ORM\Table(name="film_translation")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FilmTranslationRepository")
* #ORM\Table(
* uniqueConstraints = {
* #ORM\UniqueConstraint(columns={"entity_id", "locale"})
* }
* )
*/
class FilmTranslation extends BaseTranslation
{
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255, unique=true)
*/
private $titre;
/**
* #ORM\ManyToOne(targetEntity="Film", inversedBy="translations")
* #var Film
*/
protected $entity;
/**
* Set titre
*
* #param string $titre
*
* #return FilmTranslation
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set locale
*
* #param string $locale
*
* #return FilmTranslation
*/
public function setLocale($locale)
{
$this->locale = $locale;
return $this;
}
/**
* Set entity
*
* #param \AppBundle\Entity\Film $entity
*
* #return FilmTranslation
*/
public function setEntity(\AppBundle\Entity\Film $entity = null)
{
$this->entity = $entity;
return $this;
}
/**
* Get entity
*
* #return \AppBundle\Entity\Film
*/
public function getEntity()
{
return $this->entity;
}
}
I'm able to create a form but when I try to persist and flush I've the following error :
No mapping found for field 'id' on class 'AppBundle\Entity\Film'.
Is something I'm doing wrong ?
So remove #Polyglot\TranslationCollection from $id annotation like this ;)
class Film
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
I have create Formtype UniversitaireType but I have this error:
attribut condidat_id doesn't create in database when I try command php bin/console doctrine:schema:update --force (all attributs create in database except id_condidat) .. I make mapping OneToMany $condidat in entity Universitaire
code entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Condidat;
/**
* Universitaire.
*
* #ORM\Table(name="universitaires")
* #ORM\Entity(repositoryClass="AppBundle\Entity\UniversitaireEntityRepository")
*/
class Universitaire
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="date_start", type="string", length=255, nullable=true)
*/
private $dateStart;
/**
* #var string
*
* #ORM\Column(name="date_end", type="string", length=255, nullable=true)
*/
private $dateEnd;
/**
* #var string
*
* #ORM\Column(name="establishment", type="string", length=255, nullable=true, unique=true)
*/
private $establishment;
/**
* #var string
*
* #ORM\Column(name="diploma", type="string", length=255, nullable=true, unique=true)
*/
private $diploma;
/**
*#ORM\OneToMany(targetEntity="AppBundle\Entity\Condidat",mappedBy="id_universitaire",cascade={"persist"})
*#ORM\JoinColumn(name="id_condidat", referencedColumnName="id")
*/
private $condidat;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Add Condidat
*
* #param \AppBundle\Entity\Condidat $condidat
* #return Universitaire
*/
public function addCondidat(\AppBundle\Entity\Condidat $condidat)
{
$this->condidat[] = $condidat;
return $this;
}
/**
* Remove Condidat
*
* #param \AppBundle\Entity\Condidat $condidat
*/
public function removeCondidat(\AppBundle\Entity\Condidat $condidat)
{
$this->Condidat->removeElement($condidat);
}
/**
* Get Condidat
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCondidat()
{
return $this->condidat;
}
/**
* Set dateStart.
*
* #param string $dateStart
*
* #return Universitaire
*/
public function setdateStart($dateStart)
{
$this->dateStart = $dateStart;
return $this;
}
/**
* Get dateStart.
*
* #return string
*/
public function getdateStart()
{
return $this->dateStart;
}
/**
* Set dateEnd.
*
* #param string $dateEnd
*
* #return Universitaire
*/
public function setDateEnd($dateEnd)
{
$this->dateEnd = $dateEnd;
return $this;
}
/**
* Get dateEnd.
*
* #return string
*/
public function getdateEnd()
{
return $this->dateEnd;
}
/**
* Set establishment.
*
* #param string $establishment
*
* #return Universitaire
*/
public function setEstablishment($establishment)
{
$this->establishment = $establishment;
return $this;
}
/**
* Get establishment.
*
* #return string
*/
public function getEstablishment()
{
return $this->establishment;
}
/**
* Set diploma.
*
* #param string $diploma
*
* #return Universitaire
*/
public function setDiploma($diploma)
{
$this->diploma = $diploma;
return $this;
}
/**
* Get diploma.
*
* #return string
*/
public function getDiploma()
{
return $this->diploma;
}
public function __construct()
{
$this->ResponsableCategory = new \Doctrine\Common\Collections\ArrayCollection();
}
}
code FormType:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Entity\Universitaire;
use AppBundle\Entity\Condidat;
class UniversitaireType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('dateStart')->add('dateEnd')->add('establishment')->add('diploma')
->add('condidat',null, array(
'class' => 'AppBundle:Condidat',
'choice_label' => 'condidat',));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Universitaire',
"csrf_protection" => "false"
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_universitaire';
}
}
You have two mistakes in your "condidat" property.
You used One-To-Many (Bidirectional). If you want to have only one
candidate per "Universitaire" - then you have to use One-To-One (Bidirectional).
class Universitaire
{
## ...
/**
* Bidirectional One-To-One (Owning Side)
*
* #ORM\OneToOne(
* targetEntity="AppBundle\Entity\Condidat",
* inversedBy="universitaire",
* cascade={"persist", "remove"}
* )
* #ORM\JoinColumn(
* name="condiat_id",
* referencedColumnName="id"
* )
*/
private $condidat;
class Condidat
{
## ...
/**
* Bidirectional One-To-One (Inversed Side)
*
* #ORM\OneToOne(
* targetEntity="AppBundle\Entity\Universitaire",
* mappedBy="condidat",
* )
*/
private $universitaire;
If not, and One-To-Many was exactly you wanted to have, than you have to set in your __construct() that "condidat" is an array collection
public function __construct()
{
$this->condidat = new \Doctrine\Common\Collections\ArrayCollection();
}
If I were you I'd rather use "candidates" with "s" - to show, that this an arrayCollection.
As I've already said - your example is Bidirectional One-To-Many. In this case we use mappedBy and inversedBy. Entity, in which you set Join column is Owning side. And of course JoinColumn has to be in the "Candidate" entity. So:
class Universitaire
{
## ...
/**
* Bidirectional One-To-Many (Owning Side)
* Predicate: One Universitaire can have a lot of candidates
*
* #ORM\OneToMany(
* targetEntity="AppBundle\Entity\Condidat",
* mappedBy="universitaire",
* cascade={"persist", "remove"}
* )
*/
private $condidats;
class Condidat
{
## ...
/**
* Bidirectional Many-To-One (Owning Side)
* Predicate: Each Condidat belongs to one Universitaire
*
* #ORM\ManyToOne(
* targetEntity="AppBundle\Entity\Universitaire",
* inversedBy="condidats",
* )
* #ORM\JoinColumn(
* name="universitaire_id",
* referencedColumnName="id",
* onDelete="SET NULL"
* )
*/
private $universitaire;
I added onDelete="SET NULL". If you delete universitaire then in field universitaire of each "condidate" you will see null value.
I stuck with this for past two days. I am creating bus traveling website. Currently I am in phase of adding new bus to database.
One bus (or all of them) have many amenities (like AirCon, WiFi, Kitchen, ...) and each of these needs to have custom prices. Let says that our bus have AirCon. AirCon for this bus will cost 50 USD but for other bus AirCon might cost 100 USD. To do that I created 3 Entities (Bus Vehicles Entity, Amenities Entity and Bus Vehicles Amenities Entity). Inside Amenities Entity I iwll store Id of bus, ID of amenity and price for that amenity for that bus ID.
Problem is that I can't get it work. I got blank HTML element when rendering form for that field.I can't add or delete multiple amenities and I am not sure why it is not working.
Does someone knows where is the problem?
Here is the code that I use:
Amenities Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Amenities
*
* #ORM\Table(name="amenities", indexes={#ORM\Index(name="administrator_id", columns={"administrator_id"})})
* #ORM\Entity
*/
class Amenities
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100, nullable=true)
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private $createdAt = 'CURRENT_TIMESTAMP';
/**
* #var \DateTime
*
* #ORM\Column(name="modified_at", type="datetime", nullable=false)
*/
private $modifiedAt = 'CURRENT_TIMESTAMP';
/**
* #var \AppBundle\Entity\Users
*
* #ORM\ManyToOne(targetEntity="Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="administrator_id", referencedColumnName="id")
* })
*/
private $administrator;
/**
* #ORM\OneToMany(targetEntity="BusVehiclesAmenities", mappedBy="amenities")
*/
private $amenities;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Amenities
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
*
* #return Amenities
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Constructor
*/
public function __construct()
{
$this->amenities = new ArrayCollection();
}
/**
* Add amenities
*
* #param \AppBundle\Entity\BusVehiclesAmenities $amenities
* #return Amenities
*/
public function addAmenities(BusVehiclesAmenities $amenities)
{
$this->amenities[] = $amenities;
return $this;
}
/**
* Remove amenities
*
* #param \AppBundle\Entity\BusVehiclesAmenities $amenities
*/
public function removeAmenities(BusVehiclesAmenities $amenities)
{
$this->amenities->removeElement($amenities);
}
/**
* Get amenities_bus_vehicles
*
* #return ArrayCollection
*/
public function getAmenities()
{
return $this->amenities;
}
}
Bus Vehicles Entity:
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* BusVehicles
*
* #ORM\Table(name="bus_vehicles", indexes={#ORM\Index(name="company_id", columns={"company_id"}), #ORM\Index(name="bus_type", columns={"bus_type"}), #ORM\Index(name="fuel_type", columns={"fuel_type"}), #ORM\Index(name="emission_class", columns={"emission_class"})})
* #ORM\Entity
*/
class BusVehicles
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="licence_plate", type="string", length=100, nullable=false)
*/
private $licencePlate;
/**
* #var \AppBundle\Entity\Companies
*
* #ORM\ManyToOne(targetEntity="Companies")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="company_id", referencedColumnName="id")
* })
*/
private $company;
/**
* #var \AppBundle\Entity\BusTypes
*
* #ORM\ManyToOne(targetEntity="BusTypes", inversedBy="busType")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="bus_type", referencedColumnName="id")
* })
*/
/**
* #ORM\OneToMany(targetEntity="BusVehiclesAmenities", mappedBy="bus")
*/
private $busVehiclesAmenities;
public function __construct()
{
$this->busVehiclesAmenities = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add busVehiclesAmenities
*
* #param \AppBundle\Entity\BusVehiclesAmenities busVehiclesAmenities
* #return BusVehicles
*/
public function addBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
{
$this->busVehiclesAmenities[] = $busVehiclesAmenities;
return $this;
}
/**
* Remove busVehiclesAmenities
*
* #param \AppBundle\Entity\BusVehiclesAmenities $busVehiclesAmenities
*/
public function removeBusVehiclesAmenities(BusVehiclesAmenities $busVehiclesAmenities)
{
$this->busVehiclesAmenities->removeElement($busVehiclesAmenities);
}
/**
* Get busVehiclesAmenities
*
* #return ArrayCollection
*/
public function getBusVehiclesAmenities()
{
return $this->busVehiclesAmenities;
}
/**
* Set licencePlate
*
* #param string $licencePlate
*
* #return BusVehicles
*/
public function setLicencePlate($licencePlate)
{
$this->licencePlate = $licencePlate;
return $this;
}
/**
* Set company
*
* #param \AppBundle\Entity\Companies $company
*
* #return BusVehicles
*/
public function setCompany(Companies $company = null)
{
$this->company = $company;
return $this;
}
/**
* Get company
*
* #return \AppBundle\Entity\Companies
*/
public function getCompany()
{
return $this->company;
}
}
Bus Amenities Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* BusVehiclesAmenities
*
* #ORM\Table(name="bus_vehicles_amenities", indexes={#ORM\Index(name="amenities_id", columns={"amenities_id"}), #ORM\Index(name="bus_id", columns={"bus_id"})})
* #ORM\Entity
*/
class BusVehiclesAmenities
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
*
* #ORM\ManyToOne(targetEntity="BusVehicles", inversedBy="busVehiclesAmenities")
* #ORM\JoinColumn(name="bus_id", referencedColumnName="id")
*
*/
private $bus;
/**
*
* #ORM\ManyToOne(targetEntity="Amenities", inversedBy="amenities")
* #ORM\JoinColumn(name="amenities_id", referencedColumnName="id")
*
*/
private $amenities;
/**
* #var float
* #ORM\Column(name="price", type="float", scale=2)
*/
protected $price;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Bus
*
* #param \AppBundle\Entity\BusVehicles
*
* #return BusVehiclesAmenities
*/
public function setBus($bus)
{
$this->bus = $bus;
return $this;
}
/**
* Get busId
*
* #return integer
*/
public function getBus()
{
return $this->bus;
}
/**
* Set amenities
*
* #param \AppBundle\Entity\Amenities
*
* #return BusVehiclesAmenities
*/
public function setAmenities($amenities)
{
$this->amenities = $amenities;
return $this;
}
/**
* Get amenities
*
* #return \AppBundle\Entity\Amenities
*/
public function getAmenities()
{
return $this->amenities;
}
/**
* Set price
*
* #param float $price
*
* #return BusVehiclesAmenities
*/
public function sePrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return float
*/
public function getPrice()
{
return $this->price;
}
}
FORMS:
Add new bus form:
<?php
namespace AdminBundle\Form\Type;
use AdminBundle\Form\Type\BusVehiclesAmenitiesType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class BusVehiclesType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('licencePlate')
->add('company', EntityType::class, array(
'class' => 'AppBundle:Companies',
'choice_label' => 'name',
->add('busVehiclesAmenities', CollectionType::class, array(
'entry_type' => BusVehiclesAmenitiesType::class,
'allow_add' => true,
));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\BusVehicles'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'adminbundle_busvehicles';
}
}
Bus Vehicles Amenities Form
<?php
namespace AdminBundle\Form\Type;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\FormBuilderInterface;
use AppBundle\Entity\BusVehiclesAmenities;
use Symfony\Component\OptionsResolver\OptionsResolver;
class BusVehiclesAmenitiesType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('price', MoneyType::class, array(
'scale' => 2,
))
->add('amenities', EntityType::class, array(
'class' =>'AppBundle:Amenities',
'choice_label' => 'name',
))
;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => BusVehiclesAmenities::class
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_busvehiclesamenities';
}
}
I would not use the entity classes for form binding.
I would create a new class, (e.g. BusVehicle) which contains all properties that need to be on the form (particular fields) and use that as the 'data_class'. This way you would not only solve your problem, but you would also decouple presentation layer from business layer (see Multitier Architecture).
I usually put these classes in Form/Model directory.
In your case the class would be Form/Model/BusVehicle, and it would have $amenities property.
The amenities would be an array of Form/Model/Amenity objects.
You would probably need to use embedded forms just don't use entity classes as 'data_object'. After a successful bind, you instantiate and populate entities for persist or update.
And you don't need the third entity ("Bus Vehicles Amenities").
sorry for my poor inglish, I have two entities called USER and DATA
Here the code of the USER entity:
<?php
namespace Proyecto\LavocBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Proyecto\LavocBundle\Entity\UserRepository")
*/
class User {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="usuario", type="string", length=30)
*/
private $usuario;
/**
* #var string
*
* #ORM\Column(name="pass", type="string", length=20)
*/
private $pass;
/**
* #ORM\OneToMany(targetEntity="Pedido", mappedBy="user")
*/
private $pedidos;
/**
* #ORM\OneToOne(targetEntity="Datos", mappedBy="personales")
*/
private $datos;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set usuario
*
* #param string $usuario
* #return User
*/
public function setUsuario($usuario) {
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario() {
return $this->usuario;
}
/**
* Set pass
*
* #param string $pass
* #return User
*/
public function setPass($pass) {
$this->pass = $pass;
return $this;
}
/**
* Get pass
*
* #return string
*/
public function getPass() {
return $this->pass;
}
public function __construct() {
$this->pedidos = new ArrayCollection();
}
/**
* Set pedidos
*
* #param string $pedidos
* #return User
*/
public function setPedido($pedidos) {
$this->pedidos = $pedidos;
return $this;
}
/**
* Get pedidos
*
* #return string
*/
public function getPedidos() {
return $this->pedidos;
}
/**
* Add pedidos
*
* #param \UTN\GuardaBundle\Entity\Pedido $pedidos
* #return User
*/
public function addPedido(\Proyecto\LavocBundle\Entity\Pedido $pedidos) {
$this->pedidos[] = $pedidos;
return $this;
}
/**
* Remove pedidos
*
* #param \UTN\GuardaBundle\Entity\Pedido $pedidos
*/
public function removePedido(\Proyecto\LavocBundle\Entity\Pedido $pedidos) {
$this->pedidos->removeElement($pedidos);
}
/**
* Get datos
*
* #return string
*/
public function getDatos()
{
return $this->datos;
}
/**
* Set datos
*
* #param string $datos
* #return User
*/
public function setDatos($datos)
{
$this->datos = $datos;
return $this;
}
}
Here the code of the DATA entity:
<?php
namespace Proyecto\LavocBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Datos
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Proyecto\LavocBundle\Entity\DatosRepository")
*/
class Datos
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="empresa", type="string", length=50)
*/
private $empresa;
/**
* #var integer
*
* #ORM\Column(name="cuit", type="integer")
*/
private $cuit;
/**
* #var string
*
* #ORM\Column(name="localidad", type="string", length=50)
*/
private $localidad;
/**
* #var string
*
* #ORM\Column(name="calle", type="string", length=40)
*/
private $calle;
/**
* #var integer
*
* #ORM\Column(name="altura", type="integer")
*/
private $altura;
/**
* #var integer
*
* #ORM\Column(name="areaTel", type="integer")
*/
private $areaTel;
/**
* #var integer
*
* #ORM\Column(name="telefono", type="integer")
*/
private $telefono;
/**
* #var integer
*
* #ORM\Column(name="areaCel", type="integer")
*/
private $areaCel;
/**
* #var integer
*
* #ORM\Column(name="celular", type="integer")
*/
private $celular;
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="datos")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* #Assert\Type(type="Proyecto\LavocBundle\Entity\User")
*/
private $personales;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set empresa
*
* #param string $empresa
* #return Datos
*/
public function setEmpresa($empresa)
{
$this->empresa = $empresa;
return $this;
}
/**
* Get empresa
*
* #return string
*/
public function getEmpresa()
{
return $this->empresa;
}
/**
* Set cuit
*
* #param integer $cuit
* #return Datos
*/
public function setCuit($cuit)
{
$this->cuit = $cuit;
return $this;
}
/**
* Get cuit
*
* #return integer
*/
public function getCuit()
{
return $this->cuit;
}
/**
* Set localidad
*
* #param string $localidad
* #return Datos
*/
public function setLocalidad($localidad)
{
$this->localidad = $localidad;
return $this;
}
/**
* Get localidad
*
* #return string
*/
public function getLocalidad()
{
return $this->localidad;
}
/**
* Set calle
*
* #param string $calle
* #return Datos
*/
public function setCalle($calle)
{
$this->calle = $calle;
return $this;
}
/**
* Get calle
*
* #return string
*/
public function getCalle()
{
return $this->calle;
}
/**
* Set altura
*
* #param integer $altura
* #return Datos
*/
public function setAltura($altura)
{
$this->altura = $altura;
return $this;
}
/**
* Get altura
*
* #return integer
*/
public function getAltura()
{
return $this->altura;
}
/**
* Set telefono
*
* #param integer $telefono
* #return Datos
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
return $this;
}
/**
* Get telefono
*
* #return integer
*/
public function getTelefono()
{
return $this->telefono;
}
/**
* Set area
*
* #param integer $area
* #return Datos
*/
public function setAreaTel($areaTel)
{
$this->areaTel = $areaTel;
return $this;
}
/**
* Get area
*
* #return integer
*/
public function getAreaTel()
{
return $this->areaTel;
}
/**
* Set celular
*
* #param integer $celular
* #return Datos
*/
public function setCelular($celular)
{
$this->celular = $celular;
return $this;
}
/**
* Get celular
*
* #return integer
*/
public function getCelular()
{
return $this->celular;
}
/**
* Set areaCel
*
* #param integer $areaCel
* #return Datos
*/
public function setAreaCel($areaCel)
{
$this->areaCel = $areaCel;
return $this;
}
/**
* Get areaCel
*
* #return integer
*/
public function getAreaCel()
{
return $this->areaCel;
}
/**
* Set personales
*
* #param string $personales
* #return Datos
*/
public function setPersonales($personales)
{
$this->personales = $personales;
return $this;
}
/**
* Get personales
*
* #return string
*/
public function getPersonales()
{
return $this->personales;
}
}
The property that link User with Data is $data and the property that link Data with User is $personales.
I have a UserType and a DatosType:
Here the code of UserType:
<?php
namespace Proyecto\LavocBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('usuario');
$builder->add('pass');
}
public function getName()
{
return 'user_form';
}
}
and here the DatosType:
<?php
namespace Proyecto\LavocBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class DatosType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('empresa');
$builder->add('cuit');
$builder->add('localidad');
$builder->add('calle');
$builder->add('altura');
$builder->add('areaTel');
$builder->add('telefono');
$builder->add('areaCel');
$builder->add('celular');
}
public function getName()
{
return 'datos_form';
}
}
I have to make a form where they are the two forms. I would like to know how is the code to embed and as an actuary the controller to both generate the form and send it to the template as to receive data and store user data in a table called USER and save data DATA in the DATA table . Thanks and sorry for the inconvenience.
In your UserType you can embed your DatosType like so:
->add('datos', new DatosType())
However in DatosType you should have data_class set like so:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Proyecto\LavocBundle\Entity\Datos',
));
}
You should have a good read of the forms documentation as almost all you need is in there.
I have a problem with my project in Symfony 2 i get this error
Catchable Fatal Error: Object of class Nicearma\MemesBundle\Entity\Usuario could not be converted to string in C:\wamp\www\24memes\vendor\doctrine-dbal\lib\Doctrine\DBAL\Statement.php line 131
The problem is, that i trying to do a form, from UsuarioInfo class, and this class have one object Usuario, the form work fine, but went send the information i get the message
And i dont find the solution, anyone knows how fix this?
I have this files
registro.html.twig
<div class="usuario">
{{ form_row(form.usuario) }}
</div>
{{ form_rest(form) }}
Usuario.php
namespace Nicearma\MemesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Nicearma\MemesBundle\Entity\Usuario
*
* #ORM\Table(name="usuario")
* #ORM\Entity(repositoryClass="Nicearma\MemesBundle\Repository\Usuario")
*/
class Usuario implements UserInterface
{
/**
* #var integer $id
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $nombre
* #Assert\Type(type="String")
* #Assert\MaxLength(255)
* #Assert\NotBlank
* #ORM\Column(name="nombre", type="string", length=255, nullable=false)
*/
private $nombre;
/**
* #var string $clave
* #Assert\NotBlank
* #Assert\Type(type="String")
* #Assert\MaxLength(255)
* #ORM\Column(name="clave", type="string", length=255, nullable=false)
*/
private $clave;
/**
* #var integer $punto
*
* #ORM\Column(name="punto", type="integer", nullable=false)
*/
private $punto;
/**
* #var UsuarioEstado
*
* #ORM\ManyToOne(targetEntity="UsuarioEstado")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_usuario_estado", referencedColumnName="id")
* })
*/
private $UsuarioEstado;
/**
* #var IdUsuarioEstado
* #ORM\Column(name="id_usuario_estado", type="integer", nullable=false)
* })
*/
private $idUsuarioEstado;
/**
* #var UsuarioTipo
*
* #ORM\ManyToOne(targetEntity="UsuarioTipo")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_usuario_tipo", referencedColumnName="id")
* })
*/
private $UsuarioTipo;
/**
* #var idUsuarioTipo
* #ORM\Column(name="id_usuario_tipo", type="integer", nullable=false)
*/
private $idUsuarioTipo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* #param string $nombre
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set punto
*
* #param integer $punto
*/
public function setPunto($punto)
{
$this->punto = $punto;
}
/**
* Get punto
*
* #return integer
*/
public function getPunto()
{
return $this->punto;
}
/**
* Set UsuarioEstado
*
* #param Nicearma\MemesBundle\Entity\UsuarioEstado $idUsuarioEstado
*/
public function setUsuarioEstado(\Nicearma\MemesBundle\Entity\UsuarioEstado $UsuarioEstado)
{
$this->UsuarioEstado = $UsuarioEstado;
}
/**
* Get UsuarioEstado
*
* #return Nicearma\MemesBundle\Entity\UsuarioEstado
*/
public function getUsuarioEstado()
{
return $this->UsuarioEstado;
}
/**
* Set idUsuarioEstado
*
* #param integer $idUsuarioEstado
*/
public function setIdUsuarioEstado( $idUsuarioEstado)
{
$this->idUsuarioEstado = $idUsuarioEstado;
}
/**
* Get idUsuarioEstado
*
* #return integer
*/
public function getIdUsuarioEstado()
{
return $this->idUsuarioEstado;
}
/**
* Set UsuarioTipo
*
* #param Nicearma\MemesBundle\Entity\UsuarioTipo $idUsuarioTipo
*/
public function setUsuarioTipo(\Nicearma\MemesBundle\Entity\UsuarioTipo $UsuarioTipo)
{
$this->UsuarioTipo = $UsuarioTipo;
}
/**
* Get UsuarioTipo
*
* #return Nicearma\MemesBundle\Entity\UsuarioTipo
*/
public function getUsuarioTipo()
{
return $this->UsuarioTipo;
}
/**
* Set idUsuarioTipo
*
* #param integer $idUsuarioTipo
*/
public function setIdUsuarioTipo( $idUsuarioTipo)
{
$this->idUsuarioTipo = $idUsuarioTipo;
}
/**
* Get idUsuarioTipo
*
* #return integer
*/
public function getIdUsuarioTipo()
{
return $this->idUsuarioTipo;
}
public function equals(UserInterface $user)
{
return $this->username === $user->getUsername();
}
public function eraseCredentials() {
}
public function getPassword() {
return $this->clave;
}
public function getRoles() {
$this->idUsuarioTipo->getTipo();
}
public function getSalt() {
return null;
}
public function getUsername() {
return $this->nombre;
}
/**
* Set clave
*
* #param string $clave
*/
public function setClave($clave)
{
$this->clave = $clave;
}
/**
* Get clave
*
* #return string
*/
public function getClave()
{
return $this->clave;
}
}
UsuarioType.php
namespace Nicearma\MemesBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class UsuarioType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('nombre')
->add('clave')
;
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Nicearma\MemesBundle\Entity\Usuario',
);
}
public function getName()
{
return 'Usuario';
}
}
usuarioInfo.php
namespace Nicearma\MemesBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Nicearma\MemesBundle\Entity\UsuarioInfo
*
* #ORM\Table(name="usuario_info")
* #ORM\Entity
*/
class UsuarioInfo
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $correo
* Assert\Email
* #ORM\Column(name="correo", type="string", length=255, nullable=false)
*/
private $correo;
/**
* #var Usuario
* #Assert\Type(type="Nicearma\MemesBundle\Entity\Usuario")
* #ORM\OneToOne(targetEntity="Usuario")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_usuario", referencedColumnName="id")
* })
*/
private $Usuario;
/**
* #var idUsuario
* #ORM\Column(name="id_usuario", type="integer", nullable=false)
*/
private $idUsuario;
/**
* #var Nacionalidad
* #Assert\Type(type="Nicearma\MemesBundle\Entity\Nacionalidad")
* #ORM\ManyToOne(targetEntity="Nacionalidad")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_pais", referencedColumnName="id")
* })
*/
private $Pais;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set correo
*
* #param string $correo
*/
public function setCorreo($correo)
{
$this->correo = $correo;
}
/**
* Get correo
*
* #return string
*/
public function getCorreo()
{
return $this->correo;
}
/**
* Set Usuario
*
* #param Nicearma\MemesBundle\Entity\Usuario $Usuario
*/
public function setUsuario(\Nicearma\MemesBundle\Entity\Usuario $Usuario)
{
$this->Usuario = $Usuario;
}
/**
* Get Usuario
*
* #return Nicearma\MemesBundle\Entity\Usuario
*/
public function getUsuario()
{
return $this->Usuario;
}
/**
* Set Pais
*
* #param Nicearma\MemesBundle\Entity\Nacionalidad $Pais
*/
public function setPais(\Nicearma\MemesBundle\Entity\Nacionalidad $Pais)
{
$this->Pais = $Pais;
}
/**
* Get Pais
*
* #return Nicearma\MemesBundle\Entity\Nacionalidad
*/
public function getPais()
{
return $this->Pais;
}
}
usuarioInfoType.php
namespace Nicearma\MemesBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Doctrine\ORM\EntityRepository;
class UsuarioInfoType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('correo')
->add('pais', 'entity', array ('class'=>'Nicearma\\MemesBundle\\Entity\\Nacionalidad','property'=>'nom_pais'))
->add('usuario',new UsuarioType);
;
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Nicearma\MemesBundle\Entity\UsuarioInfo',
);
}
public function getName()
{
return 'UsuarioInfo';
}
}
And the controller is
public function registroAction(Request $peticion){
$regUs= new \Nicearma\MemesBundle\Entity\UsuarioInfo();
$formulario = $this->createForm(new \Nicearma\MemesBundle\Form\UsuarioInfoType(), $regUs);
if ($peticion->getMethod() == 'POST') {
$formulario->bindRequest($peticion);
if ($formulario->isValid()) {
// $regUs->setIdUsuario(1);
$em = $this->getDoctrine()->getEntityManager();
$
$em->persist($regUs);
$em->flush();
$base->flush();
return $this->redirect($this->generateUrl('DenunciaEnviada'));
}else{
}
}
return $this->render('NicearmaMemesBundle:Usuario:usuarioRegistro.html.twig', array('form' => $formulario->createView(),'titulo'=>'Crear usuario','descripcion'=>'usuario','claves'=>'us','nombre'=>'Prueba usuario'));
}
So Simple, It is returning you the object of the relation class.
--> you are using getter method of the main class on which you have applied query on that further use getter method of of the relation class.
for example
$exp->getExperiencesCompany()->getName();
With a OneToOne relationship, you should use the JoinColumn annotation instead of what you're doing "JoinColumns(JoinColumn)".
You can see the example from the doctrine orm documentation http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-one-bidirectional
So, you can first try to update UsuarioInfo's "Usuario"'s property annotations
/**
* #var Usuario
* #Assert\Type(type="Nicearma\MemesBundle\Entity\Usuario")
* #ORM\OneToOne(targetEntity="Usuario")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_usuario", referencedColumnName="id")
* })
*/
private $Usuario;
to
/**
* #var Usuario
* #Assert\Type(type="Nicearma\MemesBundle\Entity\Usuario")
* #ORM\OneToOne(targetEntity="Usuario")
* #ORM\JoinColumn(name="id_usuario", referencedColumnName="id")
*/
private $Usuario;
The same should apply to Usuario's "UsuarioEstado", "UsuarioTipo" properties. See the example annotation for ManyToOne http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-one-unidirectional
So make sure you properly configurer your entities by checking you're using the right annotations, and then try again :)