Question

How do I get optiongroups in a dropdown select list where the optiongroups and options are in my database?

I have this in my db:

id | categorie | subcategorie
1 apples granny smith
2 apples fiji
3 bananas chiquita

and want to have a dropdown select like:

apples

  • granny smith
  • fiji

bananas

  • chiquita

In my controller I get the array of the rows from the db. I have an array $arrSelectSubcategory and $arrSelectCategory. Answers I found suggest to use a multidimensional array so I tried to pass to the form a 2 dimensional array:

->addMultiOptions($arrSelectCategory->($arrSelectSubcategory));

but this does not work. Answers I found like this one only deal with predefined option groups where I get them from my db.

Was it helpful?

Solution

Imagine that your values ​​in an array like this one:

$fruits = array('apples'=>array('id_granny_smith'=>'granny smith', 
                                'id_fiji'=>'fiji'), 
                'bananas' => array('id_chiquita'=>'chiquita')
               );

You can try something like this:

$fruits_select = new  Zend_Form_Element_Select('fruits', array('escape' => false));
foreach($fruits as $fruit => $name_fruit){
    $fruits_select->addMultiOptions(array($fruit=>array()));
    foreach($name_fruit as $key => $val){
            $fruits_select ->addMultiOption($key, $val);
    }
}

The result is:

<select name="fruits" id="fruits">
    <optgroup label="apples">
    </optgroup>
    <option value="id_granny_smith" label="granny smith">granny smith</option>
    <option value="id_fiji" label="fiji">fiji</option>
    <optgroup label="bananas">
    </optgroup>
    <option value="id_chiquita" label="chiquita">chiquita</option>
</select>


with your comment, your array is like this:

$fruits_bdd = array('0' => array('id' => 1, 'category' => 'apples', 'subcategorie'=> 'granny smith'),
                    '1' => array('id' => 2, 'category' => 'apples', 'subcategorie'=> 'fiji'),
                    '2' => array('id' => 3, 'category' => 'bananas', 'subcategorie'=> 'chiquita'),
);

So to have the array $fruits like my answer, do that:

$fruits = array();  
foreach($fruits_bdd as $fruit_bdd){
        $fruits[$fruit_bdd['category']][$fruit_bdd['id']] =$fruit_bdd['subcategorie'];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top