I am dynamically generating forms in Symfony 6. From the controller, I am calling a Form Type class in the traditional method. Therein, I am dynamically building some form fields based on the elements of the $options
passed to the FormType
class.
<?php
public function index(Request $request): Response
{
// Entity is called Breed
$data = new Breed();
// I am passing these $options to the form
$options = [
'form_1' => true,
'form_2' => false,
'units' => 'pounds'
'form_3' => false,
];
$form = $this->createForm(BreedSurveyType::class, $data, $options);
?>
In the BreedSurveyType form class, I am able to get my variables where I declare them in the configureOptions method...
<?php
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Breed::class,
'form_1' => false,
'form_2' => false,
'units' => null
'form_3' => false,
]);
}
?>
In the buildForm method, I can access the $options, but I cannot if I embed a sub-form.
<?php
public function buildForm(FormBuilderInterface $builder,array $options): void
{
// form_1 = true
// form_2 = false
// units = 'pounds'
// form_3 = true
if ($options['form_1'] === true) {
$builder
->add(
'name',
AnimalNameType::class
);
}
if ($options['form_2'] === true) {
$builder
->add(
'sex',
AnimalSexType::class
);
}
if ($options['form_3'] === true) {
$builder
->add(
'weight',
AnimalWeightType::class
);
}
?>
.... in the parent-form, when I dump the $options variable,
array:59 [▼
// snippet from web debug toolbar
"form_1" => true
"form_2" => false
"units" => "pounds"
"form_3" => true
]
.... in the sub-form, when I dump the $options variable, I get the results from the declarations I made in the configureOptions method.
array:59 [▼
// snippet from web debug toolbar
"form_1" => false
"form_2" => false
"units" => null
"form_3" => false
]
Effectively, is there a method to pass $options
to a subform or do I need to isolate my logic of the dynamically created form in my BreedSurveyType
class?