首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Symfony 4 EntityType数据库未更新

Symfony 4 EntityType数据库未更新
EN

Stack Overflow用户
提问于 2020-04-25 14:51:27
回答 1查看 773关注 0票数 0

我对EntityType表单字段有一个问题。

实体“自由人”是与实体“Sap子域”相关的ManyToMany。在FreelancerType上的表单中,我添加了“皂子域”作为EntityType。

当我保存我的表单时,所有字段都被正确地保存到数据库中,显示“皂子域”。

我希望“自由职业者”和“Sap子域”之间的关系表得到更新,但什么也没有发生。我没有错误信息..。

谢谢你的帮助!

“自由人”实体:

代码语言:javascript
复制
<?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;
    }




}

“Sap子域”实体:

代码语言:javascript
复制
<?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;
    }

}

表格FreelancerType:

代码语言:javascript
复制
<?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:

代码语言:javascript
复制
<?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(),
        ));

    }

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

代码语言:javascript
复制
{{ form_widget(freelancer.sapsubdomains) }}

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

代码语言:javascript
复制
$subdomaintexts  = $form['sapsubdomains']->getData();

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

            $freelancer->addSapsubdomain($sapsubdomains);

但现在我收到了一条错误消息:

执行‘选择t0.id作为id_1,t0 .子域作为subdomain_2,t0.domain_id作为domain_id_3从边子域t0,其中t0.subdomain = ?’时发生异常。具有params {}: 无法将类Doctrine\ORM\PersistentCollection的对象转换为字符串

EN

回答 1

Stack Overflow用户

发布于 2020-04-26 14:45:03

您要做的是将Sapsubdomain集合保存到Freelancer类型实体中。将集合嵌入到窗体的正确方法是使用Symfony\Component\Form\Extension\Core\Type\CollectionType::class,从而使symfony能够正确地处理这些功能。

代码语言:javascript
复制
<?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:使用表单集合中找到。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61427537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档