How to display a One to Many relationship in Symfony - php

Hi I'm writing a little Web App with Symfony.
I have a one to many relation ship between two entities.
Entity one:
/**
* #ORM\Entity
* #ORM\Table(name="Helfer")
*/
class Helfer {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank()
*/
protected $name;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank()
*/
protected $lastName;
/**
* #ORM\Column(type="string")
*/
protected $tel;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank()
* #Assert\Email()
*/
protected $email;
/**
* #ORM\Column(type="string")
*/
protected $organisation;
/**
* #ORM\Column(type="integer")
* #Assert\NotBlank()
* #Assert\Range(min=6, minMessage="Du musst mindestens 6 Jahre Alt sein um bei uns helfen zu können.")
*/
protected $age;
/**
* #ORM\OneToMany(targetEntity="Aufgaben", mappedBy="helfer", cascade={"persist","remove"})
*/
protected $aufgaben;
/**
* #ORM\OneToMany(targetEntity="Zeiten", mappedBy="helfer", cascade={"persist","remove"})
*/
protected $zeiten;
/**
* Constructor
*/
public function __construct()
{
$this->aufgaben = new \Doctrine\Common\Collections\ArrayCollection();
$this->zeiten = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Helfer
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set lastName
*
* #param string $lastName
* #return Helfer
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set tel
*
* #param string $tel
* #return Helfer
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* #return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Set email
*
* #param string $email
* #return Helfer
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set organisation
*
* #param string $organisation
* #return Helfer
*/
public function setOrganisation($organisation)
{
$this->organisation = $organisation;
return $this;
}
/**
* Get organisation
*
* #return string
*/
public function getOrganisation()
{
return $this->organisation;
}
/**
* Set age
*
* #param integer $age
* #return Helfer
*/
public function setAge($age)
{
$this->age = $age;
return $this;
}
/**
* Get age
*
* #return integer
*/
public function getAge()
{
return $this->age;
}
/**
* Add aufgaben
*
* #param \DLRG\HelferBundle\Entity\Aufgaben $aufgaben
* #return Helfer
*/
public function addAufgaben(\DLRG\HelferBundle\Entity\Aufgaben $aufgaben)
{
$this->aufgaben[] = $aufgaben;
return $this;
}
/**
* Remove aufgaben
*
* #param \DLRG\HelferBundle\Entity\Aufgaben $aufgaben
*/
public function removeAufgaben(\DLRG\HelferBundle\Entity\Aufgaben $aufgaben)
{
$this->aufgaben->removeElement($aufgaben);
}
/**
* Get aufgaben
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAufgaben()
{
return $this->aufgaben;
}
/**
* Add zeiten
*
* #param \DLRG\HelferBundle\Entity\Zeiten $zeiten
* #return Helfer
*/
public function addZeiten(\DLRG\HelferBundle\Entity\Zeiten $zeiten)
{
$this->zeiten[] = $zeiten;
return $this;
}
/**
* Remove zeiten
*
* #param \DLRG\HelferBundle\Entity\Zeiten $zeiten
*/
public function removeZeiten(\DLRG\HelferBundle\Entity\Zeiten $zeiten)
{
$this->zeiten->removeElement($zeiten);
}
/**
* Get zeiten
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getZeiten()
{
return $this->zeiten;
}
}
Entity two:
/**
* #ORM\Entity
* #ORM\Table(name="Aufgaben")
*/
class Aufgaben {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $name;
/**
* #ORM\Column(type="string")
*/
protected $beschreibung;
/**
* #ORM\ManyToOne(targetEntity="Helfer", inversedBy="aufgaben")
* #ORM\JoinColumn(name="helfer_aufgaben_id", referencedColumnName="id")
*/
protected $helfer;
/**
* #ORM\OneToMany(targetEntity="Zeiten", mappedBy="aufgaben", cascade={"persist","remove"})
*/
protected $zeiten;
/**
* Constructor
*/
public function __construct()
{
$this->zeiten = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Aufgaben
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set beschreibung
*
* #param string $beschreibung
* #return Aufgaben
*/
public function setBeschreibung($beschreibung)
{
$this->beschreibung = $beschreibung;
return $this;
}
/**
* Get beschreibung
*
* #return string
*/
public function getBeschreibung()
{
return $this->beschreibung;
}
/**
* Set helfer
*
* #param \DLRG\HelferBundle\Entity\Helfer $helfer
* #return Aufgaben
*/
public function setHelfer(\DLRG\HelferBundle\Entity\Helfer $helfer = null)
{
$this->helfer = $helfer;
return $this;
}
/**
* Get helfer
*
* #return \DLRG\HelferBundle\Entity\Helfer
*/
public function getHelfer()
{
return $this->helfer;
}
/**
* Add zeiten
*
* #param \DLRG\HelferBundle\Entity\Zeiten $zeiten
* #return Aufgaben
*/
public function addZeiten(\DLRG\HelferBundle\Entity\Zeiten $zeiten)
{
$this->zeiten[] = $zeiten;
return $this;
}
/**
* Remove zeiten
*
* #param \DLRG\HelferBundle\Entity\Zeiten $zeiten
*/
public function removeZeiten(\DLRG\HelferBundle\Entity\Zeiten $zeiten)
{
$this->zeiten->removeElement($zeiten);
}
/**
* Get zeiten
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getZeiten()
{
return $this->zeiten;
}
}
My database has entries in Aufgaben table. Now my user should enter their names and attributes in Helfer.php. Than the user should choose some values from the Aufgaben Entity.
I try to add the Values from Aufgaben.php to a collection.
class HelferType extends AbstractType {
private $aufgaben;
public function __construct($aufgaben) {
$this->aufgaben = $aufgaben;
}
/**
*
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add ( 'name' )->add ( 'lastName' )->add ( 'tel' )->add ( 'email' )->add ( 'organisation' )->add ( 'age' );
$builder->add ( 'aufgaben', 'collection', array (
'type' => 'choice',
'options' => array (
'choices' => $this->aufgaben
)
) );
}
But this code doesn't work.
Any Ideas ?
Workflow should be:
Enter User information
Choose one or more values from Aufgaben.php
Save all
Thanks in advance

Depending on your exact needs, one possible solution would be to use an entity form type.
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add ( 'name' )->add ( 'lastName' )->add ( 'tel' )->add ( 'email' )->add ( 'organisation' )->add ( 'age' );
$builder->add ( 'aufgaben', 'entity', array (
'class' => 'YourBundle:Aufgaben',
'multiple' => true,
'property' => 'name',
'choices' => $this->aufgaben
)
);
}
This would result in a SELECT tag in your HTML.

maybe this and this can help you.
I resolve this kind of cases overriding the __toString() method in my entity file, not the repository file.

Related

Symfony Catchable Fatal Error: Object of class DataBundle\Entity\Location could not be converted to string

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

Load choices into form choice field from entity method

I have symfony form with choice field. I want to load choices from my entity class static method. can i use data or CallbackChoiceLoader? what is the best practise?
this is my field:
class CarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', ChoiceType::class, [
// This choices I would like to load from:
// 'choices' => $car::getTypes(),
'choices' => [
'Critical' => 'critical',
'Medium' => 'medium',
'Info' => 'info',
],
'label' => 'Type'
])
->add('name', TextType::class, [
'label' => 'Name'
])
->add('save', SubmitType::class, [
'label' => 'Save'
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\Car'
]);
}
public function getName()
{
return 'car';
}
}
This is my entity:
/**
* #ORM\Entity
* #ORM\Table(name="car")
*/
class Car
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $type
*
* #Assert\NotBlank()
* #ORM\Column(name="type")
*/
private $type;
/**
* #var string $name
*
* #Assert\NotBlank()
* #ORM\Column(name="name")
*/
private $name;
/**
* #var \DateTime $created
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
private static $types = ['main', 'custom'];
public function __construct()
{
$this->created = new \DateTime('now', new \DateTimeZone('Europe/Ljubljana'));
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get types
*
* #return array
*/
public function getTypes()
{
return self::$types;
}
/**
* Set type
*
* #param string $type
*
* #return Car
*/
public function setType($type)
{
if (in_array($type, $this->getTypes())) {
$this->type = $type;
}
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
/**
* Set name
*
* #param string $name
*
* #return Car
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return Car
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
How and what can i use to load choices from $car::getTypes() method like i commented in form so that the choices are loaded dynamicly based on values in getTypes entity method?
Edit: This is option 1. Option 2 below more directly answers the question.
The preferred method of creating a choice form field from an entity is to use the EntityType field. Here is an example from an application that requires an ethnicity field. Below that is the Ethnicity entity.
form field:
->add('ethnicity', EntityType::class, array(
'label' => 'Ethnicity:',
'class' => 'AppBundle:Ethnicity',
'choice_label' => 'abbreviation',
'expanded' => false,
'placeholder' => 'Select ethnicity',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('e')
->orderBy('e.abbreviation', 'ASC')
;
},
))
Ethnicity entity:
/**
* Ethnicity.
*
* #ORM\Table(name="ethnicity")
* #ORM\Entity
*/
class Ethnicity
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="ethnicity", type="string", length=45, nullable=true)
*/
protected $ethnicity;
/**
* #var string
*
* #ORM\Column(name="abbr", type="string", length=45, nullable=true)
*/
protected $abbreviation;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Member", mappedBy="ethnicity", cascade={"persist"})
*/
protected $members;
/**
* Constructor.
*/
public function __construct()
{
$this->members = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set ethnicity.
*
* #param string $ethnicity
*
* #return Ethnicity
*/
public function setEthnicity($ethnicity)
{
$this->ethnicity = $ethnicity;
return $this;
}
/**
* Get ethnicity.
*
* #return string
*/
public function getEthnicity()
{
return $this->ethnicity;
}
/**
* Set abbreviation.
*
* #param string $abbreviation
*
* #return Ethnicity
*/
public function setAbbreviation($abbreviation)
{
$this->abbreviation = $abbreviation;
return $this;
}
/**
* Get abbreviation.
*
* #return string
*/
public function getAbbreviation()
{
return $this->abbreviation;
}
/**
* Add members.
*
* #param \AppBundle\Entity\Member $members
*
* #return Ethnicity
*/
public function addMember(\AppBundle\Entity\Member $members)
{
$this->members[] = $members;
return $this;
}
/**
* Remove members.
*
* #param \AppBundle\Entity\Member $members
*/
public function removeMember(\Truckee\ProjectmanaBundle\Entity\Member $members)
{
$this->members->removeElement($members);
}
/**
* Get members.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMembers()
{
return $this->members;
}
/**
* #var bool
*
* #ORM\Column(name="enabled", type="boolean", nullable=true)
*/
protected $enabled;
/**
* Set enabled.
*
* #param bool $enabled
*
* #return enabled
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled.
*
* #return bool
*/
public function getEnabled()
{
return $this->enabled;
}
}
Option 2:
If you really want to do that, then here's an approach:
Modify your static property $types such that the choices are values in an array, e.g., $types = array(1 => 'main', 2 => 'custom')
In your controller, add a use statement for the Car entity.
In controller action:
$car = new Car();
$types = $car->getTypes;
Use the answer to Passing data to buildForm() in Symfony 2.8/3.0 to see how to pass $types to your form.

Sonata Admin Bundle Many-to-Many relationship not saving foreign ID

Here is my problem. I have two entities with a Many-To-Many relationship and would like to insert in a field multiple information.
I use sonata admin for administration, and here is my code:
Notification Class:
<?php
namespace App\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Notification
*
* #ORM\Table(name="notification")
* #ORM\Entity
*/
class Notification {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="message", type="string", length=255)
*/
private $message;
/**
* #ORM\ManyToMany(targetEntity="Etudiant",mappedBy="notification")
*/
private $etudiant;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set message
*
* #param string $message
* #return Notification
*/
public function setMessage($message) {
$this->message = $message;
return $this;
}
/**
* Get message
*
* #return string
*/
public function getMessage() {
return $this->message;
}
public function __toString() {
return $this->message;
}
public function __construct() {
$this->etudiant = new \Doctrine\Common\Collections\ArrayCollection();
}
public function setEtudiant($etudiant) {
if (count($etudiant) > 0) {
foreach ($etudiant as $i) {
$this->addEtudiant($i);
}
}
return $this;
}
/**
* Add etudiant
*
* #param \App\BlogBundle\Entity\Etudiant $etudiant
* #return Notification
*/
public function addEtudiant(\App\BlogBundle\Entity\Etudiant $etudiant)
{
$this->etudiant[] = $etudiant;
return $this;
}
/**
* Remove etudiant
*
* #param \App\BlogBundle\Entity\Etudiant $etudiant
*/
public function removeEtudiant(\App\BlogBundle\Entity\Etudiant $etudiant)
{
$this->etudiant->removeElement($etudiant);
}
/**
* Get etudiant
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getEtudiant()
{
return $this->etudiant;
}
}
Etudiant Class:
<?php
namespace App\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Etudiant
*
* #ORM\Table(name="etudiant")
* #ORM\Entity
*/
class Etudiant{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom", type="string", length=255)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="prenom", type="string", length=255)
*/
private $prenom;
/**
* #var \DateTime
*
* #ORM\Column(name="date_naissance", type="datetime")
*/
private $dateNaissance;
/**
* #var string
*
* #ORM\Column(name="adresse", type="text")
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var int
*
* #ORM\Column(name="telephone", type="integer")
*/
private $telephone;
/**
* #var string
*
* #ORM\Column(name="num_inscription", type="string", length=255)
*/
private $numInscription;
/**
* #var \DateTime
*
* #ORM\Column(name="date_inscription", type="datetime")
*/
private $dateInscription;
/**
* #var int
*
* #ORM\Column(name="frais_scolarite", type="integer")
*/
private $fraisScolarite;
/**
* #ORM\ManyToMany(targetEntity="Notification",inversedBy="etudiant")
*#ORM\JoinColumn(name="user_notificaiton")
*/
private $notification;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* #param string $nom
* #return Etudiant
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
* #return Etudiant
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set dateNaissance
*
* #param \DateTime $dateNaissance
* #return Etudiant
*/
public function setDateNaissance($dateNaissance)
{
$this->dateNaissance = $dateNaissance;
return $this;
}
/**
* Get dateNaissance
*
* #return \DateTime
*/
public function getDateNaissance()
{
return $this->dateNaissance;
}
/**
* Set adresse
*
* #param string $adresse
* #return Etudiant
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set email
*
* #param string $email
* #return Etudiant
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set telephone
*
* #param integer $telephone
* #return Etudiant
*/
public function setTelephone($telephone)
{
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* #return integer
*/
public function getTelephone()
{
return $this->telephone;
}
/**
* Set numInscription
*
* #param string $numInscription
* #return Etudiant
*/
public function setNumInscription($numInscription)
{
$this->numInscription = $numInscription;
return $this;
}
/**
* Get numInscription
*
* #return string
*/
public function getNumInscription()
{
return $this->numInscription;
}
/**
* Set dateInscription
*
* #param \DateTime $dateInscription
* #return Etudiant
*/
public function setDateInscription($dateInscription)
{
$this->dateInscription = $dateInscription;
return $this;
}
/**
* Get dateInscription
*
* #return \DateTime
*/
public function getDateInscription()
{
return $this->dateInscription;
}
/**
* Set fraisScolarite
*
* #param integer $fraisScolarite
* #return Etudiant
*/
public function setFraisScolarite($fraisScolarite)
{
$this->fraisScolarite = $fraisScolarite;
return $this;
}
/**
* Get fraisScolarite
*
* #return integer
*/
public function getFraisScolarite()
{
return $this->fraisScolarite;
}
public function __toString() {
return $this->nom;
}
public function __construct() {
$this->notification = new \Doctrine\Common\Collections\ArrayCollection();
}
function setNotification($notification) {
if (count($notification) > 0) {
foreach ($notification as $i) {
$this->addEtudiant($i);
}
}
return $this;
}
/**
* Add notification
*
* #param \App\BlogBundle\Entity\Notification $notification
* #return Etudiant
*/
public function addNotification(\App\BlogBundle\Entity\Notification $notification)
{
$this->notification[] = $notification;
return $this;
}
/**
* Remove notification
*
* #param \App\BlogBundle\Entity\Notification $notification
*/
public function removeNotification(\App\BlogBundle\Entity\Notification $notification)
{
$this->notification->removeElement($notification);
}
/**
* Get notification
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNotification()
{
return $this->notification;
}
}
Finally My NotificationAdmin:
<?php
namespace App\BlogBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
class NotificationAdmin extends Admin {
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper) {
$formMapper
->add('message', 'text')
->add('etudiant', 'sonata_type_model', array(
'required' => false,
'multiple' => true
))
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
$datagridMapper
->add('message')
->add('etudiant')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper) {
$listMapper
->addIdentifier('message')
->add('etudiant')
;
}
// Fields to be shown on show action
protected function configureShowFields(ShowMapper $showMapper) {
$showMapper
->add('id')
->add('nom')
;
}
public function prePersist($notification){
$this->preUpdate($notification);
}
public function preUpdate($notification){
$notification->setEtudiant($notification);
}
public function getBatchActions() {
// retrieve the default batch actions (currently only delete)
$actions = parent::getBatchActions();
if (
$this->hasRoute('edit') && $this->isGranted('EDIT') &&
$this->hasRoute('delete') && $this->isGranted('DELETE')
) {
$actions['merge'] = array(
'label' => 'action_merge',
'translation_domain' => 'SonataAdminBundle',
'ask_confirmation' => true
);
}
return $actions;
}
}
And there is nothing in my table "etudiant_notification".
Please make the following changes (bold lines) to your code:
Notification.php
/**
* Add etudiant
*
* #param \App\BlogBundle\Entity\Etudiant $etudiant
* #return Notification
*/
public function addEtudiant(\App\BlogBundle\Entity\Etudiant $etudiant)
{
$etudiant->addNotification($this);
$this->etudiant[] = $etudiant;
return $this;
}
Etudiant.php
/**
* Add notification
*
* #param \App\BlogBundle\Entity\Notification $notification
* #return Etudiant
*/
public function addNotification(\App\BlogBundle\Entity\Notification $notification)
{
$notification->addEtudiant($this);
$this->notification[] = $notification;
return $this;
}
and check what happens. No guarantee, but you can give it a try. Bonne chance!

ZF2 Doctrine get manytomany relations with objectSelect

I have multiple users, with multiple stores in a many to many relational database. Every user has multiple stores attached to them.
Now, i want to load all the storenames from a logged in user in a select form.
How can i do this?
My user entity:
namespace Application\Entity;
use BjyAuthorize\Provider\Role\ProviderInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use ZfcUser\Entity\UserInterface;
/**
* An example of how to implement a role aware user entity.
*
* #ORM\Entity
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Application\Repositories\UserRepository")
*
*/
class User implements UserInterface, ProviderInterface
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=255, unique=true, nullable=true)
*/
protected $username;
/**
* #var string
* #ORM\Column(type="string", unique=true, length=255)
*/
protected $email;
/**
* #var string
* #ORM\Column(type="string", length=50, nullable=true)
*/
protected $displayName;
/**
* #var string
* #ORM\Column(type="string", length=128)
*/
protected $password;
/**
* #var int
*/
protected $state;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Role")
* #ORM\JoinTable(name="user_role_linker",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
protected $roles;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Store")
* #ORM\JoinTable(name="user_store_linker",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="store_id", referencedColumnName="id")}
* )
*/
protected $stores;
/**
* Initialies the roles variable.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
$this->stores = new ArrayCollection();
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id
*
* #return void
*/
public function setId($id)
{
$this->id = (int) $id;
}
/**
* Get username.
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set username.
*
* #param string $username
*
* #return void
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Get email.
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
*
* #param string $email
*
* #return void
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get displayName.
*
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set displayName.
*
* #param string $displayName
*
* #return void
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* Get password.
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
*
* #param string $password
*
* #return void
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get state.
*
* #return int
*/
public function getState()
{
return $this->state;
}
/**
* Set state.
*
* #param int $state
*
* #return void
*/
public function setState($state)
{
$this->state = $state;
}
/**
* Get role.
*
* #return array
*/
public function getRoles()
{
return $this->roles->getValues();
}
/**
* Add a role to the user.
*
* #param Role $role
*
* #return void
*/
public function addRole($role)
{
$this->roles[] = $role;
}
/**
* Get store.
*
* #return array
*/
public function getStores()
{
return $this->stores;
}
/**
* Get store.
*
* #return array
*/
public function getStore($id)
{
return $this->stores[$id]->getValues();
}
/**
* Add a store to the user.
*
* #param Role $store
*
* #return void
*/
public function addStore($store)
{
$this->stores[] = $store;
}
}
My store Entity:
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* An example entity that represents a store.
*
* #ORM\Entity
* #ORM\Table(name="store")
*
*/
class Store
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", name="storeName", length=255, unique=true, nullable=true)
*/
protected $storeName;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Product" )
*/
protected $products;
/**
* Initialies the roles variable.
*/
public function __construct()
{
$this->products = new ArrayCollection();
}
/**
* Get the id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set the id.
*
* #param int $id
*
* #return void
*/
public function setId($id)
{
$this->id = (int)$id;
}
/**
* Get the store id.
*
* #return string
*/
public function getStoreName()
{
return $this->storeName;
}
/**
* Set the store id.
*
* #param string $storeName
*
* #return void
*/
public function setStoreName($storeName)
{
$this->storeName = (string) $storeName;
}
/**
* Get product.
*
* #return array
*/
public function getProducts()
{
return $this->products->getValues();
}
/**
* Add a product to the user.
*
* #param Role $product
*
* #return void
*/
public function addProduct($products)
{
$this->products[] = $products;
}
}
My form:
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'stores',
'attributes' => array(
'multiple' => true,
),
'options' => array(
'object_manager' => $objectManager,
'target_class' => 'Application\Entity\User',
'label' => 'Selecteer winkel',
'column-size' => 'sm-9',
'label_attributes' => array('class' => 'col-sm-3 control-label'),
'property' => 'stores',
'find_method' => array(
'name' => 'findBy',
'params' => array(
'criteria' => array('id' => $userid)
),
),
'is_method' => true,
),
));
I'm getting this message:
File:
zend/vendor/zendframework/zendframework/library/Zend/View/Helper/Escaper/AbstractHelper.php:70
Message:
Object provided to Escape helper, but flags do not allow recursion
Anyone?
Ok i've figured it out with a custom repository.
Add a repositoryclass to your store entity
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Entity
* #ORM\Table(name="store")
* #ORM\Entity(repositoryClass="Application\Repositories\StoreRepository")
*
*/
class Store
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", name="storeName", length=255, unique=true, nullable=true)
*/
protected $storeName;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Product", inversedBy="stores")
* #ORM\JoinTable(name="product_store")
*/
protected $products;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Category", inversedBy="stores")
* #ORM\JoinTable(name="category_store")
*/
protected $categories;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\User", inversedBy="stores")
* #ORM\JoinTable(name="user_store")
*/
protected $users;
/**
* Initialies the roles variable.
*/
public function __construct()
{
$this->products = new ArrayCollection();
$this->categories = new ArrayCollection();
$this->users = new ArrayCollection();
}
/**
* Get the id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set the id.
*
* #param int $id
*
* #return void
*/
public function setId($id)
{
$this->id = (int)$id;
}
/**
* Get the store id.
*
* #return string
*/
public function getStoreName()
{
return $this->storeName;
}
/**
* Set the store id.
*
* #param string $storeName
*
* #return void
*/
public function setStoreName($storeName)
{
$this->storeName = (string) $storeName;
}
/**
* Get product.
*
* #return array
*/
public function getProducts()
{
return $this->products->getValues();
}
/**
* Add a product to the user.
*
* #param Role $product
*
* #return void
*/
public function addProduct($products)
{
$this->products[] = $products;
}
/**
* Get category.
*
* #return array
*/
public function getCategories()
{
return $this->categories->getValues();
}
/**
* Add a product to the user.
*
* #param Role $product
*
* #return void
*/
public function addCategory($categories)
{
$this->categories[] = $categories;
}
/**
* Get category.
*
* #return array
*/
public function getUsers()
{
return $this->users->getValues();
}
/**
* Add a product to the user.
*
* #param Role $product
*
* #return void
*/
public function addUser($users)
{
$this->users[] = $users;
}
}
My user entity
namespace Application\Entity;
use BjyAuthorize\Provider\Role\ProviderInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use ZfcUser\Entity\UserInterface;
/**
*
* #ORM\Entity
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="Application\Repositories\UserRepository")
*
*/
class User implements UserInterface, ProviderInterface
{
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(type="string", length=255, unique=true, nullable=true)
*/
protected $username;
/**
* #var string
* #ORM\Column(type="string", unique=true, length=255)
*/
protected $email;
/**
* #var string
* #ORM\Column(type="string", length=50, nullable=true)
*/
protected $displayName;
/**
* #var string
* #ORM\Column(type="string", length=128)
*/
protected $password;
/**
* #var int
*/
protected $state;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Role")
* #ORM\JoinTable(name="user_role_linker",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
protected $roles;
/**
* #var \Doctrine\Common\Collections\Collection
* #ORM\ManyToMany(targetEntity="Application\Entity\Store", mappedBy="users")
*/
protected $stores;
/**
* Initialies the roles variable.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
$this->stores = new ArrayCollection();
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id
*
* #return void
*/
public function setId($id)
{
$this->id = (int) $id;
}
/**
* Get username.
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set username.
*
* #param string $username
*
* #return void
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* Get email.
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set email.
*
* #param string $email
*
* #return void
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get displayName.
*
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set displayName.
*
* #param string $displayName
*
* #return void
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
/**
* Get password.
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set password.
*
* #param string $password
*
* #return void
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get state.
*
* #return int
*/
public function getState()
{
return $this->state;
}
/**
* Set state.
*
* #param int $state
*
* #return void
*/
public function setState($state)
{
$this->state = $state;
}
/**
* Get role.
*
* #return array
*/
public function getRoles()
{
return $this->roles->getValues();
}
/**
* Add a role to the user.
*
* #param Role $role
*
* #return void
*/
public function addRole($role)
{
$this->roles[] = $role;
}
/**
* Get store.
*
* #return array
*/
public function getStores()
{
return $this->stores;
}
/**
* Get store.
*
* #return array
*/
public function getStore($id)
{
return $this->stores[$id]->getValues();
}
/**
* Add a store to the user.
*
* #param Role $store
*
* #return void
*/
public function addStore($store)
{
$this->stores[] = $store;
}
}
The object select
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'stores',
'attributes' => array(
'multiple' => true,
),
'options' => array(
'object_manager' => $objectManager,
'target_class' => 'Application\Entity\Store',
'label' => 'Selecteer winkel',
'column-size' => 'sm-9',
'label_attributes' => array('class' => 'col-sm-3 control-label'),
'property' => 'storeName',
'is_method' => true,
'find_method' => array(
'name' => 'storesByUser',
'params' => array(
'criteria' => array('id' => $userid),
),
),
),
));
My custom store repository
<?php
namespace Application\Repositories;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\DBAL\Types\Type;
class StoreRepository extends EntityRepository
{
public function storesByUser(array $criteria){
return $this->createQueryBuilder('s')
->select('s')
->innerJoin("s.users", "u", "WITH", "u=:userid")
->setParameter("userid", $criteria['id'])
->getQuery()->getResult();
}
}

Persist Many to Many relationship in different steps

Hi I try to solve this problem now for days. But I don't get it so I hope you can help me.
I have the entity Worker and it's in a many to many relation ship with the Task entity.
Now I don't want my user to do all input at one time. At first the user should enter his details and if they are valid he can choose his tasks.
So I added three methods to the standard generated code and change the url path in the createAction().
But if I press the submit button in my AddTaskType form there is nothing persisted to the database.
I hope you have suggestions for this problem.
//Worker Entity
namespace DLRG\HelferBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity
* #ORM\Table(name="Workers")
*/
class Worker {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank()
*/
protected $name;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank()
*/
protected $lastName;
/**
* #ORM\Column(type="string")
*/
protected $tel;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank()
* #Assert\Email()
*/
protected $email;
/**
* #ORM\Column(type="string")
*/
protected $organisation;
/**
* #ORM\Column(type="integer")
* #Assert\NotBlank()
* #Assert\Range(min=6, minMessage="Du musst mindestens 6 Jahre Alt sein um bei uns helfen zu können.")
*/
protected $age;
/**
* #ORM\ManyToMany(targetEntity="Task", inversedBy="workers")
* #ORM\JoinTable(name="workers_tasks")
*/
protected $tasks;
/**
* #ORM\ManyToMany(targetEntity="Time", inversedBy="workers")
* #ORM\JoinTable(name="workers_times")
*/
protected $times;
/**
* Constructor
*/
public function __construct() {
$this->tasks = new \Doctrine\Common\Collections\ArrayCollection ();
$this->times = new \Doctrine\Common\Collections\ArrayCollection ();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Worker
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set lastName
*
* #param string $lastName
* #return Worker
*/
public function setLastName($lastName) {
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName() {
return $this->lastName;
}
/**
* Set tel
*
* #param string $tel
* #return Worker
*/
public function setTel($tel) {
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* #return string
*/
public function getTel() {
return $this->tel;
}
/**
* Set email
*
* #param string $email
* #return Worker
*/
public function setEmail($email) {
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail() {
return $this->email;
}
/**
* Set organisation
*
* #param string $organisation
* #return Worker
*/
public function setOrganisation($organisation) {
$this->organisation = $organisation;
return $this;
}
/**
* Get organisation
*
* #return string
*/
public function getOrganisation() {
return $this->organisation;
}
/**
* Set age
*
* #param integer $age
* #return Worker
*/
public function setAge($age) {
$this->age = $age;
return $this;
}
/**
* Get age
*
* #return integer
*/
public function getAge() {
return $this->age;
}
/**
* Add tasks
*
* #param \DLRG\HelferBundle\Entity\Task $tasks
* #return Worker
*/
public function addTask(\DLRG\HelferBundle\Entity\Task $task) {
$task->addWorker ( $this );
$this->tasks [] = $task;
return $this;
}
/**
* Remove tasks
*
* #param \DLRG\HelferBundle\Entity\Task $tasks
*/
public function removeTask(\DLRG\HelferBundle\Entity\Task $tasks) {
$this->tasks->removeElement ( $tasks );
}
/**
* Get tasks
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTasks() {
return $this->tasks;
}
/**
* Add times
*
* #param \DLRG\HelferBundle\Entity\Time $times
* #return Worker
*/
public function addTime(\DLRG\HelferBundle\Entity\Time $time) {
$time->addWorker ( $this );
$this->times [] = $time;
return $this;
}
/**
* Remove times
*
* #param \DLRG\HelferBundle\Entity\Time $times
*/
public function removeTime(\DLRG\HelferBundle\Entity\Time $times) {
$this->times->removeElement ( $times );
}
/**
* Get times
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTimes() {
return $this->times;
}
}
//TaskEntity
namespace DLRG\HelferBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="Tasks")
*/
class Task {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
*/
protected $name;
/**
* #ORM\Column(type="string")
*/
protected $description;
/**
* #ORM\ManyToMany(targetEntity="Time", mappedBy="tasks")
*/
protected $times;
/**
* #ORM\ManyToMany(targetEntity="Worker", mappedBy="tasks")
*/
protected $workers;
public function __toString() {
return $this->name;
}
/**
* Constructor
*/
public function __construct() {
$this->times = new \Doctrine\Common\Collections\ArrayCollection ();
$this->workers = new \Doctrine\Common\Collections\ArrayCollection ();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Task
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Task
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* Add times
*
* #param \DLRG\HelferBundle\Entity\Time $times
* #return Task
*/
public function addTime(\DLRG\HelferBundle\Entity\Time $time) {
$this->times [] = $time;
return $this;
}
/**
* Remove times
*
* #param \DLRG\HelferBundle\Entity\Time $times
*/
public function removeTime(\DLRG\HelferBundle\Entity\Time $times) {
$this->times->removeElement ( $times );
}
/**
* Get times
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTimes() {
return $this->times;
}
/**
* Add workers
*
* #param \DLRG\HelferBundle\Entity\Worker $workers
* #return Task
*/
public function addWorker(\DLRG\HelferBundle\Entity\Worker $worker) {
$this->workers [] = $worker;
return $this;
}
/**
* Remove workers
*
* #param \DLRG\HelferBundle\Entity\Worker $workers
*/
public function removeWorker(\DLRG\HelferBundle\Entity\Worker $workers) {
$this->workers->removeElement ( $workers );
}
/**
* Get workers
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getWorkers() {
return $this->workers;
}
}
The added methods
//WorkerController.php
/**
* Add task to a Worker
*
* #Route("/", name="task_add")
* #Method("POST")
* #Template("DLRGHelferBundle:Task:add.html.twig")
*/
public function addTask(Request $request, $id) {
$em = $this->getDoctrine ()->getManager ();
$entity = $em->getRepository ( 'DLRGHelferBundle:Worker' )->find ( $id );
if (! $entity) {
throw $this->createNotFoundException ( 'Unable to find Worker entity.' );
}
$form = $this->createAddTaskForm ( $entity );
$form->handleRequest ( $request );
if ($form->isValid ()) {
$formData = $form->get ( 'tasks' )->getData ();
foreach ( $formData as $task ) {
$entity->addTask ( $task );
}
$em->persist ( $entity );
$em->flush ();
return $this->redirect ( $this->generateUrl ( 'worker_show', array (
'id' => $entity->getId ()
) ) );
}
return array (
'entity' => $entity,
'form' => $form->createView ()
);
}
/**
* Creates a form to add a Task to Worker entity.
*
* #param Worker $entity
* The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createAddTaskForm(Worker $entity) {
$form = $this->createForm ( new AddTaskType (), $entity, array (
'action' => $this->generateUrl ( 'task_add', array (
'id' => $entity->getId ()
) ),
'method' => 'POST'
) );
$form->add ( 'submit', 'submit', array (
'label' => 'Zeiten'
) );
return $form;
}
/**
* Displays a form to create a new Worker entity.
*
* #Route("/new/{id}/addTask", name="worker_task")
* #Method("GET")
* #Template()
*/
public function addAction($id) {
$em = $this->getDoctrine ()->getManager ();
$entity = $em->getRepository ( 'DLRGHelferBundle:Worker' )->find ( $id );
if (! $entity) {
throw $this->createNotFoundException ( 'Unable to find Worker entity.' );
}
$form = $this->createAddTaskForm ( $entity );
return array (
'entity' => $entity,
'form' => $form->createView ()
);
}
My AddTaskType looks like this:
namespace DLRG\HelferBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use DLRG\HelferBundle\Controller\HelferController;
class AddTaskType extends AbstractType {
/**
*
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add ( 'tasks', 'entity', array (
'class' => 'DLRGHelferBundle:Task',
'property' => 'name',
'multiple' => true
) );
}
/**
*
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults ( array (
'data_class' => 'DLRG\HelferBundle\Entity\Worker'
) );
}
/**
*
* #return string
*/
public function getName() {
return 'dlrg_helferbundle_addTask';
}
}

Categories