php Yii ajaxSubmitButton() 与字段验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6348581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yii ajaxSubmitButton() with fields validation
提问by dagalllll
I'm using Yii ajaxSubmitButton() to submit a form. Besides, I have set the 'enableAjaxValidation' parameter to true to validate the corresponding textboxes.
我正在使用 Yii ajaxSubmitButton() 提交表单。此外,我已将 'enableAjaxValidation' 参数设置为 true 以验证相应的文本框。
What I am able to do:
我能做什么:
- Validate the field when the focus leaves it, asynchronously.
- Invoke the server side method when the button is clicked, asynchronously.
- 当焦点离开时异步验证字段。
- 单击按钮时异步调用服务器端方法。
The problem is that I don't know how to perform the fields validation when the submit button is clicked and, if the model is validated, perform a partial rendering in client side.
问题是我不知道如何在单击提交按钮时执行字段验证,如果模型已验证,则在客户端执行部分渲染。
If I override the 'success' event in ajaxSubmitButton, I get the partial rendering, but I can't maintain the model validation..
如果我覆盖 ajaxSubmitButton 中的 'success' 事件,我会得到部分渲染,但我无法保持模型验证..
Any help?
有什么帮助吗?
EDIT
编辑
Thanks for the reply,
谢谢回复,
The validateOnSubmit flag is already set and the model would be validated correctly if the 'success' event was not set.
validateOnSubmit 标志已设置,如果未设置“成功”事件,模型将被正确验证。
When the ajaxSubmitButton is like this:
当 ajaxSubmitButton 是这样的:
<?php echo CHtml::ajaxSubmitButton( 'Send',
CHtml::normalizeUrl(array('site/ajaxIndexSubmit')),
array(
'error'=>'js:function(){
alert(\'error\');
}',
'beforeSend'=>'js:function(){
alert(\'beforeSend\');
}',
'success'=>'js:function(data){
alert(\'success, data from server: \'+data);
}',
'complete'=>'js:function(){
alert(\'complete\');
}',
//'update'=>'#where_to_put_the_response',
)
);
?>
the alert('success') will print the string corresponding to the model validation. Once I have that string, what logic must be invoken in client side?
alert('success') 将打印与模型验证对应的字符串。一旦我有了那个字符串,必须在客户端调用什么逻辑?
The reason to override the 'success' javascript handler is to receive a partial rendering from the server, different to the model validation. I want both things: validation and partial rendering.
覆盖“成功”javascript 处理程序的原因是从服务器接收部分渲染,与模型验证不同。我想要两件事:验证和部分渲染。
回答by Muhammad Riyaz
Hey I had same problem and dint get it working even with aftervalidate, beforevalidate and so on.And secondly I dint like to use a extension for this coz my app already has many. So I made this:
嘿,我遇到了同样的问题,即使使用 aftervalidate、beforevalidate 等也能正常工作。其次,我不想为此使用扩展,因为我的应用程序已经有很多。所以我做了这个:
Edit : As per Barth's suggestion , i am putting those code here itself.
编辑:根据 Barth 的建议,我将这些代码放在这里。
Step 1: @ your controller action
第 1 步:@您的控制器操作
public function actionMyAction()
{
$model=new User;
$this->performAjaxValidation($model);
if(isset($_POST['User']))
{
$model->attributes=$_POST['User'];
$valid=$model->validate();
if($valid){
//do anything here
echo CJSON::encode(array(
'status'=>'success'
));
Yii::app()->end();
}
else{
$error = CActiveForm::validate($model);
if($error!='[]')
echo $error;
Yii::app()->end();
}
}
}
Step 2: @ your view Your form may look like this
第 2 步:@您的视图您的表单可能如下所示
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>true,
'action'=>$this->createUrl('myController/MyAction'),
'enableClientValidation'=>true,
)); ?>
<div class="errorMessage" id="formResult"></div>
<div id="AjaxLoader" style="display: none"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spinner.gif"></img></div>
<div class="row-user-single">
<?php echo $form->labelEx($model,'attribute1'); ?>
<?php echo $form->passwordField($model,'attribute1',array('size'=>60,'maxlength'=>500)); ?>
<?php echo $form->error($model,'attribute1'); ?>
</div>
<div class="row-user-single">
<?php echo $form->labelEx($model,'attribute2'); ?>
<?php echo $form->passwordField($model,'attribute2',array('size'=>60,'maxlength'=>500)); ?>
<?php echo $form->error($model,'attribute2'); ?>
</div>
<div class="buttons">
<?php echo CHtml::ajaxSubmitButton('Save',CHtml::normalizeUrl(array('myController/MyAction','render'=>true)),
array(
'dataType'=>'json',
'type'=>'post',
'success'=>'function(data) {
$("#AjaxLoader").hide();
if(data.status=="success"){
$("#formResult").html("form submitted successfully.");
$("#user-form")[0].reset();
}
else{
$.each(data, function(key, val) {
$("#user-form #"+key+"_em_").text(val);
$("#user-form #"+key+"_em_").show();
});
}
}',
'beforeSend'=>'function(){
$("#AjaxLoader").show();
}'
),array('id'=>'mybtn','class'=>'class1 class2')); ?>
This is working just fine for me And all the code written above are my style of writing. You may change them as required but, there are only two things to be noted as follows: 1. @ your controller call validate of your model and return a json object if form is invalid 2. @ your view break this json object (OR traverse through it) and show the error messages under respective elements of the form.
这对我来说很好用而且上面写的所有代码都是我的写作风格。您可以根据需要更改它们,但是,只有两件事需要注意如下: 1. @您的控制器调用验证您的模型并在表单无效时返回一个 json 对象 2.@您的视图破坏此 json 对象(或遍历通过它)并在表单的各个元素下显示错误消息。
Keep it simple :)
把事情简单化 :)
You may see my blog post here too: http://www.yiiframework.com/forum/index.php/topic/37075-form-validation-with-ajaxsubmitbutton/
你也可以在这里看到我的博客文章:http: //www.yiiframework.com/forum/index.php/topic/37075-form-validation-with-ajaxsubmitbutton/
回答by k to the z
CActiveForm
has a public property called $clientOptions
. There is a validateOnSubmit
option that is false by default. You need it to be true. In your view it should look something like this:
CActiveForm
有一个名为$clientOptions
. 有一个validateOnSubmit
选项默认为 false。你需要它是真的。在您看来,它应该是这样的:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'yourFormId',
'enableAjaxValidation'=>TRUE,
'clientOptions'=>array('validateOnSubmit'=>TRUE),
)); ?>
http://www.yiiframework.com/doc/api/1.1/CActiveForm#clientOptions-detail
http://www.yiiframework.com/doc/api/1.1/CActiveForm#clientOptions-detail
回答by theex
I found a solution. My CActive Form
我找到了解决方案。我的 CActive 表格
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'gold-value-form',
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate'=>'js:function(form, data, hasError) {
if(jQuery.isEmptyObject(data)) {
alert("ok")
}
return false;
}'
),
)); ?>
My create Action
我的创造行动
public function actionCreate()
{
$this->layout=false;
$model=new GoldValue;
if(isset($_POST['ajax']) && $_POST['ajax']==='gold-value-form')
{
if(isset($_POST['GoldValue']))
{
$model->attributes=$_POST['GoldValue'];
if(!$model->save())
echo CActiveForm::validate($model);
}
}
Yii::app()->end();
}
回答by acorncom
I'm about to try sending in a different value (posted with $_GET) on ajaxSubmitButton click. Testing for the value and then running validation if the value doesn't exist. Would that work for you?
我将尝试在 ajaxSubmitButton 单击时发送不同的值(用 $_GET 发布)。测试该值,然后在该值不存在时运行验证。这对你有用吗?
回答by nlac
check this snippet, it solves the problem at client side http://www.yiiframework.com/wiki/466/a-simple-way-to-get-yii-client-side-form-validation-run-when-submitting-by-ajax/
检查这个片段,它解决了客户端的问题http://www.yiiframework.com/wiki/466/a-simple-way-to-get-yii-client-side-form-validation-run-when-submitting -by-ajax/
回答by Truongnq
Try this:
尝试这个:
/*
1) Register the snippet into the HEAD. Be sure that it is linked after jquery.yii.js is linked.
2) Configure your CActiveForm instance like this:
*/
$this->beginWidget('CActiveForm', array(
...
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate'=>'js:$.yii.fix.ajaxSubmit.afterValidate'
)
...
);
/*
3) Configure your CHtml::ajaxSubmitButton instance like this:
*/
echo CHtml::ajaxSubmitButton('Whateverlabel', 'whateverurl', array(
...
'beforeSend'=>'js:$.yii.fix.ajaxSubmit.beforeSend("#YOUR_FORM_ID")'
...
);
See more http://www.codexamples.com/90/chtml-ajaxsubmitbutton/or http://www.codexamples.com/category/chtml-8/
查看更多http://www.codexamples.com/90/chtml-ajaxsubmitbutton/或http://www.codexamples.com/category/chtml-8/