我正在尝试使用 doctrine 在数据库中保存一个简单的表单。我创建的实体(让我们命名它Brand
)php bin/console make:entity
具有布尔属性:
#[ORM\Entity(repositoryClass: BrandRepository::class)]
class Brand
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column]
private ?bool $is_enabled = null;
public function getId(): ?int
{
return $this->id;
}
public function isEnabled(): ?bool
{
return $this->is_enabled;
}
public function setEnabled(bool $is_enabled): static
{
$this->is_enabled = $is_enabled;
return $this;
}
}
此实体完全自动生成,我没有做任何更改。我还使用php bin/console make:crud
命令创建了一个表单类型。生成的表单类型名称BrandType
如下所示:
class BrandType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('is_enabled', CheckboxType::class, [
'required' => false,
// I tried these 2 options, but didn't help:
// 'empty_data' => false,
// 'false_values' => [false],
'value' => true
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Brand::class,
]);
}
}
正如您在下面看到的,表单处理程序非常简单:
#[Route('/brand')]
class BrandController extends AbstractController
{
#[Route('/new', methods: ['GET', 'POST'])]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$brand = new Brand();
$form = $this->createForm(BrandType::class, $brand);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entityManager->persist($brand);
$entityManager->flush();
return $this->redirectToRoute('blah', [], Response::HTTP_SEE_OTHER);
}
return $this->render('brand/new.html.twig', [
'brand' => $brand,
'form' => $form,
]);
}
}
但是当我提交表单时,出现此错误:
类“App\Entity\Catalog\Brand”中的方法“isEnabled”需要 0 个参数,但只应接受 1 个。
异常突出显示了$form->handleRequest($request);
控制器中的行。我使用的是PHP 8.3.6和Symfony 6.4.10,我使用的 doctrine 包如下所示:
"doctrine/dbal": "^3",
"doctrine/doctrine-bundle": "^2.12",
"doctrine/doctrine-migrations-bundle": "^3.3",
"doctrine/orm": "^3.2",