Cakephp 2.61和comboboxes

时间:2015-03-02 08:35:35

标签: mysql cakephp combobox

使用Cakephp 2.6.1,我使用以下代码

成功捕获并存储了我的数据库中的单个字符
echo $this->Form->input('grade', array('options' => array( 'G' => 'Good', 'P' => 'Pass','R'=>'Practice Required','F'=>'Fail')));

我想知道的是,当从数据库中检索这些值时,如何将这些值转换回显示值,即如果数据库包含' P',我想显示' Pass& #39;在视图和索引页面中。

我确定答案简单明了,并为我的无知而羞怯地道歉。

2 个答案:

答案 0 :(得分:0)

<强>步骤1

在Vendor文件夹下创建两个新文件。

  1. master-arrays.php
  2. 共的functions.php
  3. 并导入这两个文件

    导入过程:

    目录:app \ Config \ bootstrap.php

    添加以下两行:

    App::import('Vendor', 'common-functions');
    
    App::import('Vendor', 'master-arrays');
    

    <强>步骤-2

    现在打开'master-arrays.php' 并添加此数组

    function grade_type()
    {
        $GRADE_TYPE['G']  = 'Good';
        $GRADE_TYPE['P'] = 'Pass';
        return $GRADE_TYPE;
    }
    

    <强>步骤-3

    更改您的观点 -

    echo $this->Form->input('grade', array('options' =>grade_type())));
    

    <强>步骤4

    现在在'common-functions.php'

    中添加此功能
        function id_to_text($id, $arr_master=array()) {
        $txt_selected = "";
        $id = ''.$id;      //Added this as it was creating some warnings online for wrong parameter types
        if(is_array($arr_master) && array_key_exists($id,$arr_master)) {
            $txt_selected = $arr_master[$id];
        } else {
            $txt_selected = "";
        }   
        return $txt_selected;
    }
    

    <强>步骤5

    在Controller或视图中

    <强> 输入:     id_to_text( 'P',grade_type());

    <强>输出:

答案 1 :(得分:0)

试试这个,

    // In controller
    function fun()
    {
        $grade = array(
            'G' => 'Good',
            'P' => 'Pass',
            'R' => 'Practice Required',
            'F' => 'Fail'
        );
        $this->set('grade', $grade);
        if ($this->request->data) {
            $key = $this->request->data['Model']['grade'];
            $this->request->data['Model']['grade'] = $grade[$key];
            $this->Model->save($this->request->data);
        }
    }

    // in view

    echo $this->Form->input('grade', array(
        'options' => $grade
    ));

更新代码

// add in Model 
function afterFind($results) {
    foreach ($results as $key => $val) {
        if (isset($val['MyModel']['status'])) {
            $results[$key]['MyModel']['grade_text'] = $this->getGradeText($results[$key]['MyModel']['grade']);
        }
    }
    return $results;
}

public function getGradeText($key)
{
    $grades = array(
            'G' => 'Good',
            'P' => 'Pass',
            'R' => 'Practice Required',
            'F' => 'Fail'
        );
    $txt_selected = "";
    if(array_key_exists($key,$grades)) {
        $txt_selected = $grades[$key];
    } else {
        $txt_selected = "";
    }   
    return $txt_selected;
}

// in controller 

public function index() {
    $this->set('data' , $this->paginate('MyModel'));
}

// in view 

    foreach($data as $value) {

        echo $value['MyModel']['grade_text'];
    }

我希望它会对你有所帮助。