i have 2 entities:
Domain:
class Domain
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 191, unique: true)]
#[Assert\NotBlank(message: 'domain.name.not_blank')]
private ?string $name = null;
#[ORM\ManyToMany(targetEntity: Bill::class, inversedBy: 'domains', cascade: ['persist', 'remove'])]
private Collection $bill;
public function __construct()
{
$this->bill = new ArrayCollection();
}
public function __toString()
{
return $this->name;
}
/**
* #return Collection<int, Bill>
*/
public function getBill(): Collection
{
return $this->bill;
}
public function addBill(Bill $bill): self
{
if (!$this->bill->contains($bill)) {
$this->bill->add($bill);
}
return $this;
}
public function removeBill(Bill $bill): self
{
$this->bill->removeElement($bill);
return $this;
}
}
And Bill:
class Bill
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $number = null;
#[ORM\ManyToMany(targetEntity: Domain::class, mappedBy: 'bill')]
private Collection $domains;
public function __construct()
{
$this->domains = new ArrayCollection();
}
public function __toString()
{
return $this->number;
}
public function getId(): ?int
{
return $this->id;
}
public function getNumber(): ?string
{
return $this->number;
}
public function setNumber(string $number): self
{
$this->number = $number;
return $this;
}
/**
* #return Collection<int, Domain>
*/
public function getDomains(): Collection
{
return $this->domains;
}
public function addDomain(Domain $domain): self
{
if (!$this->domains->contains($domain)) {
$this->domains->add($domain);
$domain->addBill($this);
}
return $this;
}
public function removeDomain(Domain $domain): self
{
if ($this->domains->removeElement($domain)) {
$domain->removeBill($this);
}
return $this;
}
}
BillType form:
class BillingType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('number', TextType::class, [
'attr' => ['placeholder' => 'Numero fattura',]
])
->add('domains', EntityType::class, [
'class' => Domain::class,
'expanded' => true,
'multiple' => true,
'choice_label' => 'name'
])
->add('submit', SubmitType::class, [
'attr' => [
'class' => 'btn-success',
]
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Bill::class,
]);
}
}
I'm trying to set the bill for multiple domains at the same time, so my controller look like this:
public function domainBilling(Request $request, ManagerRegistry $doctrine, PaginatorInterface $paginator)
{
$filters = $this->getFilters($request)['filters'];
$form = $this->getFilters($request)['form'];
$dbquery = $doctrine
->getRepository(Domain::class)
->findAllPaginated($filters)
->getQuery();
$domains = $paginator->paginate(
$dbquery, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
Domain::perPage, /*limit per page*/
[
'defaultSortFieldName' => 'd.name',
'defaultSortDirection' => 'asc',
]
);
$billing_form = $this->createForm(BillingType::class);
$billing_form->handleRequest($request);
if ($billing_form->isSubmitted() && $billing_form->isValid()) {
$em = $doctrine->getManager();
$domains = $billing_form['domains']->getData();
$bill_number = $billing_form['number']->getData();
$bill = new Bill();
$bill->setNumber($bill_number);
$em->flush();
$this->addFlash(
'success',
'Le modifiche sono state effettuate!'
);
return $this->redirectToRoute('domain_dashboard');
}
return $this->render('Admin/domain_dashboard.html.twig', [
'billing_form' => $billing_form->createView(),
'form' => $form->createView(),
'domains' => $domains
]);
}
And it's working without calling $em->persist(); on bill or domain and without calling foreach to save every domain. If i persist one of them i find duplicate entry for bill inside db. Am i doing something wrong?
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 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 created a back-end system by using SonataAdminBundle in order to manage a User and Role entities which have Many-To-Many relation.
Everything goes well until I edited the role of the user.
The error showed up : FatalErrorException: Error: Call to a member function add() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/projectName/vendor/sonata-project/doctrine-orm-admin-bundle/Sonata/DoctrineORMAdminBundle/Model/ModelManager.php line 560
I tried the following commands:
php app/console doctrine:generate:entities projectBundle
php app/console doctrine:schema:update --force
php app/console cache:clear
Notthing changes... :(
Entities
User
<?php
//.. Declare namespace and use
class User implements UserInterface, \Serializable
{
// ...
// Declare variables
public function __construct()
{
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
}
function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
public function getLastName()
{
return $this->lastName;
}
public function setEmail($email)
{
$this->email = $email;
return $this;
}
public function getEmail()
{
return $this->email;
}
public function setUsername($username)
{
$this->username = $username;
return $this;
}
public function getUsername()
{
return $this->username;
}
public function setPassword($password)
{
$this->password = $password;
return $this;
}
public function getPassword()
{
return $this->password;
}
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
public function getDateCreated()
{
return $this->dateCreated;
}
public function addRole(Role $role)
{
// Link each role with the user
$role->addUser($this);
$this->roles->add($role);
return $this;
}
public function removeRole(Role $role)
{
// Link each role with the user
$role->removeUser($this);
$this->roles->removeElement($role);
}
public function getRoles()
{
return $this->roles->toArray();
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function equals(User $user)
{
return $user->getUsername() == $this->getUsername();
}
/**
* #ORM\PrePersist
*/
public function setDateCreatedValue()
{
$this->setDateCreated(new \DateTime());
}
function __toString()
{
return $this->getName();
}
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
));
}
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
) = unserialize($serialized);
}
}
Role
<?php
//.. Declare namespace and use
class Role implements RoleInterface
{
// .. Declare variables
public function __construct()
{
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setDescription($description)
{
$this->description = $description;
return $this;
}
public function getDescription()
{
return $this->description;
}
public function setDateCreated($dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
public function getDateCreated()
{
return $this->dateCreated;
}
public function addUser(User $user)
{
$user->addRole($this);
$this->users->add($user);
return $this;
}
public function removeUser(User $user)
{
$user->removeRole($this);
$this->users->removeElement($user);
}
public function getUsers()
{
return $this->users;
}
/**
* #ORM\PrePersist
*/
public function setDateCreatedValue()
{
$this->setDateCreated(new \DateTime());
}
function __toString()
{
return $this->getName();
}
public function getRole(){
return $this->getName();
}
}
SonataAdminClass
UserAdmin
<?php
//.. Declare namespace and use
class UserAdmin extends Admin
{
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', 'text', array('label' => 'Name'))
->add('lastName', 'text', array('label' => 'Last name'))
->add('email') //if no type is specified, SonataAdminBundle tries to guess it
->add('username')
->add('password')
->add('roles','sonata_type_model',array(
'expanded' => true,
'compound' => true,
'multiple' => true,
'by_reference' => true
));
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('name')
->add('lastName')
->add('roles')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('lastName')
->add('email')
->add('roles','sonata_type_model')
;
}
}
RoleAdmin
<?php
//.. Declare namespace and use
class RoleAdmin extends Admin
{
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', 'text', array('label' => 'Role name'))
->add('description', 'text', array('label' => 'Role description'))
;
}
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('name')
->add('description')
;
}
// Fields to be shown on lists
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('description')
;
}
}
I have been trying for a whole day and still not be able to figure it out. Any help would be really appreciated!!
Try to change this
$this->roles->add($role);
to this
$this->roles[] = $role;
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';
}
}