大家好我有一个小问题,希望你能提供帮助。我正在我的模型中创建4个虚拟属性:
start_time_hr start_time_mn
end_time_hr end_time_mn
使用以下内容:
/**
* Retrieves hour portion of start_time
* @return string
*/
public function getstart_time_hr(){
$str = explode(':', $this->start_time);
return $str[0];
}
这主要是针对用户界面,因此用户可以通过一组下拉框设置开始和结束时间。这样做的问题是将选择写回数据库。
我目前在我的模型中有这个:
public function setstart_time_hr($value){
$this->start_time_hr = $value;
}
public function setstart_time_mn($value){
$this->start_time_mn = $value;
}
public function beforeSave(){
if(!empty($this->start_time_hr)){
$this->start_time = $this->start_time_hr.':'.$this->start_time_mn;
}
return parent::beforeSave();
}
我的保存表单操作是:
public function actionAdminChangeShift($calId){
$model = CalShift::model()->findByPk($calId);
$model->attributes = $_POST['CalShift'];
$model->save();
//$this->redirect(array('CalDialog','calID'=>$calId,'eventType'=>'click'));
}
我也尝试在set函数中重建start_time变量,但这也没有用。我错过了什么?我是否必须手动组合来自from的变量并将其传递给模型?
$model->start_time = $_POST['CalShift']['start_time_hr'].':'.$_POST['CalShift']['start_time_mn'];
这不是一个大问题,但我宁愿这种组合在模型中作为普通保存功能的一部分发生。
附注:可能有时间以时间格式传递,它们存储在DB '01:30'中,而不是单独的值,因此需要对其进行响应。
再次感谢。
修改
我可以通过将setstart_time_hr函数更改为:
来实现此功能public function setstart_time_hr($value){
$str = explode(':', $this->start_time);
$this->start_time = $value.':'.$str[1];
}
但是使用
无效$model->attributes = $_POST['CalShifts']
我必须通过执行以下操作手动分配值:
$model->start_time_hr = $_POST['CalShift']['start_time_hr'];
$model->start_time_mn = $_POST['CalShift']['start_time_mn'];
有没有人知道让$ model->属性起作用的解决方法?
再次感谢
编辑#2
我无法回答我自己的问题,所以答案是:
对此的修复是在模型中:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
.......
array('notice_sent_date, start_time_hr, start_time_mn', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
....
);
}
public function setstart_time_hr($value){
$str = explode(':', $this->start_time);
$this->start_time = $value.':'.$str[1];
}
public function setstart_time_mn($value){
$str = explode(':', $this->start_time);
$this->start_time = $str[0].':'.$value;
}
获得$model->attributes = $_POST['CalShifts']
工作的关键是确保标记为安全的2个虚拟属性。
希望这有助于其他人..
答案 0 :(得分:3)
对此的修复是,在模型中添加:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
.......
array('notice_sent_date, start_time_hr, start_time_mn', 'safe'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
....
);
}
public function setstart_time_hr($value){
$str = explode(':', $this->start_time);
$this->start_time = $value.':'.$str[1];
}
public function setstart_time_mn($value){
$str = explode(':', $this->start_time);
$this->start_time = $str[0].':'.$value;
}
获得$model->attributes = $_POST['CalShifts']
工作的关键是确保标记为安全的2个虚拟属性。
希望这有助于其他人..