Reputation: 13
Hi I am so new in symfony2. And I'm having a hard time figuring out what to do with my select box. I need to use an array of "positions" from my database and use it as choices for my select box. Since this project is nearly due, I'd really appreciate any help from you guys.
Atm I have the following codes for my form setup:
$role = $query1->getResult(Query::HYDRATE_ARRAY);
$roles = array();
for($i = 0; $i <count($roles); $i++){
$roles[] = $role[$i]['disrole'];
}
$form = $this->createFormBuilder($position)
->add('position', 'choice', array('choices' => $roles))
->add('save', 'submit', array('label' => 'Search'))->setMethod('POST')
->getForm();
And here's how I use it in my twig template:
<div class="panel-body">
{{ form(form) }}
</div>
I simply output my form like that cause I'm not very familiar with splicing up the form parts. I'd really really appreciate your answers guys! Thank you in advance!
Upvotes: 1
Views: 1478
Reputation: 261
Instead of a choice field you could use an entity field, which is a choice field designed to load its options from Doctrine :
$form->add(
'position',
'entity',
[
'class' => 'YourBundle:Role',
'query_builder' => function (RoleRepository $repository) {
$queryBuilder = $repository->createQueryBuilder('role');
// create your query here, or get it from your repository
return $queryBuilder;
},
'choice_label' => 'disrole'
]
);
Upvotes: 2
Reputation: 2633
To use choices in a form I'd use the following possibility:
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('stuff', 'choice', ['choices' => $this->getChoices()]);
}
private function getChoices()
{
$contents = $this->someRepoInjectedInForm->findChoices();
$result = [];
foreach ($contents as $content) {
$result[$content->getId()] = $content->getLabel();
}
return $result;
}
Your choice label will be the array value, and the value which is send to your backend via form will be the key of the corresponding key-value-pair in your array.
Upvotes: 0