今天做一個功能,我有一個表,是寄存系統所有公司的信息,但是公司的類別更加type這個字段把公司分爲一般公司名字和重要公司名字,但2個都是保存到companyName這個字段下面。yii的attributeLabels很方便可以做到那個輸入字段的提示文字。現在問題來了,如何讓它在同一個model裏面顯示不同的labels名字呢。
直接貼代碼。
/** implementation */
private $_currentLabelCollection = null;
public function getCurrentLabelCollection() {
return $this->_currentLabelCollection;
}
public function setCurrentLabelCollection($value) {
if(!$value || array_key_exists($value, $this->_attributeLabelCollections)) {
$this->_currentLabelCollection = $value;
} else {
throw new CException(Yii::t("error", "Model {model} does not have a label collection named {key}.", array(
'{model}' => get_class($this),
'{key}' => $value,
)));
}
}
private $_attributeLabelCollections = array(
'collection1' => array(
'line_1' => 'Authentication Number',
),
'collection2' => array(
'line_1' => 'Receipt Number',
),
);
public function attributeLabels() {
if($this->_currentLabelCollection) {
return $this->_attributeLabelCollections[$this->_currentLabelCollection];
} else {
return reset($this->_attributeLabelCollections);
}
}
/** usage */
// use labels from 'collection2'
$model->currentLabelCollection = 'collection2';
// use labels from the first defined collection
$model->currentLabelCollection = null;
資料來自這裏:http://stackoverflow.com/questions/10134702/multiple-labels-in-a-single-model-yii
全英文