I am using many to many relations in my symfony2 project, i have successfully made two entities 'Users' and Groups and i have also successfully persisted data which inserts data into users,groups and users_groups table by using
$user = new User();
$user->getGroups()->add($group);
now i want to edit the user which should also edit users_groups record..
I have searched a lot but no luck.Any help would be appreciated ...
CONTROLLER
public function editAction()
{
if($this->getRequest()->query->get("id")){
$id = $this->getRequest()->query->get("id");
$request = $this->getRequest();
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('DesignAppBundle:Users')->find($id);
$editForm = $this->createForm(new UserType());
if ($this->getRequest()->getMethod() == 'POST') {
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$postData = $request->request->get('users');
$repository = $this->getDoctrine()
->getRepository('Bundle:groups');
$group = $repository->findOneById($postData['group']);
$entity->addGroups($group );
$em->flush();
return $this->redirect($this->generateUrl('index'));
}
}
return $this->render('User.html.twig',array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
));
}
}
FORM
<?php
use and include .....
class UserType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$request = Request::createFromGlobals();
$builder->add('group', 'entity', array(
'class' => 'Bundle:Groups',
'property' => 'name',
'empty_value' => 'All',
'required' => true,
'multiple'=>true,
'data' => $request->get('group_id')
));
}
public function getDefaultOptions(array $options)
{
return array(
'validation_groups' => array('users'),
'csrf_protection' => false,
);
}
public function getName()
{
return 'users';
}
}
User
/**
* #ORM\ManyToMany(targetEntity="Groups", inversedBy="users")
* #ORM\JoinTable(name="users_groups",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
**/
protected $group;
public function __construct()
{
$this->group= new ArrayCollection();
}
public function addgroups(\Design\AppBundle\Entity\Categories $group)
{
$this->group[] = $group;
}
Group
/**
* #ORM\ManyToMany(targetEntity="Users", mappedBy="group")
*/
protected $users;
public function __construct()
{
$this->users= new ArrayCollection();
}
/**
* Add users
*
* #param Bundle\Entity\Users $users
*/
public function addUsers(Bundle\Users $users)
{
$this->users[] = $users;
}
/**
* Get users
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
You should not be adding the group_id, you should be adding the groups property
$builder->add('groups');
The group_id column is automatically handled by Doctrine and you should not be handling it yourself directly. Do you have a group_id property? If you do, you should remove it.
The group entity should be:
/**
* #ORM\ManyToMany(targetEntity="Users", mappedBy="group")
*/
protected $users;
public function __construct()
{
$this->users= new ArrayCollection();
}
/**
* Add users
*
* #param Bundle\Entity\User $user
*/
public function addUsers(Bundle\User $users)
{
$this->users[] = $users;
}
/**
* Get users
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
EDIT
This is how your controller should be:
public function editAction($request)
{
$id = $this->getRequest()->query->get("id");
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('DesignAppBundle:Users')->find($id);
$editForm = $this->createForm(new UserType(),$entity);
if ($this->getRequest()->getMethod() == 'POST') {
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$em->persits($entity);
$em->flush();
return $this->redirect($this->generateUrl('index'));
}
}
return $this->render('User.html.twig',array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
));
}
and this is how your UserType should be:
class UserType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('group', 'entity', array(
'class' => 'Bundle:Groups',
'property' => 'name',
'empty_value' => 'All',
'required' => true,
'multiple'=>true,
));
}
public function getDefaultOptions(array $options)
{
return array(
'validation_groups' => array('users'),
'csrf_protection' => false,
);
}
public function getName()
{
return 'users';
}
}
Related
Symfony 3.4 Doctrine 1.9
I have found a lot of articles about this. But nothing could resolve my
problem.
I have two Entities User and Company which are mapped as Many2Many.
Both Entities should be filled with a form submit. Therefor I have the following FormTypes:
CustomerRegistrationType
This includes the CollectionType with entry_type of CompanyFormType, which returns the Company:class
class CustomerRegistrationType extends AbstractType
{
private $translator;
private $session;
public function __construct(TranslatorInterface $translator,Session $session)
{
$this->session = $session;
$this->translator = $translator;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('mandant',HiddenType::class,array('data'=>
->add('newsletter',CheckboxType::class,array('label' => false,'required' => false))
->add('company', CollectionType::class, array('entry_type' => CompanyFormType::class, 'entry_options' => array('label' => false)));
}
CompanyFormType
class CompanyFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('telephone', TextType::class,array('required' => false))
->add('company_name', TextType::class,array('label' => false,'required' => false))
->add('company_supplement', TextType::class,array('label' =>
->add('send_info', CheckboxType::class,array('label' => false,'required' => false))
->add('send_invoice', CheckboxType::class,array('label' => false,'required' => false))
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Company'));
}
}
Many2Many mapping
class User extends BaseUser
{
public function __construct()
{
parent::__construct();
$this->company = new ArrayCollection();
}
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Company",inversedBy="users")
* #ORM\JoinTable(name="user_comp_comp_user",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="company_id", referencedColumnName="id")}
* )
*/
protected $company;
public function getCompany()
{
return $this->company;
}
public function setCompany($company)
{
$this->company = $company;
return $this;
}
public function addCompany(Company $company)
{
if ($this->company->contains($company)) {
return;
}
$this->company[] = $company;
return $this;
}
public function removeCompany(Company $company)
{
if (!$this->company->contains($company)) {
return;
}
$this->company->removeElement($company);
return $this;
}
class Company
{
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* #var \Doctrine\Common\Collections\Collection|Company[]
* #ORM\ManyToMany(targetEntity="User",mappedBy="company")
*/
protected $users;
}
In the Controller I want to save all Data to the different Entities.
Therefor I do:
public function registerAction(Request $request)
{
$user = $this->userManager->createUser();
$form = $this->createForm(CustomerRegistrationType::class,$user);
$form->handleRequest($request);
$company = $user->getCompany();
$company->setSendInvoice(true);
$company->setSendInfo(true);
if ($form->isSubmitted()){
$user->addCompany($company);
$this->userManager->updateUser($user);
....
}
return $this->render('Registration/register.html.twig',[
'form' => $form->createView()
]);
}
I does not matter, which way I try, eachtime I get an error. In this example, the company data is empty. Other ways are in conflict with the ArrayCollection() of $this->company in User()
User {#907 ▼
#id: null
#company: ArrayCollection {#926 ▼
-elements: []
}
#groups: null
#mandant: null
#salutation: null
#first_name: null
#last_name: null
#fullname: null
#created: DateTime #1544539763 {#901 ▶}
#telephone: null
Update:
In Twig form I have no access to
{{ form_widget(form.company.company_name, {'attr': {'class': 'form-control'}})}}
Neither the property "company_name" nor one of the methods "company_name()", "getcompany_name()"/"iscompany_name()"/"hascompany_name()" or "__call()" exist and have public access in class "Symfony\Component\Form\FormView".
This comes up before form submit.
I found the solution here:
https://groups.google.com/forum/#!topic/symfony2/DjwwzOfUIuQ
So I used an array based form in the controller
$form = $this->createFormBuilder()
->add('user', CustomerRegistrationType::class, array(
'data_class' => 'AppBundle\Entity\User'
))
->add('company', CompanyFormType::class, array(
'data_class' => 'AppBundle\Entity\Company'
))
->getForm();
The different Objects can catched like this:
$form->handleRequest($request);
$user = $form->get('user')->getData();
$company = $form->get('company')->getData();
and then
if ($form->isSubmitted()){
...
$user->addCompany($company);
$this->userManager->updateUser($user);
}
That's it
I try to insert records with relations OneToMany-ManyToOne, but I got error.
Expected argument of type "string", "App\Entity\Question" given.
I have next entities question and answer.
class Question
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $title;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Answer", mappedBy="question", orphanRemoval=true)
*/
private $answers;
public function __construct()
{
$this->answers = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
/**
* #return Collection|Answer[]
*/
public function getAnswers(): Collection
{
return $this->answers;
}
public function addAnswer(Answer $answer): self
{
if (!$this->answers->contains($answer)) {
$this->answers[] = $answer;
$answer->setQuestion($this);
}
return $this;
}
public function removeAnswer(Answer $answer): self
{
if ($this->answers->contains($answer)) {
$this->answers->removeElement($answer);
if ($answer->getQuestion() === $this) {
$answer->setQuestion(null);
}
}
return $this;
}
}
Entity Answer
class Answer
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $text;
/**
* #ORM\Column(type="boolean")
*/
private $is_correct;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="answers")
* #ORM\JoinColumn(nullable=false)
*/
private $question;
public function getId(): ?int
{
return $this->id;
}
public function getText(): ?string
{
return $this->text;
}
public function setText(string $text): self
{
$this->text = $text;
return $this;
}
public function getIsCorrect(): ?bool
{
return $this->is_correct;
}
public function setIsCorrect(bool $is_correct): self
{
$this->is_correct = $is_correct;
return $this;
}
public function getQuestion(): ?question
{
return $this->question;
}
public function setQuestion(?Question $question): self
{
$this->question = $question;
return $this;
}
}
My form
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', EntityType::class, array(
'class' => Question::class,
'choice_label' => 'title',
'label' => 'Question'
));
$builder
->add('answers', CollectionType::class, array(
'entry_type' => AnswerType::class,
'entry_options' => array('label' => false),
'allow_add' => true,
'by_reference' => false,
));
$builder
->add('create', SubmitType::class, ['label' => 'Add', 'attr' => ['class' => 'btn btn-primary']]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Question::class
]);
}
My fragment of controller
$question = new Question();
$answer = new Answer();
$question->addAnswer($answer);
$form1 = $this->createForm(QuestionAnswerType::class, $question);
$form1->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($question);
$em->flush();
}
The error pointer at next line
$form1->handleRequest($request);
I know I have problem with my controller, but I don't know how resolve it.
I don't get it how right insert records with relations OneToMany-ManyToOne. Could you help me?
I think the reason that you are seeing this error is due to the fact that in your Question class you have defined the title field as a Text type (#ORM\Column(type="text")).
However in your Form you have defined the form field title as an EntityType this is the reason I think why you are seeing this error.
You can fix this by changing the database mapping of the title field in your Question class or you could change your Form to use a TextType instead of an EntityType
Hope this helps
You have to do changes into two places.
1) First change into "Question" class
/**
* #ORM\Column(type="string")
*/
private $title;
2) Second into your form class replace "EntityType::class" with "TextType::class" and remove 'class' and 'choice_label' attribute from title
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, array(
'label' => 'Question'
));
..... your other code ...
}
In class Question __toString function is missing
public function __toString()
{
return $this->property-to-show;
}
I've 2 entity: User and Strain with a ManyToMany bidirectional relation, the owner of the relation is User.
I want do a form for edit the rights (the User own some Strains), when I do a form for the User where I can select some Strains I want, it works fine (I use an EntityType on Strain). But... Sometimes, I want edit the rights by the other side of the relation: Strain. ie edit the Strain and select the Users I want. But it doesn't work...
I give you my entities User and Strain and the two FormType, and my Uglys Solution...
User.php
/**
* The authorized strains for this user.
*
* #var Strain|ArrayCollection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Strain", inversedBy="authorizedUsers")
*/
private $authorizedStrains;
/**
* User constructor.
*/
public function __construct()
{
$this->authorizedStrains = new ArrayCollection();
}
/**
* Add an authorized strain.
*
* #param Strain $strain
*
* #return $this
*/
public function addAuthorizedStrain(Strain $strain)
{
$this->authorizedStrains[] = $strain;
$strain->addAuthorizedUser($this);
return $this;
}
/**
* Remove an authorized strain.
*
* #param Strain $strain
*/
public function removeAuthorizedStrain(Strain $strain)
{
$this->authorizedStrains->removeElement($strain);
$strain->removeAuthorizedUser($this);
}
/**
* Get authorized strains.
*
* #return Strain|ArrayCollection
*/
public function getAuthorizedStrains()
{
return $this->authorizedStrains;
}
Strain.php
/**
* The authorized user.
* For private strains only.
*
* #var User|ArrayCollection
*
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\User", mappedBy="authorizedStrains")
*/
private $authorizedUsers;
/**
* Strain constructor.
*/
public function __construct()
{
/**
* Add authorized user.
*
* #param User $user
*
* #return $this
*/
public function addAuthorizedUser(User $user)
{
$this->authorizedUsers[] = $user;
return $this;
}
/**
* Remove authorized user.
*
* #param User $user
*/
public function removeAuthorizedUser(User $user)
{
$this->authorizedUsers->removeElement($user);
}
/**
* Get authorized users.
*
* #return User|ArrayCollection
*/
public function getAuthorizedUsers()
{
return $this->authorizedUsers;
}
UserRightsType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('authorizedStrains', EntityType::class, array(
'class' => 'AppBundle\Entity\Strain',
'choice_label' => 'name',
'expanded' => true,
'multiple' => true,
'required' => false,
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User',
));
}
StrainRightsType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('authorizedUsers', EntityType::class, array(
'class' => 'AppBundle\Entity\User',
'query_builder' => function(UserRepository $ur) {
return $ur->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
'choice_label' => function ($user) {
return $user->getUsername().' ('.$user->getFirstName().' '.$user->getLastName().')';
},
'expanded' => true,
'multiple' => true,
'required' => false,
))
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Strain',
));
}
StrainController.php the ugly solution
public function userRightsAction(Request $request, Strain $strain)
{
$form = $this->createForm(StrainRightsType::class, $strain);
$form->add('save', SubmitType::class, [
'label' => 'Valid the rights',
]);
foreach($strain->getAuthorizedUsers() as $authorizedUser) {
$authorizedUser->removeAuthorizedStrain($strain);
}
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
foreach($strain->getAuthorizedUsers() as $authorizedUser)
{
$authorizedUser->addAuthorizedStrain($strain);
$em->persist($authorizedUser);
}
$em->flush();
$request->getSession()->getFlashBag()->add('success', 'The user\'s rights for the strain '.$strain->getName().' were successfully edited.');
return $this->redirectToRoute('strain_list');
}
return $this->render('strain/userRights.html.twig', [
'strain' => $strain,
'form' => $form->createView(),
]);
}
As you can see, I do 2 foreach: the first to remove all the rights on the Strain, and the second to give rights.
I think Symfony have anticipated this problem, but I don't know how to do, and I've found nothing in the documentation...
Thank you in advance for your help,
Sheppard
Finaly, I've found.
On the inversed side (Strain.php):
public function addAuthorizedUser(User $user)
{
$user->addAuthorizedStrain($this);
$this->authorizedUsers[] = $user;
return $this;
}
public function removeAuthorizedUser(User $user)
{
$user->removeAuthorizedStrain($this);
$this->authorizedUsers->removeElement($user);
}
And, on the owner side (User.php)
public function addAuthorizedStrain(Strain $strain)
{
if (!$this->authorizedStrains->contains($strain)) {
$this->authorizedStrains[] = $strain;
}
return $this;
}
public function removeAuthorizedStrain(Strain $strain)
{
if ($this->authorizedStrains->contains($strain)) {
$this->authorizedStrains->removeElement($strain);
}
}
And in the FormType (for the inverse side) (StrainRightsType)), add 'by_reference' => false
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('authorizedUsers', EntityType::class, array(
'class' => 'AppBundle\Entity\User',
'query_builder' => function(UserRepository $ur) {
return $ur->createQueryBuilder('u')
->orderBy('u.username', 'ASC');
},
'choice_label' => function ($user) {
return $user->getUsername().' ('.$user->getFirstName().' '.$user->getLastName().')';
},
'by_reference' => false,
'expanded' => true,
'multiple' => true,
'required' => false,
))
;
}
I have two entities. Container and Schooltype. The entity container have a "oneToMany" relation to entity Schooltype.
Entity Container:
/**
* #ORM\OneToMany(targetEntity="App\MyBundle\Entity\SchoolType", mappedBy="container", cascade={"persist", "remove"})
*/
protected $schooltype;
Entity Schooltype:
/**
* #ORM\ManyToOne(targetEntity="App\MyBundle\Entity\Container", inversedBy="schooltype")
* #ORM\JoinColumn(name="container_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $container;
Now i create a form for container, so i can add one or many schooltypes. In my entity Container i modify the "removeSchooltype" method, it's look like.
Entity Container, remove method for schooltype:
public function removeSchooltype(\App\MyBundle\Entity\SchoolType $schooltype)
{
$this->schooltype->removeElement($schooltype);
$schooltype->setContainer(null);
}
Form ContainerType:
->add('schooltype', 'entity', array(
'class' => 'AppMyBundle:Schooltype',
'choices' => $schoolTypes,
'label' => 'msg.schoolType',
'translation_domain' => 'messages',
'multiple' => true,
'expanded' => false)
)
I try to handle the store process in my controller.
Container controller, edit method:
$object = new Container();
// Exists any object?
if (!$object) {
$this->get('session')->getFlashBag()->add('danger', $this->get('translator')->trans('notfound'));
return $this->redirect($this->generateUrl('app_container_list'));
}
$form = $this->createForm($this->get('form.type.container'), $object)->add('save', 'submit', array('label' => 'save', 'translation_domain' => 'messages', 'attr' => array('class' => 'btn btn-primary')));
$form->handleRequest($request);
// Check if form isValid
if ($form->isValid()) {
// Store object
$em = $this->getDoctrine()->getManager();
$em->persist($object);
// Flush statements
$em->flush();
$em->clear();
$this->get('session')->getFlashBag()->add('info', $this->get('translator')->trans('objectEdited', array()));
return $this->redirect($this->generateUrl('app_container_list'));
}
return $this->render('AppMyBundle:Container:edit.html.twig', array("form" => $form->createView()));
Everything works fine, i can add one or many schooltypes in my container and this was saved successfull. But if i remove a schooltype from selectbox in form and post my form the relation between container and schooltype will not be removed, have someone a hint why this happens?
1 Country to N League. Example below shows you how things are done. Just apply to yours. If you want the full CRUD example for 1 to N relationships, it is here.
Country
class Country
{
protected $id;
/**
* #ORM\OneToMany(
* targetEntity="League",
* mappedBy="country",
* cascade={"persist", "remove"}
* )
*/
protected $league;
public function __construct()
{
$this->league = new ArrayCollection();
}
public function addLeague(League $league)
{
$this->league[] = $league;
return $this;
}
public function removeLeague(League $league)
{
$this->league->removeElement($league);
}
public function getLeague()
{
return $this->league;
}
}
League
class League
{
/**
* #ORM\ManyToOne(
* targetEntity="Country",
* inversedBy="league"
* )
* #ORM\JoinColumn(
* name="country_id",
* referencedColumnName="id",
* onDelete="CASCADE",
* nullable=false
* )
*/
protected $country;
public function setCountry(Country $country)
{
$this->country = $country;
return $this;
}
public function getCountry()
{
return $this->country;
}
}
LeagueType
class LeagueType extends AbstractType
{
private $country;
public function __construct()
{
$this->country = [
'class' => 'FootballFrontendBundle:Country',
'property' => 'name',
'multiple' => false,
'expanded' => false,
'required' => false,
'empty_value' => '',
'query_builder' => function (EntityRepository $repo)
{
return $repo->createQueryBuilder('c')->orderBy('c.name', 'ASC');
}
];
}
public function buildForm(FormBuilderInterface $builder, array $options = [])
{
$builder
->setMethod($options['method'])
->setAction($options['action'])
->add('whatever properties you have in your entitiy')
->add('country', 'entity', $this->country);
}
public function getName()
{
return 'league';
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
['data_class' => 'Football\FrontendBundle\Entity\League']
);
}
}
Controller delete/remove method
/**
* Deletes country.
*
* #param int $id
*
* #Route("/delete/{id}", requirements={"id"="\d+"})
* #Method({"GET"})
*
* #return RedirectResponse|Response
* #throws LeagueException
*/
public function deleteAction($id)
{
try {
$em = $this->getDoctrine()->getEntityManager();
$repo = $em->getRepository('FootballFrontendBundle:League');
$league = $repo->findOneByIdAsObject($id);
if (!$league instanceof League) {
throw new LeagueException(sprintf('League read: league [%s] cannot be found.', $id));
}
$em->remove($league);
$em->flush();
} catch (DBALException $e) {
$message = sprintf('DBALException [%s]: %s', $e->getCode(), $e->getMessage());
} catch (ORMException $e) {
$message = sprintf('ORMException [%s]: %s', $e->getCode(), $e->getMessage());
} catch (Exception $e) {
$message = sprintf('Exception [%s]: %s', $e->getCode(), $e->getMessage());
}
if (isset($message)) {
throw new LeagueException($message);
}
return $this->redirect($this->generateUrl('where ever you want'));
}
I'm trying to create a form type with a inherited property, I have one entity (Candidate) that have two attributes (String dni and User user).
I made another question but I want a solution without a embeded form, something like this (by FyodorX):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('dni', null, array_merge(array(
'label' => 'form.dni',
'translation_domain' => 'DroidersCandidateBundle',
), $this->mergeOptions))
->add('username', null, array_merge(array(
'label' => 'form.username',
'property_path' => 'user.username',
'translation_domain' => 'SonataUserBundle'
), $this->mergeOptions))
;
}
But with this I had this error:
Expected argument of type "object or array", "NULL" given
500 Internal Server Error - UnexpectedTypeException
This is my code:
Candidate.php
class Candidate
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $dni;
/**
* #var /Application\Sonata\UserBundle\Entity\User
*/
private $user;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dni
*
* #param string $dni
* #return Candidate
*/
public function setDni($dni)
{
$this->dni = $dni;
return $this;
}
/**
* Get dni
*
* #return string
*/
public function getDni()
{
return $this->dni;
}
/**
* Set user
*
* #param \Application\Sonata\UserBundle\Entity\User $user
* #return Candidate
*/
public function setUser(\Application\Sonata\UserBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \Application\Sonata\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
RegistrationFormType.php
class RegistrationFormType extends AbstractType{
private $class;
/**
* #var array
*/
protected $mergeOptions;
/**
* #param string $class The User class name
* #param array $mergeOptions Add options to elements
*/
public function __construct($class, array $mergeOptions = array())
{
$this->class = $class;
$this->mergeOptions = $mergeOptions;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('dni', null, array_merge(array(
'label' => 'form.dni',
'translation_domain' => 'DroidersCandidateBundle',
), $this->mergeOptions))
->add('username', null, array_merge(array(
'label' => 'form.username',
'property_path' => 'user.username',
'translation_domain' => 'SonataUserBundle'
), $this->mergeOptions))
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => $this->class,
'intention' => 'registration',
));
}
public function getName()
{
return 'candidate_registration';
}
}
RegistrationCandidateController.php:
class RegistrationCandidateController extends RegistrationFOSUser1Controller {
public function registerAction()
{
$user = $this->container->get('security.context')->getToken()->getUser();
if ($user instanceof UserInterface) {
$this->container->get('session')->getFlashBag()->set('sonata_user_error', 'sonata_user_already_authenticated');
$url = $this->container->get('router')->generate('sonata_user_profile_show');
return new RedirectResponse($url);
}
$form = $this->container->get('droiders_candidates.registration.form');
$formHandler = $this->container->get('droiders_candidates.registration.form.handler');
$confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');
$process = $formHandler->process($confirmationEnabled);
if ($process) {
$candidate = $form->getData();
$user = $candidate->getUser();
$authUser = false;
if ($confirmationEnabled) {
$this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
$url = $this->container->get('router')->generate('fos_user_registration_check_email');
} else {
$authUser = true;
$route = $this->container->get('session')->get('sonata_basket_delivery_redirect');
if (null !== $route) {
$this->container->get('session')->remove('sonata_basket_delivery_redirect');
$url = $this->container->get('router')->generate($route);
} else {
$url = $this->container->get('session')->get('sonata_user_redirect_url');
}
}
$this->setFlash('fos_user_success', 'registration.flash.user_created');
$response = new RedirectResponse($url);
if ($authUser) {
$this->authenticateUser($user, $response);
}
return $response;
}
$this->container->get('session')->set('sonata_user_redirect_url', $this->container->get('request')->headers->get('referer'));
return $this->container->get('templating')->renderResponse('DroidersCandidateBundle:Registration:register.html.'.$this->getEngine(), array(
'form' => $form->createView(),
));
}
}
services.yml:
droiders_candidates.registration.form:
factory_method: createNamed
factory_service: form.factory
class: Symfony\Component\Form\Form
arguments:
- droiders_registration_form
- #droiders_candidates.registration.form.type
- null
- { validation_groups: %fos_user.registration.form.validation_groups% }
droiders_candidates.registration.form.type:
class: Droiders\CandidateBundle\Form\Type\RegistrationFormType
arguments:
- %droiders.model.candidate.class%
- %sonata.user.registration.form.options%
droiders_candidates.registration.form.handler:
class: Droiders\CandidateBundle\Form\Handler\RegistrationFormHandler
scope: request
arguments:
- #droiders_candidates.registration.form
- #request
- #droiders.candidate_manager
- #fos_user.mailer
- #fos_user.util.token_generator