Bidirectionnal relation in form - symfony

i'm having difficulties to save a form that contains a collection from a OneToMany bidirectionnal relation.
I got the following error :
An exception occurred while executing 'INSERT INTO fieldsgroup (title, colloque_id) VALUES (?, ?)' with params ["groupe 1", null]:
Here are the queries that the profiler gives me :
START TRANSACTION;
INSERT INTO colloque (title)
VALUES
('titre du colloque');
INSERT INTO fieldsgroup (title, colloque_id)
VALUES
('titre de mon groupe de champs', null)
ROLLBACK
My controller :
public function createColloqueAction()
{
$colloque = new Colloque();
$form = $this->createForm(new ColloqueType, $colloque);
$request = $this->get('request');
if ($request->getMethod() == 'POST'){
$form->bind($request);
if ($form->isValid()) {
$this->get('session')->getFlashBag()->add('notice', 'Colloque correctement enregistré');
$em = $this->getDoctrine()->getManager();
$em->persist($colloque);
$em->flush();
return $this->redirect($this->generateUrl('ptolemee_admin_homepage'));
}
}
return $this->render('PtolemeeAdminBundle:Admin:createColloque.html.twig',array(
'form' => $form->createView()
));
}
My "Colloque" entity :
class Colloque
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Ptolemee\ColloqueBundle\Entity\FieldsGroup", mappedBy="colloque", cascade={"persist"})
*/
private $fieldsGroups;
public function __construct()
{
$this->fieldsGroups = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add fieldsGroups
*
* #param \Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups
* #return Colloque
*/
public function addFieldsGroup(\Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups)
{
$this->fieldsGroups[] = $fieldsGroups;
$fieldsGroups->setColloque($this);
return $this;
}
/**
* Remove fieldsGroups
*
* #param \Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups
*/
public function removeFieldsGroup(\Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups)
{
$this->fieldsGroups->removeElement($fieldsGroups);
}
/**
* Get fieldsGroups
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFieldsGroups()
{
return $this->fieldsGroups;
}
}
Its form, ColloqueType :
class ColloqueType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text')
->add('date', 'datetime')
->add('successMessage', 'textarea')
->add('fieldsGroups', 'collection', array( 'type' => new FieldsGroupType(),
'allow_add' => true,
'allow_delete' => true))
;
}
}
My class FieldsGroup
class FieldsGroup
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Ptolemee\ColloqueBundle\Entity\Colloque", inversedBy="fieldsGroups")
* #ORM\JoinColumn(nullable=false)
*/
private $colloque;
/**
* Set colloque
*
* #param \Ptolemee\ColloqueBundle\Entity\Colloque $colloque
* #return FieldsGroup
*/
public function setColloque(\Ptolemee\ColloqueBundle\Entity\Colloque $colloque)
{
$this->colloque = $colloque;
return $this;
}
/**
* Get colloque
*
* #return \Ptolemee\ColloqueBundle\Entity\Colloque
*/
public function getColloque()
{
return $this->colloque;
}
}
And its form, FieldsGroupType :
class FieldsGroupType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text')
/*->add('fields', 'collection', array('type' => new FieldType(),
'allow_add' => true,
'allow_delete' => true))*/
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ptolemee\ColloqueBundle\Entity\FieldsGroup'
));
}
/**
* #return string
*/
public function getName()
{
return 'ptolemee_colloquebundle_fieldsgroup';
}
}
I know this should work properly without any more perist(), or anything else...
Any help would be highly appreciated, i've been working on that for hours without finding what's the right way to do....
Thanks a lot !

Just add setFieldsGroup(ArrayCollection) to your entity
public function addFieldsGroup(\Ptolemee\ColloqueBundle\Entity\FieldsGroup $fieldsGroups)
{
$this->fieldsGroups[] = $fieldsGroups;
$fieldsGroups->setColloque($this);
return $this;
}
public function setFieldsGroup(ArrayCollection $fieldsGroups)
{
foreach ($fieldsGroups as $fieldsGroup) {
$fieldsGroup->setColloque($this);
}
$this->fieldsGroups = $fieldsGroups;
}

Adding setFieldsGroup(ArrayCollection) is working but it's a trick.
Simply add , cascade={"persist"} to your ManyToOne field
/**
* #ORM\ManyToOne(targetEntity="Ptolemee\ColloqueBundle\Entity\Colloque", inversedBy="fieldsGroups", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $colloque;
PS1 :
Prefer handleRequest() instead of $request->getMethod() == 'POST' and $form->bind($request) if you have Symfony2.x x>=3.
PS2 :
You can get request like this when needed (more elegant way) :
public function createColloqueAction(Request $request)

Related

Vichuploader not work on production server

I have a problem since 2 days! I try to upload file with vichuploaderBundle on a symfony 3.4 project.
I've already done this many times. But this time...It doesn't work and i don't understand why. On my local version, it work fine but on my production server it doesn't work.
Here is the error message:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image_name' cannot be null
The file entity is persisted (with an id and a created date but the image name is empty???)it's like the vichuploader mapping doesn't work???
I have an Entity (NoteFrais) and each NoteFrais has a one relation with an another Entity (JustificatifDefraiement).
here is my JustificatifDefraiement entity:
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* JustificatifDefraiement
*
* #ORM\Table(name="justificatif_defraiement")
* #ORM\Entity(repositoryClass="MKG\MystiBundle\Repository \JustificatifDefraiementRepository")
* #vich\Uploadable
*/
class JustificatifDefraiement
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="justificatif", fileNameProperty="imageName")
*
* #var File
*/
private $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
private $imageName;
/**
* #ORM\Column(type="datetime")
*
* #var \DateTime
*/
private $updatedAt;
/**
* Constructor
*/
public function __construct()
{
$this->updatedAt = new \DateTime();
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|UploadedFile $justificatifDefraiement
* #return JustificatifDefraiement
*/
public function setImageFile(File $justificatifDefraiement = null)
{
$this->imageFile = $justificatifDefraiement;
if ($justificatifDefraiement) {
$this->updatedAt = new \DateTime();
}
return $this;
}
/**
* #return File|null
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
*
* #param $imageName
*
* #return $this
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* #return string|null
*/
public function getImageName()
{
return $this->imageName;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
*
* #return JustificatifDefraiement
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
}
My form:
class JustificatifDefraiementType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('imageFile', FileType::class, array(
//'data_class' => null,
'label' => false,
'required' => true,
'attr' => array(
'class' => 'NoteFraisBootstrapFileInput',
'type' => 'file',
'placeholder' => 'Selectionner un justificatif (jpeg, png, jpg, pdf)',
'data-preview-file-type' => 'text',
'data-allowed-file-extensions' => '["jpeg", "png", "jpg", "pdf"]',
)
));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MKG\MystiBundle\Entity\JustificatifDefraiement'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'mkg_mystibundle_justificatifDefraiement';
}
}
The configuration:
parameters:
locale: fr
app.path.logos: /uploads/logos
app.path.imports: /uploads/imports
app.path.justificatifs: /uploads/justificatifs
I have this relation with another entity:
class NoteFrais
{
//.......//
/**
* #ORM\OneToOne(targetEntity="MKG\MystiBundle\Entity\JustificatifDefraiement", cascade={"persist"})
* #ORM\JoinColumn(name="justificatif_defraiement_id", referencedColumnName="id", onDelete="CASCADE", nullable=true)
*/
private $justificatifDefraiement;
//.......//
}
And the noteFraisType:
class NoteFraisType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//.......//
->add('justificatifDefraiement', JustificatifDefraiementType::class, array(
'required' => false));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MKG\MystiBundle\Entity\NoteFrais'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'mkg_mystibundle_notefrais';
}
}
Please help me!!
When you use VichUploader then you must use VichFileType inside your FormType
Then your buildForm ...
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('imageFile', VichFileType::class, array(
//Options ...
));
}

symfony object could not be converted to string

i'm newbie in symfony and I'm trying to implement a Data Transformer. I followed the documentation and looked different solutions posted in here. But I haven't found what is wrong with my code.
I'm getting this error:
Catchable Fatal Error: Object of class AppBundle\Entity\Todo could not be converted to string
If someone knows another post with the solution, please tell me know where I could look for it.
Thank you in advance.
So, these are my Entities. Todo class
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Todo
*
* #ORM\Table(name="todo")
* #ORM\Entity(repositoryClass="AppBundle\Repository\TodoRepository")
*/
class Todo
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=20)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="category", type="string", length=20)
*/
private $category;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=10)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="priority", type="string", length=10)
*/
private $priority;
/**
*
* #ORM\ManyToOne(
* targetEntity="AppBundle\Entity\User",
* inversedBy="todos"
* )
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $creatorId;
//... getters and setters
User class:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* #ORM\OneToMany(
* targetEntity="AppBundle\Entity\Todo",
* mappedBy="creatorId"
* )
*/
private $todos;
}
In the User class, I don't have getter/setters
My TodoType
class TodoType extends AbstractType{
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, array(
'label' => 'Name',
'required' => true
)
)
->add('category', TextType::class, array(
'label' => 'Category'
)
)
->add('priority', EntityType::class, array(
'class' => 'AppBundle:Todo',
'choice_label' => 'priority',
)
)
->add('creatorId', TextType::class, array(
'label' => 'creator Id:',
));
$builder->get('creatorId')
->addModelTransformer(new IssueToNumberTransformer($this->manager));
}
public function getName()
{
return 'todo';
}
}
Transformer
<?php
namespace FOS\UserBundle\Form\DataTransformer;
use AppBundle\Entity\User;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class IssueToNumberTransformer implements DataTransformerInterface
{
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
/**
* Transforms an object (creatorId) to a string (number).
*
* #param creatorId|null $creatorId
* #return string
*/
public function transform($creatorId)
{
if (null === $creatorId) {
return '';
}
return $creatorId->getId();
}
/**
* Transforms a string (number) to an object (creatorId).
*
* #param string $creatorId
* #return creatorId|null
* #throws TransformationFailedException if object (creatorId) is not found.
*/
public function reverseTransform($creatorId)
{
// no issue number? It's optional, so that's ok
if (!$creatorId) {
return;
}
$creatorId = $this->manager
->getRepository('AppBundle:User')
// query for the issue with this id
->find($creatorId);
if (null === $creatorId) {
throw new TransformationFailedException(sprintf(
'A user with number "%s" does not exist!',
$creatorId
));
}
return $creatorId;
}
}
Controller (function)
public function createAction(Request $request){
$em = $this->getDoctrine()->getManager();
// 1) build the form
$todo = new Todo();
$form = $this->createForm(new TodoType($em), $todo);
// 2) handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 3) save the Todo!
$em->persist($todo);
$em->flush();
return $this->redirectToRoute('todo_create');
}
return $this->render('todo/create.html.twig', array(
'todo'=>$todo,
'form'=>$form->createView()
));
}
It's at this part:
return $this->render('todo/create.html.twig', array(
'todo'=>$todo,
'form'=>$form->createView()
));
Because you are trying to pass the $todo object to your Twig template. You can't do that. What do you need? If you just need the Todo name and you have created getters/setter, you could instead do like this:
return $this->render('todo/create.html.twig', array(
'todo_name' => $todo->getName(),
'form' => $form->createView()
));
Hopefully that makes sense.
EDIT #2 based on comments.
Also this line is wrong in your controller:
$form = $this->createForm(new TodoType($em), $todo);
Should be like this:
$form = $this->createForm(TodoType::class, $todo);

How to list entity in form

I have an entity Hall which can either welcome another hall(subhall), or a stand.
I'm stuck with the hall form (or at least it's what I think needs to be edited).
I can't figure out how to have it display a <select> of all hall with parent=0
I also need a default option which will be blank with 0 as value
Here are my files:
Hall Entity:
<?php
namespace SalonBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Hall
*
* #ORM\Table(name="hall")
* #ORM\Entity(repositoryClass="SalonBundle\Repository\HallRepository")
*/
class Hall {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $idHall;
/**
* #var string
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var integer
* #ORM\Column(name="parent", type="integer", options={"default":0})
*/
private $parent;
/**
* #var
* #ORM\OneToMany(targetEntity="SalonBundle\Entity\Stand", mappedBy="hall")
*/
private $stand;
public function __construct()
{
$this->stand = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get idHall
* #return integer
*/
public function getIdHall()
{
return $this->idHall;
}
/**
* Set name
* #param string $name
* #return Hall
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set parent
* #param integer $parent
* #return Hall
*/
public function setParent($parent)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
* #return string
*/
public function getParent()
{
return $this->parent;
}
/**
* Add stand
* #param \SalonBundle\Entity\Stand $stand
* #return Hall
*/
public function addStand(\SalonBundle\Entity\Stand $stand)
{
$this->stand[] = $stand;
return $this;
}
/**
* Remove stand
* #param \SalonBundle\Entity\Stand $stand
*/
public function removeStand(\SalonBundle\Entity\Stand $stand)
{
$this->stand->removeElement($stand);
}
/**
* Get stand
* #return \Doctrine\Common\Collections\Collection
*/
public function getStand()
{
return $this->stand;
}
/**
* toString
* #return string
*/
public function __toString() {
return $this->getName();
}
}
Hall Form :
<?php
namespace SalonBundle\Form;
use SalonBundle\Entity\Hall;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class HallType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('parent') // Need to complete this part
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'SalonBundle\Entity\Hall'
));
}
}
How should I proceed ?
With the 'query_builder' option you can filter the entities:
http://symfony.com/doc/current/reference/forms/types/entity.html#ref-form-entity-query-builder
$builder->add('users', EntityType::class, array(
'class' => 'AppBundle:User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
'choice_label' => 'username',
));
I guess you use Doctrine so try the EntityType:
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
$builder->add('nom')
->add('description')
->add('parent', EntityType::class, [
'class' => 'SalonBundle:Hall',
'choice_label' => 'nom',
'choice_value' => 'idHall'
])
->add([...]);
}

Doctrine cascade persistence never check if object exists Symfony 2

I have a form which save queries. This is organized in the way of a people who ask is saved also this create a threat where is saving the id_question and emailperson. The issue is that the same person does another question. Logically, this report a primary key error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'drj00003#ujaen.es' for key 'PRIMARY'
How do I fix it? In the constructor of class I cannot check if this exists and all registers are generated automatically in cascade without form.
It should be easy but I can't solve this.
class HiloType extends AbstractType{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('consultanteemail', new ConsultanteType(), array ('label' => false))
->add('personalemail', 'entity', array(
'label' => 'Personal de Soporte',
'class' => 'GuiasDocentes\AppBundle\Entity\Personal',
'property' => 'Enunciado',
'by_reference' => 'false',
'query_builder' => function(PersonalRepository $pr) {
$query= $pr->createQueryBuilder('u')
;
return $query;
},
'empty_value' => 'Elige un perfil de consulta:',
))
;
}
...
class Hilo{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \GuiasDocentes\AppBundle\Entity\Personal
*
* #ORM\ManyToOne(targetEntity="Personal", inversedBy="hilos", cascade ={"ALL"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="personalEmail", referencedColumnName="email")
* })
*/
private $personalemail;
/**
* #var \GuiasDocentes\AppBundle\Entity\Consultante
*
* #ORM\ManyToOne(targetEntity="Consultante", inversedBy="hilos", cascade ={"ALL"} )
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="consultanteEmail", referencedColumnName="email")
* })
*/
private $consultanteemail;
/* Customized code */
/**
* #ORM\OneToMany(targetEntity="GuiasDocentes\AppBundle\Entity\Consulta", mappedBy="hiloid")
* #Assert\Valid()
*/
private $consultas;
public function __construct(){
$this->consultas = new ArrayCollection();
}
public function setConsultas (Consulta $consulta){
$this->hilos[]=$consulta;
}
public function addConsulta (\GuiasDocentes\AppBundle\Entity\Consulta $consulta){
$this->hilos[] = $consulta;
}
/* End customized code */
...
class Consultante{
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=50, nullable=false)
* #ORM\Id
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=30, nullable=true)
*/
private $nombre;
/**
* #var string
*
* #ORM\Column(name="apellidos", type="string", length=50, nullable=true)
*/
private $apellidos;
/* Customized code */
/**
* #ORM\OneToMany(targetEntity="GuiasDocentes\AppBundle\Entity\Hilo", mappedBy="consultanteemail")
* #Assert\Valid()
*/
private $hilos;
public function __construct(){
$this->hilos = new ArrayCollection();
}
public function setHilos (Hilo $hilo){
$this->hilos[]=$hilo;
}
public function addHilo (\GuiasDocentes\AppBundle\Entity\Hilo $hilo){
$this->hilos[] = $hilo;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/* End customize code */
...
public function contactoAction (Request $request){
$session = $request->getSession();
$perfil = $session->get('perfil');
$consultaHasAsignatura = new ConsultaHasAsignatura();
$form = $this->createForm(new ConsultaHasAsignaturaType(), $consultaHasAsignatura);
if ($request->isMethod('POST')){
$form->handleRequest($request);
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($consultaHasAsignatura);
$em->flush();
return $this->redirectToRoute('guias_docentes_app_homepage');
}
}
return $this->render('GuiasDocentesAppBundle:FAQ:contacto.html.twig', array('perfil'=>$perfil,
'form' => $form->createView()
));
}

Symfony2 - Doctrine2 - ManyToOne relationship / Expected argument of type "Doctrine\Common\Collections\Collection", "Proxies\...Entity...Proxy" given

I'm trying to build the "edit" controller/view but i encounter this error. From i've read it could be an asociation problem, and i've tried to fix it but i don't know what it's wrong with it. It supposed to return a collection but i don't even know what "proxy" means and how it's getting it.
The entity for which i'm building the edit view:
<?php
namespace Monse\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\WebBundle\Entity\BasedeDatos
*
* #ORM\Table()
* #ORM\Entity
*/
class BasedeDatos
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Monse\WebBundle\Entity\ServidoresBD")
* #ORM\JoinColumn(name="servidores_id", referencedColumnName="id",nullable=false)
*
*/
private $servidorBD;
/**
* #var string $nombreBD
*
* #ORM\Column(name="nombreBD", type="string", length=255,unique=true)
*/
private $nombreBD;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set servidorBD
*
* #param integer $servidorBD
*/
public function setServidorBD(\Monse\WebBundle\Entity\ServidoresBD $servidorBD)
{
$this->servidorBD = $servidorBD;
}
/**
* Get servidorBD
*
* #return integer
*/
public function getServidorBD()
{
return $this->servidorBD;
}
/**
* Set nombreBD
*
* #param string $nombreBD
*/
public function setNombreBD($nombreBD)
{
$this->nombreBD = $nombreBD;
}
/**
* Get nombreBD
*
* #return string
*/
public function getNombreBD()
{
return $this->nombreBD;
}
public function __construct()
{
$this->servidorBD = new Doctrine\Common\Collections\ArrayCollection();
}
}
FormType:
<?php
namespace Monse\WebBundle\Form;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class BasedeDatosType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('ServidorBD','entity',
array ('class' => 'MonseWebBundle:ServidoresBD',
'multiple' => true,
'required' => true,
'label' => 'Servidor de Base de Datos: ',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.url', 'ASC');
},
))
->add('nombreBD','text', array( 'required' => true, 'label' => 'Nombre Base de Datos: '))
->add('UsuarioBD','entity',array('class' => 'MonseWebBundle:UsuariosBD','multiple' => true,
'required' => true, 'label' => 'Usuario Asociado: ',
'property_path' => false,
'query_builder' => function (EntityRepository $er){
return $er->createQueryBuilder('s')
->orderBy ('s.usuario','ASC'); },))
;
}
public function getName()
{
return 'basededatos';
}
}
The entity responsible for the problem (i think):
<?php
namespace Monse\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\WebBundle\Entity\ServidoresBD
*
* #ORM\Table()
* #ORM\Entity
*/
class ServidoresBD
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $url
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
*
* #ORM\OneToOne (targetEntity="Monse\WebBundle\Entity\Dominios")
* #ORM\JoinColumn(name="dominio_id", referencedColumnName="id",nullable=false,unique=true)
*/
private $dominio;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dominio
*
* #param integer $dominio
*/
public function setDominio(\Monse\WebBundle\Entity\Dominios $dominio)
{
$this->dominio = $dominio;
}
/**
* Get dominio
*
* #return integer
*/
public function getDominio()
{
return $this->dominio;
}
/**
* Set url
*
* #param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
public function __toString()
{
return $this->getUrl();
}
}
Form Type:
<?php
namespace Monse\WebBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ServidoresBDType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('url')
->add('dominio', 'collection', array('type' => new DominiosType()));
;
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Monse\WebBundle\Entity\ServidoresBD'
);
}
public function getName()
{
return 'issue_selector';
}
}
Where should i add the arraycollection to be returned? How do i prevent this from happening again? I'm sorry if this is an stupid question, i'm trying to learn.
I changed the two "multiple" attributes to false in the first form type.

Resources