I can’t figure out how to embed a form form a template twig partials in FormType when I want to add another FormType under some condition.
I’am trying to embed a form in symfony 6.
In entity UserSession I have a ManyToOne property
` #[ORMManyToOne(inversedBy: 'userSessions')]
private ?Employer $employer = null;`
in FormType I need to add a FormType field under a condition
`
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
if ($data && $data->getFunding()) {
$form->add('employer', EmployerType::class);
}
});`
Then I use a js ajax that fetch a controller method
const bodyContainer = document.body; // Use a common ancestor that is always present
if (user_register_session_admin_funding) {
bodyContainer.addEventListener("change", function (event) {
const target = event.target;
if (target && target.id === "user_register_session_admin_funding") {
const fundingId = target.value;
showEmployerForm(user_register_session_admin_funding, fundingId);
}
});
}
function showEmployerForm(element, fundingId) {
fetch("/get_funding_details", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Requested-With": "XMLHttpRequest",
},
body: JSON.stringify({ fundingId: fundingId }),
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok " + response.statusText);
}
return response.json();
})
.then((data) => {
const employerFormContainer = document.getElementById("employer-form");
employerFormContainer.innerHTML = data.form;
})
.catch((error) =>
console.error("There was a problem with the fetch operation:", error)
);
}
So what i want is to include the EmloyerType form from a partial twig
#[Route('/get_funding_details', name: 'admin_funding_details')]
public function fetchBForm(
Request $request,
FormFactoryInterface $formFactory,
FundingRepository $fundingRepo): JsonResponse
{
$data = json_decode($request->getContent(), true);
$fundingId = $data['fundingId'] ?? null;
$funding = $fundingRepo->findOneBy(['id' => $fundingId]);
if ($funding) {
$form = $formFactory->create(UserRegisterSessionAdminType::class);
$formHtml = $this->renderView('shared/_employer_form.html.twig', [
'form' => $form->createView(),
]);
return new JsonResponse(['form' => true]);
}
return new JsonResponse(['bFormHtml' => '']);
}
and here the twig partial
{{ form_row(form.employer.firstName) }}
{{ form_row(form.employer.lastName) }}
that gives the following error 500
<!-- Neither the property "employer" nor one of the methods "employer()", "getemployer()"/"isemployer()"/"hasemployer()" or "__call()" exist and have public access in class "SymfonyComponentFormFormView". (500 Internal Server Error) -->
I am aware that my mogic is wrong but I can’t see where. If someone could help me point where
I I follow the doc https://symfony.com/doc/current/form/embedded.htmland and I add my EmployerType without any condition it’s working perfectly.
Thank you for your help 🙂