簡體   English   中英

Symfony 4 | ManyToMany關系-無法確定屬性的訪問類型

[英]Symfony 4 | ManyToMany Relation - Could not determine access type for property

大家好,

我目前正在研究Symfony 4上的一個項目。我在兩個學說實體(Groupe和Contact)之間建立了ManyToMany關系,但是當我嘗試創建新的聯系人時,出現以下錯誤:(我強調這些實體是使用make:實體創建)。預先感謝您的幫助。

例外:無法確定類“ App \\ Entity \\ Contact”中屬性“ groupe”的訪問類型:可以使用方法“ addGroupe()”,“ removeGroupe”定義類“ App \\ Entity \\ Contact”中的屬性“ groupe” ()”,但新值必須是\\ Traversable的數組或實例,並指定了“ App \\ Entity \\ Groupe”。

// Contact.php

 namespace App\Entity;

 use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;
 use Doctrine\ORM\Mapping as ORM;
 use Symfony\Component\Validator\Constraints as Assert;

 /**
  * @ORM\Entity(repositoryClass="App\Repository\ContactRepository")
  * @ORM\Table(name="cm_f_contact")
  */

 class Contact
 {
  // .....

  /**
   * @ORM\ManyToMany(targetEntity="App\Entity\Groupe", inversedBy="contacts")
   * @Assert\Valid
   */
   private $groupe;


   public function __construct()
   {
     $this->groupe = new ArrayCollection();
   }


   /**
    * @return Collection|Groupe[]
    */
   public function getGroupe(): Collection
   {
     return $this->groupe;
   }

   public function addGroupe(Groupe $groupe): self
   {
     if (!$this->groupe->contains($groupe)) {
        $this->groupe[] = $groupe;
     }

    return $this;
   }

   public function removeGroupe(Groupe $groupe): self
   {
     if ($this->groupe->contains($groupe)) {
        $this->groupe->removeElement($groupe);
     }

    return $this;
   }
}

// Groupe.php

  namespace App\Entity;

  use Doctrine\Common\Collections\ArrayCollection;
  use Doctrine\Common\Collections\Collection;
  use Doctrine\ORM\Mapping as ORM;
  use Symfony\Component\Validator\Constraints as Assert;


  /**
   * @ORM\Entity(repositoryClass="App\Repository\GroupeRepository")
   * @ORM\Table(name="cm_f_group")
   */

   class Groupe
   {

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Contact", mappedBy="groupe")
     */
    private $contacts;


    public function __construct()
    {
     $this->contacts = new ArrayCollection();
    }

   /**
    * @return Collection|Contact[]
    */
   public function getContacts(): Collection
   {
     return $this->contacts;
   }

   public function addContact(Contact $contact): self
   {
     if (!$this->contacts->contains($contact)) {
        $this->contacts[] = $contact;
        $contact->addGroupe($this);
     }

    return $this;
   }

   public function removeContact(Contact $contact): self
   {
    if ($this->contacts->contains($contact)) {
        $this->contacts->removeElement($contact);
        $contact->removeGroupe($this);
    }

    return $this;
   }

}

// ContactController.php

 <?php

  namespace App\Controller;

  use App\Entity\Contact;
  use App\Form\ContactType;
  use App\Repository\ContactRepository;
  use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\Routing\Annotation\Route;

  /**
   * @Route("/contact")
   */

   class ContactController extends AbstractController
   {

    //...

    /**
     * @Route("/new", name="contact_new", methods={"GET","POST"})
     */
     public function new(Request $request): Response
     {
      $contact = new Contact();
      $form = $this->createForm(ContactType::class, $contact);
      $form->handleRequest($request);

      if ($form->isSubmitted() && $form->isValid()) {    
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($contact);
        $entityManager->flush();

        return $this->redirectToRoute('contact_index');
       }

      return $this->render('contact/new.html.twig', [
        'contact' => $contact,
        'form' => $form->createView(),
      ]);
    }
   }

ContactType.php`

    <?php

  namespace App\Form;

  use App\Entity\Contact;
  use App\Entity\Groupe;
  use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  use Symfony\Component\Form\AbstractType;
  use Symfony\Component\Form\FormBuilderInterface;
  use Symfony\Component\OptionsResolver\OptionsResolver;

  class ContactType extends AbstractType
  {
    public function buildForm(FormBuilderInterface $builder, array $options)
     {
      $builder
        ->add('firstname')
        ->add('lastname')
        ->add('email')
        ->add('sms_no')
        ->add('birth_date')
        ->add('created_by')
        ->add('groupes', EntityType::class, [
            'class' => Groupe::class,
            'choice_label' => 'name',
        ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Contact::class,
        ]);
    }
}

Symfony Forms將使用get<Property>set<Property>讀取和寫入模型數據。 在您的情況下,由於在Contact上沒有setGroupe()方法,因此在提交表單時表單不知道如何將值寫回實體。

對於這種情況,Symfony表單具有數據映射器

數據映射器負責從父表單讀取數據和將數據寫入父表單。

在您的情況下,您可能需要這樣的東西:

public function mapFormToData($forms, &$data)
{
    $forms = iterator_to_array($forms);
    // "groupe" is the name of the field in the ContactType form
    $groupe = $forms['groupe'];

    foreach ($groupe as $group) {
        // $data should be a Contact object
        $data->addGroup($group);
    }

    // ...Map remaining form fields to $data
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM