Answer the question
In order to leave comments, you need to log in
How to make ActiveForm display validate?
Good afternoon,
Folks, I'm making an Ajax form from a simple working form.
Without Ajax, everything works as it should, as soon as I make the Ajax form, validation stops working.
Zama form
$form = ActiveForm::begin([
'id' => $model->formName(),
'enableAjaxValidation' => true,
'options' => [
'enctype' => 'multipart/form-data',
'class' => false,
],
'errorCssClass' => 'hasError',
]);
public function actionTest(){
$model = new MyPersonalForm('', $user, Yii::$app->request->post('myPersonals'));
if(Yii::$app->request->isPost && $model->validate()){
if($model->saveMyPersonal()){
}
}
return $this->renderAjax('test', [
'model' => $model,
]);
}
public function validate($attributes=null, $clearErrors=true){
$return = parent::validate($attributes,$clearErrors);
$skip_activity =false;
foreach($this->user_personal as $ui)
{
if(!$ui->validate())
{
$this->addErrors($ui->getErrors());
$return = false;
}
if($ui->is_active){
$skip_activity =true;
}
}
if(!$skip_activity){
foreach($this->user_personal as $ui)
$ui->addError('is_active','At least one activity must be selected or None.');
$return = false;
}
return $return;
}
Answer the question
In order to leave comments, you need to log in
This is how I always do it.
I create a trait in the core components (I use it everywhere where there is ajax validation)
trait AjaxValidationTrait
{
/**
* Performs ajax validation.
*
* @param Model $model
*
* @throws \yii\base\ExitException
*/
protected function performAjaxValidation(Model $model)
{
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();
}
}
}
class DefaultController extends BaseAdminController
{
use AjaxValidationTrait;
public function actionCreate()
{
$model = new Point();
$this->performAjaxValidation($model);
if ($model->validate()) {
....
} else {
return $this->render('create', [
'model' => $model]
);
}
}
}
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
'enableClientValidation' => false,
]); ?>
1. You check if the ajax request is valid and what it returns. Why dig into the code when there is probably a specific error in debug. Maybe the routing is wrong.
2. Judging by your code in the controller, you do not return the validation result. What are you expecting? You receive a request, it is validated and saved if successful, or it returns a render of a certain view. And it should validate and return for example:echo json_encode(ActiveForm::validate($model));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question