开发者

Yii ajaxSubmitButton() with fields validation

I'm using Yii ajaxSubmitButton() to submit a form. Besides, I have set the 'enableAjaxValidation' parameter to true to validate the corresponding textboxes.

What I am able to do:

  1. Validate the field when the focus leaves it, asynchronously.
  2. 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..

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.

When the ajaxSubmitButton is like this:

<?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?

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.


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:

Edit : As per Barth's suggestion , i am putting those code here itself.

Step 1: @ your controller action

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

<?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.

Keep it simple :)

You may see my blog post here too: http://www.yiiframework.com/forum/index.php/topic/37075-form-validation-with-ajaxsubmitbutton/


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:

<?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


I found a solution. My CActive Form

<?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();
}


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?


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/


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜