Yii 2.0: How to implement form events


You have that, when a product is on development they can change its API anytime. This change is quite important though, its related on how to set the events of your form, for example, the useful beforeSubmit.

Before, we could do that easily on an 'ActiveForm's property but now we have to do some extra work and register the javascript event your self.

Now, lets imagine we wish to deal with a 'beforeSubmit' event on our form:

<?php $form = ActiveForm::begin(
        // make sure you set the id of the form
        'id' => $model->formName(), 
        'action' => ['yada/create']
<!-- more stuff here -->
<?php ActiveForm::end();?>

In order to register your beforeSubmit event, we will have to register the event this way:

$js = <<<JS
// get the form id and set the event
$('form#{$model->formName()}').on('beforeSubmit', function(e) {
   var \$form = $(this);
   // do whatever here, see the parameter \$form? 
   // is a jQuery Element to your form
}).on('submit', function(e){

And thats it... hope you find it useful. Its a bit confusing at first when you do not know what has just happened.

NOTE: You can prevent the form from being submitted by returning false. Returning either true, null or undefined will cause the form to be submitted. See below:

$js = <<<JS
$('body').on('beforeSubmit', 'form#{$model->formName()}', function () {
    var form = $(this);
    if (form.find('.has-error').length) {
        return false;
    // return undefined; // form gets submitted
    // return null; // form gets submitted
    // return true; // form gets submitted
    return false; // form does not get submitted

When using return false to prevent submission, there is no need to use e.preventDefault() on the submit event:

$js = <<<JS
// get the form id and set the event
$('form#{$model->formName()}').on('beforeSubmit', function(e) {
    // return false to prevent submission
    return false;
}).on('submit', function(e){    // can be omitted
    e.preventDefault();         // can be omitted

web development has never been so fun

Total 4 comments

#18152 report it
Antonio Ramirez at 2014/09/17 06:32am

Yep... that is up to you. What I exposed on the tuto is just a demo.

#18139 report it
PinkBrainPlan at 2014/09/15 04:01pm
JSExpression usage instead of outcasting?


wouldn't it be easier to just JSExpression($js) before you pass it over to the view?

Otherwise great how-to!

#18137 report it
Antonio Ramirez at 2014/09/15 10:44am
Good to mention

I forgot to mention that we should look into the yii.activeForm.js file in order to know which events are available:

  • ajaxComplete
  • ajaxBeforeSend
  • beforeSubmit
  • afterValidate
  • beforeValidate
#18126 report it
sirin k at 2014/09/13 06:37am


Leave a comment

Please to leave your comment.

Write new article