Reputation: 381
I am trying to implement with custom function in model its not working i am not getting what's wrong in my code. i am trying to call with basic later i will put my condition.
Here is model code
public function rules()
{
return [
['mobile_number', 'required'],
['mobile_number', 'myfunction'],
];
}
public function myfunction($attribute,$params)
{
$this->addError($attribute, 'You have already submitted');
}
Here is controller code
public function actionCreate()
{
$model = new Createuser();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
its not assiging the error to a form-field.
Thanks in advance.
Upvotes: 0
Views: 4646
Reputation: 47
I guess the parameter named mobile_number
does not exist in your data or it is an empty string, so try to add 'skipOnEmpty' => false
in your code.
Anyway, it works for me.
public function rules()
{
return [
['mobile_number', 'required', 'skipOnEmpty' => false],
['mobile_number', 'myfunction', 'skipOnEmpty' => false],
];
}
Upvotes: 3
Reputation: 3079
try this in your controller
protected function performAjaxValidation($model = NULL) {
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
echo json_encode(ActiveForm::validate($model));
Yii::$app->end();
}
}
public function actionCreate()
{
$model = new Createuser();
$this->performAjaxValidation($model);
if ($model->load(Yii::$app->request->post()) && $model->save() && $model->validate()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Upvotes: 0
Reputation: 4261
Your Model:
public function rules()
{
return [
['mobile_number', 'required'],
['mobile_number', 'myfunction'],
];
}
public function myfunction($attribute,$params)
{
$this->addError($attribute, 'You have already submitted');
return false;
}
And your controller:
public function actionCreate()
{
$model = new Createuser();
if ($model->load(Yii::$app->request->post()) && $model->save() && $model->validate()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Upvotes: 0
Reputation: 1331
are you sure you are not extending the model class ? if so you need to put this :
$model->validate()
Upvotes: 0