Above is a sample REST API code written to creating a user. If any validation error I`ll send first error in the $model->errors object. Response is like "{"statusCode":100,"statusMessage":"Validation failed. Reason:First Name cannot be blank."}".
Here statusCode is same for any validation error but statusMessage is changed according to the Yii error message.
Now I want to send separate error codes to each validation error. Ex: first name required - 100, last name required - 101 etc…
Is there any proper way to achieve this rather than checking them individually? Can we bind error code to the rules without interrupting to the web flow.
Thank you for the solution. I just wanted to get an error code for validation instead of a error message the I can directly send that error code to REST request. Anyway I achieved it another way.
// Model rules
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
$rules = array(
array('firstName, lastName', 'required', 'on'=>'create'),
);
if ($this->isApi) {
$rules = array(
array('firstName', 'required', 'message'=>100, 'on'=>'create'),
array('lastName', 'required', 'message'=>101, 'on'=>'create'),
);
}
return $rules;
}
// Controller action
public function actionCreate()
{
$model = new User();
$model->scenario = 'create';
$model->isApi = true; // Saying that action related to API call and rules prepared according to it
$model->attributes = $this->params;
if ($model->validate()) {
try {
$model->save();
$statusCode = RestServer::SUCCESS;
} catch (Exception $e) {
$statusCode = RestServer::FAILED;
}
} else {
// Getting the first error of the $model->errors, So it will be error code
$errors = $model->errors;
$error = current($errors);
$statusCode = $error[0];
}
$this->sendResponse($statusCode);// Sending REST response via another function.
}