I'm attempting to create a OneToOne Undirectional relationship between two entities. I've created the schema but when I submit the form it does not persist the data to the collection. Based off all my research I suspect it's because I don't have the owning entity set up correctly but I've tried everything I can to figure it out with no luck.
Entity - Products.php (Owning Side)
<?php
namespace SCWDesignsBundle\Entity\Products;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Mapping\ClassMetaData;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="SCWDesignsBundle\Entity\Repository\Products\ProductRespository")
* #ORM\Table(name="products")
*/
class Products {
/**
* #ORM\ID
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="ProductCategories")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
* #Assert\NotBlank()
*/
protected $category_id;
/**
* #ORM\Column(type="boolean", options={"default" = 0})
*/
protected $featured;
/**
* #ORM\Column(type="boolean", options={"default" = 1})
*/
protected $enabled;
/**
* #ORM\Column(type="boolean", options={"default" = 0})
*/
protected $free_shipping;
/**
* #ORM\OneToOne(targetEntity="ProductSales")
* #ORM\JoinColumn(name="participate_sale", referencedColumnName="id")
*/
protected $participate_sale;
/**
* #ORM\Column(type="decimal")
*/
protected $price;
/**
* #ORM\Column(type="integer")
*/
protected $sku;
/**
* #ORM\Column(type="datetime")
*/
protected $arrival_date;
/**
* #ORM\Column(type="datetime")
*/
protected $update_date;
/*
* ArrayCollection for ProductDescription
* #ORM\OneToOne(targetEntity="ProductDescription", mappedBy="product_id", cascade={"persist"})
* #ORM\JoinColumn(name="description", referencedColumnName="product_id")
*/
protected $description;
public function __construct() {
$this->setArrivalDate(new \DateTime());
$this->description = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set featured
*
* #param boolean $featured
* #return Products
*/
public function setFeatured($featured) {
$this->featured = $featured;
return $this;
}
/**
* Get featured
*
* #return boolean
*/
public function getFeatured() {
return $this->featured;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return Products
*/
public function setEnabled($enabled) {
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled() {
return $this->enabled;
}
/**
* Set free_shipping
*
* #param boolean $freeShipping
* #return Products
*/
public function setFreeShipping($freeShipping) {
$this->free_shipping = $freeShipping;
return $this;
}
/**
* Get free_shipping
*
* #return boolean
*/
public function getFreeShipping() {
return $this->free_shipping;
}
/**
* Set price
*
* #param string $price
* #return Products
*/
public function setPrice($price) {
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice() {
return $this->price;
}
/**
* Set sku
*
* #param integer $sku
* #return Products
*/
public function setSku($sku) {
$this->sku = $sku;
return $this;
}
/**
* Get sku
*
* #return integer
*/
public function getSku() {
return $this->sku;
}
/**
* Set arrival_date
*
* #param \DateTime $arrivalDate
* #return Products
*/
public function setArrivalDate($arrivalDate) {
$this->arrival_date = $arrivalDate;
return $this;
}
/**
* Get arrival_date
*
* #return \DateTime
*/
public function getArrivalDate() {
return $this->arrival_date;
}
/**
* Set update_date
*
* #param \DateTime $updateDate
* #return Products
*/
public function setUpdateDate($updateDate) {
$this->update_date = $updateDate;
return $this;
}
/**
* Get update_date
*
* #return \DateTime
*/
public function getUpdateDate() {
return $this->update_date;
}
/**
* Set category_id
*
* #param \SCWDesignsBundle\Entity\Products\ProductCategories $categoryId
* #return Products
*/
public function setCategoryId(\SCWDesignsBundle\Entity\Products\ProductCategories $categoryId = null) {
$this->category_id = $categoryId;
return $this;
}
/**
* Get category_id
*
* #return \SCWDesignsBundle\Entity\Products\ProductCategories
*/
public function getCategoryId() {
return $this->category_id;
}
/**
* Set participate_sale
*
* #param \SCWDesignsBundle\Entity\Products\ProductSales $participateSale
* #return Products
*/
public function setParticipateSale(\SCWDesignsBundle\Entity\Products\ProductSales $participateSale = null) {
$this->participate_sale = $participateSale;
return $this;
}
/**
* Get participate_sale
*
* #return \SCWDesignsBundle\Entity\Products\ProductSales
*/
public function getParticipateSale() {
return $this->participate_sale;
}
/**
* Set description
*
* #param \SCWDesignsBundle\Entity\Products\ProductDescrition $description
* #return Products
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
}
Entity - ProductDescription.php
<?php
namespace SCWDesignsBundle\Entity\Products;
use Doctrine\ORM\Mapping as ORM;
use SCWDesignsBundle\Entity\BaseEntity;
use Symfony\Component\Validator\Mapping\ClassMetaData;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="product_description")
*/
class ProductDescription extends BaseEntity {
/**
* #ORM\ManyToOne(targetEntity="Products")
* #ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $product_id;
/**
* #ORM\Column(type="string", columnDefinition="VARCHAR(255)")
* #Assert\Length(
* min = 2,
* max = 255,
* minMessage = "The item name must be at least {{ limit }} characters long.",
* maxMessage = "The item name cannot be longer than {{ limit }} characters."
* )
* #Assert\NotBlank()
*/
protected $name;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank()
*/
protected $brief_description;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank()
*/
protected $full_description;
/**
* #ORM\Column(type="string", columnDefinition="VARCHAR(255)")
* #Assert\Length(
* min = 2,
* max = 255,
* minMessage = "The tags characters must be at least {{ limit }} characters long.",
* maxMessage = "The tags characters cannot be longer than {{ limit }} characters."
* )
* #Assert\NotBlank()
*/
protected $meta_tags;
/**
* #ORM\Column(type="string", columnDefinition="VARCHAR(255)")
* #Assert\Length(
* min = 2,
* max = 255,
* minMessage = "The tags title must be at least {{ limit }} characters long.",
* maxMessage = "The tags title cannot be longer than {{ limit }} characters."
* )
* #Assert\NotBlank()
*/
protected $meta_title;
/**
* #ORM\Column(type="text")
* #Assert\NotBlank()
*/
protected $meta_description;
/**
* Set name
*
* #param string $name
* #return ProductDescription
*/
public function setName($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName() {
return $this->name;
}
/**
* Set brief_description
*
* #param string $briefDescription
* #return ProductDescription
*/
public function setBriefDescription($briefDescription) {
$this->brief_description = $briefDescription;
return $this;
}
/**
* Get brief_description
*
* #return string
*/
public function getBriefDescription() {
return $this->brief_description;
}
/**
* Set full_description
*
* #param string $fullDescription
* #return ProductDescription
*/
public function setFullDescription($fullDescription) {
$this->full_description = $fullDescription;
return $this;
}
/**
* Get full_description
*
* #return string
*/
public function getFullDescription() {
return $this->full_description;
}
/**
* Set meta_tags
*
* #param string $metaTags
* #return ProductDescription
*/
public function setMetaTags($metaTags) {
$this->meta_tags = $metaTags;
return $this;
}
/**
* Get meta_tags
*
* #return string
*/
public function getMetaTags() {
return $this->meta_tags;
}
/**
* Set meta_title
*
* #param string $metaTitle
* #return ProductDescription
*/
public function setMetaTitle($metaTitle) {
$this->meta_title = $metaTitle;
return $this;
}
/**
* Get meta_title
*
* #return string
*/
public function getMetaTitle() {
return $this->meta_title;
}
/**
* Set meta_description
*
* #param string $metaDescription
* #return ProductDescription
*/
public function setMetaDescription($metaDescription) {
$this->meta_description = $metaDescription;
return $this;
}
/**
* Get meta_description
*
* #return string
*/
public function getMetaDescription() {
return $this->meta_description;
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set product_id
*
* #param \SCWDesignsBundle\Entity\Products\Products $productId
* #return ProductDescription
*/
public function setProductId(\SCWDesignsBundle\Entity\Products\Products $productId = null) {
$this->product_id = $productId;
return $this;
}
/**
* Get product_id
*
* #return \SCWDesignsBundle\Entity\Products\Products
*/
public function getProductId() {
return $this->product_id;
}
}
FormType - NewProductFormType.php
<?php
namespace SCWDesignsBundle\Form\Admin;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use SCWDesignsBundle\Form\Types\ProductDescriptionType;
class NewProductFormType extends AbstractType {
private $entityManager;
public function __construct($entityManager) {
$this->entityManager = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('featured', 'checkbox', array('label' => 'Featured', 'required' => false))
->add('enabled', 'checkbox', array('label' => 'Enabled', 'required' => false))
->add('freeshipping', 'checkbox', array('label' => 'Free Shipping', 'required' => false))
// ->add('participate_sale', 'checkbox', array('label' => 'Sale', 'required' => false))
->add('price', 'text', array('label' => 'Price', 'required' => true))
->add('sku', 'text', array('label' => 'Sku', 'required' => false))
->add('description', 'collection', array(
'type' => new ProductDescriptionType(),
'allow_add' => true,
'by_reference' => true
))
->add('category_id', 'entity', array(
'class' => 'SCWDesignsBundle:Products\ProductCategories',
'property' => 'name',
'placeholder' => false
));
}
public function getName() {
return 'product_new';
}
}
Type - ProductDescriptionType.php
<?php
namespace SCWDesignsBundle\Form\Types;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProductDescriptionType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name', null, array('label' => 'Product Name', 'required' => true))
->add('full_description', 'textarea', array('label' => 'Full Description', 'required' => false))
->add('brief_description', 'textarea', array('label' => 'Brief Description', 'required' => false))
->add('meta_tags', null, array('label' => 'Meta Tags', 'required' => false))
->add('meta_title', null, array('label' => 'Meta Title', 'required' => false))
->add('meta_description', 'text', array('label' => 'Meta Description', 'required' => false));
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array('data_class' => '\SCWDesignsBundle\Entity\Products\ProductDescription'));
}
public function getName() {
return 'product_description';
}
}
Controller - ProductsController.php
public function addProductAction(Request $request) {
$categories = $this->getCategories();
$em = $this->getDoctrine()->getEntityManager();
$product = new Products();
$form = $this->createForm(new NewProductFormType($em), $product);
$form->handleRequest($request);
if ($form->isValid()) {
$date = new \DateTime('NOW');
$product->setUpdateDate($date);
$em->persist($product);
$em->flush();
return $this->redirect($this->generateUrl('scw_designs_admin_products'));
}
return $this->render('SCWDesignsBundle:Admin\Products\Actions:new.html.twig', array(
'active_page' => 'products',
'categories' => $categories,
'form' => $form->createView(),
'action' => $this->generateUrl('scw_designs_admin_products_new')
));
}
As this caused me quite a bit of grief I've decided to post my answers after working with sshaun and ddproxy in the official #symfony irc channel.
First, I did have the owning relationship wrong. Needed to switch the inversedby to the product.php. Second I needed to presist the data, so I added the below to the controller and voila, as if magic, it worked.
if ($form->isValid()) {
$date = new \DateTime('NOW');
$product->setUpdateDate($date);
$em->persist($product);
$em->flush();
$description = $product->getDescription()->first();
$description->setProductId($product);
$em->persist($description);
$em->flush();
return $this->redirect($this->generateUrl('scw_designs_admin_products'));
}
Related
I have this problem when i execute my project, I use FormEvent in FormType
entity Departement.php:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Departement
*
* #ORM\Table(name="departement")
* #ORM\Entity(repositoryClass="AppBundle\Repository\DepartementRepository")
*/
class Departement
{
/**
* #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 int
*
* #ORM\Column(name="code", type="integer")
*/
private $code;
/**
*#ORM\ManyToOne(targetEntity="AppBundle\Entity\Region")
*/
private $region;
/**
*#ORM\OneToMany(targetEntity="AppBundle\Entity\Ville", mappedBy="departement")
*/
private $villes;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Departement
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set code
*
* #param integer $code
* #return Departement
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return integer
*/
public function getCode()
{
return $this->code;
}
/**
* Constructor
*/
public function __construct()
{
$this->villes = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set region
*
* #param \AppBundle\Entity\Region $region
* #return Departement
*/
public function setRegion(\AppBundle\Entity\Region $region = null)
{
$this->region = $region;
return $this;
}
/**
* Get region
*
* #return \AppBundle\Entity\Region
*/
public function getRegion()
{
return $this->region;
}
/**
* Add villes
*
* #param \AppBundle\Entity\Ville $villes
* #return Departement
*/
public function addVille(\AppBundle\Entity\Ville $villes)
{
$this->villes[] = $villes;
return $this;
}
/**
* Remove villes
*
* #param \AppBundle\Entity\Ville $villes
*/
public function removeVille(\AppBundle\Entity\Ville $villes)
{
$this->villes->removeElement($villes);
}
/**
* Get villes
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getVilles()
{
return $this->villes;
}
public function __toString(){
return $this->name;
}
}
entity ville.php:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Ville
*
* #ORM\Table(name="ville")
* #ORM\Entity(repositoryClass="AppBundle\Repository\VilleRepository")
*/
class Ville
{
/**
* #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 int
*
* #ORM\Column(name="code", type="integer")
*/
private $code;
/**
*#ORM\ManyToOne(targetEntity="AppBundle\Entity\Departement")
*/
private $departement;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Ville
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set code
*
* #param integer $code
* #return Ville
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get code
*
* #return integer
*/
public function getCode()
{
return $this->code;
}
/**
* Set departement
*
* #param \AppBundle\Entity\Departement $departement
* #return Ville
*/
public function setDepartement(\AppBundle\Entity\Departement $departement = null)
{
$this->departement = $departement;
return $this;
}
/**
* Get departement
*
* #return \AppBundle\Entity\Departement
*/
public function getDepartement()
{
return $this->departement;
}
public function __toString(){
return $this->name;
}
}
Form MedecinType.php:
<?php
namespace AppBundle\Form;
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\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormInterface;
use AppBundle\Entity\Region;
use AppBundle\Entity\Departement;
use AppBundle\Entity\Ville;
class MedecinType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('region', EntityType::class, [
'class' => 'AppBundle\Entity\Region',
'placeholder' => 'Sélectionnez votre région',
'mapped' => false,
'required' => false
]);
$builder->get('region')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) {
$form = $event->getForm();
$this->addDepartementField($form->getParent(), $form->getData());
}
);
}
private function addDepartementField(FormInterface $form, Region $region)
{
$builder = $form->getConfig()->getFormFactory()->createNamedBuilder(
'departement',
EntityType::class,
null,
[
'class' => 'AppBundle\Entity\Departement',
'placeholder' => 'Sélectionnez votre département',
'mapped' => false,
'required' => false,
'auto_initialize' => false,
'choices' => $region->getDepartements()
]);
$builder->addEventListener(
FormEvents::POST_SUBMIT,
function(FormEvent $event) {
$form= $event->getForm();
$this->addVilleField($form->getParent(), $form->getData());
}
);
$form->add($builder->getForm());
}
private function addVilleField(FormInterface $form, Departement $departement)
{
$form->add('ville', EntityType::class, [
'class' => 'AppBundle\Entity\Ville',
'placeholder' => 'Sélectionnez votre ville',
'choices' => $departement->getVilles()
]);
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Medecin'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_medecin';
}
}
help me please for resolve this problem and thank you advanced
Since you've set departement field as nullable with 'required' => false,, the method $form->getData() in event listener may be either an instance of Departement entity or null if no departement was chosen.
You have to check if $form->getData() returns instance of your entity and
handle if it's not.
That would be something like:
$builder->addEventListener(
FormEvents::POST_SUBMIT,
function(FormEvent $event) {
$form= $event->getForm();
$formData = $form->getData();
if(! $formData instanceof Departement) {
//handle this case or just do nothing and return from the listener
return;
}
// here's the default case
$this->addVilleField($form->getParent(), $form->getData());
}
);
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.
Hi i have problem with form embeded.
I have 3 class with relation OneToMany
StockTaking OneToMany StockTakingDetail ManyToOne Hardware
Wheh i submit the form i get error.
I dont know where I made a mistake.
Error:
Catchable Fatal Error: Argument 1 passed to
AppBundle\Entity\MagazineStockTakingDetails::setHardware() must be an
instance of AppBundle\Entity\Hardware, array given, called in
C:\Projekty\sla\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php
on line 442 and defined
Below i past code my class and form. Please help me find mistake.
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class MagazineStockTaking
* #package AppBundle\Entity
* #ORM\Entity()
* #ORM\Table(name="sla_stocktaking")
*/
class MagazineStockTaking
{
/**
* #ORM\Id
* #ORM\Column(name="stockTakingId", type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="stockinNumber", type="string", length=20, nullable=false)
*/
protected $stockingnumber;
/**
* #ORM\Column(name="stockinDate", type="datetime", nullable=false)
*/
protected $stockingdate;
/**
* #ORM\Column(name="stockingNote", type="string", length=1000, nullable=false)
*/
protected $stockingnote;
////////////////////////////////////////////////
// RELACJE
////////////////////////////////////////////////
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Magazine", inversedBy="stocktaking")
* #ORM\JoinColumn(name="magazine_id", referencedColumnName="magazineId", nullable=false)
*/
protected $magazine;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="stocktaking")
* #ORM\JoinColumn(name="user_id", referencedColumnName="userId", nullable=false)
*/
protected $user;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\MagazineStockTakingDetails", mappedBy="stocktaking", cascade={"persist"})
*/
protected $details;
////////////////////////////////////////////////
// GET SET
////////////////////////////////////////////////
/**
* Constructor
*/
public function __construct()
{
$this->details = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set stockingnumber
*
* #param string $stockingnumber
* #return MagazineStockTaking
*/
public function setStockingnumber($stockingnumber)
{
$this->stockingnumber = $stockingnumber;
return $this;
}
/**
* Get stockingnumber
*
* #return string
*/
public function getStockingnumber()
{
return $this->stockingnumber;
}
/**
* Set stockingdate
*
* #param \DateTime $stockingdate
* #return MagazineStockTaking
*/
public function setStockingdate($stockingdate)
{
$this->stockingdate = $stockingdate;
return $this;
}
/**
* Get stockingdate
*
* #return \DateTime
*/
public function getStockingdate()
{
return $this->stockingdate;
}
/**
* Set stockingnote
*
* #param string $stockingnote
* #return MagazineStockTaking
*/
public function setStockingnote($stockingnote)
{
$this->stockingnote = $stockingnote;
return $this;
}
/**
* Get stockingnote
*
* #return string
*/
public function getStockingnote()
{
return $this->stockingnote;
}
/**
* Set magazine
*
* #param \AppBundle\Entity\Magazine $magazine
* #return MagazineStockTaking
*/
public function setMagazine(\AppBundle\Entity\Magazine $magazine)
{
$this->magazine = $magazine;
return $this;
}
/**
* Get magazine
*
* #return \AppBundle\Entity\Magazine
*/
public function getMagazine()
{
return $this->magazine;
}
/**
* Set user
*
* #param \AppBundle\Entity\User $user
* #return MagazineStockTaking
*/
public function setUser(\AppBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \AppBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Add details
*
* #param \AppBundle\Entity\MagazineStockTakingDetails $details
* #return MagazineStockTaking
*/
public function addDetail(\AppBundle\Entity\MagazineStockTakingDetails $details)
{
$this->details[] = $details;
return $this;
}
/**
* Remove details
*
* #param \AppBundle\Entity\MagazineStockTakingDetails $details
*/
public function removeDetail(\AppBundle\Entity\MagazineStockTakingDetails $details)
{
$this->details->removeElement($details);
}
/**
* Get details
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDetails()
{
return $this->details;
}
}
Second Class
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Class MagazineStockTakingDetails
* #package AppBundle\Entity
* #ORM\Entity()
* #ORM\Table(name="sla_stocktakingdetails")
*/
class MagazineStockTakingDetails
{
/**
* #ORM\Id()
* #ORM\Column(name="stackTakingDetailsId", type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="hardwareCount", type="integer", nullable=false)
*/
protected $count = 1;
/////////////////////////////////////////////
// RELACJE
/////////////////////////////////////////////
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\MagazineStockTaking", inversedBy="details")
* #ORM\JoinColumn(name="stacktaking_id", referencedColumnName="stockTakingId", nullable=false)
*/
protected $stocktaking;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Hardware", inversedBy="stocktakingdetails",cascade={"persist"})
* #ORM\JoinColumn(name="hardware_id", referencedColumnName="hardwareId", nullable=false)
*/
protected $hardware;
/////////////////////////////////////////////
// GET SET
/////////////////////////////////////////////
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set count
*
* #param integer $count
* #return MagazineStockTakingDetails
*/
public function setCount($count)
{
$this->count = $count;
return $this;
}
/**
* Get count
*
* #return integer
*/
public function getCount()
{
return $this->count;
}
/**
* Set stocktaking
*
* #param \AppBundle\Entity\MagazineStockTaking $stocktaking
* #return MagazineStockTakingDetails
*/
public function setStocktaking(\AppBundle\Entity\MagazineStockTaking $stocktaking)
{
$this->stocktaking = $stocktaking;
return $this;
}
/**
* Get stocktaking
*
* #return \AppBundle\Entity\MagazineStockTaking
*/
public function getStocktaking()
{
return $this->stocktaking;
}
/**
* Set hardware
*
* #param \AppBundle\Entity\Hardware $hardware
* #return MagazineStockTakingDetails
*/
public function setHardware(\AppBundle\Entity\Hardware $hardware)
{
$this->hardware = $hardware;
return $this;
}
/**
* Get hardware
*
* #return \AppBundle\Entity\Hardware
*/
public function getHardware()
{
return $this->hardware;
}
}
Third Class
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
use JMS\Serializer\Annotation\Groups;
/**
* Class Hardware
* #package AppBundle\Entity
* #ORM\Entity(repositoryClass="HardwareRepository", )
* #ORM\Table(name="sla_hardwares")
* #JMS\ExclusionPolicy("all")
*/
class Hardware
{
/**
* #ORM\Id()
* #ORM\Column(name="hardwareId", type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="hardwareSn", type="string", length=200, nullable=true)
*/
protected $sn;
/**
* #ORM\Column(name="hardwareGwarantyDate", type="datetime", nullable=true)
*/
protected $gwarantydate;
/**
* #ORM\Column(name="hardwareNote", type="string", length=750, nullable=true)
*/
protected $note;
/**
* #ORM\Column(name="hardwareIsReturned", type="boolean", nullable=false)
*/
protected $isreturned = false;
////////////////////////////////////////
//// RELACJE
////////////////////////////////////////
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\HardwareProducent", inversedBy="hardware")
* #ORM\JoinColumn(name="producent_id", referencedColumnName="producentId", nullable=false)
*/
protected $producent;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\HardwareCategory", inversedBy="hardware")
* #ORM\JoinColumn(name="category_id", referencedColumnName="hardwareCategoryId", nullable=false)
*/
protected $category;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\HardwareModel", inversedBy="hardware")
* #ORM\JoinColumn(name="model_id", referencedColumnName="hardwareModelId", nullable=false)
*/
protected $model;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\HardwareStatus", inversedBy="hardware")
* #ORM\JoinColumn(name="status_id", referencedColumnName="statusId", nullable=false)
*/
protected $status;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\HardwareStatusHistory", mappedBy="hardware")
*/
protected $statushistory;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\MagazineDetails", mappedBy="hardware")
*/
protected $magazine;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\MagazineShiftDetails", mappedBy="hardware")
*/
protected $magazineshift;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\MagazineUtilizeDetails", mappedBy="hardware")
*/
protected $utilize;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\MagazineStockTakingDetails", mappedBy="hardware", cascade={"persist"})
*/
protected $stocktakingdetails;
////////////////////////////////////////
//// GET SET
////////////////////////////////////////
/**
* Constructor
*/
public function __construct()
{
$this->statushistory = new \Doctrine\Common\Collections\ArrayCollection();
$this->magazine = new \Doctrine\Common\Collections\ArrayCollection();
$this->magazineshift = new \Doctrine\Common\Collections\ArrayCollection();
$this->utilize = new \Doctrine\Common\Collections\ArrayCollection();
$this->stocktakingdetails = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set sn
*
* #param string $sn
* #return Hardware
*/
public function setSn($sn)
{
$this->sn = $sn;
return $this;
}
/**
* Get sn
*
* #return string
*/
public function getSn()
{
return $this->sn;
}
/**
* Set gwarantydate
*
* #param \DateTime $gwarantydate
* #return Hardware
*/
public function setGwarantydate($gwarantydate)
{
$this->gwarantydate = $gwarantydate;
return $this;
}
/**
* Get gwarantydate
*
* #return \DateTime
*/
public function getGwarantydate()
{
return $this->gwarantydate;
}
/**
* Set note
*
* #param string $note
* #return Hardware
*/
public function setNote($note)
{
$this->note = $note;
return $this;
}
/**
* Get note
*
* #return string
*/
public function getNote()
{
return $this->note;
}
/**
* Set isreturned
*
* #param boolean $isreturned
* #return Hardware
*/
public function setIsreturned($isreturned)
{
$this->isreturned = $isreturned;
return $this;
}
/**
* Get isreturned
*
* #return boolean
*/
public function getIsreturned()
{
return $this->isreturned;
}
/**
* Set producent
*
* #param \AppBundle\Entity\HardwareProducent $producent
* #return Hardware
*/
public function setProducent(\AppBundle\Entity\HardwareProducent $producent)
{
$this->producent = $producent;
return $this;
}
/**
* Get producent
*
* #return \AppBundle\Entity\HardwareProducent
*/
public function getProducent()
{
return $this->producent;
}
/**
* Set category
*
* #param \AppBundle\Entity\HardwareCategory $category
* #return Hardware
*/
public function setCategory(\AppBundle\Entity\HardwareCategory $category)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \AppBundle\Entity\HardwareCategory
*/
public function getCategory()
{
return $this->category;
}
/**
* Set model
*
* #param \AppBundle\Entity\HardwareModel $model
* #return Hardware
*/
public function setModel(\AppBundle\Entity\HardwareModel $model)
{
$this->model = $model;
return $this;
}
/**
* Get model
*
* #return \AppBundle\Entity\HardwareModel
*/
public function getModel()
{
return $this->model;
}
/**
* Set status
*
* #param \AppBundle\Entity\HardwareStatus $status
* #return Hardware
*/
public function setStatus(\AppBundle\Entity\HardwareStatus $status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return \AppBundle\Entity\HardwareStatus
*/
public function getStatus()
{
return $this->status;
}
/**
* Add statushistory
*
* #param \AppBundle\Entity\HardwareStatusHistory $statushistory
* #return Hardware
*/
public function addStatushistory(\AppBundle\Entity\HardwareStatusHistory $statushistory)
{
$this->statushistory[] = $statushistory;
return $this;
}
/**
* Remove statushistory
*
* #param \AppBundle\Entity\HardwareStatusHistory $statushistory
*/
public function removeStatushistory(\AppBundle\Entity\HardwareStatusHistory $statushistory)
{
$this->statushistory->removeElement($statushistory);
}
/**
* Get statushistory
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getStatushistory()
{
return $this->statushistory;
}
/**
* Add magazine
*
* #param \AppBundle\Entity\MagazineDetails $magazine
* #return Hardware
*/
public function addMagazine(\AppBundle\Entity\MagazineDetails $magazine)
{
$this->magazine[] = $magazine;
return $this;
}
/**
* Remove magazine
*
* #param \AppBundle\Entity\MagazineDetails $magazine
*/
public function removeMagazine(\AppBundle\Entity\MagazineDetails $magazine)
{
$this->magazine->removeElement($magazine);
}
/**
* Get magazine
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMagazine()
{
return $this->magazine;
}
/**
* Add magazineshift
*
* #param \AppBundle\Entity\MagazineShiftDetails $magazineshift
* #return Hardware
*/
public function addMagazineshift(\AppBundle\Entity\MagazineShiftDetails $magazineshift)
{
$this->magazineshift[] = $magazineshift;
return $this;
}
/**
* Remove magazineshift
*
* #param \AppBundle\Entity\MagazineShiftDetails $magazineshift
*/
public function removeMagazineshift(\AppBundle\Entity\MagazineShiftDetails $magazineshift)
{
$this->magazineshift->removeElement($magazineshift);
}
/**
* Get magazineshift
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getMagazineshift()
{
return $this->magazineshift;
}
/**
* Add utilize
*
* #param \AppBundle\Entity\MagazineUtilizeDetails $utilize
* #return Hardware
*/
public function addUtilize(\AppBundle\Entity\MagazineUtilizeDetails $utilize)
{
$this->utilize[] = $utilize;
return $this;
}
/**
* Remove utilize
*
* #param \AppBundle\Entity\MagazineUtilizeDetails $utilize
*/
public function removeUtilize(\AppBundle\Entity\MagazineUtilizeDetails $utilize)
{
$this->utilize->removeElement($utilize);
}
/**
* Get utilize
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUtilize()
{
return $this->utilize;
}
/**
* Add stocktakingdetails
*
* #param \AppBundle\Entity\MagazineStockTakingDetails $stocktakingdetails
* #return Hardware
*/
public function addStocktakingdetail(\AppBundle\Entity\MagazineStockTakingDetails $stocktakingdetails)
{
$this->stocktakingdetails[] = $stocktakingdetails;
$stocktakingdetails->setHardware($this);
return $this;
}
/**
* Remove stocktakingdetails
*
* #param \AppBundle\Entity\MagazineStockTakingDetails $stocktakingdetails
*/
public function removeStocktakingdetail(\AppBundle\Entity\MagazineStockTakingDetails $stocktakingdetails)
{
$this->stocktakingdetails->removeElement($stocktakingdetails);
}
/**
* Get stocktakingdetails
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getStocktakingdetails()
{
return $this->stocktakingdetails;
}
}
First Form Class
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class StockTakingFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('stockingnote','textarea',array(
'label' => false,
'attr' => array(
'class' => 'gui-textarea',
'placeholder' => 'Uwagi',
'data-text' => 'Uwagi'
),
'required' => false
))
->add('details','collection',array(
'type' => new StockTakingDetailFormType(),
'allow_add' => true,
'by_reference' => false
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\MagazineStockTaking',
'attr' => array(
'id' => 'form_stoking'
)
));
}
public function getName() {
return 'stocktaking';
}
}
Second Form Class
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class StockTakingDetailFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('count','number',array(
'label' => false,
'data' => '1',
'required' => false
))
->add('hardware','collection',array(
'type' => new HardwareFormType(),
'allow_add' => true,
'by_reference' => false
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\MagazineStockTakingDetails'
));
}
public function getName()
{
return 'stocktakingtetail';
}
}
Third Form Class
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class HardwareFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sn','text',array(
'label' => false,
'attr' => array(
'class' => 'gui-input',
'placeholder' => 'Numer Seryjny Urządzenia'
),
'required' => true
))
->add('gwarantydate','number',array(
'label' => false,
'attr' => array(
'class' => 'gui-input',
'placeholder' => 'Ilość Gwarancji (miesięcy)'
),
'required' => false
))
->add('isreturned','checkbox',array(
'label' => 'Sprzęt Rotacyjny',
'label_attr' => array(
'class' => 'option-primary'
),
'required' => true
))
->add('note','textarea' ,array(
'label' => false,
'attr' => array(
'class' => 'gui-textarea',
'placeholder' => 'Opis',
'data-text' => 'Opis'
),
'required' => false
))
->add('producent','entity',array(
'class' => 'AppBundle\Entity\HardwareProducent',
'property' => 'name',
'label' => false,
'attr' => array(
'class' => 'select',
'placeholder' => 'Producent'
),
'required' => true
))
->add('category','entity',array(
'class' => 'AppBundle\Entity\HardwareCategory',
'property' => 'name',
'label' => false,
'attr' => array(
'class' => 'select',
'placeholder' => 'Kategoria'
),
'required' => true
))
->add('model','entity',array(
'class' => 'AppBundle\Entity\HardwareModel',
'property' => 'name',
'label' => false,
'attr' => array(
'class' => 'select',
'placeholder' => 'Model'
),
'required' => true
))
->add('status','entity',array(
'class' => 'AppBundle\Entity\HardwareStatus',
'property' => 'name',
'label' => false,
'attr' => array(
'class' => 'select',
'placeholder' => 'Status'
),
'required' => true
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Hardware'
));
}
public function getName()
{
return 'hardware';
}
}
If you have a ManyToOne on the hardware the MagazineStockTakingDetails has a reference to an object of the type Hardware, therefore you can only set one object of the type hardware, but you are trying to set an ArrayCollection.
This can't work:
->add('hardware','collection',array(
'type' => new HardwareFormType(),
'allow_add' => true,
'by_reference' => false
))
You will need to do something like this:
->add('hardware', new HardwareFormType(),array(
...
))
I have two entities (namely Book, Image) having OneToMany relationship between them, i.e. One book can have more than one images.
Now when I am trying to edit the details of the book, how can I do edit for any particular image for that particular book?
More clearly if I say, I want to alter only one particular image out of all the images previously uploaded. Can anyone help me on this please?
Below are my entities and forms.
/**
* #ORM\Table(name="books")
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="Library\MainBundle\Entity\BookRepository")
*/
class Book
{
/**
* #var integer
*
* #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="subject", type="string", length=255)
*/
private $subject;
/**
* #var string
*
* #ORM\Column(name="isbn", type="string", length=255)
*/
private $isbn;
/**
* #var string
*
* #ORM\Column(name="Description", type="text")
*/
private $description;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="books")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
**/
private $category;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="bookpublishers")
* #ORM\JoinColumn(name="publisher_id", referencedColumnName="id")
**/
private $publisher;
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="bookauthors")
* #ORM\JoinTable(name="book_author")
**/
private $author;
/**
* #ORM\OneToMany(targetEntity="BookReview", mappedBy="bookreview", cascade={"all"})
**/
private $reviews;
/**
* #var string $image
* #Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
* #ORM\Column(name="image", type="string", length=255)
*/
private $image;
/**
* #ORM\OneToMany(targetEntity="Image", mappedBy="book", cascade={"all"})
**/
private $pictures;
/**
* #var string
*/
private $imageName;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Book
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set subject
*
* #param string $subject
* #return Book
*/
public function setSubject($subject)
{
$this->subject = $subject;
return $this;
}
/**
* Get subject
*
* #return string
*/
public function getSubject()
{
return $this->subject;
}
/**
* Set isbn
*
* #param string $isbn
* #return Book
*/
public function setIsbn($isbn)
{
$this->isbn = $isbn;
return $this;
}
/**
* Get isbn
*
* #return string
*/
public function getIsbn()
{
return $this->isbn;
}
/**
* Set description
*
* #param string $description
* #return Book
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set category
*
* #param \Library\MainBundle\Entity\Category $category
* #return Book
*/
public function setCategory(Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \Library\MainBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Set publisher
*
* #param \Library\MainBundle\Entity\User $publisher
* #return Book
*/
public function setPublisher(User $publisher = null)
{
$this->publisher = $publisher;
return $this;
}
/**
* Get publisher
*
* #return \Library\MainBundle\Entity\User
*/
public function getPublisher()
{
return $this->publisher;
}
/**
* Add author
*
* #param \Library\MainBundle\Entity\User $author
* #return Book
*/
public function addAuthor(User $author)
{
$this->author[] = $author;
return $this;
}
/**
* Remove author
*
* #param \Library\MainBundle\Entity\User $author
*/
public function removeAuthor(User $author)
{
$this->author->removeElement($author);
}
/**
* Get author
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set author
*
* #return User
*/
public function setAuthor(User $author)
{
$this->author[] = $author;
}
/**
* Add reviews
*
* #param \Library\MainBundle\Entity\BookReview $reviews
* #return Book
*/
public function addReview(BookReview $reviews)
{
$this->reviews[] = $reviews;
return $this;
}
/**
* Remove reviews
*
* #param \Library\MainBundle\Entity\BookReview $reviews
*/
public function removeReview(BookReview $reviews)
{
$this->reviews->removeElement($reviews);
}
/**
* Get reviews
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getReviews()
{
return $this->reviews;
}
public function getFullImagePath() {
return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir().$this->getId()."/";
}
protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/upload/books/';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
$tempImageName = time() . '_' .$this->image->getClientOriginalName();
if(!$this->id){
$this->setImageName($this->image->getClientOriginalName());
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $tempImageName);
unlink($this->getUploadRootDir().$this->getImageName());
}
$this->setImage($tempImageName);
}
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->image) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir().$this->getImageName(), $this->getFullImagePath());
unlink($this->getTmpUploadRootDir().$this->getImageName());
}
/**
* #ORM\PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
/**
* Set image
*
* #param string $image
* #return Book
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set image
*
* #param string $image
* #return Book
*/
public function setImageName($image)
{
$this->imageName = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
/**
* Constructor
*/
public function __construct()
{
$this->author = new ArrayCollection();
$this->reviews = new ArrayCollection();
$this->pictures = new ArrayCollection();
}
/**
* Add pictures
*
* #param \Library\MainBundle\Entity\Image $pictures
* #return Book
*/
public function addPicture(Image $pictures)
{
$this->pictures[] = $pictures;
$pictures->setBook($this);
return $this;
}
/**
* Remove pictures
*
* #param \Library\MainBundle\Entity\Image $pictures
*/
public function removePicture(Image $pictures)
{
$this->pictures->removeElement($pictures);
}
/**
* Get pictures
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPictures()
{
return $this->pictures;
}
}
Image Entity (Image.php)
/**
* Image
*
* #ORM\Table(name="book_images")
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="Library\MainBundle\Entity\ImageRepository")
*/
class Image
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\File( maxSize = "1024k", mimeTypesMessage = "Please upload a valid Image")
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="Book", inversedBy="pictures")
* #ORM\JoinColumn(name="book_id", referencedColumnName="id")
**/
private $book;
/**
* #var string
*/
private $imageName;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Image
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set book
*
* #param \Library\MainBundle\Entity\Book $book
* #return Image
*/
public function setBook(Book $book)
{
$this->book = $book;
return $this;
}
/**
* Get book
*
* #return \Library\MainBundle\Entity\Book
*/
public function getBook()
{
return $this->book;
}
/**
* Set image
*
* #param string $image
* #return Book
*/
public function setImageName($image)
{
$this->imageName = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImageName()
{
return $this->imageName;
}
public function getFullImagePath() {
return null === $this->name ? null : $this->getUploadRootDir(). $this->name;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir().$this->getBook()->getId()."/";
}
protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../../web/upload/books/';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->name) {
return;
}
$tempImageName = time() . '_' .$this->name->getClientOriginalName();
if(!$this->getBook()->getId()){
$this->setImageName($this->name->getClientOriginalName());
$this->name->move($this->getTmpUploadRootDir(), $this->name->getClientOriginalName());
}else{
$this->name->move($this->getUploadRootDir(), $tempImageName);
unlink($this->getUploadRootDir().$this->getImageName());
}
$this->setName($tempImageName);
}
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->name) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir().$this->getImageName(), $this->getFullImagePath());
unlink($this->getTmpUploadRootDir().$this->getImageName());
}
/**
* #ORM\PreRemove()
*/
public function removeImage()
{
unlink($this->getFullImagePath());
rmdir($this->getUploadRootDir());
}
}
My Forms :
BookType.php
namespace Library\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Library\MainBundle\Entity\Role;
use Library\MainBundle\Entity\Image;
class BookType extends AbstractType
{
/**
* #var \Library\MainBundle\Entity\Role
*/
protected $publisherrole;
/**
* #var \Library\MainBundle\Entity\Role
*/
protected $authorrole;
public function __construct (Role $publisherRole, Role $authorRole)
{
$this->publisherrole = $publisherRole;
$this->authorrole = $authorRole;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array('label' => 'book.label.name',
'attr' => array('class' => 'element text medium')))
->add('subject', 'text', array('label' => 'book.label.subject',
'attr' => array('class' => 'element text medium')))
->add('isbn', 'text', array('label'=> 'book.label.isbn',
'attr' => array('class' => 'element text medium')))
->add('description', 'textarea', array('label' => 'book.label.description',
'attr' => array('class' => 'element textarea medium')))
->add('category', 'entity', array(
'class' => 'LibraryMainBundle:Category',
'property' => 'name',
"label" => 'book.label.category',
"attr" => array('class' => 'element select medium')))
->add('publisher', 'entity', array(
'class' => 'LibraryMainBundle:User',
'property' => 'name',
'label' => 'book.label.publisher',
'choices' => $this->publisherrole->getUser(),
'attr' => array('class' => 'element select medium')
))
->add('author', 'entity', array(
'class' => 'LibraryMainBundle:User',
'property' => 'name',
'label' => 'book.label.author',
'choices' => $this->authorrole->getUser(),
'multiple' => 'true',
'attr' => array('class' => 'element select medium')
))
->add('image', 'file', array('label' => 'book.label.coverpic',
'attr' => array('class' => 'element textarea medium'),
'data_class' => null
))
->add("pictures", 'collection', array(
'type'=>new FileType(),
'allow_add'=>true,
'by_reference' => true,
'data'=>array(new Image(),
new Image()
)
))
->add("save", "submit", array('label' => 'book.button.save'));
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Library\MainBundle\Entity\Book'
));
}
/**
* #return string
*/
public function getName()
{
return 'library_mainbundle_book';
}
}
FileType.php
namespace Library\MainBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class FileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
return $builder->add("name", "file");
}
public function getName()
{
return "filetype";
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class'=>'Library\MainBundle\Entity\Image',
'csrf_protection'=>true,
'csrf_field_name'=>'_token',
'intention'=>'file'
));
}
}
Please let me know if anything more required from my end.
I have two entities Store and Category and each Store has it's own categories.
I'd like that when a Store owner's try to add a new category and category_parent, just the categories related to current Store will be displayed.
Right now, all categories are displayed in the select-option.
I'm using Tree Gedmo extension to manage Category entity and I use getChildrenQueryBuilder method to select categories.
How can I modify this method and add my specific constraint ?
$store which is the constraint is declared in the controller action down.
I'd like te set current Category option disabled when he try to add a category_parent, so category and category parent must be differnt.
I hope it's clear
CategoryType.php
<?php
namespace Project\StoreBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
class CategoryType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//..........
//..........
->add('category', 'entity', array(
'required' => false,
'label' => 'Category parent',
'class' => 'ProjectStoreBundle:Category',
'attr' => array('class' => 'col-sm-8'),
'empty_value' => 'Select one category',
'property' => 'indentedName',
'multiple' => false,
'expanded' => false ,
'query_builder' => function (\Project\StoreBundle\Entity\CategoryRepository $r)
{
return $r->getChildrenQueryBuilder(null, null, 'root', 'asc', false);
}
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\StoreBundle\Entity\Category'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_storebundle_category';
}
}
Entity/Category.php
<?php
namespace Project\StoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Category
* #Gedmo\Tree(type="nested")
* #ORM\Table()
* #ORM\Entity(repositoryClass="Project\StoreBundle\Entity\CategoryRepository")
* #ORM\HasLifeCycleCallbacks()
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*
*#Assert\NotBlank(message="Please enter the name of categorie.")
*/
private $name;
/**
* #Gedmo\slug(fields={"name"}, unique_base="uniqueBase")
* #ORM\Column(name="slug",length=255, unique=false)
*/
private $slug ;
/**
* #ORM\Column(name="uniqueBase", type="integer")
*/
private $uniqueBase ;
/**
* #ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* #ORM\Column(name="metaDescription", type="string", length=255, nullable=true)
*
* #Assert\Length(
* max=255,
* maxMessage="message"
* )
*/
private $metaDescription;
/**
* #ORM\Column(name="metaKeywords", type="string", length=255, nullable=true)
*
* #Assert\Length(
* max=255,
* maxMessage="message"
* )
*/
private $metaKeywords;
/**
* #ORM\Column(name="enabled", type="boolean", nullable=false)
*/
private $enabled;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
/**
*non mapped property
*/
private $indentedName;
/**
*non mapped property
*/
private $category;
/**
* #ORM\ManyToOne(targetEntity="Project\StoreBundle\Entity\Store", inversedBy="categories", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $store ;
/**
* Constructor
*/
public function __construct()
{
$this->children = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set slug
*
* #param string $slug
* #return Category
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set uniqueBase
*
* #param integer $uniqueBase
* #return Category
*/
public function setUniqueBase($uniqueBase)
{
$this->uniqueBase = $uniqueBase;
return $this;
}
/**
* Get uniqueBase
*
* #return integer
*/
public function getUniqueBase()
{
return $this->uniqueBase;
}
/**
* Set description
*
* #param string $description
* #return Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set metaDescription
*
* #param string $metaDescription
* #return Category
*/
public function setMetaDescription($metaDescription)
{
$this->metaDescription = $metaDescription;
return $this;
}
/**
* Get metaDescription
*
* #return string
*/
public function getMetaDescription()
{
return $this->metaDescription;
}
/**
* Set metaKeywords
*
* #param string $metaKeywords
* #return Category
*/
public function setMetaKeywords($metaKeywords)
{
$this->metaKeywords = $metaKeywords;
return $this;
}
/**
* Get metaKeywords
*
* #return string
*/
public function getMetaKeywords()
{
return $this->metaKeywords;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return Category
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set parent
*
* #param \Project\StoreBundle\Entity\Category $parent
* #return Category
*/
public function setParent(\Project\StoreBundle\Entity\Category $parent = null)
{
$this->parent = $parent;
return $this;
}
/**
* Get parent
*
* #return \Project\StoreBundle\Entity\Category
*/
public function getParent()
{
return $this->parent;
}
/**
* Set lft
*
* #param integer $lft
* #return Category
*/
public function setLft($lft)
{
$this->lft = $lft;
return $this;
}
/**
* Get lft
*
* #return integer
*/
public function getLft()
{
return $this->lft;
}
/**
* Set lvl
*
* #param integer $lvl
* #return Category
*/
public function setLvl($lvl)
{
$this->lvl = $lvl;
return $this;
}
/**
* Get lvl
*
* #return integer
*/
public function getLvl()
{
return $this->lvl;
}
/**
* Set rgt
*
* #param integer $rgt
* #return Category
*/
public function setRgt($rgt)
{
$this->rgt = $rgt;
return $this;
}
/**
* Get rgt
*
* #return integer
*/
public function getRgt()
{
return $this->rgt;
}
/**
* Set root
*
* #param integer $root
* #return Category
*/
public function setRoot($root)
{
$this->root = $root;
return $this;
}
/**
* Get root
*
* #return integer
*/
public function getRoot()
{
return $this->root;
}
/**
* Add children
*
* #param \Project\StoreBundle\Entity\Category $children
* #return Category
*/
public function addChild(\Project\StoreBundle\Entity\Category $children)
{
$this->children[] = $children;
return $this;
}
/**
* Remove children
*
* #param \Project\StoreBundle\Entity\Category $children
*/
public function removeChild(\Project\StoreBundle\Entity\Category $children)
{
$this->children->removeElement($children);
}
/**
* Get children
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getChildren()
{
return $this->children;
}
/**
* Get IndentedName
*
*/
public function getIndentedName()
{
return str_repeat("-----", $this->lvl).$this->name;
}
/**
* Get category
*
*/
public function getCategory()
{
return $this->category;
}
/**
* Set store
*
* #param \Project\StoreBundle\Entity\Store $store
* #return Category
*/
public function setStore(\Project\StoreBundle\Entity\Store $store = null)
{
$this->store = $store;
return $this;
}
/**
* Get store
*
* #return \Project\StoreBundle\Entity\Store
*/
public function getStore()
{
return $this->store;
}
}
Controller
/**
* Create a new Category entity.
*
*/
/**
* #ParamConverter("store", options={"mapping": {"store_id":"id"}})
*/
public function newAction(Store $store)
{
// keep in mind, this will call all registered security voters
if (false === $this->get('security.context')->isGranted('edit', $store)) {
throw new AccessDeniedException('Unauthorised access!');
}
$category = new Category();
$category->setStore($store);
$category->setUniqueBase($store->getId());
$form = $this->createForm(new CategoryType(), $category);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
$this->get('session')->getFlashBag()->add('message', 'Category enregistred');
return $this->redirect( $this->generateUrl('dashboard_category_index', array('store_id' => $store->getId())));
}
}
return $this->render('ProjectDashboardBundle:Category:new.html.twig',
array(
'form' => $form->createView() ,
'store' =>$store,
));
}
I managed to pass the parameter $store to the form, but I don't know how to use it as a constraint in getChildrenQueryBuilder method.
Should I create a new custom method? I prefer to use getChildrenQueryBuilder if it is possible.
Here is the new code
CategoryType.php
class CategoryType extends AbstractType
{
private $store;
public function __construct($store)
{
$this->store = $store;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$store = $this->store;
$builder
//...........
//...........
->add('parent', 'entity', array(
'required' => false,
'label' => 'Category parent',
'class' => 'ProjectStoreBundle:Category',
'attr' => array('class' => 'col-sm-8'),
'empty_value' => 'Select one category',
'property' => 'indentedName',
'multiple' => false,
'expanded' => false ,
'query_builder' => function (\Project\StoreBundle\Entity\CategoryRepository $r) use ($store)
{
return $r->getChildrenQueryBuilder(null, null, 'root', 'asc', false);
}
))
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Project\StoreBundle\Entity\Category'
));
}
/**
* #return string
*/
public function getName()
{
return 'project_storebundle_category';
}
}
Controller
/**
* #ParamConverter("store", options={"mapping": {"store_id":"id"}})
*/
public function newAction(Store $store)
{
// keep in mind, this will call all registered security voters
if (false === $this->get('security.context')->isGranted('edit', $store)) {
throw new AccessDeniedException('Unauthorised access!');
}
$category = new Category();
$category->setStore($store);
$category->setUniqueBase($store->getId());
$form = $this->createForm(new CategoryType($store), $category);
$request = $this->getRequest();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($category);
$em->flush();
$this->get('session')->getFlashBag()->add('message', 'Category enregistred');
return $this->redirect( $this->generateUrl('dashboard_category_index', array('store_id' => $store->getId())));
}
}
return $this->render('ProjectDashboardBundle:Category:new.html.twig',
array(
'form' => $form->createView() ,
'store' =>$store,
));
}
You're not saying which Symfony2 version you're using, but generically speaking, you just need to find a way to pass the current store to your form builder and use it in the method that filters the possible categories.
Take a look at this one, or this one, basically you just need to inject the $store into your form builder, and then you (almost) have it :-)