Search code examples
symfonydoctrinesymfony-formssymfony-3.4arraycollection

Symfony Form with ManyToMany Mapping


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.


Solution

  • 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