2011-09-05 46 views
0

我在我的add视图如何将数组的值保存到表中?

$status = array('0' => 'Resolved', '1' => 'Assigned/Unresolved', '2' => 'Suspended', '3' => 'Closed', '4' => 'Bypassed'); 
echo $this->Form->input('status', array('options' => $status)); 

这些代码和而不是保存的值(例如解决)的表,它保存在阵列的索引。有任何想法吗?

回答

1

你应该做这样的事情:

$status = array('resolved' => 'Resolved', 'assigned' => 'Assigned/Unresolved'...); 

它保存数组的索引。但这不是一个好习惯,而是尝试使用枚举。看看这个:

/** 
    * Get Enum Values 
    * Snippet v0.1.3 
    * http://cakeforge.org/snippet/detail.php?type=snippet&id=112 
    * 
    * Gets the enum values for MySQL 4 and 5 to use in selectTag() 
    */ 
    function getEnumValues($columnName=null, $respectDefault=false) 
    { 
     if ($columnName==null) { return array(); } //no field specified 
     //Get the name of the table 
     $db =& ConnectionManager::getDataSource($this->useDbConfig); 
     $tableName = $db->fullTableName($this, false); 


     //Get the values for the specified column (database and version specific, needs testing) 
     $result = $this->query("SHOW COLUMNS FROM {$tableName} LIKE '{$columnName}'"); 

     //figure out where in the result our Types are (this varies between mysql versions) 
     $types = null; 
     if  (isset($result[0]['COLUMNS']['Type'])) { $types = $result[0]['COLUMNS']['Type']; $default = $result[0]['COLUMNS']['Default']; } //MySQL 5 
     elseif (isset($result[0][0]['Type']))   { $types = $result[0][0]['Type']; $default = $result[0][0]['Default']; } //MySQL 4 
     else { return array(); } //types return not accounted for 

     //Get the values 
     $values = explode("','", preg_replace("/(enum)\('(.+?)'\)/","\\2", $types)); 

     if($respectDefault){ 
        $assoc_values = array("$default"=>Inflector::humanize($default)); 
        foreach ($values as $value) { 
            if($value==$default){ continue; } 
            $assoc_values[$value] = Inflector::humanize($value); 
        } 
     } 
     else{ 
        $assoc_values = array(); 
        foreach ($values as $value) { 
            $assoc_values[$value] = Inflector::humanize($value); 
        } 
     } 

     return $assoc_values; 
    } //end getEnumValues 

在你的AppModel中粘贴该方法。

将表中的列创建为具有posible值的枚举,并使用该方法获取它们。

+0

嗨圣地亚哥,我不知道这是否回答我的问题,但我不想在我的数据库上创建另一个表。这是我用默认选项填充下拉框的目的(已解决,未解决,关闭...),所以我不必从我的数据库中获取它们。我唯一的问题是当我添加/保存一条记录时,无论我在下拉框中选择了什么,它都会将索引保存在数据库中,而不是数据本身。 – Lyman

+0

该列的数据类型是什么以及您使用的是什么RDMBS? – santiagobasulto

1

你不能将索引定义为你想要的值吗?

$status = array('Resolved' => 'Resolved', 'Assigned/Unresolved' => 'Assigned/Unresolved', etc etc); 
    echo $this->Form->input('status', array('options' => $status)); 
相关问题