我对员工代码应用了唯一验证。它在添加Emp的情况下运行良好。但我不明白为什么在更新的情况下它不起作用,以下是我为此使用的代码:
我的规则方法是:
public function rules()
{
return array(
array('is_active', 'numerical', 'integerOnly'=>true),
array('first_name, last_name, employee_code, username, password, role,joining_date,', 'required','on'=>array('create','update')),
array('employee_code', 'numerical', 'integerOnly'=>true),
array('employee_code', 'unique','on'=>array('create','update')),
array('employee_code', 'length', 'min' => 4, 'max'=>4, 'message'=>Yii::t("translation", "{attribute} is too short.")),
array('username','email'),
array('username','valid_username','on'=>array('create')),
array('username', 'required','on'=>array('forgotPassword')),
array('currentPassword, newPassword, newPasswordRepeat', 'required','on'=>array('change')),
array('newPassword', 'compare', 'compareAttribute'=>'newPasswordRepeat','on'=>array('change'),'message'=>'New and Confirm Password do not match.'),
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements(),'on'=>array('forgotPassword')),
array('joining_date', 'safe'),
array('years', 'safe'),
array('user_id, first_name, last_name, employee_code, username, password, role, joining_date, pending_regular_leave, pending_medical_leave, allocated_regular_leave, allocated_medical_leave, is_active', 'safe', 'on'=>'search'),
);
请有人能认出我错在哪里吗。请帮帮我。
看起来字段"employee code"的值放入表单字段,而您正试图保存它。它不是唯一的,也不是保存的。
无论如何,你可以:
$employee->validate(array('/* Here is list of attributes, except employee code */'));
或:
$employee->save(array('/* Here is list of attributes, except employee code */'));
在更新操作中。
您还可以删除验证规则中的场景:
array('employee_code', 'unique','on'=>array('insert');
当您更新记录时,它已经存在于数据库中,并且您要验证的值也已经存在。这就是为什么在进行更新时,应将要更新的记录从检查中排除。否则,检查将失败,并显示类似的消息
员工代码"某个值"已被采用。
例如(带标准的新规则)
array(
'employee_code',
'unique',
'criteria' => array(
'condition' => 'user_id != :id',
'params' => array(':id' => $this->user_id),
),
'on' => array('create', 'update'),
),
我假设user_id
是主键。
从形式上讲,您可能希望update
和create
有不同的场景,因为您不需要对create
场景进行任何额外的检查。单一场景也可以,但你可能想做一些类似的事情
array(
'employee_code',
'unique',
'on' => array('create'),
),
array(
'employee_code',
'unique',
'criteria' => array(
'condition' => 'user_id != :id',
'params' => array(':id' => $this->user_id),
),
'on' => array('update'),
),
附言:正如其中一条评论中提到的,您可能希望使用insert
而不是create
,因为默认情况下,新建模型的场景是insert
。这是比较常用的名称。