我有一个用户创建页面,它使用带有用户名和电子邮件属性的用户实体表单。
我希望在创建用户时能够选择他可以访问的工具。为此,检索所有工具并将它们显示在复选框中。因此,一旦表单被验证,用户将获得用户名、电子邮件和他可以访问的工具。
在我的用户类中,我可以使用AddTool()方法从工具实体中添加一个工具。
如何将这些工具集成到用户创建表单中?我不知道该怎么做我迷路了。
类用户:
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180)
*/
private $username;
/**
* @ORM\Column(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\ManyToMany(targetEntity=Tool::class, mappedBy="users", fetch="EAGER")
*/
private $tools;
/**
* @ORM\Column(type="string", length=125, unique=true)
*/
private $email;
public function __construct()
{
$this->tools = new ArrayCollection();
}
// SOME FUNCTIONS
/**
* @return Collection|Tool[]
*/
public function getTools(): Collection
{
return $this->tools;
}
public function addTool(Tool $tool): self
{
if (!$this->tools->contains($tool)) {
$this->tools[] = $tool;
$tool->addUser($this);
}
return $this;
}
public function removeTool(Tool $tool): self
{
if ($this->tools->removeElement($tool)) {
$tool->removeUser($this);
}
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
}UserType:
<?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('username')
->add('email')
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}发布于 2022-01-17 11:12:04
在UserType buildForm函数中添加如下内容:
$builder
->add('username')
->add('email')
->add('Tools', EntityType::class, [
'class' => Tool::class,
'multiple' => true
])
;您需要在Tool::class定义中创建一个函数,该函数允许将其显示为字符串:
#[Pure] public function __toString(): string
{
return ''.$this->getFullName();
}它应该允许您在生成用户表单期间选择工具实体。
https://stackoverflow.com/questions/70739734
复制相似问题