Привет, парень, я внедрил приложение, которое управляет конными соревнованиями. Я борюсь со строителем запросов. Когда пользователь вошел в систему и получил роль гонщика, он может зарегистрироваться на событие (в конкурсе, в котором много событий за день). Он уже зарегистрировал своих лошадей. Поэтому мой конструктор запросов хочет выбрать только одну из лошадей, которую зарегистрировал пользователь. На мой взгляд, все идет хорошо, я получил всех лошадей пользователя в моем списке выбора, но когда я отправляю свою форму, я получаю эту ошибку: ожидаемый аргумент типа "строка", "объект", заданный в пути свойства "имя". Я не могу избавиться от этого. Я не знаю, как построить форму запроса, чтобы в моем пути «имя» он брал объект, а не строку ... Не могли бы вы мне помочь, пожалуйста? Вот моя форма построителя запросов:
class SelectHorseFormType extends AbstractType
{
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', EntityType::class, [
'class' => Horse::class,
'choice_label' => function (Horse $horse) {
dump($horse->getName());
return $horse->getName();
},
'attr' => [
'class' => 'form-control'
],
'query_builder' => function (HorseRepository $repo) {
return $repo->createQueryBuilder('h')
->andWhere('h.user = :val')
->setParameter('val', $this->security->getUser()->getId());
}
])
->add('select', SubmitType::class, [
'attr' => [
'class' => 'main-button'
]
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// 'data_class' => Horse::class,
]);
}
}
Вот мои сущности: класс Horse
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
/**
* @ORM\Entity(repositoryClass="App\Repository\HorseRepository")
*/
class Horse
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $name;
/**
* @ORM\Column(type="string", length=40)
*/
private $gender;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Horserider", mappedBy="horse", orphanRemoval=true)
*/
private $horseriders;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="horses")
* @JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
public function __construct()
{
$this->horseriders = new ArrayCollection();
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getGender(): ?string
{
return $this->gender;
}
public function setGender(string $gender): self
{
$this->gender = $gender;
return $this;
}
/**
* @return Collection|Horserider[]
*/
public function getHorseriders(): Collection
{
return $this->horseriders;
}
public function addHorserider(Horserider $horserider): self
{
if (!$this->horseriders->contains($horserider)) {
$this->horseriders[] = $horserider;
$horserider->setHorse($this);
}
return $this;
}
public function removeHorserider(Horserider $horserider): self
{
if ($this->horseriders->contains($horserider)) {
$this->horseriders->removeElement($horserider);
// set the owning side to null (unless already changed)
if ($horserider->getHorse() === $this) {
$horserider->setHorse(null);
}
}
return $this;
}
public function _toString() {
return (string) $this->getName();
}
}
класс User
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
class User implements UserInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\Column(type="string", length=60)
*/
private $first_name;
/**
* @ORM\Column(type="string", length=60)
*/
private $last_name;
/**
* @ORM\Column(type="string", length=16)
*/
private $licence_number;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Contest", mappedBy="user", orphanRemoval=true)
*/
private $contests;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Horserider", mappedBy="user", orphanRemoval=true)
*/
private $horseriders;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Horse", mappedBy="user")
*/
private $horses;
public function __construct()
{
$this->contests = new ArrayCollection();
$this->horseriders = new ArrayCollection();
$this->horses = new ArrayCollection();
}
/**
* @return Collection|Horse[]
*/
public function getHorses(): Collection
{
return $this->horses;
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
$roles[] = 'ROLE_RIDER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstName(): ?string
{
return $this->first_name;
}
public function setFirstName(string $first_name): self
{
$this->first_name = $first_name;
return $this;
}
public function getLastName(): ?string
{
return $this->last_name;
}
public function setLastName(string $last_name): self
{
$this->last_name = $last_name;
return $this;
}
public function getLicenceNumber(): ?string
{
return $this->licence_number;
}
public function setLicenceNumber(string $licence_number): self
{
$this->licence_number = $licence_number;
return $this;
}
/**
* @return Collection|Contest[]
*/
public function getContests(): Collection
{
return $this->contests;
}
public function addContest(Contest $contest): self
{
if (!$this->contests->contains($contest)) {
$this->contests[] = $contest;
$contest->setUser($this);
}
return $this;
}
public function removeContest(Contest $contest): self
{
if ($this->contests->contains($contest)) {
$this->contests->removeElement($contest);
// set the owning side to null (unless already changed)
if ($contest->getUser() === $this) {
$contest->setUser(null);
}
}
return $this;
}
/**
* @return Collection|Horserider[]
*/
public function getHorseriders(): Collection
{
return $this->horseriders;
}
public function addHorserider(Horserider $horserider): self
{
if (!$this->horseriders->contains($horserider)) {
$this->horseriders[] = $horserider;
$horserider->setUser($this);
}
return $this;
}
public function removeHorserider(Horserider $horserider): self
{
if ($this->horseriders->contains($horserider)) {
$this->horseriders->removeElement($horserider);
// set the owning side to null (unless already changed)
if ($horserider->getUser() === $this) {
$horserider->setUser(null);
}
}
return $this;
}
public function addHorse(Horse $horse): self
{
if (!$this->horses->contains($horse)) {
$this->horses[] = $horse;
$horse->setUser($this);
}
return $this;
}
public function removeHorse(Horse $horse): self
{
if ($this->horses->contains($horse)) {
$this->horses->removeElement($horse);
// set the owning side to null (unless already changed)
if ($horse->getUser() === $this) {
$horse->setUser(null);
}
}
return $this;
}
}
класс Horserider
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\HorseriderRepository")
*/
class Horserider
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $start_number;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Event", inversedBy="horseriders")
* @ORM\JoinColumn(nullable=false)
*/
private $event;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="horseriders")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Horse", inversedBy="horseriders")
* @ORM\JoinColumn(nullable=false)
*/
private $horse;
public function getId(): ?int
{
return $this->id;
}
public function getStartNumber(): ?int
{
return $this->start_number;
}
public function setStartNumber(int $start_number): self
{
$this->start_number = $start_number;
return $this;
}
public function getEvent(): ?Event
{
return $this->event;
}
public function setEvent(?Event $event): self
{
$this->event = $event;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function getHorse(): ?Horse
{
return $this->horse;
}
public function setHorse(?Horse $horse): self
{
$this->horse = $horse;
return $this;
}
}
Вот мой контроллер:
/**
* @Route("/horse/rider/event{id}", name="horse_rider")
* @throws \Exception
*/
public function index(EventRepository $eventRepository, $id, Request $request, Horse $horse, Horserider $horserider, HorseRepository $horseRepository)
{
$horserider = new Horserider();
$form = $this->createForm(SelectHorseFormType::class, $horse);
$form->handleRequest($request);
$user = $this->getUser();
$horses = $user->getHorses();
$event = $eventRepository->find($id);
$horsesUser = $this->getDoctrine()->getRepository(User::class)->findOneByIdJoinedToHorse($id);
dump($horsesUser);
// $horse = $horseRepository->findOneBy($horsesUser[$horses]);
// dump($horse);
$random = random_int(1, 25);
if ($form->isSubmitted() && $form->isValid()) {
$horseName = $form['name']->getData();
dump($horseName);
$horse = $this->getDoctrine()->getRepository(Horse::class)->find($id);
$horserider->setEvent($event);
$horserider->setUser($user);
$horserider->setHorse($horseName);
$horserider->setStartNumber($random);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('event/show.html.twig', ['id' => $event->getId()]);
}
return $this->render('horse_rider/index.html.twig', [
'horseForm' => $form->createView(),
'user' => $user,
'event' => $event,
'horses' => $horses,
]);
}