Вы можете использовать validate()
method для проверки атрибутов индивидуально, так что вы можете сначала проверить start_date
и пропустить проверку, если есть ошибки с этим, что-то вроде:
<?php
// ... code ...
// in your controller's actionCreate for the particular model
// ... other code ...
if(isset($_POST['SomeModel'])){
$model->attributes=$_POST['SomeModel'];
if ($model->validate(array('start_date'))){
// alright no errors with start_date, so continue validating others, and saving record
if ($model->validate(array('end_date'))){
// assuming you have only two fields in the form,
// if not obviously you need to validate all the other fields,
// so just pass rest of the attribute list to validate() instead of only end_date
if($model->save(false)) // as validation is already done, no need to validate again while saving
$this->redirect(array('view','id'=>$model->id));
}
}
}
// ... rest of code ...
// incase you didn't know error information is stored in the model instance when we call validate, so when you render, the error info will be passed to the view
В качестве альтернативы можно также использовать атрибут skipOnError
из CValidator class:
// in your model's rules, mark every validator rule that includes end_date as skipOnError,
// so that if there is any error with start_date, validation for end_date will be skipped
public function rules(){
return array(
array('start_date, end_date', 'required', 'skipOnError'=>true),
array('start_date, end_date', 'date', 'skipOnError'=>true),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, start_date, end_date', 'safe', 'on'=>'search'),
);
}
Надеется, что это помогает.
Отказ от ответственности: я не уверен в решении skipOnError, это может повлиять на порядок валидаторов, вы можете проверить его (я еще не тестировал) и выяснить, работает ли он. Разумеется, индивидуальное решение для проверки будет работать в любой день.
Я только что завершил этот вид проверки с помощью Yii. вы можете отсылать его отсюда. http://chevronscode.com/index.php/yii-model-rules-dynamic-required-if-extension.html – chen
В ** Yii2 ** вы можете использовать ['when'] (http: // www. yiiframework.com/doc-2.0/guide-input-validation.html#conditional-validation). –