简体   繁体   中英

How to use an array as choices for “choice” in form builder symfony2

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!

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'
    ]
);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM