How to list entity in form - symfony

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([...]);
}

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 error when inserting new entity data

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.

Sonata admin with a2lix_translatable. How to do relationships?

I want to create table Pracownik which can contain zero or few instances of Zaklady and control it using Sonata Admin. Both of tables are translated using a2lix_translatable.
So I have classes:
<?php
namespace JCuryllo\InstituteBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* Pracownik
*
* #ORM\Table()
* #ORM\Entity
*/
class Pracownik
{
use ORMBehaviors\Translatable\Translatable;
public function __call($method, $arguments)
{
return $this->proxyCurrentLocaleTranslation($method, $arguments);
}
/**
* #ORM\ManyToOne(targetEntity="ZakladyTranslation")
**/
private $zaklady;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* and other properties
*/
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/* and other getters and setter */
}
And Translation:
<?php
namespace JCuryllo\InstituteBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* #ORM\Entity
*/
class PracownikTranslation
{
use ORMBehaviors\Translatable\Translation;
public function __toString()
{
return $this->getTitle();
}
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/* and other properties */
/**
* Set name
*
* #param string $name
* #return Pracownik
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/* and other getters and setter *.
}
I've used very similar code in Zaklady and ZakladyTranslation. Then in PracownikAdmin I try to do sth like:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('zaklady', 'many_to_one',array(
'required' => false,
))
->add('translations', 'a2lix_translations')
;
}
but it doesn't work (error: Could not load type "many_to_one").
many_to_one is not an available form type for Sonata, you have to use sonata_type_model or sonata_type_model_list for a many to one relation.
Example:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('zaklady', 'sonata_type_model_list',array(
'required' => false,
))
->add('translations', 'a2lix_translations');
}
Documentation : http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/form_field_definition.html#advanced-usage-many-to-one
Ok, I have done it.
In Zaklady I added:
public function __toString()
{
return $this->getTitle(); // getTitle is in ZakladyTranslation!
}
In Pracownik I changed:
/**
* #ORM\ManyToOne(targetEntity="ZakladyTranslation")
**/
private $zaklady;
to:
/**
* #ORM\ManyToOne(targetEntity="Zaklady")
**/
private $zaklady;
and PracownikAdmin:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('translations', 'a2lix_translations')
->add('zaklady', 'sonata_type_model', array(
'multiple' => true,
'by_reference' => false,
'required' => false
))
;
}

One-to-Many Doctrine relationship not working?

In my Symdony2 project I've two related entities: "Reglement and "Article". This should be many-to-one relationship, because each "Reglement" can have many "Articles", and each "Article" can belongs to one "Reglement".
Moreover, I need a user interface to manage Reglement and Articles. So, when adding a Reglement, user should be able to add many articles it belongs.
I've already achieved this by setting up a One-To-Many relation in my Doctrine entites. Everything is working like a charm, including user interface build on custom form types in Symfony2 (I've used "Collection" form field type to allow user to add "Articles" in "Reglement). The only problem I've is that I can save only the last article in the database !!
Here is my "Reglement" entity source code:
<?php
namespace GestionEnvironnementale\ISO14001Bundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Reglement
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="GestionEnvironnementale\ISO14001Bundle\Entity\ReglementRepository")
*/
class Reglement
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="domaineApplication", type="string", length=255)
*/
private $domaineApplication;
/**
* #var string
*
* #ORM\Column(name="texteLegislatif", type="text")
*/
private $texteLegislatif;
/**
* #var string
*
* #ORM\Column(name="contenuText", type="text")
*/
private $contenuText;
/**
* #ORM\OneToMany(targetEntity="GestionEnvironnementale\ISO14001Bundle\Entity\Article", cascade={"persist"}, mappedBy="reglement")
*/
private $articles;
public function __construct()
{
$this->articles = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getArticles()
{
return $this->articles;
}
public function setArticles(ArrayCollection $articles)
{
foreach ($articles as $article) {
$article->addReglement($this);
}
$this->articles = $articles;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set domaineApplication
*
* #param string $domaineApplication
* #return Reglement
*/
public function setDomaineApplication($domaineApplication)
{
$this->domaineApplication = $domaineApplication;
return $this;
}
/**
* Get domaineApplication
*
* #return string
*/
public function getDomaineApplication()
{
return $this->domaineApplication;
}
/**
* Set texteLegislatif
*
* #param string $texteLegislatif
* #return Reglement
*/
public function setTexteLegislatif($texteLegislatif)
{
$this->texteLegislatif = $texteLegislatif;
return $this;
}
/**
* Get texteLegislatif
*
* #return string
*/
public function getTexteLegislatif()
{
return $this->texteLegislatif;
}
/**
* Set contenuText
*
* #param string $contenuText
* #return Reglement
*/
public function setContenuText($contenuText)
{
$this->contenuText = $contenuText;
return $this;
}
/**
* Get contenuText
*
* #return string
*/
public function getContenuText()
{
return $this->contenuText;
}
/**
* Add articles
*
* #param \GestionEnvironnementale\ISO14001Bundle\Entity\Article $articles
* #return Reglement
*/
public function addArticle(\GestionEnvironnementale\ISO14001Bundle\Entity\Article $articles)
{
$this->articles[] = $articles;
return $this;
}
/**
* Remove articles
*
* #param \GestionEnvironnementale\ISO14001Bundle\Entity\Article $articles
*/
public function removeArticle(\GestionEnvironnementale\ISO14001Bundle\Entity\Article $articles)
{
$this->articles->removeElement($articles);
}
}
And here is my Article entity source code:
<?php
namespace GestionEnvironnementale\ISO14001Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Article
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="GestionEnvironnementale\ISO14001Bundle\Entity\ArticleRepository")
*/
class Article
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="GestionEnvironnementale\ISO14001Bundle\Entity\Reglement", inversedBy="articles")
* #ORM\JoinColumn(nullable=false)
*/
private $reglement;
/**
* #var string
*
* #ORM\Column(name="exigenceArticle", type="string", length=255)
*/
private $exigenceArticle;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set exigenceArticle
*
* #param string $exigenceArticle
* #return Article
*/
public function setExigenceArticle($exigenceArticle)
{
$this->exigenceArticle = $exigenceArticle;
return $this;
}
/**
* Get exigenceArticle
*
* #return string
*/
public function getExigenceArticle()
{
return $this->exigenceArticle;
}
/**
* Set reglement
*
* #param \GestionEnvironnementale\ISO14001Bundle\Entity\Reglement $reglement
* #return Article
*/
public function setReglement(\GestionEnvironnementale\ISO14001Bundle\Entity\Reglement $reglement)
{
$this->reglement = $reglement;
return $this;
}
/**
* Get reglement
*
* #return \GestionEnvironnementale\ISO14001Bundle\Entity\Reglement
*/
public function getReglement()
{
return $this->reglement;
}
public function addReglement(Reglement $reglement)
{
if (!$this->reglements->contains($reglement)) {
$this->reglements->add($reglement);
}
}
}
and here is my reglement form :
<?php
namespace GestionEnvironnementale\ISO14001Bundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ReglementType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('domaineApplication')
->add('texteLegislatif')
->add('contenuText')
->add('articles', 'collection', array(
'type' => new ArticleType(),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false,
));
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'GestionEnvironnementale\ISO14001Bundle\Entity\Reglement'
));
}
/**
* #return string
*/
public function getName()
{
return 'gestionenvironnementale_iso14001bundle_reglementtype';
}
}
and my article form :
<?php
namespace GestionEnvironnementale\ISO14001Bundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ArticleType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('exigenceArticle')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'GestionEnvironnementale\ISO14001Bundle\Entity\Article'
));
}
/**
* #return string
*/
public function getName()
{
return 'gestionenvironnementale_iso14001bundle_article';
}
}
And here is part of my ReglementController source code:
public function ajouterReglementAction()
{
$reglement = new Reglement();
$form = $this->createForm(new ReglementType(), $reglement);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$reglement->getArticles()->clear();
$em = $this->getDoctrine()->getManager();
$em->persist($reglement);
$em->flush();
foreach ($form->get('articles')->getData() as $ac) {
$ac->setReglement($reglement);
$em->persist($ac);
}
$em->flush();
$this->get('session')->getFlashBag()->add('info', 'Reglement bien enregistré');
return $this->redirect( $this->generateUrl('reglement_voir', array('id' => $reglement->getId())));
}
}
return $this->render('ISO14001Bundle:Reglements:ajouter.html.twig', array(
'form' => $form->createView()
));
}
finnally the form view source code :
<div class="well">
<form method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<br/> <input type="submit" value="Envoyer" class="btn btn-primary" />
</form>
<script src="{{ asset('js/jquery-2.1.1.min.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
var $container = $('div#gestionenvironnementale_iso14001bundle_reglementtype_articles');
var $lienAjout = $('Ajouter un article');
$container.append($lienAjout);
$lienAjout.click(function(e) {
ajouterArticle($container);
e.preventDefault();
return false;
});
var index = $container.find(':input').length;
if (index == 0) {
ajouterArticle($container);
} else {
$container.children('div').each(function() {
ajouterLienSuppression($(this));
});
}
function ajouterArticle($container) {
var $prototype = $($container.attr('data-prototype').replace(/__name__label__/g, 'Article n°' + (index+1))
.replace(/\$\$name\$\$/g, index));
ajouterLienSuppression($prototype);
$container.append($prototype);
index++;
}
function ajouterLienSuppression($prototype) {
$lienSuppression = $('Supprimer');
$prototype.append($lienSuppression);
$lienSuppression.click(function(e) {
$prototype.remove();
e.preventDefault();
return false;
});
}
});
I hope you can help me ;)
hi everyone I found the solution of my problem ^_^
the error is in line 27 of form view, there must be __name__ instead of $$name$$ as follows :
function ajouterArticle($container) {
var $prototype = $($container.attr('data-prototype').replace(/__name__label__/g, 'Article n°' + (index+1))
.replace(/__name__/g, index));
ajouterLienSuppression($prototype);
$container.append($prototype);
index++;
}
good luck ;)

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