I'm trying to save a simple form in database using doctrine. The entity I've created - lets name it Brand
- using php bin/console make:entity
has a boolean property:
#[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;
}
}
This entity is completely auto-generated and I changed nothing. I also have created a form-type using php bin/console make:crud
command. The generated form-type named BrandType
is shown below:
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,
]);
}
}
As you can see below, the form handler is so simple:
#[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,
]);
}
}
But when I submit the form, I get this error:
The method "isEnabled" in class "App\Entity\Catalog\Brand" requires 0 arguments, but should accept only 1..
And the exception highlights the $form->handleRequest($request);
line in controller. I'm using PHP 8.3.6 with Symfony 6.4.10 and the doctrine packages I'm using are listed below:
"doctrine/dbal": "^3",
"doctrine/doctrine-bundle": "^2.12",
"doctrine/doctrine-migrations-bundle": "^3.3",
"doctrine/orm": "^3.2",
Logically the property of the class Brand
should be named enabled
, with a setter setEnabled
and a getter isEnabled
.
To solve the error, rename the property to enabled
or alternatively rename the getter to getIsEnabled
.
See also this discussion.