I'm having an issue with something I think is probably fairly basic but the cause is escaping me.
I have a two entities, an Organisation and a Subscription. An organisation is linked with one subscription.
I want to be able to edit this via a form (creating via form already works). When I do the following:
$organisation = $this->getDoctrine()->getRepository('AppBundle\Entity\Organisation')
->findOneBy(array(
'id' => $id
));
$form = $this->createForm(new OrganisationType(), $organisation, array(
'method' => 'POST'
));
$form->submit($paramFetcher->all());
I get an exception because the subscription property of the organisation entity is not set (despite passing one which has a subscription into the form defaults). The exception is as follows:
Expected argument of type "AppBundle\Entity\Subscription", "NULL" given
This is obviously being thrown by the setSubscription method on the Organisation entity but I'm not sure why as the form should be converting the int value passed to a Subscription entity automatically.
Am I doing something stupid here? I have attached the relevant code below. Thank you!
The simplest controller action that replicates this issue
public function testAction(Request $request)
{
$organisation = $this->getDoctrine()->getRepository('AppBundle\Entity\Organisation')
->findOneBy(array('id' => 7));
$form = $this->createForm(new OrganisationType(), $organisation);
$form->submit($request->request->all());
return $this->render('test.html.twig', array(
'testform' => $form->createView()
));
}
Organisation.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Organisation
*
* #ORM\Table(name="organisation")
* #ORM\Entity(repositoryClass="AppBundle\Repository\OrganisationRepository")
*/
class Organisation
{
const ENABLED = 1;
const DISABLED = 2;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #JMS\Groups({"default", "list-organisation"})
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #JMS\Groups({"default", "list-organisation"})
*/
private $name;
/**
* #var Subscription|null The subscription this organisation is currently linked to
* #ORM\ManyToOne(targetEntity="Subscription", inversedBy="organisations")
* #ORM\JoinColumn(name="subscription_id", referencedColumnName="id", onDelete="set null")
* #JMS\Groups({"default", "list-organisation"})
*/
private $subscription;
/**
* #var Collection
* #ORM\OneToMany(targetEntity="User", mappedBy="organisation")
* #JMS\Groups({})
*/
private $users;
/**
* #var Collection
* #ORM\OneToMany(targetEntity="Subgroup", mappedBy="organisation")
* #JMS\Groups({"default"})
*/
private $subgroups;
/**
* #var string $enabled
*
* #ORM\Column(type="string")
*/
private $enabled = self::ENABLED;
/**
* #var datetime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
* #JMS\Groups({"default", "list-organisation"})
*/
private $created;
/**
* #var datetime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
* #JMS\Groups({"default", "list-organisation"})
*/
private $updated;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Organisation
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Sets subscription
*
* #param Subscription $subscription
* #return $this
*/
public function setSubscription(Subscription $subscription)
{
$this->subscription = $subscription;
return $this;
}
/**
* Gets subscription
*
* #return Subscription|null
*/
public function getSubscription()
{
return $this->subscription;
}
/**
* Sets enabled
*
* #param $enabled
*/
public function setEnabled($enabled)
{
if (!in_array($enabled, array(self::ENABLED, self::DISABLED))) {
throw new \InvalidArgumentException('Invalid enabled status');
}
$this->enabled = $enabled;
}
/**
* Gets enabled
*
* #return string
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns Users belonging to this organisation
*
* #return Collection
*/
public function getUsers()
{
return $this->users;
}
public function __toString()
{
return $this->getName();
}
}
Subscription.php
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Organisation
*
* #ORM\Table(name="subscription")
* #ORM\Entity(repositoryClass="AppBundle\Repository\SubscriptionRepository")
*/
class Subscription
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #JMS\Groups({"default", "list-organisation"})
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #JMS\Groups({"default", "list-organisation"})
*/
private $name;
/**
* #var Collection
* #ORM\OneToMany(targetEntity="Organisation", mappedBy="subscription")
* #JMS\Groups({"default"})
*/
private $organisations;
/**
* #var datetime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
* #JMS\Groups({"default"})
*/
private $created;
/**
* #var datetime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
* #JMS\Groups({"default"})
*/
private $updated;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Subscription
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns Organisations with this subscription type
*
* #return Collection
*/
public function getOrganisations()
{
return $this->organisations;
}
/**
* #return string
*/
public function __toString()
{
return $this->getName();
}
}
OrganisationType.php
<?php
namespace AppBundle\Form;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class OrganisationType extends AbstractType
{
private $manager;
public function __construct(ObjectManager $objectManager)
{
$this->manager = $objectManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
$builder->add('subscription', EntityType::class, array(
'class' => 'AppBundle\Entity\Subscription'
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Organisation',
'csrf_protection' => false
));
}
}
On a fresh Symfony 3.1, this works like a charm (and this is the recommended way to handle form submission, as stated in a previous comment) :
public function testAction(Request $request)
{
$organisation = $this->getDoctrine()->getRepository('AppBundle\Entity\Organisation')
->find(1);
$form = $this->createForm(OrganisationType::class, $organisation);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->persist($organisation);
$this->getDoctrine()->getManager()->flush();
die('saved into database.');
}
return $this->render('test.html.twig', array(
'testform' => $form->createView()
));
}
Related
Thank you all for your answers from now. ThatÅ› the question. I have a symfony 2 app with two entities (Tasks and Products). When i tried to find (findBy,findOneBy,findAll) a product it returns an empty array.
Tasks Entity
<?php
namespace pablo\UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Task
*
* #ORM\Table(name="tasks")
* #ORM\Entity(repositoryClass="pablo\UserBundle\Repository\TaskRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Task
{
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="tasks")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $user;
/**
* #ORM\ManyToOne(targetEntity="Product", inversedBy="task")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $product;
public function __construct()
{
$this->tasks = new ArrayCollection();
}
/**
* Set product
*
* #param \pablo\UserBundle\Entity\Product $product
*
* #return Task
*/
public function setProduct(\pablo\UserBundle\Entity\Product $product = null)
{
$this->product = $product;
return $this;
}
/**
* Get product
*
* #return \pablo\UserBundle\Entity\Product
*/
public function getProduct()
{
return $this->product;
}
/**
* #return ArrayCollection
*/
public function getTasks()
{
return $this->tasks;
}
/**
* #param ArrayCollection $tasks
*/
public function setTasks($tasks)
{
$this->tasks = $tasks;
}
And Products Entity
<?php
namespace pablo\UserBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Products
*
* #ORM\Table(name="products")
* #ORM\Entity(repositoryClass="pablo\UserBundle\Repository\ProductsRepository")
* #UniqueEntity("productsName")
*/
class Product
{
/**
* #ORM\OneToMany(targetEntity="Task", mappedBy="product")
*/
protected $task;
/**
* #ORM\OneToMany(targetEntity="Publicaciones", mappedBy="product")
*/
protected $publicaciones;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="products_name", type="string", length=255)
* #Assert\NotBlank()
*/
private $productsName;
public function __construct()
{
$this->task = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set productsName
*
* #param string $productsName
*
* #return Product
*/
public function setProductsName($productsName)
{
$this->productsName = $productsName;
return $this;
}
/**
* Get productsName
*
* #return string
*/
public function getProductsName()
{
return $this->productsName;
}
public function __toString() {
return $this->productsName;
}
/**
* Get task
*
* #return \Doctrine\Common\Collections\ArrayCollection
*/
public function getTask()
{
return $this->task;
}
/**
* Set task
*
* #param \Doctrine\Common\Collections\ArrayCollection $typeSponsor
*
* #return Task
*/
public function setTask($task)
{
$this->task = $task;
}
/**
* #return mixed
*/
public function getPublicaciones()
{
return $this->publicaciones;
}
/**
* #param mixed $publicaciones
*/
public function setPublicaciones($publicaciones)
{
$this->publicaciones = $publicaciones;
}
}
Now, when i tried to find a product from controller it returns an empty array ({}). I can't see what is wrong with this.
$productId = '18';
$product = $this->get('doctrine.orm.default_entity_manager')->getRepository('pabloUserBundle:Product')->find($productId);
Actually you have a result, it just is an empty object because you have not defined which of the properties should be printed.
The best solution is for your entity to implement JsonSerializable.
class Product implements \JsonSerializable
{
...
public function jsonSerialize()
{
return [
"id"=> $this->getId(),
"name" => $this->getProductsName()
];
}
Now it knows what it should print when converting the class to json object.
If you want the task collection also, implement JsonSerializable for the Task Entity and add in Product Entity:
public function jsonSerialize()
{
return [
"id"=> $this->getId(),
"name" => $this->getProductsName(),
"task" => $this->getTask()->toArray()
];
}
The JsonSerializable interface
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").
I am trying to create a little CRUD system with 2 entities and a OneToMany relationship between these 2 entities.
My entities are Location & Job. I created the entities and created the crud controller via doctrine for both.
Location CRUD works great but Job only Read & Delete works. When I try to create a new Job it throws the following exception:
Catchable Fatal Error: Object of class DataBundle\Entity\Location
could not be converted to string
I have no idea what it means or what is causing it.
If anyone could help me out that would be realy awesome!
Many thanks in advance!
Here is my code.
Entities:
Location
<?php
namespace DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Location
*
* #ORM\Table(name="location")
* #ORM\Entity(repositoryClass="DataBundle\Repository\LocationRepository")
*/
class Location
{
/**
* #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=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="street", type="string", length=255)
*/
private $street;
/**
* #var string
*
* #ORM\Column(name="number", type="string", length=25)
*/
private $number;
/**
* #var string
*
* #ORM\Column(name="postalcode", type="string", length=4)
*/
private $postalcode;
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=255)
*/
private $city;
/**
* #var Job[] Available jobs for this location.
*
* #ORM\OneToMany(targetEntity="Job", mappedBy="location")
*/
private $jobs;
public function __construct()
{
$this->jobs = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Location
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set street
*
* #param string $street
*
* #return Location
*/
public function setStreet($street)
{
$this->street = $street;
return $this;
}
/**
* Get street
*
* #return string
*/
public function getStreet()
{
return $this->street;
}
/**
* Set number
*
* #param string $number
*
* #return Location
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* Get number
*
* #return string
*/
public function getNumber()
{
return $this->number;
}
/**
* Set postalcode
*
* #param string $postalcode
*
* #return Location
*/
public function setPostalcode($postalcode)
{
$this->postalcode = $postalcode;
return $this;
}
/**
* Get postalcode
*
* #return string
*/
public function getPostalcode()
{
return $this->postalcode;
}
/**
* Set city
*
* #param string $city
*
* #return Location
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return string
*/
public function getCity()
{
return $this->city;
}
/**
* Add job
*
* #param \DataBundle\Entity\Job $job
*
* #return Location
*/
public function addJob(\DataBundle\Entity\Job $job)
{
$this->jobs[] = $job;
return $this;
}
/**
* Remove job
*
* #param \DataBundle\Entity\Job $job
*/
public function removeJob(\DataBundle\Entity\Job $job)
{
$this->jobs->removeElement($job);
}
/**
* Get jobs
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getJobs()
{
return $this->jobs;
}
}
Job:
<?php
namespace DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Job
*
* #ORM\Table(name="job")
* #ORM\Entity(repositoryClass="DataBundle\Repository\JobRepository")
*/
class Job
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #var Location
*
* #ORM\ManyToOne(targetEntity="Location", inversedBy="jobs")
* #ORM\JoinColumn(name="location_id", referencedColumnName="id")
*/
private $location;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Job
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*
* #return Job
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set location
*
* #param \DataBundle\Entity\Location $location
*
* #return Job
*/
public function setLocation(\DataBundle\Entity\Location $location = null)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return \DataBundle\Entity\Location
*/
public function getLocation()
{
return $this->location;
}
}
My new action in the JobController:
/**
* Creates a new job entity.
*
*/
public function newAction(Request $request)
{
$job = new Job();
$form = $this->createForm('DataBundle\Form\JobType', $job);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($job);
$em->flush($job);
return $this->redirectToRoute('job_show', array('id' => $job->getId()));
}
return $this->render('job/new.html.twig', array(
'job' => $job,
'form' => $form->createView(),
));
}
DataBundle/Form/JobTypep
<?php
namespace DataBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class JobType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title')->add('description')->add('location') ;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'DataBundle\Entity\Job'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'databundle_job';
}
}
You can't use location as text field in your form, location is object.
You can fix this error by using form data transformers that will convert location into text on form output and text in location object on form submit.
http://symfony.com/doc/current/form/data_transformers.html
Or by using form type EnityType for location:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title')->add('description');
$builder
->add('location', Symfony\Bridge\Doctrine\Form\Type\EntityType::class, [
'required' => false,
'expanded' => false,
'multiple' => false,
'class' => 'DataBundle\\Entity\\Location',
'empty_data' => '',
'choice_label' => 'name',
'label' => 'Location',
]);
}
http://symfony.com/doc/current/reference/forms/types/entity.html
I have an Organisation entity referencing an embedded form containing a Country entity. The form saves without issue, but the Country EntityType field does not correctly pick up the value upon editing, and as such the first option in the dropdown is always selected rather than the correct option.
The OrganisationType form:
<?php
namespace AppBundle\Form\Type\Meta;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
class OrganisationType extends AbstractType
{
public function __construct()
{
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', new TitleType(),
array('required' => true, 'label' => false))
->add('country', new CountryType(), array('label' => false))
->add('location', 'text',
array('required' => false, 'label' => 'City'));
}
public function getName()
{
return 'organisation';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Organisation',
'csrf_protection' => true,
'csrf_field_name' => '_token',
// a unique key to help generate the secret token
'intention' => 'organisation',
'cascade_validation' => true
));
}
}
The CountryType form:
<?php
namespace AppBundle\Form\Type\Meta;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
class CountryType extends AbstractType
{
public function __construct()
{
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', EntityType::class, array(
'label' => 'Country',
'class' => 'AppBundle:Country',
'choice_label' => 'name',
'placeholder' => 'Choose an option...',
'query_builder' => function (EntityRepository $repository) {
return $repository->createQueryBuilder('c')->orderBy('c.name', 'ASC');
}
));
}
public function getName()
{
return 'country';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Country'
));
}
}
Organisation Entity:
<?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 Gedmo\Mapping\Annotation as Gedmo;
use AppBundle\Model\OrganisationModel;
/**
* Organisation
*
* #ORM\Table(name="organisation", indexes={#ORM\Index(name="fk_meta_org_country_idx", columns={"country_id"}), #ORM\Index(name="fk_meta_org_subdivision_idx", columns={"country_subdivision_id"}), #ORM\Index(name="fk_meta_org_user_entered_idx", columns={"entered_by_user_id"}), #ORM\Index(name="fk_meta_org_user_updated_idx", columns={"updated_by_user_id"}), #ORM\Index(name="fk_meta_org_title_idx", columns={"title_id"})})
* #ORM\Entity(repositoryClass="AppBundle\Entity\OrganisationRepository")
*/
class Organisation extends OrganisationModel
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=45, nullable=false)
*/
private $location;
/**
* #var boolean
*
* #ORM\Column(name="hidden", type="boolean", nullable=false)
*/
private $hidden;
/**
* #var \DateTime
*
* #ORM\Column(name="date_entered", type="datetime", nullable=false)
* #Gedmo\Timestampable(on="create")
*/
private $dateEntered;
/**
* #var \DateTime
*
* #ORM\Column(name="date_updated", type="datetime", nullable=false)
* #Gedmo\Timestampable(on="update")
*/
private $dateUpdated;
/**
* #var \AppBundle\Entity\Country
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Country")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="country_id", referencedColumnName="id")
* })
*/
private $country;
/**
* #var \AppBundle\Entity\CountrySubdivision
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\CountrySubdivision")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="country_subdivision_id", referencedColumnName="id")
* })
*/
private $countrySubdivision;
/**
* #var \AppBundle\Entity\Title
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Title", cascade="persist")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="title_id", referencedColumnName="id")
* })
* #Assert\Type(type="AppBundle\Entity\Title")
* #Assert\Valid()
*/
private $title;
/**
* #var \AppBundle\Entity\User
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="entered_by_user_id", referencedColumnName="id")
* })
*/
private $enteredByUser;
/**
* #var \AppBundle\Entity\User
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="updated_by_user_id", referencedColumnName="id")
* })
*/
private $updatedByUser;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set location
*
* #param string $location
* #return Organisation
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set hidden
*
* #param boolean $hidden
* #return Organisation
*/
public function setHidden($hidden)
{
$this->hidden = $hidden;
return $this;
}
/**
* Get hidden
*
* #return boolean
*/
public function getHidden()
{
return $this->hidden;
}
/**
* Set dateEntered
*
* #param \DateTime $dateEntered
* #return Organisation
*/
public function setDateEntered($dateEntered)
{
$this->dateEntered = $dateEntered;
return $this;
}
/**
* Get dateEntered
*
* #return \DateTime
*/
public function getDateEntered()
{
return $this->dateEntered;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
* #return Organisation
*/
public function setDateUpdated($dateUpdated)
{
$this->dateUpdated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated()
{
return $this->dateUpdated;
}
/**
* Set country
*
* #param \AppBundle\Entity\Country $country
* #return Organisation
*/
public function setCountry(\AppBundle\Entity\Country $country = null)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return \AppBundle\Entity\Country
*/
public function getCountry()
{
return $this->country;
}
/**
* Set countrySubdivision
*
* #param \AppBundle\Entity\CountrySubdivision $countrySubdivision
* #return Organisation
*/
public function setCountrySubdivision(\AppBundle\Entity\CountrySubdivision $countrySubdivision = null)
{
$this->countrySubdivision = $countrySubdivision;
return $this;
}
/**
* Get countrySubdivision
*
* #return \AppBundle\Entity\CountrySubdivision
*/
public function getCountrySubdivision()
{
return $this->countrySubdivision;
}
/**
* Set title
*
* #param \AppBundle\Entity\Title $title
* #return Organisation
*/
public function setTitle(\AppBundle\Entity\Title $title = null)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return \AppBundle\Entity\Title
*/
public function getTitle()
{
return $this->title;
}
/**
* Set enteredByUser
*
* #param \AppBundle\Entity\User $enteredByUser
* #return Organisation
*/
public function setEnteredByUser(\AppBundle\Entity\User $enteredByUser = null)
{
$this->enteredByUser = $enteredByUser;
return $this;
}
/**
* Get enteredByUser
*
* #return \AppBundle\Entity\User
*/
public function getEnteredByUser()
{
return $this->enteredByUser;
}
/**
* Set updatedByUser
*
* #param \AppBundle\Entity\User $updatedByUser
* #return Organisation
*/
public function setUpdatedByUser(\AppBundle\Entity\User $updatedByUser = null)
{
$this->updatedByUser = $updatedByUser;
return $this;
}
/**
* Get updatedByUser
*
* #return \AppBundle\Entity\User
*/
public function getUpdatedByUser()
{
return $this->updatedByUser;
}
}
Country Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
/**
* Country
*
* #ORM\Table(name="country", uniqueConstraints={#ORM\UniqueConstraint(name="unique", columns={"code"})})
* #ORM\Entity(repositoryClass="AppBundle\Entity\CountryRepository")
*/
class Country
{
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=2, nullable=false)
*/
private $code;
/**
* #var string
*
* #ORM\Column(name="code_iso_3", type="string", length=3, nullable=true)
*/
private $codeIso3;
/**
* #var string
*
* #ORM\Column(name="code_iso_numeric", type="string", length=4, nullable=true)
*/
private $codeIsoNumeric;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="capital", type="string", length=30, nullable=true)
*/
private $capital;
/**
* #var string
*
* #ORM\Column(name="continent_name", type="string", length=15, nullable=true)
*/
private $continentName;
/**
* #var string
*
* #ORM\Column(name="continent_code", type="string", length=2, nullable=true)
*/
private $continentCode;
/**
* #var boolean
*
* #ORM\Column(name="hidden", type="boolean", nullable=false)
*/
private $hidden;
/**
* #var \DateTime
*
* #ORM\Column(name="date_entered", type="datetime", nullable=false)
*/
private $dateEntered;
/**
* #var \DateTime
*
* #ORM\Column(name="date_updated", type="datetime", nullable=false)
*/
private $dateUpdated;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var Doctrine\Common\Collections\ArrayCollection
*
* #ORM\OneToMany(targetEntity="CountrySubdivision", mappedBy="country")
*/
private $subdivisions;
/*
* #var AppBundle\Entity\CountrySubdivision
* Stored purely for the purposes of form capture
*/
private $subdivision;
/**
* #var Doctrine\Common\Collections\ArrayCollection
*
* #ORM\OneToMany(targetEntity="CountrySubdivisionType", mappedBy="country")
*/
private $subdivisionTypes;
public function __construct()
{
$this->subdivisions = new ArrayCollection();
$this->subdivisionTypes = new ArrayCollection();
}
public function getSubdivisions()
{
return $this->subdivisions->toArray();
}
public function getSubdivisionsOfParentId($parentId)
{
$criteria = Criteria::create()
->where(Criteria::expr()->eq("parentId", $parentId))
->orderBy(array("name" => Criteria::ASC));
return $this->subdivisions->matching($criteria)->toArray();
}
public function setSubdivisions($subdivisions)
{
}
public function getSubdivision()
{
return $this->subdivision;
}
public function setSubdivision($subdivision)
{
$this->subdivision = $subdivision;
}
public function setId($id)
{
$this->id = $id;
}
public function getSubdivisionTypeOfParentId($parentId)
{
$criteria = Criteria::create()
->where(Criteria::expr()->eq("subdivisionId", $parentId))
->orderBy(array("name" => Criteria::ASC));
return $this->subdivisionTypes->matching($criteria)[0];
}
/**
* Set code
*
* #param string $code
* #return Country
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return string
*/
public function getCode()
{
return $this->code;
}
/**
* Set codeIso3
*
* #param string $codeIso3
* #return Country
*/
public function setCodeIso3($codeIso3)
{
$this->codeIso3 = $codeIso3;
return $this;
}
/**
* Get codeIso3
*
* #return string
*/
public function getCodeIso3()
{
return $this->codeIso3;
}
/**
* Set codeIsoNumeric
*
* #param string $codeIsoNumeric
* #return Country
*/
public function setCodeIsoNumeric($codeIsoNumeric)
{
$this->codeIsoNumeric = $codeIsoNumeric;
return $this;
}
/**
* Get codeIsoNumeric
*
* #return string
*/
public function getCodeIsoNumeric()
{
return $this->codeIsoNumeric;
}
/**
* Set name
*
* #param string $name
* #return Country
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set capital
*
* #param string $capital
* #return Country
*/
public function setCapital($capital)
{
$this->capital = $capital;
return $this;
}
/**
* Get capital
*
* #return string
*/
public function getCapital()
{
return $this->capital;
}
/**
* Set continentName
*
* #param string $continentName
* #return Country
*/
public function setContinentName($continentName)
{
$this->continentName = $continentName;
return $this;
}
/**
* Get continentName
*
* #return string
*/
public function getContinentName()
{
return $this->continentName;
}
/**
* Set continentCode
*
* #param string $continentCode
* #return Country
*/
public function setContinentCode($continentCode)
{
$this->continentCode = $continentCode;
return $this;
}
/**
* Get continentCode
*
* #return string
*/
public function getContinentCode()
{
return $this->continentCode;
}
/**
* Set hidden
*
* #param boolean $hidden
* #return Country
*/
public function setHidden($hidden)
{
$this->hidden = $hidden;
return $this;
}
/**
* Get hidden
*
* #return boolean
*/
public function getHidden()
{
return $this->hidden;
}
/**
* Set dateEntered
*
* #param \DateTime $dateEntered
* #return Country
*/
public function setDateEntered($dateEntered)
{
$this->dateEntered = $dateEntered;
return $this;
}
/**
* Get dateEntered
*
* #return \DateTime
*/
public function getDateEntered()
{
return $this->dateEntered;
}
/**
* Set dateUpdated
*
* #param \DateTime $dateUpdated
* #return Country
*/
public function setDateUpdated($dateUpdated)
{
$this->dateUpdated = $dateUpdated;
return $this;
}
/**
* Get dateUpdated
*
* #return \DateTime
*/
public function getDateUpdated()
{
return $this->dateUpdated;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
If I replace, in the CountryType form...
->add('id', EntityType::class, ...
With...
->add('name')
...then I see the country name displayed without any issue. Where am I going wrong with the EntityType?
I think you're not using custom FormType correctly. You're not supposed to add anything to the builder in a custom FormType. Try this :
<?php
namespace AppBundle\Form\Type\Meta;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
class OrganisationType extends AbstractType
{
public function __construct()
{
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', new TitleType(),
array('required' => true, 'label' => false))
->add('country', new CountryType(), array(
'label' => 'Country',
'choice_label' => 'name',
'placeholder' => 'Choose an option...',
'query_builder' => function (EntityRepository $repository) {
return $repository->createQueryBuilder('c')->orderBy('c.name', 'ASC');
}
))
->add('location', 'text',
array('required' => false, 'label' => 'City'));
}
public function getName()
{
return 'organisation';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Organisation',
'csrf_protection' => true,
'csrf_field_name' => '_token',
// a unique key to help generate the secret token
'intention' => 'organisation',
'cascade_validation' => true
));
}
}
with
<?php
namespace AppBundle\Form\Type\Meta;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;
class CountryType extends AbstractType
{
public function getName()
{
return 'country';
}
public function getParent()
{
return EntityType::class;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Country'
));
}
}
I created a one to many relationship between a society and its employees. Everything worked great, I can see the user list when I'm editing the society page and I can select some of them, but the problem is that I can't save / persist those data, and i don't know why.
I tried a lot of things, like adding allow_add =>true or by_reference => false inside the FormType, but it doesn't work even though it still saves the rest of the form, such as the society's name and its address.
Here are the entities :
Societe.php
<?php
namespace SocieteBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Societe
*
* #ORM\Table(name="societe")
* #ORM\Entity(repositoryClass="SocieteBundle\Repository\SocieteRepository")
*/
class Societe
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="RaisonSociale", type="string", length=255, unique=true)
*/
private $raisonSociale;
/**
* #var string
*
* #ORM\Column(name="adresse", type="string", length=255, unique=true)
*/
private $adresse;
/**
* #ORM\OneToMany(targetEntity="UserBundle\Entity\User", mappedBy="entreprise", cascade={"persist"})
*/
private $salaries;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set raisonSociale
*
* #param string $raisonSociale
*
* #return Societe
*/
public function setRaisonSociale($raisonSociale)
{
$this->raisonSociale = $raisonSociale;
return $this;
}
/**
* Get raisonSociale
*
* #return string
*/
public function getRaisonSociale()
{
return $this->raisonSociale;
}
/**
* Set adresse
*
* #param string $adresse
*
* #return Societe
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Constructor
*/
public function __construct()
{
$this->salaries = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add salary
*
* #param \UserBundle\Entity\User $salary
*
* #return Societe
*/
public function addSalary(\UserBundle\Entity\User $salary)
{
$this->salaries[] = $salary;
return $this;
}
/**
* Remove salary
*
* #param \UserBundle\Entity\User $salary
*/
public function removeSalary(\UserBundle\Entity\User $salary)
{
$this->salaries->removeElement($salary);
}
/**
* Get salaries
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSalaries()
{
return $this->salaries;
}
/**
* Set salaries
* Something I tried, didn't work
*/
public function setSalaries($salaries)
{
$this->salaries = $salaries;
return $this;
}
}
User.php
<?php
namespace UserBundle\Entity;
use FOS\UserBundle\Model\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;
/**
* #var string
* #ORM\Column(name="prenom", type="string", length=255, nullable=true)
*/
protected $prenom;
/**
* #var string
* #ORM\Column(name="nom", type="string", length=255, nullable=true)
*/
protected $nom;
/**
* #var string
* #ORM\Column(name="telephone", type="string", length=255, nullable=true)
*/
protected $telephone;
/**
* #ORM\OneToMany(targetEntity="MissionBundle\Entity\Mission", mappedBy="createur", cascade={"remove", "persist"})
*
*/
protected $post;
/**
* #ORM\ManyToOne(targetEntity="EcoleBundle\Entity\Ecole", inversedBy="representant", cascade={"persist"})
* #ORM\JoinColumn(name="ecole_id", referencedColumnName="id")
*/
protected $ecole;
/**
* #ORM\ManyToOne(targetEntity="SocieteBundle\Entity\Societe", inversedBy="salaries", cascade={"persist"})
* #ORM\JoinColumn(name="salaries_id", referencedColumnName="id")
*/
private $entreprise;
/**
* Set prenom
*
* #param string $prenom
*
* #return User
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set nom
*
* #param string $nom
*
* #return User
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set telephone
*
* #param string $telephone
*
* #return User
*/
public function setTelephone($telephone)
{
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* #return string
*/
public function getTelephone()
{
return $this->telephone;
}
/**
* Add post
*
* #param \MissionBundle\Entity\Mission $post
*
* #return User
*/
public function addPost(\MissionBundle\Entity\Mission $post)
{
$this->post[] = $post;
return $this;
}
/**
* Remove post
*
* #param \MissionBundle\Entity\Mission $post
*/
public function removePost(\MissionBundle\Entity\Mission $post)
{
$this->post->removeElement($post);
}
/**
* Get post
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPost()
{
return $this->post;
}
/**
* Set post
*
* #param \Doctrine\Common\Collections\Collection $comments
*/
public function setDeskComment(\Doctrine\Common\Collections\Collection $post){
$this->post = $post;
}
/**
* Set ecole
*
* #param \EcoleBundle\Entity\Ecole $ecole
*
* #return User
*/
public function setEcole(\EcoleBundle\Entity\Ecole $ecole = null)
{
$this->ecole = $ecole;
return $this;
}
/**
* Get ecole
*
* #return \EcoleBundle\Entity\Ecole
*/
public function getEcole()
{
return $this->ecole;
}
/**
* Set entreprise
*
* #param \SocieteBundle\Entity\Societe $entreprise
*
* #return User
*/
public function setEntreprise(\SocieteBundle\Entity\Societe $entreprise = null)
{
$this->entreprise = $entreprise;
return $this;
}
/**
* Get entreprise
*
* #return \SocieteBundle\Entity\Societe
*/
public function getEntreprise()
{
return $this->entreprise;
}
}
SocieteType.php
<?php
namespace SocieteBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
//use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class SocieteType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('raisonSociale')
->add('adresse')
->add('salaries', null, array(
'by_reference' => false,
)
)
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'SocieteBundle\Entity\Societe'
));
}
}
SocieteController.php
<?php
namespace SocieteBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use SocieteBundle\Entity\Societe;
use SocieteBundle\Form\SocieteType;
/**
* Societe controller.
*
* #Route("/societe")
*/
class SocieteController extends Controller
{
/**
* Lists all Societe entities.
*
* #Route("/", name="societe_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$societes = $em->getRepository('SocieteBundle:Societe')->findAll();
return $this->render('societe/index.html.twig', array(
'societes' => $societes,
));
}
/**
* Creates a new Societe entity.
*
* #Route("/new", name="societe_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$societe = new Societe();
$form = $this->createForm('SocieteBundle\Form\SocieteType', $societe);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($societe);
$em->flush();
return $this->redirectToRoute('societe_show', array('id' => $societe->getId()));
}
return $this->render('societe/new.html.twig', array(
'societe' => $societe,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Societe entity.
*
* #Route("/{id}", name="societe_show")
* #Method("GET")
*/
public function showAction(Societe $societe)
{
$deleteForm = $this->createDeleteForm($societe);
return $this->render('societe/show.html.twig', array(
'societe' => $societe,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Societe entity.
*
* #Route("/{id}/edit", name="societe_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Societe $societe)
{
$deleteForm = $this->createDeleteForm($societe);
$editForm = $this->createForm('SocieteBundle\Form\SocieteType', $societe);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($societe);
$em->flush();
return $this->redirectToRoute('societe_edit', array('id' => $societe->getId()));
}
return $this->render('societe/edit.html.twig', array(
'societe' => $societe,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Societe entity.
*
* #Route("/{id}", name="societe_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, Societe $societe)
{
$form = $this->createDeleteForm($societe);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($societe);
$em->flush();
}
return $this->redirectToRoute('societe_index');
}
/**
* Creates a form to delete a Societe entity.
*
* #param Societe $societe The Societe entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Societe $societe)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('societe_delete', array('id' => $societe->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
Please tell me if you want me to add a file to the question, I'll edit it. Thank you in advance
edit: I can see the array with the user I selected if I dump the form content
In your SocieteType.php change:
->add('salaries', null, array(
'by_reference' => false,
)
to
->add('salaries', 'entity', array(
'class' => 'SocieteBundle\Entity\Societe',
'property' => 'raisonSociale',
)