今天在搜索 『Yii2 performAjaxValidation 』,然后发现一个挺好用的 Trait,分享给大家
/*
* This file is part of the Dektrium project
*
* (c) Dektrium project
*
* For the full copyright and license information, please view the LICENSE.md
* file that was distributed with this source code.
*/
namespace app\traits;
use yii\base\Model;
use yii\web\Response;
use yii\widgets\ActiveForm;
/**
* @author Dmitry Erofeev
*/
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;
\Yii::$app->response->data = ActiveForm::validate($model);
\Yii::$app->response->send();
\Yii::$app->end();
}
}
}
本文由 forecho 创作,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。
可自由转载、引用,但需署名作者且注明文章出处。
打赏作者
如果这篇文章对您有帮助,不妨微信小额赞助我一下,让我有动力继续写出高质量的教程。