我有两个模型,Product和Product_Methodology。在我的产品编辑视图中,我有一个选择表单字段,用于从多种方法中选择一种或不选择(第一个选项为空)。在我的products表中,我有一个INT(10)
methodology_id
属性,它与从select表单字段中选择的方法的id一起保存。直到今天,一切都很顺利,我不得不对系统进行调整,从现在起,选择方法是可选的。因此,我更改了products表的methodology_id
字段以允许NULL
值,并删除了模型上的not_empty
验证规则。
现在的问题是,当我保存选择空选项的模型时,我得到的不是预期的NULL
,而是0
(零)值
有线索吗?非常感谢,如果不太清楚,请告诉我。
您使用什么形式的输入来选择方法?是<select>
吗?如果是这样,当没有选择方法时,choosen选项的值可能会设置为0,并与其他表单数据一起发送。
在这种情况下,我在模型的filters()
方法中创建了一个自定义过滤器,当它是empty()
时,将值设置为NULL(正如PHP所处理的那样),类似于以下内容:
public function filters()
{
return array(
'methodology_id' => array(
array('Filter::null', array(':value')),
),
);
}
其中Filter是具有静态方法的辅助类。比如…:
class Kohana_Filter {
public static function null($value)
{
return (empty($value) ? NULL : $value);
}
}
希望这有帮助:)
即使提交的表单字段为空,它也是一个具有任何空值的字符串,而不是NULL。当保存到INT字段(至少在mysql中)时,它会被强制转换为0。要保留空值,请执行以下操作:
$methodology_id = (empty($methodology_id) ? NULL : $methodology_id);
如果字段值为空字符串,则使用闭包返回NULL值的示例:
public function filters()
{
return array(
// Return a NULL value if empty string.
'field_name' => array(
array(function($value){
return ($value === '') ? NULL : $value;
}, array(':value')),
)
);
}
您应该做的是将选择框中None值的键设置为0。
您应该为字段保留not_empty规则。然后,您应该为字段制定一个规则,确保该值是product_methodology的合法值或零。
我扩展了ORM并具有以下两个功能:
public function exists_or_zero(Validation $validation, $field, $model, $pk)
{
// The exists() function is only called if the field has a non-zero value
if ($validation[$field]) {
$this->exists($validation, $field, $model, $pk);
}
}
public function exists(Validation $validation, $field, $model, $pk)
{
if ( ! ORM::factory($model, $pk)->loaded()) {
$validation->error($field, 'exists', array($validation[$field]));
}
}
如果要使用这些函数,产品类中的规则将如下所示:
public function rules()
return array(
'product_methodology_id' => array(
array('not_empty'),
array(array($this, 'exists_or_zero'), array(':validation', ':field', 'product_methodology', ':value')),
),
);
}