Đây là biểu mẫu của bạn trong chế độ xem. Tôi thích sử dụng các hành động khác nhau để xác thực và lưu. Bạn có thể kết hợp chúng thành một phương thức duy nhất.
<?php $form = \yii\widgets\ActiveForm::begin([
'id' => 'my-form-id',
'action' => 'save-url',
'enableAjaxValidation' => true,
'validationUrl' => 'validation-rul',
]); ?>
<?= $form->field($model, 'email')->textInput(); ?>
<?= Html::submitButton('Submit'); ?>
<?php $form->end(); ?>
Trong hành động xác thực bạn nên viết. Nó xác nhận form của bạn và trả về danh sách các errrs cho client. :
public function actionValidate()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
Và đây là hành động lưu. Để xác thực dữ liệu đầu vào cho bảo mật:
public function actionSave()
{
$model = new MyModel();
$request = \Yii::$app->getRequest();
if ($request->isPost && $model->load($request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
return ['success' => $model->save()];
}
return $this->renderAjax('registration', [
'model' => $model,
]);
}
Mã này sẽ xác thực biểu mẫu của bạn đang hoạt độngValidate() và. Để gửi biểu mẫu của bạn qua AJAX, hãy sử dụng beforeSubmit event. Trong tệp javascript của bạn viết:
$(document).on("beforeSubmit", "#my-form-id", function() {
// send data to actionSave by ajax request.
return false; // Cancel form submitting.
});
Đó là tất cả.
Nguồn
2015-09-03 13:45:49
Trên thực tế, đây chỉ là những gì Yii đã cung cấp với ActiveForm - bao gồm JavaScript để tự động xác nhận trên máy khách trước khi gửi dữ liệu đến máy chủ. – robsch
@robsch Nó không gửi biểu mẫu bằng AJAX mà người dùng đang yêu cầu. – TheStoryCoder