0

I'm wondering how to do this in Yii.

I have a form I want to be able to validate on submit. If the form has a validation error, the regular form summary should be shown, but if the form validates, i want to receive some data from the controller, inject it onto the page, and reset the form.

I've come up with this code so far.

$('#node-window form').submit(function(){
    var $form = $(this);
    $.ajax({
        type : 'POST',
        url : $form.attr('action'),
        data : $form.serialize(),
        dataType : 'json',
        success : function(data) {
            if(data.status=='error') {
                // Renders the validation summary
                $('#node-window').html(data.form);
            } else {
                // No errors, so inject the data.

            }
        }
    });
    return false;
});

This actually works, but if the form has errors, the error summary is shown, and the second time "Submit" it pressed, the "Submit" event is naturally not intercepted.

There has to be some way to do this easier/smarter in Yii??

1 Answer 1

1

There probably is a better way to do this in Yii but actually you can solve this fairly quickly. As long as you're using a recent version of jQuery change your top line to:

$('#node-window').on('submit', 'form', function(){

This will bind the event to #node-window and it will listen for form submits there. Then when the form is replaced it won't matter.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Pretty easy solution, i like it :). And it's easier when I have to replace the form with another form. Yeah, i thought there might be some default way to do this in Yii.
Yeh, there are ajax form submit options in Yii, and you can add hooks to them to other things. But in my experience with it, for a small feature like this it's easier to do it yourself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.