我在添加视图中有这些代码
$status = array('0' => 'Resolved', '1' => 'Assigned/Unresolved', '2' => 'Suspended', '3' => 'Closed', '4' => 'Bypassed');
echo $this->Form->input('status', array('options' => $status));
而不是将值(例如Resolved)保存到表中,它保存了数组的索引。有什么想法吗?
答案 0 :(得分: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值的枚举列,并使用该方法获取它们。
答案 1 :(得分:1)
您能否将索引定义为您想要的值?
$status = array('Resolved' => 'Resolved', 'Assigned/Unresolved' => 'Assigned/Unresolved', etc etc );
echo $this->Form->input('status', array('options' => $status));