lasar71
lasar71

Reputation: 21

Get option values of multiple selected from form

I make the form using this code:

$builder
    ->add('person','entity',array(
        'class'=>'MyBundle:Person',
        'multiple' => true,
        'empty_value' => 'None',
        'required'=>false,
        'mapped'=>false));

And as a result I get this html:

<select id="mybundle_person_person" multiple="multiple" name="mybundle_person[person][]">
        <option value="1">Surname1</option>
        <option value="5">Surname2</option>
        <option value="6">Surname3</option>
        <option value="11">Surname4</option>
        <option value="19">Surname5</option>
</select>

Here, the value "option value" (1,5,6,11,19) corresponds to the data fields "Id" from the table (from the entity) "Person".

Yet it's OK.

When processing the form in Controller I want to get these option'svalues of selected items. For example, were selected items "Surname2", "Surname3", "Surname5" and I want to get values "2", "6", "19". My question is how to do it?

If I use this code

if ($form->isValid()) {
    $per = $form->get('person')->getData();

    $logger=$this->get('logger');

    foreach($per as $key => $value){
        $logger->info('person: key='.$key.' value='.$value);
    }

in variable $key gets the number of the order 0,1,2,... (array indexes). But this is not what I need.

Upvotes: 1

Views: 3981

Answers (2)

debugall
debugall

Reputation: 310

By this line $per = $form->get('person')->getData(); you retrieve a list of persons object and not an indexed array

So inside your loop just do $logger->info('person: key='.$value->getId().' value='.$value);

Upvotes: 0

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

If you have created a form by using entity and person field is a mapped property of YourEntity like

$form = $this->createFormBuilder(new YourEntity());

Then you can simply call the getter of your property like

if ($form->isValid()) {
    $persons=$form->getData()->getPerson();
    echo '<pre>';print_r($persons);echo '</pre>';
}

If your form is not mapped through entity then you can get all the from request like

if ($form->isValid()) {
    $requestAll = $this->getRequest()->request->all();
    $persons = $requestAll['mybundle_person']['person'];
    echo '<pre>';print_r($persons);echo '</pre>';
}

Upvotes: 1

Related Questions