In Symfony I have this part of my code where I am building a view with some data and a form with some radio buttons. When submitting the form I am doing a dump in the view to check which data has been submitted, but the data does not match with the one the form was build. Can someone help? Thanks.
public function playAction(Request $request){
$data = $this->getDbQuestion();
$questionData = $data[0];
dump($questionData);
$answerData = $data[1];
dump($answerData);
$form = $this->createFormBuilder($answerData)
->add('answers', ChoiceType::class,
array(
'choices'=> $answerData,
'multiple'=>false,'expanded'=>true,
'choice_label' => 'answer',
))
->add('Submit',SubmitType::class, array('label' => 'Send Answer'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted()) {
$formData = $form->getData();
return $this->render('QuizViews/correctAnswer.html.twig', array(
'ss' => $formData
));
}
return $this->render('QuizViews/playQuiz.html.twig', array(
'form' => $form->createView(),
'question' => $questionData
));
}
Twig
<a href="/quiz/question">
<input type="button" value="Start Quiz" />
</a>
<br>
FormData Correct {{ dump(ss) }}
After chatting, this might be a better solution for the answer section:
->add('answers', EntityType::class, array(
'class' => 'AppBundle:Answer',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('a')
->where('a.question_id->getId() = :qID')
->setParameter('qID', 1);
},
'multiple'=>false,
'expanded'=>true,
'choice_label' => 'answer',
))
Try it!
Your call to get the data after verifying the form isSubmitted is incorrect. You need to call like so:
$formData = $form->get('answers')->getData();
That just gets the 'answers' only.
Edit #2
You might also want to change this:
->add('answers', ChoiceType::class,
array(
'choices'=> $answerData,
'multiple'=>false,
'expanded'=>true,
'choice_label' => 'answer',
'choice_value' => $answerData,
))
Which sets the 'choice_value', what is actually selected and returned from the getData().
Can you post your twig answers file please? Edit your post and so I can see.
Related
I create 2 forms not linked to any entity in the same controller.
Each form have it owns submitted button.
I never goes to the submitted function of the second form.
I think it is because the 2 forms have same default name 'form'.
The problem is how to change the form name?
Below what I did
public function index(Request $request)
{
$form1 = $this->createFormBuilder()
->add('sn', TextType::class, [
'required' => false,
])
->add('search', SubmitType::class, ['label' => 'Search'])
->getform();
$form1->handleRequest($request);
if ($form1->isSubmitted() && $form1->isValid()) {
//Do something
}
$form2 = $this->createFormBuilder();
$form2->add('Agree', CheckboxType::class, [
'label' => 'Agree',
'required' => false,
]);
$form2->add('detail', SubmitType::class, ['label' => 'Detail']);
$form2 = $form2->getForm();
$form2->handleRequest($request);
if ($form2->isSubmitted() && $form2->isValid()) {
//Do something else
}
return $this->render('search/index.html.twig', [
'form1' => $form1->createView(),
'form2' => $form2->createView(),
]);
}
If you want to modify the form name, use the createNamed() method:
$form1 = $this
->get('form.factory')
->createNamed('my_name', TextType::class, $task);
You can even suppress the name completely by setting it to an empty string.
i need some help.
I have a Form where i would like to either choose an existing Entity or submit a new one. So i have a Class Dolmetscher (Interpreter for languages) with title, name, surname and language. To create the Form i have a Class InterpreterType with the function
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('anrede', ChoiceType::class, array(
'choices' => array(
'Herr' => 'Herr',
'Frau' => 'Frau'
)
))
->add('vorname')
->add('nachname')
->add('sprache')
->add('dolmetscher', EntityType::class, array(
'class' => 'AppBundle:Dolmetscher',
'placeholder' => 'Dolmetscher wählen',
'label' => 'Dolmetscher',
'choice_value' => 'id',
'choice_label' => function ($dolmetscher) {
return $dolmetscher->getAnrede() . ' ' .
$dolmetscher->getVorname() . ' ' .
$dolmetscher->getNachname();
},
'mapped' => false,
))
->add('select', SubmitType::class, array(
'label' => 'Übernehmen',
'attr' => array(
'class' => 'btn btn-default',
'formnovalidate' => 'formnovalidate'
)
))
->add('save', SubmitType::class, array(
'label' => 'OK',
'attr' => array(
'style' => 'float: right',
'class' => 'btn btn-default'
)
))
->add('reset', SubmitType::class, array(
'label' => 'Zurücksetzen',
'attr' => array(
'style' => 'float: right; margin-right: 10px',
'class' => 'btn btn-warning',
'formnovalidate' => 'formnovalidate'
)
));
}
So i have a selection with Entities, which is working, with a 'select' Button and Form fields for a new Dolmetscher with a 'save' Button. Also a 'reset' Button
My Controller Class looks like
/**
* #Route("/u01/5", name="u1_5")
*/
public function dolmetscherAction(Request $request) {
$session = $this->get("session");
var_dump($session->get("foo"));
if (!$session->get("dolmetscher")) {
$dolmetscher = new Dolmetscher();
} else {
$dolmetscher = $session->get("dolmetscher");
}
$dolmetscherForm = $this->createForm(DolmetscherType::class, $dolmetscher);
$dolmetscherForm->handleRequest($request);
if ($dolmetscherForm->get('select')->isClicked()) {
$dolmetscher = $dolmetscherForm->get('dolmetscher');
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('u1_5');
}
if ($dolmetscherForm->get('reset')->isClicked()) {
$dolmetscher = new Dolmetscher();
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('u1_5');
}
if ($dolmetscherForm->get('save')->isClicked() && $dolmetscherForm->isSubmitted() && $dolmetscherForm->isValid()) {
$dolmetscher = $dolmetscherForm->getData();
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('homepage');
}
return $this->render('urkunden/u01/5.html.twig', [
'form' => $dolmetscherForm->createView(),
'page_title' => 'U01'
]);
}
I want to put the Dolmetscher from the selection into $_SET for later use ,e.g. persist in DB, which works fine for a new Dolmetscher but not for my selection. I get an Exception
Serialization of 'Closure' is not allowed
I'm not sure if I'm doing this right at all (I have some OneToMany Relations and wanted to have a view for each Entity/Form and persist everything at once at the end so that i don't have only a Dolmetscher in my DB when the user quits in mid process)
I also thought it might be possible to populate the Form fields from the selection which I couldn't get to work. Can someone please help me, i would appreciate it.
This part of code is probably the origin of your problems :
if ($dolmetscherForm->get('select')->isClicked()) {
$dolmetscher = $dolmetscherForm->get('dolmetscher'); <------ this one
$session->set("dolmetscher", $dolmetscher);
return $this->redirectToRoute('u1_5');
}
you are trying to serialize a form object which contains a closure. Closure can not be serialized ( visit this link for more insights Exception: Serialization of 'Closure' is not allowed )
If you dump $dolmetscher variable you will probably get a form object not the entity you want. try to replace the line :
$dolmetscher = $dolmetscherForm->get('dolmetscher');
with :
$dolmetscher = $dolmetscherForm->get('dolmetscher')->getData();
How to get field value in form builder in Symfony.
I have 2 Dropdowns in the form
I want to should the related option in Dropdown2 based on Dropdown1 in when the Page is Opening.
Here is My Form
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Event\DataEvent;
use C2Educate\ToolsBundle\Entity\Students;
public function buildForm(FormBuilder $builder, array $options) {
Field 1:
$builder->add('leadSource', 'entity', array(
'label' => 'How did you hear about C2? Source ',
'class' => 'C2EducateToolsBundle:LeadSources',
'query_builder' => function($repo) {
return $repo->createQueryBuilder('p')->orderBy('p.sort_order', 'ASC');
},
'property' => 'name',
'empty_value' => 'Select'
));
$leadSource = 1;
$leadSource = 1; - it works when I assign value statically, but I want to get the value of "leadSource" and assign it to $leadSource
I want to get the leadSource and pass it to leadSourceSub query
Field 2:
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) {
$form = $event->getForm();
$entity = $event->getData();
$leadSource = $entity->getLeadSourceID();
$form->add('leadSourceSub', 'C2Educate\ToolsBundle\Entity\Students', array(
'label' => ' Source Detail ',
'required' => true,
'class' => 'C2EducateToolsBundle:LeadSourceSubs',
'query_builder' => function($repo) use ($leadSource) {
return $repo->createQueryBuilder('p')
->where('p.lead_source_id =:leadSource')
->setParameter('leadSource', $leadSource)
->orderBy('p.sort_order', 'ASC');
},
'property' => 'name',
'empty_value' => 'Select'
));
});
You cannot get form data from $builder, because... it's a form builder, not a form. It doesn't contain any data yet.
To make this work you need to make use of FormEvents. In this case, you probably will need FormEvents::PRE_SET_DATA event listener.
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$form = $event->getForm();
// in your case it's C2EducateToolsBundle:LeadSourceSubs
$entity = $event->getData();
$leadSource = $entity->getLeadSource();
// adding this field again will override it.
$form->add('leadSourceSub', 'entity', array(
'label' => ' Source Detail ',
'required' => true,
'class' => 'C2EducateToolsBundle:LeadSourceSubs',
'query_builder' => function($repo) use ($leadSource) {
return $repo->createQueryBuilder('p')
->where('p.lead_source_id =:leadSource')
->setParameter('leadSource', $leadSource)
->orderBy('p.sort_order', 'ASC');
},
'property' => 'name',
'empty_value' => 'Select'
));
}
});
Please note that this code is not tested and may need some validation like to check if $entity is what you expect it to be in any case.
I started learn symfony 3. For the first project i chose a simple totodlist.
So now i have possibility to create and save the user in my database. Next I can create a task for them.
I want to create a checkbox where can i choose a users to perform a task.
So i need put data from my user database to checkbox form ($temp_users varbiable). I don't know how to do it.
Can anybody show me how to do it.
below is my code:
public function createAction(Request $request)
{
$todo = new Todo;
$users = $this->getDoctrine()
->getRepository('AppBundle:User')
->findAll();
$temp_users = array();
foreach($users as $user) {
$temp_users[$user->getUsername()] = $user->getId();
}
$form = $this->createFormBuilder($todo)
->add('name', TextType::class, array('attr' => array('class' => 'form- control', 'style' => 'margin-bottom:15px')))
->add('wykona', CheckboxType::class, array('label' => $temp_users, 'required' => false,))
I'm not sure what you mean by checkbox - are you wanting to select one, or many users? I'm going to assume you want to select just one for simplicity's sake (you can adapt this to your liking)
You don't need to get all the users like you're trying to do, something like this should work (untested)
$form = $this->createFormBuilder($todo)
->add('user', EntityType::class, array(
'label' => 'Name',
'class' => AppBundle\Entity\User::class,
'choice_label' => 'name', //if you have a variable 'name' in your User entity, otherwise you will need a __toString method in the User entity
));
Try this code inside your createAction.
ADD this into your code
$form = $this->createFormBuilder($todo)
->add('users', EntityType::class, array(
'class' => 'AppBundle:User',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.name', 'ASC')
},
'choice_label' => 'name',
'multiple' => true,
'expanded' => true,
));
Also you don't need the following code anymore inside createAction.
REMOVE Below code from your code
$users = $this->getDoctrine()
->getRepository('AppBundle:User')
->findAll();
$temp_users = array();
foreach($users as $user) {
$temp_users[$user->getUsername()] = $user->getId();
In Symfony I am building a form with four possible choices as radio buttons. When the user submits the form with a choice, I am taking the submitted form data (the user choice) and display it in twig. The problem is that sometimes the submitted form data is null even if the user selected a radio, and sometimes the selected choice is passed and displayed in twig. Also sometimes after reciving null in twig and refreshing the page the data is shown, but this doesn't always happen. Why this inconsistency? How can I solve this? Thanks
public function playAction(Request $request){
$data = $this->getDbQuestion();
$questionData = $data[0];
$questionID = $questionData->getId();
dump($questionData);
$answerData = $data[1];
dump($answerData);
$form = $this->createFormBuilder($answerData)
->add('answers', EntityType::class, array(
'class' => 'QuizBundle:Answer',
'query_builder' => function (EntityRepository $er) use ($questionID) {
return $er->createQueryBuilder('a')
->where('a.question = :qID')
->setParameter('qID', $questionID);
},
'multiple'=>false,
'expanded'=>true,
'error_bubbling' => true,
'choice_label' => 'answer',
))
->add('Submit',SubmitType::class, array('label' => 'Send Answer'))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$formData = $form->get('answers')->getData();
$errors = $form->getErrors();
return $this->render('QuizViews/correctAnswer.html.twig', array('ss' => $formData, 'errors' => $errors ));
}
return $this->render('QuizViews/playQuiz.html.twig', array('form' => $form->createView(),'question' => $questionData));
}
Dumping the submitted form data in twig
<a href="/quiz/question">
<input type="button" value="Start Quiz" />
</a>
<br>
FormData Correct {{ dump(ss) }}
Form Errors {{ dump(errors) }}
Adding $form->isValid()I get this in twig when the answer is not submitted.
Glad you got further.
I believe that the "$formData" is coming back as an answer object, and all you have to do in twig is call something like:
{{ ss.getAnswer }}
Where getAnswer is a method for the Entity Answer (I don't remember your code). The form data correct you show above looks exactly like a dump of an "object". Remember you need to think in terms of objects.
Let me know if that doesn't work.
Edit #2.
Try this change:
->add('answers', EntityType::class, array(
'class' => 'QuizBundle:Answer',
'query_builder' => function (EntityRepository $er) use ($questionID) {
return $er->createQueryBuilder('a')
->where('a.question = :qID')
->setParameter('qID', $questionID);
},
'multiple'=>false,
'expanded'=>true,
'choice_value' => 'answer',
'choice_label' => 'answer',
))
Where I've added 'choice_value' => 'answer', in this case 'answer' should be the answer value stored in the Answer Entity.
Edit #3.
This is weird. I'm not sure why it's not working.
You shouldn't need to pass in the $answerData into the builder. Try leaving it blank, and let's change it to a drop-down list (default):
$form = $this->createFormBuilder()
->add('answers', EntityType::class, array(
'class' => 'QuizBundle:Answer',
'label' => 'Select an Answer',
'choice_value' => 'answer',
'choice_label' => 'answer',
))
If that doesn't work, something else is definitely wrong, possibly your Entities. This returns the Entity value in the db for me.
Did you tryed to check if your form was valid?
if($form->isSubmitted() && $form->isValid()) {
Also, set and display form errors may help a lot, to check what is wrong, and which part of your form isn't correct.