我快要疯了,在一个相当简单的问题上尝试不同的解决方案
我的应用程序存储了数百个日期,而我的客户端的源数据有一个坏习惯,即日期采用不同的格式。
例如,我的一个模型具有如下规则(为了完成,列出了此特定模型的所有规则)
public function rules() {
return array(
array('function, junior, ces,agreement_expected,start_date', 'required'),
array('start_budget', 'numerical'),
array('visa_received,training_days', 'numerical', 'integerOnly' => true),
array('function, junior, ces,currency', 'length', 'max' => 10),
array('agreement_received, status, stop_date_original, stop_date_extended', 'safe'),
array('agreement_received, visa_received, stop_date_original, stop_date_extended', 'default', 'setOnEmpty' => true, 'value' => null),
array('agreement_received,agreement_expected,start_date,stop_date_original,stop_date_extended', 'date', 'format' => 'Y-m-d', 'allowEmpty' => true),
array('id, Sname,PFces, PFdomain,PDkeyword, PFstatus, PRname,PRcountry,PRscore,PRcomment,PRngo,TRname,TRpic, TFfunction, TFx, TRdateofbirth,TRedufields,TRcoach,TRlocation,TRtask,TRcontract,TRproject,TRcontact,TFdateofbirth,TFedufields,TFcoach,TFlocation,TFtask,TFcontract,TFproject,TFcontact,
date1,date2,idate, ddomains,dkeywords,country,agreement, function,ngo, status,group, junior, junior_lastname, junior_firstname,search_all,search_interrupt, ces, agreement_expected, agreement_received, visa_received, start_date, stop_date_original, stop_date_extended,currency, start_budget, training_days', 'safe', 'on' => 'search'),
);
}
我想要实现的目标由以下规则描述
array('agreement_received, visa_received, stop_date_original, stop_date_extended', 'default', 'setOnEmpty' => true, 'value' => null),
array('agreement_received,agreement_expected,start_date,stop_date_original,stop_date_extended', 'date', 'format' => 'Y-m-d', 'allowEmpty' => true),
当我有一个表单,并且我在 stop_date_extended 上提交一个空值时,它不会设置为 NULL,而是一个空字符串。
我做错了什么?当然,必须有一个简单的解决方法,因为不使用日期验证器会像桃子一样工作。
Yii 默认验证器类处理空值如下:
/framework/validators/CDefaultValueValidator.php
protected function validateAttribute($object,$attribute)
{
if(!$this->setOnEmpty)
$object->$attribute=$this->value;
else
{
$value=$object->$attribute;
if($value===null || $value==='')
$object->$attribute=$this->value;
}
}
鉴于上面的功能,您唯一的问题可能是按表单发布的值[即$value]可能不是空字符串,可能it might have spaces
。也许您可以在将值分配给模型属性之前尝试修剪()。或扩展默认值验证器,例如
class CMyDefaultValueValidator extends CDefaultValueValidator
{
protected function validateAttribute($object,$attribute)
{
if(!$this->setOnEmpty)
$object->$attribute=$this->value;
else
{
$value=trim($object->$attribute);
if($value===null || $value==='')
$object->$attribute=$this->value;
}
}
}
请注意以下行:$value=trim($object->$attribute);
虽然,我没有测试上面的代码,我不知道这是否可以用更好的方式完成,
如果要为空字符串插入 null,可以在验证后在模型中执行此操作:
public function afterValidate()
{
if(empty(trim($this->yourField))) // put whatever logic that you need
$this->yourField = null;
return parent::afterValidation();
}