Closed
Description
Symfony version(s) affected: 5.0.*
Description
Error when handling request using symfony/form : Typed property Car::$brandName must not be accessed before initialization.
How to reproduce
1 - create a class with typed property :
Class Car
{
/**
* @var string
*/
private string $brandName;
public function getBrandName(): string
{
return $this->brandName;
}
public function setBrandName(string $brandName): self
{
$this->brandName = $brandName;
return $this;
}
}
2 - Create a form type for your class.
Class CarType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('brandName')
;
}
/**
* {@inheritDoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Car::class,
]);
}
}
3 - Handle your request
Class CarController extends AbstractController
{
public function postCar(Request $request, FormFactoryInterface $formFactory): Response
{
$form = $formFactory->create(CarType::class);
$form->handleRequest($request); // this will throw the error
}
}
Possible Solution
Check if the property is initialized before accessing.
Additional context
After consulting trace, the error origin is here : https://github.com/symfony/property-access/blob/18617a8c26b97a262f816c78765eb3cd91630e19/PropertyAccessor.php#L382