Search code examples
phphtml-selectcakephp-1.2

Set the default value of drop-down list with the last value chosen


I'm using cakephp 1.2, and I have a search form which has also this menu:

Classificazione&nbsp;&nbsp;<select style="margin-top: 5px;" name="classificazione">
            <option value="art0"></option>
            <option value="C">Articoli</option>
            <option value="D">Documentazione</option>
            <option value="A">Libri</option>
            <option value="G">Materiali</option>
            <option value="B">Riviste</option>
            <default value="A">
</select><br />

In the next page I want to set the default value of this menu with what the user has chosen before.

I SOLVED like this (for example, with the first option): In the controller:

$getParams['classificazione'] = isset($params['classificazione']) ? $params['classificazione'] : '';
...
$this->set('getParams', $getParams);            

In the view:

<option value="C" <?php if ($getParams['classificazione']=="C") echo "selected"; ?> >Articoli</option>

Solution

  • Save the value in a session variable and use that to echo selected for that option

    <?php
        function is_selected($selected_option, $list_option_value) {
           if($selected_option == $list_option_value) {
              return 'selected';
           }
        }
    ?>
    
    <select>
       <option <?php echo is_selected($_SESSION['selected_option'], '1'); ?>>1</option>
    </select>