简体   繁体   中英

CakePHP : How to Create OptGroup Drop down list from DataBase?

i am new to CakePHP, and developing a new project. i just want to know that, how to show optgroup dropdown list that is fetched from database.

i want to fetch array like this below

$arr = array(
    'optgroup' => array(
        '1','2','3'),
     'optgroup2' => array(
         '1','2','3')
);     

I'm assuming you already have your model set up.

In your controller you will need to assign variables to the results of find(list) calls and then set() them. Here's an example from a project where I have dropdowns for requests, currencies, etc.:

    $requests = $this->Purchase->Request->find('list');
    $currencies = $this->Purchase->Currency->find('list', $options);
    $shippingCurrencies = $this->Purchase->ShippingCurrency->find('list', $options);
    $finalCurrencies = $this->Purchase->FinalCurrency->find('list', $options);
    $receivers = $this->Purchase->ReceiverUser->find('list');
    $this->set(compact('requests', 'currencies', 'shippingCurrencies', 'finalCurrencies', 'receivers'));

(You can also do that with a series of $this->set(...) calls rather than using variables and the $this->set(compact(...)) .)

Then in your view you use the Form->input() call to make the select statement. Here's another example:

    $empty_currency = array('empty'=>'(choose a currency)');
    ...
    echo "<table class=\"all order\"><tr><td>\n";
    echo $this->Form->input('tax_currency_id', $empty_currency);
    echo "</td></tr></table>\n";
    echo "<table><tr><td colspan='2' class='all order receive'>\n";
    echo $this->Form->input('shipping_comment');
    echo "</td></tr><tr class='all order costing'><td>\n";
    echo $this->Form->input('shipping_cost');
    echo "</td><td>\n";
    echo $this->Form->input('shipping_currency_id', $empty_currency);
    echo "</td></tr></table>\n";

Sometimes if you haven't followed naming conventions perfectly then you will have to specify array(...'type'=>'select') in your input call. Here's an example:

    echo $this->Form->input('budget_year_dflt', array('type'=>'select', 'options'=>$budgetYears, 'label'=>'Default Budget Year'));

If you're new to cakephp, do yourself a favor and THOROUGHLY read and understand the naming conventions before you do your table design and well before you start developing. Life is so easy if you follow their conventions and so hard if you don't...

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