Задача: В таблице есть поле типа "Дата", сделать приложение в котором это поле можно было бы заполнять с помощью трёх dropDownList.
1. Модуль (выполняем следующие шаги)
1.1. Объявляем переменную
Код: Выделить всё
public $DateArr;
Код: Выделить всё
public function rules(){
return array(
array('DateArr', 'required'),
array('Dateofbirth','type','type'=>'date','dateFormat'=>'yyyy-M-d','allowEmpty'=>true,
'message'=>'Некорректно указана дата.'),
);
}
Код: Выделить всё
public function beforeValidate(){
foreach($this->attributeNames() as $name):
if (strcmp($this->tableSchema->getColumn($name)->dbType,'date')==0):
$temp=$this->DateArr[$name];
$this->$name=(empty($temp['year']) && empty($temp['month']) && empty($temp['day'])) ?
NULL : $temp['year'].'-'.$temp['month'].'-'.$temp['day'];
endif;
endforeach;
return parent::beforeValidate();
}
Код: Выделить всё
public function afterFind(){
foreach($this->attributeNames() as $name) :
if (strcmp($this->tableSchema->getColumn($name)->dbType,'date')==0) :
$bd = array();
list($bd['year'],$bd['month'],$bd['day'])=(!is_NULL($this->$name)) ?
explode('-', $this->$name) : array(0,0,0);
foreach($bd as $key => $val)
$this->DateArr[$name][$key]=(int)$val;
endif;
endforeach;
parent::afterFind();
}
Код: Выделить всё
public static function getRange($start, $end){
$range = array();
for ($i=$start; $i<=$end; $i++) $range[$i]=$i;
return $range;
}
2.1.
Код: Выделить всё
<?php echo $form->dropDownList($model,'DateArr[Dateofbirth][day]',$model->getRange(1,31),array('empty' => 'День')); ?>
<?php echo $form->dropDownList($model,'DateArr[Dateofbirth][month]',$model->getRange(1,12),array('empty' => 'Месяц')); ?>
<?php echo $form->dropDownList($model,'DateArr[Dateofbirth][year]',$model->getRange(1940,2011),array('empty' => 'Год')); ?>
Вот собственно и всё.
Если в таблице есть несколько полей то например ещё поле с названием "Data2"
то измениться всего несколько строк в модели, а именно в:
Код: Выделить всё
array('Dateofbirth,Data2','type','type'=>'date','dateFormat'=>'yyyy-M-d','allowEmpty'=>true,
'message'=>'Некорректно указана дата.'),
);
Код: Выделить всё
<?php echo $form->dropDownList($model,'DateArr[date2][day]',$model->getRange(1,31),array('empty' => 'День')); ?>
<?php echo $form->dropDownList($model,'DateArr[date2][month]',$model->getRange(1,12),array('empty' => 'Месяц')); ?>
<?php echo $form->dropDownList($model,'DateArr[date2][year]',$model->getRange(1940,2011),array('empty' => 'Год')); ?>