How to access submitted data inside FormType
class in Symfony 4/5?
Assuming that form is not mapped with any Entity and its submit back to same controller / action.
// src\Form\SomeFormType.php -----------------------------------------------------
...
public function buildForm(FormBuilderInterface $builder, array $options)
{
/**
* How to get submited data with in FormType class
*/
$userChoiceSubmitedData = // ... <<<<<<<<<<<<<<<<<<
/**
* I want to get those value on form submit
* (form submites to self and is not redirecting)
*/
$builder
->add('userChoice', ChoiceType::class, [
'placeholder' => 'Select value',
'choices'=> [
'ONE' => 1,
'TWO' => 2,
],
])
->add('send', SubmitType::class);
;
/** On form submit one of those fields should be added to the form */
if ($getUserChoiceSubmitedData === 1) {
/* add another field*/
$builder
->add('userSelectedNum1', IntegerType::class)
;
}
if ($getUserChoiceSubmitedData === 2) {
/* add another field*/
$builder
->add('userSelectedNum2', IntegerType::class)
;
}
}
...
And in controller it would look something like that:
// src\Controller\SomeController.php ---------------------------------------
...
/**
* @Route("/", name="index")
*/
public function index(MailerInterface $mailer, Request $request)
{
$form = $this->createForm(CCPayFormType::class);
$form->handleRequest($request);
...
if($form->isSubmitted() && $form->isValid()){
$userChoice = $form->getData();
$userChoice = $form->get('userChoice')->getData(); // shows 1 or 2
if(isset($cardType)){
// $form->passToFormType(['userChoiceSubmitedData'=>$userChoice]) // fake code!
}
...
...
return $this->render('index/index.html.twig', [
'form' => $form->createView()
]);
}