Symfony Forms embedded forms - php

Following the symfony documentation I am trying to embed a collection to a form. But when sending a post request to my endpoint the embedded form with the People collection stays empty.
My entities:
user.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* User
*
* #ORM\Entity
* #UniqueEntity(fields="email", message="Email already taken")
* #ORM\HasLifecycleCallbacks()
*/
class User implements UserInterface
{
use Mapping\UserTrait;
/**
* #param Person $person
*/
public function addPeople(Person $person)
{
$this->people->add($person);
$person->setOwner($this);
}
/**
* #param Person $person
*/
public function removePeople(Person $person)
{
$this->people->removeElement($person);
}
}
UserTrait.php
<?php
namespace App\Entity\Mapping;
use App\Entity\Person;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table()
*/
trait UserTrait
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="hash", type="string")
*/
private $hash;
/**
* #var bool
*
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #var string
* #ORM\Column(name="email", type="string")
* #Assert\NotBlank
* #Assert\Email
*/
private $email;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\OneToMany(targetEntity="App\Entity\Person", mappedBy="owner", cascade={"persist"})
*/
private $people;
/**
* #var string
* #Assert\NotBlank
* #Assert\Length(max=4096)
*/
private $plainPassword;
/**
* Constructor
*/
public function __construct()
{
$this->people = new ArrayCollection();
$this->roles = ['ROLE_USER'];
$this->isActive = 1;
}
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
/**
* #return bool
*/
public function isActive(): bool
{
return $this->isActive;
}
/**
* #param bool $isActive
*/
public function setIsActive(bool $isActive): void
{
$this->isActive = $isActive;
}
/**
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* #param string $email
*/
public function setEmail(string $email): void
{
$this->email = $email;
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getPeople(): \Doctrine\Common\Collections\Collection
{
return $this->people;
}
/**
* #param \Doctrine\Common\Collections\Collection $people
*/
public function setPeople(\Doctrine\Common\Collections\Collection $people): void
{
$this->people = $people;
}
/**
* #return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* #param string $plainPassword
*/
public function setPlainPassword(string $plainPassword): void
{
$this->plainPassword = $plainPassword;
}
/**
* Implementation of UserInterface: Get password hash.
* #return string
*/
public function getPassword()
{
return $this->hash;
}
/**
* Implementation of UserInterface
*/
public function eraseCredentials()
{
$this->plainPassword = null;
}
/**
* Implementation of UserInterface
*/
public function getUsername()
{
return $this->email;
}
public function getSalt()
{
return null;
}
public function getRoles()
{
return ["User"];
}
/**
* #return string
*/
public function getHash(): string
{
return $this->hash;
}
/**
* #param string $hash
*/
public function setHash(string $hash): void
{
$this->hash = $hash;
}
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function updatedTimestamps(): void
{
$dateTimeNow = new \DateTime('now');
$this->setUpdatedAt($dateTimeNow);
if ($this->getCreatedAt() === null) {
$this->setCreatedAt($dateTimeNow);
}
}
/**
* #return \DateTime
*/
public function getUpdatedAt(): \DateTime
{
return $this->updatedAt;
}
/**
* #param \DateTime $updatedAt
*/
public function setUpdatedAt(\DateTime $updatedAt): void
{
$this->updatedAt = $updatedAt;
}
/**
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #param \DateTime $createdAt
*/
public function setCreatedAt(\DateTime $createdAt): void
{
$this->createdAt = $createdAt;
}
}
Person.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Person
*
* #ORM\Entity
*/
class Person
{
use Mapping\PersonTrait;
}
PersonTrait.php
<?php
namespace App\Entity\Mapping;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Person
*
* #ORM\Table()
*/
trait PersonTrait
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="family_name", type="string")
* #Assert\NotBlank
*/
private $familyName;
/**
* #var string
*
* #ORM\Column(name="given_name", type="string")
* #Assert\NotBlank
*/
private $givenName;
/**
* #var string
*
* #ORM\Column(name="title", type="string")
*/
private $title;
/**
* #var \DateTime
*
* #ORM\Column(name="birth_date", type="datetime")
*/
private $birthDate;
/**
* #var string
*
* #ORM\Column(name="salutation", type="string")
*/
private $salutation;
/**
* #var string
*
* #ORM\Column(name="gender", type="string")
*/
private $gender;
/**
* #var \App\Entity\User
*
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="people")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="owner_id", referencedColumnName="id")
* })
*/
private $owner;
/**
* #return string
*/
public function getFamilyName()
{
return $this->familyName;
}
/**
* #param string $familyName
*/
public function setFamilyName($familyName)
{
var_dump($familyName);
$this->familyName = $familyName;
}
/**
* #return string
*/
public function getGivenName()
{
return $this->givenName;
}
/**
* #param string $givenName
*/
public function setGivenName($givenName)
{
$this->givenName = $givenName;
}
/**
* #return string
*/
public function getTitle(): string
{
return $this->title;
}
/**
* #param string $title
*/
public function setTitle(string $title): void
{
$this->title = $title;
}
/**
* #return \DateTime
*/
public function getBirthDate(): \DateTime
{
return $this->birthDate;
}
/**
* #param \DateTime $birthDate
*/
public function setBirthDate(\DateTime $birthDate): void
{
$this->birthDate = $birthDate;
}
/**
* #return string
*/
public function getSalutation(): string
{
return $this->salutation;
}
/**
* #param string $salutation
*/
public function setSalutation(string $salutation): void
{
$this->salutation = $salutation;
}
/**
* #return string
*/
public function getGender(): string
{
return $this->gender;
}
/**
* #param string $gender
*/
public function setGender(string $gender): void
{
$this->gender = $gender;
}
/**
* #return \App\Entity\User
*/
public function getOwner(): \App\Entity\User
{
return $this->owner;
}
/**
* #param \App\Entity\User $owner
*/
public function setOwner(\App\Entity\User $owner): void
{
$this->owner = $owner;
}
}
Now to my form types:
UserType.php
<?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class)
->add('plainPassword', PasswordType::class)
->add(
"people",
CollectionType::class,
[
'entry_type' => PersonType::class,
'allow_add' => true,
'by_reference' => false,
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'data_class' => User::class,
'csrf_protection' => false
]
);
}
}
PersonType.php
<?php
namespace App\Form;
use App\Entity\Person;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PersonType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('familyName', TextType::class)
->add('givenName', TextType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'data_class' => Person::class,
'csrf_protection' => false,
]
);
}
}
Using this Types I am now trying to register a user and create a Person and add it to the user using this code:
/**
* #Route("/register")
* #param Request $request
* #param UserPasswordEncoderInterface $passwordEncoder
*/
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->submit($request->request->all());
if ($form->isSubmitted() && $form->isValid()) {
$password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
$user->setHash($password);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return new Response("ok", 300);
}
return new Response("not ok", 500);
}
My problem now is that when I send a post request with postman with following parameters and content:
email: test#test.de
plainPassword: test1234
people.familyName: testLastname
people.givenName: testFirstname
I get the following error which means that it does not recognize the data for the person entity
"This form should not contain extra fields."
How do I make symfony forms to recognize that people.givenName and people.familyName are meant to create a instance of Person
Edit: comment by u_mulder suggested to change the post body to person[0].givenName and now I am getting the error message
This value is not valid.

I had two problems which had to be fixed. First hint from u_mulder was that I have to use the index for people since its a collection. So instead of
people["givenName"]
I had to use
people[0]["givenName"]
Second mistake was that the structure of the postman body was wrong. Instead of
people[0]["givenName"]
I had to remove the quotes.
people[0][givenName]
After fixing both problems the forms work as expected.

Related

Symfony $form->getData() return empty Object with values concatenated

This is my controller
/**
* #Route("/offre/add", name="offre_add")
* #param Request $request
* #return RedirectResponse|Response
* #throws \Exception
*/
public function addOffre(Request $request) {
$offre = new Offre();
$em = $this->getDoctrine()->getManager();
$formOffre = $this->createForm(OffreType::class, $offre);
$formOffre->handleRequest($request);
if ($formOffre->isSubmitted() && $formOffre->isValid()) {
$offre = $formOffre->getData();
dd($offre);
}
return $this->render('admin/offre/add_offre.html.twig', [
'form' => $formOffre->createView()
]);
}
And this is my OffreType
<?php
namespace App\Form;
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\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class OffreType extends AbstractType {
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('numeroOffre', TextType::class)
->add('version', TextType::class)
->add('statut', TextType::class)
->add('signature', TextType::class)
->add('prixTotal', TextType::class)
->add('commentaire', TextareaType::class)
->add('visibilite', ChoiceType::class, array('choices' => array(
'Oui' => 'Oui',
'Non' => 'Non')
))
->add('save', SubmitType::class)
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'App\Entity\Offre'
));
}
}
When I try to validate my form like this :
The result is an empty Object, and the values I inserted in my form are concatenated to my object (with the same Key/Value)
If I print the $_POST variable, the form seems to works fine
Why is the method getData() not working ?
edit:
This is my Offre Class
<?php
namespace App\Entity;
use DateTime;
use Doctrine\ORM\Mapping as ORM;
/**
* Offre
*
* #ORM\Table(name="offre")
* #ORM\Entity(repositoryClass="App\Repository\OffreRepository")
*/
class Offre
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="numero_offre", type="string", length=50)
*/
private $numeroOffre;
/**
* #var string
*
* #ORM\Column(name="statut", type="string", length=255, nullable=true)
*/
private $statut;
/**
* #var string
*
* #ORM\Column(name="version", type="string", length=255, nullable=true)
*/
private $version;
/**
* #var string
*
* #ORM\Column(name="signature", type="string", length=255, nullable=true)
*/
private $signature;
/**
* #var string
*
* #ORM\Column(name="commentaire", type="string", length=255, nullable=true)
*/
private $commentaire;
/**
* #var string
*
* #ORM\Column(name="visibilite", type="string", length=255)
*/
private $visibilite;
/**
* #var string
*
* #ORM\Column(name="prix_total", type="string", length=255)
*/
private $prixTotal;
/**
* #var DateTime
*
* #ORM\Column(name="date_create", type="date", nullable=true)
*/
private $dateCreate;
/**
* #var string
*
* #ORM\Column(name="user_create", type="string", length=255)
*/
private $userCreate;
/**
* #var DateTime
*
* #ORM\Column(name="date_change", type="date", nullable=true)
*/
private $dateChange;
/**
* #var string
*
* #ORM\Column(name="user_change", type="string", length=255, nullable=true)
*/
private $userChange;
/**
* #var boolean
*
* #ORM\Column(name="active", type="boolean")
*/
private $active = true;
/**
* #ORM\ManyToOne(targetEntity=Client::class, inversedBy="offres")
*/
private $client;
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return string
*/
public function getNumeroOffre()
{
return $this->numeroOffre;
}
/**
* #param string $numeroOffre
*/
public function setNumeroOffre($numeroOffre)
{
$this->$numeroOffre = $numeroOffre;
}
/**
* #return string
*/
public function getPrixTotal()
{
return $this->prixTotal;
}
/**
* #param string $prixTotal
*/
public function setPrixTotal($prixTotal)
{
$this->$prixTotal = $prixTotal;
}
/**
* #return string
*/
public function getStatut()
{
return $this->statut;
}
/**
* #param string $statut
*/
public function setStatut($statut)
{
$this->$statut = $statut;
}
/**
* #return string
*/
public function getVersion()
{
return $this->version;
}
/**
* #param string $version
*/
public function setVersion($version)
{
$this->$version = $version;
}
/**
* #return string
*/
public function getSignature()
{
return $this->signature;
}
/**
* #param string $signature
*/
public function setSignature($signature)
{
$this->$signature = $signature;
}
/**
* #return string
*/
public function getCommentaire()
{
return $this->commentaire;
}
/**
* #param string $commentaire
*/
public function setCommentaire($commentaire)
{
$this->$commentaire = $commentaire;
}
/**
* #return string
*/
public function getVisibilite()
{
return $this->visibilite;
}
/**
* #param string $visibilite
*/
public function setVisibilite($visibilite)
{
$this->$visibilite = $visibilite;
}
/**
* #return DateTime
*/
public function getDateCreate()
{
return $this->dateCreate;
}
/**
* #param DateTime $dateCreate
*/
public function setDateCreate($dateCreate)
{
$this->dateCreate = $dateCreate;
}
/**
* #return string
*/
public function getUserCreate()
{
return $this->userCreate;
}
/**
* #param string $userCreate
*/
public function setUserCreate($userCreate)
{
$this->userCreate = $userCreate;
}
/**
* #return DateTime
*/
public function getDateChange()
{
return $this->dateChange;
}
/**
* #param DateTime $dateChange
*/
public function setDateChange($dateChange)
{
$this->dateChange = $dateChange;
}
/**
* #return string
*/
public function getUserChange()
{
return $this->userChange;
}
/**
* #param string $userChange
*/
public function setUserChange(string $userChange)
{
$this->userChange = $userChange;
}
/**
* #return bool
*/
public function isActive()
{
return $this->active;
}
/**
* #param bool $active
*/
public function setActive(bool $active)
{
$this->active = $active;
}
public function getClient()
{
return $this->client;
}
public function setClient(?Client $client)
{
$this->client = $client;
return $this;
}
}
The problem comes from dollar "$" symbol in the setters entity definition.
/**
* #param string $prixTotal
*/
public function setPrixTotal($prixTotal)
{
$this->$prixTotal = $prixTotal;
}
Have just delete them and it works well.

Expected argument of type "string", "AclBundle\Entity\Image" given

I get this error from adding a ImageType to the user Form , i'm using FOSUserBundle for User Entity ! ANY HELP
this my User Entity
<?php
namespace AclBundle\Entity;
use AclBundle\Entity\Image;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
*
* #ORM\Table(name="ab_user")
* #ORM\Entity(repositoryClass="AclBundle\Repository\UserRepository")
*/
class User extends BaseUser
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="cin", type="string", length=255, unique=true)
*/
private $cin;
/**
* #var string
*
* #ORM\Column(name="firstname", type="string", length=255)
*/
private $firstname;
/**
* #var string
*
* #ORM\Column(name="lastname", type="string", length=255)
*/
private $lastname;
/**
* #var \DateTime
*
* #ORM\Column(name="birthdate", type="date")
*/
private $birthdate;
/**
* #var string
*
* #ORM\Column(name="phone", type="string", length=255)
*/
private $phone;
/**
* #Assert\NotBlank(message="Please, upload the picture as a image file.")
* #Assert\Image(mimeTypes={ "image/jpeg" })
* #ORM\OneToOne(targetEntity="Image", cascade={"remove", "persist"})
*
*/
private $photo;
/**
* #var \DateTime
*
* #ORM\Column(name="dateSubscribe", type="date", length=255)
*/
private $dateInscription;
/**
* #ORM\Column(name="role", type="json_array")
*/
private $role = [];
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set cin
*
* #param string $cin
*
* #return User
*/
public function setCin($cin)
{
$this->cin = $cin;
return $this;
}
/**
* Get cin
*
* #return string
*/
public function getCin()
{
return $this->cin;
}
/**
* Set firstname
*
* #param string $firstname
*
* #return User
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
*
* #return User
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set birthdate
*
* #param \DateTime $birthdate
*
* #return User
*/
public function setBirthdate($birthdate)
{
$this->birthdate = $birthdate;
return $this;
}
/**
* Get birthdate
*
* #return \DateTime
*/
public function getBirthdate()
{
return $this->birthdate;
}
/**
* Set phone
*
* #param string $phone
*
* #return User
*/
public function setPhone($phone)
{
$this->phone = $phone;
return $this;
}
/**
* Get phone
*
* #return string
*/
public function getPhone()
{
return $this->phone;
}
/**
* #return mixed
*/
public function getRole()
{
return $this->role;
}
/**
* #param mixed $role
* #return string
*/
public function setRole($role)
{
$this->role = $role;
if(in_array('ROLE_SUPER_ADMIN', $this->role)) $role = 'Super Administrator';
else if(in_array('ROLE_ADMIN', $this->role)) $role = 'Administrator';
else if(in_array('ROLE_MANAGER', $this->role)) $role = 'Manager';
else if(in_array('ROLE_ASSOCIATION', $this->role)) $role = 'Association';
else if(in_array('ROLE_USER', $this->role)) $role = 'Member';
return $role;
}
/**
* Get photo
*
* #return \AclBundle\Entity\Image
*/
public function getPhoto()
{
return $this->photo;
}
/**
* #param \AclBundle\Entity\Image $photo
*
* #return User
*
*/
public function setPhoto(\AclBundle\Entity\Image $photo = null)
{
$this->photo = $photo;
}
/**
* #return \DateTime
*/
public function getDateInscription()
{
return $this->dateInscription;
}
/**
* #param \DateTime $dateInscription
*/
public function setDateInscription($dateInscription)
{
$this->dateInscription = $dateInscription;
}
public function __construct()
{
parent::__construct();
$this->dateInscription = new \DateTime('NOW');
}
}
and My RegistrationType looks like
<?php
namespace AclBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cin',TextType::class)
->add('firstname',TextType::class)
->add('lastname',TextType::class)
->add('birthdate',DateType::class,[
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'attr' => [
'class' => 'form-control input-inline date',
'data-provide' => 'datepicker',
'data-date-format' => 'dd-mm-yyyy'
],
'html5' => false,
]
)
->add('phone',TextType::class)
->add('photo',ImageType::class, array('required' => false));
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
}
My ImageType is :
<?php
namespace AclBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ImageType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file',FileType::class);
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AclBundle\Entity\Image'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'aclbundle_image';
}
}
I tried a lot of suggested solution but it didn't work for my case ! , i think it is a simple error but my mind is blowed up

Symfony 3 form pre-populate collection field type

Is it possible to populate collection with some default items
Say you have collection of prices, but each price can be of different type. And what I want is that collection always has some predefined (generated somehow) items?
Main entity
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\ManyToMany;
/**
* Class Stamp
* #package AppBundle\Entity
*
*
* #ORM\Entity(repositoryClass="AppBundle\Repository\StampRepository")
* #ORM\Table(name="stamp")
* #ORM\HasLifecycleCallbacks()
*/
class Stamp
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=512, nullable=true)
*/
private $title;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Price", cascade={"persist", "remove"})
* #ORM\JoinTable(name="stamps_prices",
* joinColumns={#ORM\JoinColumn(name="stamp_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={#ORM\JoinColumn(name="price_id", referencedColumnName="id", onDelete="CASCADE")}
* )
*/
private $prices;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
/**
* #ORM\Column(type="datetime")
*/
private $updatedAt;
public function __construct()
{
$this->prices = new ArrayCollection();
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* #param mixed $title
*
* #return Stamp
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* #return mixed
*/
public function getPrices()
{
return $this->prices;
}
public function addPrice(Price $price)
{
$this->prices->add($price);
}
/**
* #param mixed $prices
*
* #return Stamp
*/
public function setPrices(ArrayCollection $prices)
{
$this->prices = $prices;
return $this;
}
/**
* #return mixed
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #param mixed $createdAt
*
* #return Stamp
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* #return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* #param mixed $updatedAt
*
* #return Stamp
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function updateTimestamps()
{
$this->setUpdatedAt(new \DateTime('now'));
if (null == $this->getCreatedAt()) {
$this->setCreatedAt(new \DateTime());
}
}
}
Main entity form
<?php
namespace AppBundle\Form;
use AppBundle\Entity\Stamp;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AdminStampForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', null, [
'label' => false,
'attr' => [
'id' => 'stamp-title',
'class' => 'form-control input-md',
'placeholder' => 'Enter title',
'autocomplete' => 'off'
]
])
->add('prices', CollectionType::class, [
'label' => false,
'entry_type' => AdminStampPriceForm::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Stamp::class,
]);
}
public function getName()
{
return 'app_bundle_admin_stamp_form';
}
}
Price entity
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Price
* #package AppBundle\Entity
*
* #ORM\Entity(repositoryClass="AppBundle\Repository\PriceRepository")
* #ORM\Table(name="price")
*/
class Price
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\PriceType")
* #ORM\JoinColumn(name="type_id", nullable=false, referencedColumnName="id")
*/
private $type;
/**
* #ORM\Column(type="string")
*/
private $value;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $city;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $issueDate;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getType()
{
return $this->type;
}
/**
* #param mixed $type
* #return Price
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* #return mixed
*/
public function getValue()
{
return $this->value;
}
/**
* #param mixed $value
*
* #return Price
*/
public function setValue($value)
{
$this->value = $value;
return $this;
}
/**
* #return mixed
*/
public function getCity()
{
return $this->city;
}
/**
* #param mixed $city
*
* #return Price
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* #return mixed
*/
public function getIssueDate()
{
return $this->issueDate;
}
/**
* #param mixed $issueDate
*
* #return Price
*/
public function setIssueDate($issueDate)
{
$this->issueDate = $issueDate;
return $this;
}
}
PriceType Entity
<?php
namespace AppBundle\Entity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class PriceType
* #package AppBundle\Entity
*
* #ORM\Entity(repositoryClass="AppBundle\Repository\PriceTypeRepository")
* #ORM\Table(name="price_type")
* #ORM\HasLifecycleCallbacks()
*/
class PriceType
{
const SECTION_UNUSED = 1;
const SECTION_USED = 2;
const SECTION_FDC = 3;
const SECTION_CUSTOM = 4;
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="integer")
*/
private $section;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\Column(type="boolean")
*/
private $hasCityName = false;
/**
* #ORM\Column(type="boolean")
*/
private $hasIssueDate = false;
/**
* #ORM\Column(type="boolean")
*/
private $isPredefined = false;
/**
* #ORM\Column(type="datetime")
*/
private $createdAt;
/**
* #ORM\Column(type="datetime")
*/
private $updatedAt;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getSection()
{
return $this->section;
}
/**
* #param mixed $section
*
* #return PriceType
*/
public function setSection($section)
{
$this->section = $section;
return $this;
}
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*
* #return PriceType
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #return mixed
*/
public function getHasCityName()
{
return $this->hasCityName;
}
/**
* #param mixed $hasCityName
*
* #return PriceType
*/
public function setHasCityName($hasCityName)
{
$this->hasCityName = $hasCityName;
return $this;
}
/**
* #return mixed
*/
public function getHasIssueDate()
{
return $this->hasIssueDate;
}
/**
* #param mixed $hasIssueDate
*
* #return PriceType
*/
public function setHasIssueDate($hasIssueDate)
{
$this->hasIssueDate = $hasIssueDate;
return $this;
}
/**
* #return mixed
*/
public function getIsPredefined()
{
return $this->isPredefined;
}
/**
* #param mixed $isPredefined
*
* #return PriceType
*/
public function setIsPredefined($isPredefined)
{
$this->isPredefined = $isPredefined;
return $this;
}
/**
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* #param \DateTime $createdAt
*
* #return PriceType
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* #param \DateTime $updatedAt
*
* #return PriceType
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function updateTimestamps()
{
$this->setUpdatedAt(new \DateTime('now'));
if (null == $this->getCreatedAt()) {
$this->setCreatedAt(new \DateTime());
}
}
}
PriceType repository
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* Class PriceTypeRepository
* #package AppBundle\Entity
*/
class PriceTypeRepository extends EntityRepository
{
public function getPredefinedPriceTypes($section)
{
return $this
->createQueryBuilder('pt')
->andWhere('pt.section = :section')
->setParameter('section', $section)
->andWhere('pt.isPredefined = :isPredefined')
->setParameter('isPredefined', true)
->getQuery()
->getResult()
;
}
}
Priec form
<?php
namespace AppBundle\Form;
use AppBundle\Entity\Price;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class AdminStampPriceForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('value', null, [
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Price::class,
]);
}
public function getBlockPrefix()
{
return 'app_bundle_admin_stamp_price_form';
}
}
Main entity controller newAction
/**
* #Route("/new", name="admin_stamps_new")
* #Template(engine="haml")
*/
public function newAction(Request $request)
{
$stamp = new Stamp();
$priceTypeRepo = $this->getDoctrine()->getManager()->getRepository('AppBundle:PriceType');
$priceTypes = $priceTypeRepo->getPredefinedPriceTypes(PriceType::SECTION_UNUSED);
/** #var PriceType $priceType */
foreach ($priceTypes as $priceType) {
$price = new Price();
$price->setType($priceType->getId());
$stamp->addPrice($price);
}
$form = $this->createForm(AdminStampForm::class, $stamp);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** #var Stamp $stamp */
$stamp = $form->getData();
$user = $this->getUser();
$stamp->setUser($user);
$stamp->setCountry($user->getAdminConfig()->getCountry());
$em = $this->getDoctrine()->getManager();
$em->persist($stamp);
$em->flush();
$this->addFlash('success', 'Successfully added a new stamp!');
return $this->redirectToRoute('admin_stamps_list');
}
return [
'form' => $form->createView(),
];
}
So I tried to populate Stamp entity itself. But what I actually need is to have 4 separate field sets of prices (each field set for a price type). And (and) to have some predefined $priceType->isPredefined() prices to be there. I'm not sure if you understand correctly what I'm trying to say. So I will answer all upcoming questions.

Multiple file upload with VlabsMediaBundle in Symfony2

i'm trying to make a multiple upload file on an entity with the vlabsmediaBundle.
So i have an advert who can have many images but each can be linked with only one advert.
I followed the tutorial(tuto) of the bundle but get an error.
Here:
Entity Image.php
namespace MDB\PlatformBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Vlabs\MediaBundle\Entity\BaseFile as VlabsFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Image
*
* #ORM\Table()
* #ORM\Entity
*/
class Image extends VlabsFile {
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #ORM\ManyToOne(targetEntity="MDB\AnnonceBundle\Entity\Annonce", inversedBy="images")
* #ORM\JoinColumn(nullable=true)
*/
private $annonce;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set url
*
* #param string $url
* #return Image
*/
public function setUrl($url) {
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl() {
return $this->url;
}
/**
* Set alt
*
* #param string $alt
* #return Image
*/
public function setAlt($alt) {
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt() {
return $this->alt;
}
public function getAnnonce() {
return $this->annonce;
}
public function setAnnonce($annonce) {
$this->annonce = $annonce;
}
/**
* #var string $path
*
* #ORM\Column(name="path", type="string", length=255)
* #Assert\Image()
*/
private $path;
/**
* Set path
*
* #param string $path
* #return Image
*/
public function setPath($path) {
$this->path = $path;
return $this;
}
/**
/**
* Get path
*
* #return string
*/
public function getPath() {
return $this->path;
}
}
Annonce.php (advert enity)
<?php
namespace MDB\AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Vlabs\MediaBundle\Annotation\Vlabs;
/**
* Annonce
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MDB\AnnonceBundle\Entity\AnnonceRepository")
*/
class Annonce {
public function __construct() {
$this->date = new \Datetime();
$this->categories = new ArrayCollection();
$this->images = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255)
*/
private $description;
/**
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #var float
*
* #ORM\Column(name="prix", type="float")
*/
private $prix;
/**
* #ORM\ManyToOne(targetEntity="MDB\AdresseBundle\Entity\Ville", inversedBy="annonces")
*/
private $ville;
/**
* #ORM\ManyToMany(targetEntity="MDB\AnnonceBundle\Entity\Category", cascade={"persist"})
*/
private $categories;
/**
* #ORM\ManyToMany(targetEntity="MDB\UserBundle\Entity\User")
*
*/
private $wishlist;
/**
* #var boolean
*
* #ORM\Column(name="telAppear", type="boolean")
*/
private $telAppear;
/**
* #ORM\ManyToOne(targetEntity="MDB\UserBundle\Entity\User", inversedBy="annonces")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #var VlabsFile
* #ORM\OneToMany(targetEntity="MDB\PlatformBundle\Entity\Image", mappedBy="annonce")
* #Vlabs\Media(identifier="image_entity", upload_dir="files/images")
* #Assert\Valid()
*/
private $images;
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set titre
*
* #param string $titre
* #return Annonce
*/
public function setTitre($titre) {
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre() {
return $this->titre;
}
/**
* Set description
*
* #param string $description
* #return Annonce
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription() {
return $this->description;
}
/**
* Set prix
*
* #param float $prix
* #return Annonce
*/
public function setPrix($prix) {
$this->prix = $prix;
return $this;
}
/**
* Get prix
*
* #return float
*/
public function getPrix() {
return $this->prix;
}
public function addCategory(Category $category) {
// Ici, on utilise l'ArrayCollection vraiment comme un tableau
$this->categories[] = $category;
return $this;
}
public function removeCategory(Category $category) {
$this->categories->removeElement($category);
}
public function getCategories() {
return $this->categories;
}
public function getDate() {
return $this->date;
}
public function setDate($date) {
$this->date = $date;
}
public function getWishlist() {
return $this->wishlist;
}
public function setWishlist($wishlist) {
$this->wishlist = $wishlist;
}
public function getVille() {
return $this->ville;
}
public function setVille($ville) {
$this->ville = $ville;
}
public function getTelAppear() {
return $this->telAppear;
}
public function setTelAppear($telAppear) {
$this->telAppear = $telAppear;
}
public function getUser() {
return $this->user;
}
public function setUser($user) {
$this->user = $user;
}
public function addImage(Image $image) {
$this->images[] = $image;
$image->setUser($this);
return $this;
}
public function removeImage(Image $image) {
$this->images->removeElement($image);
}
public function getImages() {
return $this->images;
}
}
config.yml
vlabs_media:
image_cache:
cache_dir: files/c
mapping:
image_entity:
class: MDB\PlatformBundle\Entity\Image
AnnonceSellType.php
<?php
namespace MDB\AnnonceBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use MDB\PlatformBundle\Form\ImageType;
class AnnonceSellType extends AbstractType {
private $arrayListCat;
public function __construct( $arrayListCat)
{
$this->arrayListCat = $arrayListCat;
}
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->remove('wishlist')
->remove('date')
->remove('images')
->add('titre')
->add('description', 'textarea')
->add('prix')
->add('categories', 'choice', array(
'choices' => $this->arrayListCat,
'multiple' => true,
'mapped'=>false,
))
//->add('images', 'collection', array('type' => new ImageType()))
->add('image', 'vlabs_file', array(
'required' => false
))
;
}
/**
* #return string
*/
public function getName() {
return 'mdb_annoncebundle_annonce_sell';
}
public function getParent() {
return new AnnonceType();
}
}
And i have the following error : Catchable Fatal Error: Argument 1 passed to Vlabs\MediaBundle\EventListener\BaseFileListener::preSetData() must be an instance of Symfony\Component\Form\Event\DataEvent, instance of Symfony\Component\Form\FormEvent given in C:\wamp\www\Mdb\vendor\vlabs\media-bundle\Vlabs\MediaBundle\EventListener\BaseFileListener.php line 59
i tried to change this line :
->add('image', 'vlabs_file', array(
'required' => false
))
with :
->add('images', 'collection', array('type' => 'vlabs_file'))
but i just have the image label who appear in this case
if someone have an idea ?
I was a little bit investigating about your problem and Vlabs Media Bundle seems to be unmaintained. There is form listener on PRE_SET_DATA event (Vlabs\MediaBundle\EventListener\BaseFileListener::preSetData()) that is not compatible with new version of Symfony (it expects DataEvent as parametr instead FormEvent). They fixed it but after 1.1.1 release (you can compare dates from links). If really wanna give a try, change composer.json and run composer update. I can't guarantee there will not be another possible issues.
composer.json
"vlabs/media-bundle": "dev-master"
Library update
composer update vlabs/media-bundle

How to get the value of a form field through the form class in symfony2?

I would like to know how to get the value of a form field through the form class in symfony2. The explanation is as below:
This is the code of the entity class:
<?php
namespace Ikproj\HomeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="Ikproj\HomeBundle\Entity\UserRepository")
*/
class User
{
/**
* #var integer
*
* #ORM\Column(name="id_user", 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="username", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="pseudo", type="string", length=255)
*/
private $pseudo;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $passWD;
/**
* #var string
*
* #ORM\Column(name="sexeuser", type="string", length=255)
*/
private $sexeuser;
/**
* #var \DateTime
*
* #ORM\Column(name="dateanniv", type="date")
*/
private $dateanniv;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set pseudo
*
* #param string $pseudo
* #return User
*/
public function setPseudo($pseudo)
{
$this->pseudo = $pseudo;
return $this;
}
/**
* Get pseudo
*
* #return string
*/
public function getPseudo()
{
return $this->pseudo;
}
/**
* Set passWD
*
* #param string $passWD
* #return User
*/
public function setPassWD($passWD)
{
$this->passWD = $passWD;
return $this;
}
/**
* Get passWD
*
* #return string
*/
public function getPassWD()
{
return $this->passWD;
}
/**
* Set sexeuser
*
* #param string $sexeuser
* #return User
*/
public function setSexeuser($sexeuser)
{
$this->sexeuser = $sexeuser;
return $this;
}
/**
* Get sexeuser
*
* #return string
*/
public function getSexeuser()
{
return $this->sexeuser;
}
/**
* Set dateanniv
*
* #param \DateTime $dateanniv
* #return User
*/
public function setDateanniv($dateanniv)
{
$this->dateanniv = $dateanniv;
return $this;
}
/**
* Get dateanniv
*
* #return \DateTime
*/
public function getDateanniv()
{
return $this->dateanniv;
}
}
And this is the code of the form class (the form builder):
<?php
namespace Ikproj\HomeBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserprofilechangeType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('sexeuser', 'text');
$def = $builder->add('sexeuser', 'text');
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ikproj\HomeBundle\Entity\User'
));
}
/**
* #return string
*/
public function getName()
{
return 'ikproj_homebundle_user';
}
}
Actually, what I would like to know is how to put the value of the field "sexeuser" inside the variable $def. In other words, how shall I change this line $def = $builder->add('sexeuser', 'text'); in order to get the value of the field sexeuser?
You need dynamically modify Form using Form Events:
In this case, everything happens before loading data into the form (PRE_SET_DATA)
// src/Acme/DemoBundle/Form/Type/FriendMessageFormType.php
namespace Acme\DemoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class FriendMessageFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('subject', 'text')
->add('body', 'textarea');
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$data = $event->getData();
var_dump($data);die;
}
);
}
public function getName()
{
return 'acme_friend_message';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
}
}
http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html

Categories