首页 > 解决方案 > Symfony 4 通过 FORM 添加 ManyToMany Entity

问题描述

在将一个实体传递给另一个实体时,我严重陷入了通过 html.twig 插入数据的问题。我能够添加或编辑单个实体,但我不知道如何处理添加关系。

锦标赛实体类 - 删除了不重要的东西

<?php

namespace App\Entity;

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

/**
 * Tournament.
 *
 * @ORM\Table(name="tournament")
 * @ORM\Entity(repositoryClass="App\Repository\TournamentRepository")
 */
class Tournament
{
    /**
     * @var int
     *
     * @ORM\Column(name="id_tournament", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idTournament;

    /**
     * @var string
     *
     * @ORM\Column(name="name_of_event", type="string", length=128, nullable=false)
     */
    private $nameOfEvent;

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=16, nullable=false)
     */
    private $type;

    /**
     * @var string
     *
     * @ORM\Column(name="prizepool", type="string", length=32, nullable=false)
     */
    private $prizepool;

    /**
     * @var string
     *
     * @ORM\Column(name="location", type="string", length=128, nullable=false)
     */
    private $location;

    /**
     * @var string
     *
     * @ORM\Column(name="country", type="string", length=32, nullable=false)
     */
    private $country;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="start_date", type="date", nullable=false)
     */
    private $startDate;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="end_date", type="date", nullable=false)
     */
    private $endDate;

    /**
     * @var string|null
     *
     * @ORM\Column(name="tournament_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
     */
    private $tournamentImg = 'NULL';

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="tourn")
     */
    private $events;

    /**
     * @ORM\OneToMany(targetEntity=Comment::class, mappedBy="tourn_id")
     */
    private $comments;

    /**
     * @ORM\ManyToMany(targetEntity=Team::class, inversedBy="tournaments")
     * @ORM\JoinTable(name="playedAt", joinColumns={@ORM\JoinColumn(name="tourn_id", referencedColumnName="id_tournament")},
     * inverseJoinColumns={@ORM\JoinColumn(name="team_id", referencedColumnName="ID_Team")})
     */
    private $teams;

    /**
     * @return ArrayCollection
     */
    public function getEvents(): Collection
    {
        return $this->events;
    }

    /**
     * @param ArrayCollection $events
     */
    public function setEvents(Collection $events): void
    {
        $this->events = $events;
    }

    public function __construct()
    {
        $this->teams    = new ArrayCollection();
        $this->events   = new ArrayCollection();
        $this->comments = new ArrayCollection();
    }

    public function getIdTournament(): ?int
    {
        return $this->idTournament;
    }

    public function addTeam(Team $team): self
    {
        if (!$this->teams->contains($team)) {
            $this->teams[] = $team;
        }

        return $this;
    }

    public function removeTeam(Team $team): self
    {
        if ($this->teams->contains($team)) {
            $this->teams->removeElement($team);
        }

        return $this;
    }
}

团队实体类

<?php

namespace App\Entity;

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

/**
 * Team.
 *
 * @ORM\Table(name="team")
 * @ORM\Entity(repositoryClass="App\Repository\TeamRepository")
 */
class Team
{
    /**
     * @var int
     *
     * @ORM\Column(name="ID_Team", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idTeam;

    /**
     * @var string
     *
     * @ORM\Column(name="Name", type="string", length=128, nullable=false)
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="Region", type="text", length=65535, nullable=false)
     */
    private $region;

    /**
     * @var string
     *
     * @ORM\Column(name="Coach", type="string", length=64, nullable=false)
     */
    private $coach;

    /**
     * @var string
     *
     * @ORM\Column(name="Total_Earnings", type="string", length=64, nullable=false)
     */
    private $totalEarnings;

    /**
     * @var string|null
     *
     * @ORM\Column(name="img_Path", type="string", length=64, nullable=true, options={"default"="NULL"})
     */
    private $imgPath = 'NULL';

    /**
     * @ORM\OneToMany(targetEntity=Player::class, mappedBy="team", cascade={"persist","remove"})
     */
    private $ownedPlayers;

    /**
     * @var string|null
     *
     * @ORM\Column(name="player_Img", type="string", length=64, nullable=true, options={"default"="NULL"})
     */
    private $playerImg = 'NULL';

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Eventstandings", mappedBy="team")
     */
    private $playedEventAsoc;

    /**
     * @ORM\ManyToMany(targetEntity=Tournament::class, mappedBy="teams")
     */
    private $tournaments;

    public function getIdTeam(): ?int
    {
        return $this->idTeam;
    }

    public function __construct()
    {
        $this->tournaments     = new ArrayCollection();
        $this->playedEventAsoc = new ArrayCollection();
        $this->ownedPlayers    = new ArrayCollection();
    }

    public function getPlayedEventAsoc(): Collection
    {
        return $this->playedEventAsoc;
    }

    public function setPlayedEventAsoc(Collection $playedEventAsoc): void
    {
        $this->playedEventAsoc = $playedEventAsoc;
    }

    public function getStandings(): void
    {
        $standings = getPlayedEventAsoc().$this->getStandings();
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getRegion(): ?string
    {
        return $this->region;
    }

    public function setRegion(string $region): self
    {
        $this->region = $region;

        return $this;
    }

    public function getCoach(): ?string
    {
        return $this->coach;
    }

    public function setCoach(string $coach): self
    {
        $this->coach = $coach;

        return $this;
    }

    public function getTotalEarnings(): ?string
    {
        return $this->totalEarnings;
    }

    public function setTotalEarnings(string $totalEarnings): self
    {
        $this->totalEarnings = $totalEarnings;

        return $this;
    }

    public function getImgPath(): ?string
    {
        return $this->imgPath;
    }

    public function setImgPath(?string $imgPath): self
    {
        $this->imgPath = $imgPath;

        return $this;
    }

    public function getPlayerImg(): ?string
    {
        return $this->playerImg;
    }

    public function setPlayerImg(?string $playerImg): self
    {
        $this->playerImg = $playerImg;

        return $this;
    }

    public function addPlayer(Player $player): self
    {
        if (!$this->ownedPlayers->contains($player)) {
            $this->ownedPlayers[] = $player;
            $player->setTeam($this);
        }

        return $this;
    }

    public function removePlayer(Player $player): self
    {
        if ($this->ownedPlayers->contains($player)) {
            $this->ownedPlayers->removeElement($player);
            // set the owning side to null (unless already changed)
            if ($player->getTeam() === $this) {
                $player->setTeam(null);
            }
        }

        return $this;
    }

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

    public function addOwnedPlayer(Player $ownedPlayer): self
    {
        if (!$this->ownedPlayers->contains($ownedPlayer)) {
            $this->ownedPlayers[] = $ownedPlayer;
            $ownedPlayer->setTeam($this);
        }

        return $this;
    }

    public function removeOwnedPlayer(Player $ownedPlayer): self
    {
        if ($this->ownedPlayers->contains($ownedPlayer)) {
            $this->ownedPlayers->removeElement($ownedPlayer);
            // set the owning side to null (unless already changed)
            if ($ownedPlayer->getTeam() === $this) {
                $ownedPlayer->setTeam(null);
            }
        }

        return $this;
    }

    public function addEvents(Eventstandings $event): self
    {
        if (!$this->playedEventAsoc->contains($event)) {
            $this->playedEventAsoc[] = $event;
            $event->setTeam($this);
        }

        return $this;
    }

    public function removeEvents(Eventstandings $event): self
    {
        if ($this->playedEventAsoc->contains($event)) {
            $this->playedEventAsoc->removeElement($event);
            // set the owning side to null (unless already changed)
            if ($event->getTeam() === $this) {
                $event->setTeam(null);
            }
        }

        return $this;
    }

    public function addEvent(Eventstandings $event): self
    {
        if (!$this->playedEventAsoc->contains($event)) {
            $this->playedEventAsoc[] = $event;
            $event->setTeam($this);
        }

        return $this;
    }

    public function removeEvent(Eventstandings $event): self
    {
        if ($this->playedEventAsoc->contains($event)) {
            $this->playedEventAsoc->removeElement($event);
            // set the owning side to null (unless already changed)
            if ($event->getTeam() === $this) {
                $event->setTeam(null);
            }
        }

        return $this;
    }

    public function getEventData(PersistentCollection $playedEvents): array
    {
        $eventdata = $playedEvents->getValues();

        return $eventdata;
    }

    public function addPlayedEventAsoc(Eventstandings $playedEventAsoc): self
    {
        if (!$this->playedEventAsoc->contains($playedEventAsoc)) {
            $this->playedEventAsoc[] = $playedEventAsoc;
            $playedEventAsoc->setTeam($this);
        }

        return $this;
    }

    public function removePlayedEventAsoc(Eventstandings $playedEventAsoc): self
    {
        if ($this->playedEventAsoc->contains($playedEventAsoc)) {
            $this->playedEventAsoc->removeElement($playedEventAsoc);
            // set the owning side to null (unless already changed)
            if ($playedEventAsoc->getTeam() === $this) {
                $playedEventAsoc->setTeam(null);
            }
        }

        return $this;
    }

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

    public function addTournament(Tournament $tournament): self
    {
        if (!$this->tournaments->contains($tournament)) {
            $this->tournaments[] = $tournament;
            $tournament->addTeam($this);
        }

        return $this;
    }

    public function removeTournament(Tournament $tournament): self
    {
        if ($this->tournaments->contains($tournament)) {
            $this->tournaments->removeElement($tournament);
            $tournament->removeTeam($this);
        }

        return $this;
    }
}

我可以通过表格编辑锦标赛或团队数据并将其保存到数据库中。我无法将数据添加到此关系中。

为此的表单类

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('team', EntityType::class, array(
        'class'    => Team::class,
        'multiple' => true,
        'expanded' => true,
    ))
        ->add('Add Team', SubmitType::class);
}

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

锦标赛控制器方法 addTeam - 应该将团队实体添加到锦标赛团队集合中

/**
 * @param Team $team
 * @param Request $request
 * @Route("/addTeamToEvent/{idTournament}",name="addTeamToEvent")
 * @return RedirectResponse|\Symfony\Component\HttpFoundation\Response
 */
public function addTeam(Tournament $tournament, Request $request)
{
    $form = $this->createForm(TeamToEvent::class, $tournament);

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $this->entityManager->persist($tournament);
        $this->entityManager->flush();

        return new RedirectResponse($this->router->generate('welcome'));
    }

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

正确的方法应该是什么?我完全迷失了,我不知道该怎么做。

标签: phpsymfonydoctrine-ormdoctrinetwig

解决方案


推荐阅读