How to write js:beforeValidate in AJAX validation

Hi all,

My form has a "submit" button and "cancel" button, and I want my form to behave like this:

  • Blur (Hit tab key in input) : AJAX validation

  • Hit return key in input : AJAX validation + submit

  • Hit submit button : AJAX Validation + submit

  • Hit cancel button : submit without AJAX validation

So I have written like the following …




<?php

$form = $this->beginWidget('CActiveForm',

	array(

		'id' => 'contact-form',

		'enableAjaxValidation' => true,

		'clientOptions' => array(

			'validateOnSubmit' => true,

			'beforeValidate' => 'js:beforeValidate',

		),

	)

);

$js = "function beforeValidate(form){ if( cancel button has been clicked ) return false; return true; }";

Yii::app()->clientScript->registerScript('contact-form-beforeValidate', $js);

?>



Please let me know how to determine if the submittion has been caused by the cancel button or not.

It might be just a javascript issue, not Yii’s … but someone please.

OK, I couldn’t wait long and had to write on my own …




<?php

$form = $this->beginWidget('CActiveForm',

  array(

    'id' => 'contact-form',

    'enableAjaxValidation' => true,

    'clientOptions' => array(

      'validateOnSubmit' => ture,

      'beforeValidate' => 'js:beforeValidate',

    ),

  )

);

$js = <<< EOF_JS

function beforeValidate(form) {

- if (form.data('submitObject')[0].id == 'cancel_btn') {

+ if (form.data('submitObject') && form.data('submitObject')[0].id == 'cancel_btn') {

    this.validateOnSubmit = false;

    this.beforeValidate = '';

    form.submit();

    return false;

  } else {

    return true;

  }

}

EOF_JS;

Yii::app()->clientScript->registerScript('contact-form-beforeValidate', $js);

?>



It seems working good, so far.

But please let me know if you have noticed something bad in this code, or if you have a smart solution for this.

revised 2011-03-03