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();
Related
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 have a problem when I would to set a default value in a select (selected="selected") in a form generated with Symfony 2 (2.8.9).
I have this code in my controller:
$news = new News();
$news->setCategory(1);
//create form
$form = $this->createForm(NewsType::class, $news);
And this in my FormType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('category', EntityType::class,
array(
'placeholder' => 'Choise',
'class' => 'AppBundle:NewsCat',
'choice_label' => 'name'
));
}
AppBundle:NewsCat create a list of id => name (ex: 1 => 'Sport', 2 => 'Politic', etc), and I want that when I setCategory(1) it should be seen "Sport" as selected="selected" in my select.
Now i see ever "Choise".
I have tried to search everywhere on the web, I hope you can help me :)
Thanks to all
HTML code screen
You need to use data option to set selected object. My example below.
$defaultTech = $company->getDefaultTech();
if ($company->getForceDefaultTech() && $defaultTech != null) {
$builder->add('tech', HiddenType::class, ['data' => $defaultTech->getId()]);
} else {
$builder->add('tech', EntityType::class, [
'class' => 'HelpBundle\Entity\UserAccount',
'choice_label' => 'displayName',
'data' => $defaultTech,
'query_builder' => function (EntityRepository $er) use ($company) {
$qb = $er->createQueryBuilder('ua');
return $qb
->where('ua.company = :company')
->andWhere('ua.techie = 1')
->setParameter('company', $company);
},
]);
}
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.
I'm using Silex FormBuilder in my application. The structure of a builder is like this:
$form = $app['form.factory']->createBuilder('form')
->add('name', 'text', array(
'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5)))
))
->add('email', 'text', array(
'constraints' => new Assert\Email()
))
->add('gender', 'choice', array(
'choices' => array(1 => 'male', 2 => 'female'),
'expanded' => true,
'constraints' => new Assert\Choice(array(1, 2)),
))
->getForm();
Let's say I would build such builder from blocks, which would be stored in a database as a whole. Always, in any form I would create I know, that e-mail field will always be defined the same. So I would get definitions from database and foreach them to create form.
->add('email', 'text', array(
'constraints' => new Assert\Email()))
When i get this from a database (posgresql in my case) this would be a string (because the database field is text type).My question: is there any possibility to convert this to a valid code?
I thought of something like this:
$form = $app['form.factory']->createBuilder('form')
foreach ($definitions as $definition) {
something to do with the $definition;
}
->getForm();
But instead of foreach createBuilder expects ->add... method, and this is where im stuck.
Best Regards,Kamil
/*Concidering $definitions = array("$form->add('email', 'text', array(
'constraints' => new Assert\Email()
));");
*/
$form = $app['form.factory']->createBuilder('form');
foreach($definitions as $definition){
eval($definition);
}
$form->getForm();
I would not recommend you use eval like so... You'd better store the parameters to pass to the function to make it work... You could also create a function or class to handle typical elements such as your email, so you would only need to reference the kind of input in the database, a bit like so:
function addFormElement(&$form,$type){
switch($type){
case 'email':$form->add('email', 'text', array(
'constraints' => new Assert\Email()
));
break;
}
}
/*Concidering $definitions = array("email");
*/
$form = $app['form.factory']->createBuilder('form');
foreach($definitions as $definition){
addFormElement($form,$definition);
}
$form->getForm();