Symfony 4 EntityType数据库未更新

问题描述 投票:0回答:1

我对EntityType表单字段有问题。

实体“ Freelancer”与实体“ Sapsubdomain”相关联的ManyToMany。在FreelancerType的表单中,我添加了“ sapsubdomains”作为EntityType。

当我保存表单时,所有字段都正确地保存到数据库中,而不是“ sapsubdomains”。

我希望“ Freelancer”和“ Sapsubdomain”之间的关系表得到更新,但没有任何反应。我没有错误信息...

感谢您的帮助!

“自由职业者”实体:

<?php

namespace App\Entity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\FreelancerRepository")
 */
class Freelancer
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $about;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\User", cascade={"persist", "remove"})
     */
    private $Userid;


    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Sapsubdomain", mappedBy="freelancer")
     */
    private $sapsubdomains;

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


    /**
     * @return Collection|Sapsubdomain[]
     */
    public function getSapsubdomains(): Collection
    {
        return $this->sapsubdomains;
    }

    public function addSapsubdomain(Sapsubdomain $sapsubdomain): self
    {
        if (!$this->sapsubdomains->contains($sapsubdomain)) {
            $this->sapsubdomains[] = $sapsubdomain;
            $sapsubdomain->addFreelancer($this);
        }

        return $this;
    }

    public function removeSapsubdomain(Sapsubdomain $sapsubdomain): self
    {
        if ($this->sapsubdomains->contains($sapsubdomain)) {
            $this->sapsubdomains->removeElement($sapsubdomain);
            $sapsubdomain->removeFreelancer($this);
        }

        return $this;
    }




}

“ Sapsubdomain”实体:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\SapsubdomainRepository")
 */
class Sapsubdomain
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $subdomain;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Sapdomain", inversedBy="sapsubdomains")
     * @ORM\JoinColumn(nullable=false)
     */
    private $domain;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\freelancer", inversedBy="sapsubdomains")
     */
    private $freelancer;

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


    public function getId(): ?int
    {
        return $this->id;
    }

    public function getSubdomain(): ?string
    {
        return $this->subdomain;
    }

    public function setSubdomain(?string $subdomain): self
    {
        $this->subdomain = $subdomain;

        return $this;
    }

    public function getDomain(): ?sapdomain
    {
        return $this->domain;
    }

    public function setDomain(?sapdomain $domain): self
    {
        $this->domain = $domain;

        return $this;
    }

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

    public function addFreelancer(freelancer $freelancer): self
    {
        if (!$this->freelancer->contains($freelancer)) {
            $this->freelancer[] = $freelancer;
        }

        return $this;
    }

    public function removeFreelancer(freelancer $freelancer): self
    {
        if ($this->freelancer->contains($freelancer)) {
            $this->freelancer->removeElement($freelancer);
        }

        return $this;
    }

}

Form FreelancerType:

<?php

namespace App\Form;

use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;


class FreelancerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder

            ->add('sapsubdomains', EntityType::class, array(
                'class' => Sapsubdomain::class,
                'choice_label' => 'subdomain',
                'required' => false,
                'multiple' => true,
                 ))

FreelancerController:

<?php

namespace App\Controller;

/**
* @Route("/freelancer", name="freelancer")
* @Security("is_granted('ROLE_FREELANCER')")
*/
class FreelancerController extends AbstractController
{
    /**
    * @Route("/settings/", name="freelancer_settings")
    */
    public function modifyfreelancesettings(Request $request, FileUploader $fileUploader)
    {
        //On récupére l'utilisateur
        $user = $this->getUser();

        //On recherche le profil freelance du user
        $freelancer = $this->getDoctrine()
        ->getRepository(Freelancer::class)
        ->findOneBy(array('Userid'=>$user));

        // Si le profil freelance n'existe pas pour le user on appel la fonction de création du profil
        if (!$freelancer) {
            $this->createfreelancesettings($request);
        }

        //Sinon on met à jour le profil du freelance
        $form = $this->createForm(FreelancerType::class, $freelancer);
        $form->handleRequest($request);

        //On des données du freelance pour éventuellement les envoyer à TWIG
        $tjm = $form->get('dailyrate')->getData();
        $curr = $form->get('ratecurrency')->getData();

        // On vérifie que le formulaire est soumis

        if ($form->isSubmitted() && $form->isValid()) {


            $freelancer->setUpdateDate(new \DateTime('now'));


            /** @var UploadedFile $pictureFile */
            $pictureFile  = $form['picture']->getData();

                if ($pictureFile ) {
                    $pictureFileName  = $fileUploader->upload($pictureFile);
                    $freelancer->setProfilePicture($pictureFileName);
                }

            //Mise à jour des relations
            $sapsubdomains  = $form['sapsubdomains']->getData();    

            $em = $this->getDoctrine()->getManager();
            $em -> flush();

            $this->addFlash('notice',
                        'Your SAP Profile has been saved !'
                        );

                            return $this->redirect($request->getUri());


        }

        return $this->render('freelancer/settings.html.twig', array(
            'picture' => $freelancer,
            'curr' => $curr,
            'freelancer'=> $form->createView(),
        ));

    }

在此字段的模板中,我只有:

{{ form_widget(freelancer.sapsubdomains) }}

编辑:我将其添加到控制器中:

$subdomaintexts  = $form['sapsubdomains']->getData();

            $sapsubdomains = $this->getDoctrine()
            ->getRepository(Sapsubdomain::class)
            ->findBy(array('subdomain'=>$subdomaintexts));

            $freelancer->addSapsubdomain($sapsubdomains);

但是现在我收到此错误消息:

[执行'SELECT t0.id AS id_1时发生异常,t0.subdomain AS subdomain_2,t0.domain_id AS domain_id_3 FROMsapsubdomain t0 WHERE t0.subdomain =?'带有参数[{}]:

Doctrine \ ORM \ PersistentCollection类的对象不能为转换为字符串

symfony symfony4 symfony-forms
1个回答
0
投票

您想要做的是将Sapsubdomain的集合保存到Freelancer类型的实体。将集合嵌入表单的正确方法是使用Symfony\Component\Form\Extension\Core\Type\CollectionType::class,以便symfony正确处理收藏。

<?php

class FreelancerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** Other Fields **/

        $builder->add('sapsubdomains', CollectionType::class, [
            'entry_type' => SapsubdomainType::class,
            'entry_options' => ['label' => false],
             /** Other Options **/
        ]);
    }

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

整个示例代码可在Symfony Docs中找到:Using Form Collections

© www.soinside.com 2019 - 2024. All rights reserved.