Error when persisting an embedded document with DoctrineMongoDB : array given - php

I'm working on a project using Doctrine-MongoDB and Symfony.
I've embedded a document into an other using \#EmbedMany annotation.
Here are the documents :
MusicalInfos :
<?php
// app/Resources/Document/Musical.php
namespace AppBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document(collection="bv_musical_infos")
*/
class MusicalInfos
{
/**
* #MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* #MongoDB\ReferenceOne(targetDocument="User")
*/
protected $user;
/**
* #MongoDB\EmbedMany(targetDocument="InstrumentsPlayed")
*/
protected $instruments = array();
And the embedded document :
<?php
namespace AppBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\EmbeddedDocument
*/
class InstrumentsPlayed
{
/**
* #MongoDB\ReferenceOne(targetDocument="Instruments")
*/
protected $instrument;
/**
* #MongoDB\Field(type="int")
*/
protected $practiceLevel;
After that I've created a form to fill those documents :
<?php
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class MusicalInfosType extends AbstractType
{
private $dm;
public function __construct($dm)
{
$this->dm = $dm;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('instruments', 'collection', array(
'type' => new InstrumentsPlayedType($this->dm),
'allow_add' => true,
'allow_delete' => true
));
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Document\MusicalInfos',
));
}
public function getName()
{
return 'musical_infos';
}
}
Controller
<?php
//...
if('POST' === $request->getMethod()) {
$form->bind($request);
if($form->isValid()) {
$user = $this->container->get('security.context')->getToken()->getUser();
$musicalInfos->setUser($user);
$dm->persist($musicalInfos);
$dm->flush();
$response = new JsonResponse();
$response->setData(array('registred_musical' => true));
return $response;
}
But when I try this I always obtain this exception :
Warning: spl_object_hash() expects parameter 1 to be object, array given
I don't know why ...
Thanks for your help !

Related

Constraint is not taken in consideration

I am doing a crud for an entity in my application. The form have to upload a file, so i added the assert in the entity file. But when i submit my form the validator give me an error and said to me that the field image have to be a string. I've done upload of file a hundred times, that why i don't understand this time why the validator bundles react like that.
My entity:
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="App\Repository\AlgorithmeRepository")
*/
class Algorithme
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $titre;
/**
* #ORM\Column(type="date")
*/
private $dateCreationArticle;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*
* #Assert\File(mimeTypes={ "image/jpeg","image/png"})
*/
private $image;
/**
* #ORM\Column(type="array")
*/
private $analyse = [];
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getDateCreationArticle(): ?\DateTimeInterface
{
return $this->dateCreationArticle;
}
public function setDateCreationArticle(\DateTimeInterface $dateCreationArticle): self
{
$this->dateCreationArticle = $dateCreationArticle;
return $this;
}
public function getImage()
{
return $this->image;
}
public function setImage($image)
{
$this->image = $image;
return $this;
}
public function getAnalyse(): ?array
{
return $this->analyse;
}
public function setAnalyse(array $analyse): self
{
$this->analyse = $analyse;
return $this;
}
}
The form :
<?php
namespace App\Form;
use App\Entity\Algorithme;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AlgorithmeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('titre')
->add('dateCreationArticle',DateType::class,[
'widget' => 'single_text',
// prevents rendering it as type="date", to avoid HTML5 date pickers
'html5' => false,
// adds a class that can be selected in JavaScript
'attr' => ['class' => 'js-datepicker'],
])
->add('image',FileType::class,[
'required' => false,
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Algorithme::class,
]);
}
}
And the controller:
<?php
namespace App\Controller;
use App\Entity\Algorithme;
use App\Form\AlgorithmeType;
use App\Repository\AlgorithmeRepository;
use App\Services\CreateFormForArray;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
/**
* #Route("/algorithme")
*/
class AlgorithmeController extends AbstractController
{
/**
* #Route("/new", name="algorithme_new", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$algorithme = new Algorithme();
$form = $this->createForm(AlgorithmeType::class, $algorithme);
$form->handleRequest($request);
// die();
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$CreateFormForArray = new CreateFormForArray();
$CreateFormForArray->handleArrayString($request,$algorithme,"analyse");
$entityManager->persist($algorithme);
$entityManager->flush();
return $this->redirectToRoute('algorithme_index');
} else {
}
return $this->render('algorithme/new.html.twig', [
'algorithme' => $algorithme,
'form' => $form->createView(),
]);
}
}
I found the problem for those who will wondering is was
#auto_mapping:
# App\Entity\: []
that was uncomment in config/packages/validator.yaml

symfony 4 form collection entity with file type create

How to create and upload the document using entity where fileType field is embedded in parent form via collectionType. I did read the documentation Symfony Upload. But didn't manage to accomplish this. Always get this error "Type error: Argument 1 passed to App\Service\FileUploader::upload() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, instance of App\Entity\Attachment given".
Below is my Invoice entity
class Invoice
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Attachment", mappedBy="invoiceId", cascade={"persist"})
*/
private $attachments;
public function __construct()
{
$this->attachments = new ArrayCollection();
}
/**
* #return Collection|Attachment[]
*/
public function getAttachments(): Collection
{
return $this->attachments;
}
public function addAttachment(Attachment $attachment): self
{
if (!$this->attachments->contains($attachment)) {
$this->attachments[] = $attachment;
$attachment->setInvoiceId($this);
}
return $this;
}
Attachment entity
class Attachment
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $path;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Invoice", inversedBy="attachments")
*/
private $invoiceId;
public function getId()
{
return $this->id;
}
public function getPath(): ?string
{
return $this->path;
}
public function setPath(string $path): self
{
$this->path = $path;
return $this;
}
public function getInvoiceId(): ?Invoice
{
return $this->invoiceId;
}
public function setInvoiceId(?Invoice $invoiceId): self
{
$this->invoiceId = $invoiceId;
return $this;
}
Attachment form type
namespace App\Form;
use App\Entity\Attachment;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class AttachmentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('path',FileType::class, array(
'label' => false,
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Attachment::class,
]);
}
}
Invoice form type
namespace App\Form;
use App\Entity\Invoice;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class InvoiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('attachments', CollectionType::class, array(
'entry_type' => AttachmentType::class,
'entry_options' => array('label' => false),
'allow_add' => true
))
->add('submit', SubmitType::class, array(
'label' => $options['set_button_label']
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Invoice::class,
'set_button_label' => "Create Invoice",
]);
}
}
and the Controller
namespace App\Controller;
use App\Entity\Invoice;
use App\Form\InvoiceType;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use App\Service\FileUploader;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class InvoiceController extends Controller
{
/**
* #Route("/invoice/create", name="createInvoice")
* #param Request $request
* #param UserInterface $user
* #param FileUploader $fileUploader
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function createInvoice( Request $request, UserInterface $user, FileUploader $fileUploader)
{
Debug::enable();
$invoice = new Invoice();
$form = $this->createForm(InvoiceType::class,$invoice);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid())
{
// Prepare upload file
/** #var UploadedFile $files */
$files = $invoice->getAttachments();
foreach($files as $file){
$fileName = $fileUploader->upload($file);
}
$file->move(
$this->getParameter('attachment_directory'),
$fileName
);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($invoice);
$entityManager->flush();
return $this->redirectToRoute('user');
}
return $this->render('invoice/createInvoice.html.twig', [
'controller_name' => 'UserController',
'form' => $form->createView()
]);
}
I think the problem is the FileType field return attachment entity instance while it should return File instance. the question is how do i get the value as File instance?
In your case the property $path type of UploadedFile and not $invoice->getAttachments().
Try to add a property to your Attachement class called $file without doctrine mapping, generate it's getter and setter methods.
/**
* #var UploadedFile
*/
protected $file;
In your AttachmentType class change 'path' => 'file'.
Now, try to update this part in your controller:
$attachements = $invoice->getAttachments();
foreach($attachements as $attachement){
/** #var UploadedFile $file */
$file = $attachement->getFile(); // This is the file
$attachement->setPath($this->fileUploader->upload($file));
}
Please, make your fileUploader service the unique responsible for uploading file, no need to use $file->move().

Symfony - form - many to many relation - collection type

Here is the situation:
I have an entity Property
class Property
{
/**
* #ORM\Id
* #ORM\Column(type="string")
* #ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="PropertyEquipment", inversedBy="properties")
*/
protected $propertyEquipments;
public function __construct()
{
$this->propertyEquipments = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function addPropertyEquipment(\AppBundle\Entity\PropertyEquipment $propertyEquipment)
{
$this->propertyEquipments[] = $propertyEquipment;
return $this;
}
public function removePropertyEquipment(\AppBundle\Entity\PropertyEquipment $propertyEquipment)
{
$this->propertyEquipments->removeElement($propertyEquipment);
}
public function getPropertyEquipments()
{
return $this->propertyEquipments;
}
}
And the entity PropertyEquipment:
class PropertyEquipment
{
/**
* #ORM\Id
* #ORM\Column(type="string")
* #ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="Property", mappedBy="propertyEquipments")
*/
protected $properties;
/**
* #ORM\Column(type="string", length=100)
* #Gedmo\Translatable
*/
protected $equipmentName;
public function __construct()
{
$this->properties = new ArrayCollection();
}
/**
* Get id
*
* #return string
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getEquipmentName()
{
return $this->equipmentName;
}
/**
* #param mixed $equipmentName
*/
public function setEquipmentName($equipmentName)
{
$this->equipmentName = $equipmentName;
}
public function addProperty(Property $property)
{
$this->properties[] = $property;
return $this;
}
public function removeProperty(Property $property)
{
$this->properties->removeElement($property);
}
public function getProperties()
{
return $this->properties;
}
}
The form PropertyCreation
class PropertyCreation extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//with this I see the values coming from DB in the template
->add("propertyEquipments", PropertyEquipmentCreation::class)
//with this it's empty :/
/*->add("propertyEquipments", CollectionType::class, array(
"entry_type" => PropertyEquipmentCreation::class,
))*/
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Property::class
));
}
}
Here is the form PropertyEquipmentCreation:
class PropertyEquipmentCreation extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('propertyEquipment', EntityType::class, [
'class' => 'AppBundle\Entity\PropertyEquipment',
'choice_label' => 'equipmentName',
'expanded' => true,
'multiple' => true
]);
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => PropertyEquipment::class,
]);
}
}
And the controller
public function createPropertyAction(Request $request)
{
$property = new Property();
$form = $this->createForm(PropertyCreation::class, $property);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($property);
$entityManager->flush();
return $this->redirectToRoute('homepage');
}
return $this->render('form/owner_create_property.html.twig', ["form" => $form->createView()]);
}
My error:
Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "AppBundle\Entity\Property#$propertyEquipments", got "Doctrine\Common\Collections\ArrayCollection" instead.
Must I transform these with something like class PropertyEquipmentTransformer implements DataTransformerInterface?
I think you should use getParent() function in PropertyEquipmentCreation and inherit from EntityType::class then put all your field configs in the configureOptions() function (remove the buildForm function) and it should work.
You are having this problem because it is a compound form in your implementation and no simple form and symfony is unable to resolve which field created inside the subform needs to be used as source for the entity field
First !
Big thanks to Nickolaus !
Here is the solution (PropertyEquipmentCreation):
namespace AppBundle\Form\Type;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PropertyEquipmentCreation extends AbstractType
{
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'class' => 'AppBundle\Entity\PropertyEquipment',
'choice_label' => 'equipmentName',
'expanded' => true,
'multiple' => true,
]);
}
public function getParent()
{
return EntityType::class;
}
}
And for (PropertyCreation)
<?php
namespace AppBundle\Form;
use AppBundle\Form\Type\PropertyEquipmentCreation;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PropertyCreation extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('description', TextareaType::class)
->add('name', TextType::class)
->add("propertyEquipments", PropertyEquipmentCreation::class)
->add('save', SubmitType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Property::class
));
}
}
Many thanks !
Try using Doctrine ArrayCollection instead of ArrayCollections:
$this->propertyEquipments = new \Doctrine\Common\Collections\ArrayCollection();
This should work!

How to get symfony 2 forms to return entities from a dynamic value

Ok here is a quick overview of what I am trying to do. I have a "Client" entity with a relationship to a "ClientDomain" entity. I need to have a form that will show me a list of all the ClientDomains for a given client. In the controller I know what client i need to filter for but im unsure how to pass that information to the formBuilder.
Heres what i have so far:
//src/NameSpace/ClientBundle/Entity/Client.php
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Client{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $client_id;
/**
* #ORM\Column(type="string")
*/
protected $name;
/**
* #ORM\OneToMany(targetEntity="ClientDomain", mappedBy="client")
*/
protected $domains;
...
}
And the form:
//src/LG/ClientBundle/Form/ClientDomainSelectionForm.php
namespace LG\ProjectBundle\Form\Projects;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ClientDomainSelectionForm extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('client_domain', 'entity', array(
'class' => 'LG\ClientBundle\Entity\ClientDomain',
'query_builder'=> function(EntityRepository $er) {
return $er->createQueryBuilder('cd')
/* NEEDS TO FIND DOMAINS BY CLIENT X */
},
'property' => 'domain',
'label' => 'Domain: '
));
}
}
And then finally the controller:
//src/LG/ClientBundle/Controller/DomainSelectorController.php
namespace LG/ClientBundle/Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use LG\ClientBundle\Entity\Client;
use LG\ClientBundle\Entity\ClientDomain;
use LG\ClientBundle\Entity\ClientActiveDomain;
use LG\ClientBundle\Form\ClientDomainSelectionForm;
/**
* #Route("")
*/
class DomainSelectorController extends Controller{
/**
* #Route("/client/{client_slug}/select-domain", name="lg.client.clientdomainselection.selectclient")
* #Template
*/
public function selectDomainAction(Request $request, Client $client){
$activeDomain = new ClientActiveDomain();
$form = $this->createForm(new ClientDomainSelectionForm(), $activeDomain );
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($activeDomain );
$em->flush();
return $this->redirect(/*huge long url*/);
}
}
return array(
'form' => $form->createView(),
);
}
}
As you can see I have access to the client entity in the controller im just not sure how to give that to the form builder so that it will only return domains for the current client.
I Have found the answer, you just need to add a constructor to the form and pass in the client from the controller like so:
//src/LG/ClientBundle/Form/ClientDomainSelectionForm.php
namespace LG\ProjectBundle\Form\Projects;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ClientDomainSelectionForm extends AbstractType {
protected $client;
public function __construct(Client $client) {
$this->client = $client;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$client = $this->client;
$builder->add('client_domain', 'entity', array(
'class' => 'LG\ClientBundle\Entity\ClientDomain',
'query_builder'=> function(\Doctrine\ORM\EntityRepository $er) use ($client) {
return $er->createQueryBuilder('cd')
->where('cd.client = :client')
->orderBy('cd.domain', 'ASC')
->setParameter('client',$client->getClientId());
},
'property' => 'domain',
'label' => 'Domain: '
));
}
}
And Then in the controller:
//src/LG/ClientBundle/Controller/DomainSelectorController.php
...
public function selectDomainAction(Request $request, Client $client){
...
$form = $this->createForm(new ClientDomainSelectionForm($client), $activeDomain );
...
}
...

Form embedded for many to many & many to one in symfony2.

I have a problem when I try to embed a form in Symfony2 for many to many relations or many to one relations.
I have two entities called 'Address' and 'AddressType' and they are related as you can see on code below.
What I tried to do is when I created a form for Address, I embedded the form for AddressType. I've already tried embedding a collection of AddressType to Address form, but when I try to embed the result of this to Address it seems not to work.
Address Entity
namespace Webmuch\ProductBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
*/
class Address
{
protected $id;
protected $line1;
protected $line2;
protected $state;
protected $city;
protected $zip;
protected $country;
protected $phone;
/**
* #ORM\ManyToOne(targetEntity="AddressType")
* #ORM\JoinColumn(name="address_type_id", referencedColumnName="id")
*/
protected $type;
public function __construct()
{
$this->type = new ArrayCollection();
}
/**
* Set type
*
* #param Webmuch\ProductBundle\Entity\AddressType $type
*/
public function setType(\Webmuch\ProductBundle\Entity\AddressType $type)
{
$this->type = $type;
}
/**
* Get type
*
* #return Webmuch\ProductBundle\Entity\AddressType
*/
public function getType()
{
return $this->type;
}
}
AddressType Entity:
namespace Webmuch\ProductBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class AddressType
{
protected $id;
protected $title;
public function __construct()
{
$this->title = false;
}
}
In form section->
form
AddressType:
namespace Webmuch\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class AddressType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('line1')
->add('line2')
->add('city')
->add('zip')
->add('country')
->add('phone')
->add('type','collection', array( 'type' => new AddressTypeType(),
'allow_add' => true,
'prototype' => true,
'by_reference' => false,
));
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Webmuch\ProductBundle\Entity\Address');
}
public function getName()
{
return 'address';
}
}
AddressTypeType:
namespace Webmuch\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class AddressTypeType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('title');
;
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Webmuch\ProductBundle\Entity\AddressType',
);
}
public function getName()
{
return 'addresstypetype';
}
}
Controller Section->
namespace Webmuch\AdminBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Webmuch\ProductBundle\Entity\Address;
use Webmuch\AdminBundle\Form\AddressType;
/**
* Address controller.
*
* #Route("/cusadmin/address")
*/
class AddressController extends Controller
{
/**
* Displays a form to create a new Address entity.
*
* #Route("/new", name="admin_address_new")
* #Template()
*/
public function newAction()
{
$entity = new Address();
$form = $this->createForm(new AddressType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
}
I've spent the whole day stuck with this and I have tried a lot of things but I couldn't manage get it working.
Any help is appreciated!
Thanks
Edit form AddressType: nd write this code,may be this is help full....
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('line1')
->add('line2')
->add('city')
->add('zip')
->add('country')
->add('phone')
->add('type','entity', array('class'=>'WebmuchProductBundle:AddressType','property'=>'value','multiple'=>true
));

Categories