Difference between #3 and #10 of
How to implement form events

Changes

Title unchanged

How to implement form events

Category unchanged

How-tos

Yii version unchanged

Tags unchanged

yii2, forms, how to

Content changed

[...]
```php
<?php
$js = <<<JS
// get the form id and set the event
$('form#{$model->formName()}').on('beforeSubmit', function(e
, \$form) {) {
 
   var \$form = $(this);

// do whatever here, see the parameter \$form?
// is a jQuery Element to your form
[...]
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:
 
 
 
```php 
$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
 
 
});
 
JS;
 
 
$this->registerJs($js);
 
 
```
 
 
When using `return false` to prevent submission, there is no need to use ` e.preventDefault()` on the `submit` event:
 
 
 
```php 
<?php
 
$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
 
});
 
JS;
 
 
 
$this->registerJs($js);
 
 
```
 
 
> [![2amigOS!](http://www.gravatar.com/avatar/55363394d72945ff7ed312556ec041e0.png)](http://www.2amigos.us) <i>web development has never been so fun</i> [www.2amigos.us](http://www.2amigos.us)
5 0
6 followers
Viewed: 39 504 times
Version: 2.0
Category: How-tos
Tags: Forms, How to, yii2
Written by: Antonio Ramirez
Last updated by: deacs
Created on: Sep 12, 2014
Last updated: 9 years ago
Update Article

Revisions

View all history