Dropdown select list in CakePHP

2020-02-09 04:16发布

Does anybody know how to select the contents of one take from a different view in CakePHP?

I have a take itemgroups that has 2 fields ID and Description. I need to make a down down list in the item add page but I can not find a good way to get all of the values from another table into an array to put into the page.

Below I have also listed my models for each.

<?php

class Item extends AppModel
{
    var $name = 'Item';
    var $belongsTo = 'Itemgroup';
}

?>


class Itemgroup extends AppModel
{
    var $name = 'Itemgroup';
    var $hasOne = array('Item');
    var $validate = array(
        'description' => array(
            'rule' => 'notEmpty'
        ),
        'description' => array(
            'rule' => 'notEmpty'
        )
    );
}

?>

标签: cakephp
10条回答
家丑人穷心不美
2楼-- · 2020-02-09 05:11
<?php 
    $arrCategory=array(1=>"Car",2=>"Boat",3=>"Bike");
    echo $form->input('inputname', array('options'=>$arrCategory, 'label'=>false,
                                  'empty'=>'Category','selected'=>'Your Value')); 
?>
查看更多
Bombasti
3楼-- · 2020-02-09 05:11

You can use like this in your controller and view...

//In Controller:
    $data=$this->Model->find('list',array('conditions'=>array()));
    $this->set('data',$data);

//In View:

    echo $this->Form->select('field_name',$data,null,array("escape"=>false,"empty"=>"select"));

If you want to show initially select value in dropdown then you can pass value where use null in above line.

查看更多
唯我独甜
4楼-- · 2020-02-09 05:12

This is the right solution in my opinion: of choices from column SET or ENUM type

* 
* @param string $sColumn - col name
* @param string $sTable - if use other table as Model
* @return array 
*/
function fGetArrayFromSQLSet($sColumn, $sTable=null) {

    # Pokud neni urcena tabulka, pouzij tabulku modelu
    if( !$sTable ) {
        $sTable= $this->useTable;
    }

    # Nacti nastaveni daneho pole dane tabulky
    $tmpHlaseno=$this->query("SELECT COLUMN_TYPE
                    FROM information_schema.columns
                    WHERE TABLE_NAME = '$sTable'
                        AND COLUMN_NAME = '$sColumn'
        "); //db($tmpHlaseno);
    $tmpList= $tmpHlaseno[0]['columns']['COLUMN_TYPE']; 

    # Ziskej hodnoty z nastaveni a uloz je do pole
    $sTmp= str_replace(')', '', str_replace('set(', '', str_replace('enum(', '', $tmpList)));
    $aTmp= explode(',', str_replace("'", '', $sTmp));
    foreach( $aTmp as $value ) {
        $aSetList[$value]= $value;
    }   //db($aSetList);

    return $aSetList;   
}       // END of fGetArrayFromSQLSet 
查看更多
甜甜的少女心
5楼-- · 2020-02-09 05:16

please use

    //In controller
    $data=$this->Model->find('list');
    $this->set('data',$data);

In View :

    $this->Form->input('list',array("options"=>$data));
查看更多
登录 后发表回答