[英]CakePhp: How to display specific enum values from a list of multiple ones
我想获取并显示特定枚举值的下拉列表。
例如,我有一个名为status的列。 具有枚举值:-“打开”,“读取”,“进度”,“片断”,“提升”,“协调”,“完成”,“关闭”
我想要一种用于选择和仅在下拉列表中显示枚举值“ Closed”的方法。
我编写了一种主要方法来获取App Model中的枚举值,如下所示。
public function getEnumValues($columnName=null, $respectDefault=false ,$blank =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] = __t(Inflector::humanize($value));
}
}else{
$assoc_values = array();
if($blank){
$assoc_values[] = '-- انتخاب نشده --';
}
foreach ( $values as $value ) {
$assoc_values[$value] = __t(Inflector::humanize($value));
}
}
return $assoc_values;
} //end getEnumValues
我将不得不为这个问题找到解决方案
我尝试阻止mysql枚举,因为CakePHP不支持它们。
而是尝试使用类似方法,例如http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/,并使用tinyint(2)和简单的静态模型方法对其进行仿真。 它更快,更动态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.