5

I have two related fields in a Yii model. They are items_per and items_period.

items_per is an integer that reflects how many items to be processed in a given time period.

items_period is the number of seconds in that period (a dropdown with options labelled as seconds, minutes, hours). Multiply items_per by items_period and you have "items per second".

I've got a custom validation rule set up to limit items per second being above a certain amount. That all works fine and gives a sensible error message using ajax validation when you change the value in the items_per field (on blur).

I need for the validation on the items_per field to be triggered whenever the items_period field is changed (100 / second may not be allowed, but 100 / minute is).

I tried adding an onchange function to the items_per dropdown to trigger "blur" or "change" on the items_per field, but it doesn't seem to make the ajax request for validation. Submitting the form just to trigger the validation isn't an option, as it's possible it might not have any errors and simply save the record before the user is ready.

Any suggestions how I can force one field to trigger ajax validation in another?

2 Answers 2

5

You can achieve validation client-side (with JS), through AJAX and for plain requests all together in one package if you define a custom validator extending CValidator.

For "plain" validation, set up the validator with the correct attribute names and parameters and override the validateAttribute method.

For client-side validation, additionally override the clientValidateAttribute method. If client validation is enabled for the form this will result in your custom JS automatically being called to validate the input. From within the override you will be outputting JS code that runs in this context:

function(value, messages, attribute) {
    // your code goes here
    // value: current value of attribute
    // messages: array of strings (validation errors) you should append to
    // attribute: name of the attribute
}

You can see how the built-in validators work in this framework with an example. Also see CActiveForm.clientOptions.

For AJAX validation, you can submit the form for validation. The idea is that you configure validation to either include a special parameter (e.g. ajax=something) or exclude one (e.g. to not include the value of your submit button). In fact, Yii already does this by automatically including an ajax=formId parameter in all AJAX validation requests!

This way you can easily write controller code that always validates but only saves when it should. There's an example for this too in the Yii reference for CActiveForm (search for "To respond to the AJAX validation requests, we need the following class code: ").

Finally, you can programmatically set the validation status for any attribute with Javascript by calling $.fn.yiiactiveform.updateInput. If you do this it would be a good idea to keep imitating Yii by calling $.fn.yiiactiveform.updateSummary as well.

7
  • Thanks, I looked at a custom validator first of all, but they only fire for the specific field they're attached to - what I need is for another field (per_period) to fire the validation for items_per
    – Hippyjim
    Jul 13, 2012 at 11:27
  • @Hippyjim: You could simply attach the validator to both fields so that it triggers for both I think. In any case, I have updated the answer with additional information you might find useful.
    – Jon
    Jul 13, 2012 at 11:58
  • I'm currently using a function in the model to provide the validation, and tried attaching that validation to both fields. Unfortunately, if it was fired by per_period, it didn't clear the error message when validation passed. I'll take a look at the updateInput function as that might be the missing piece for my onchange method. Thanks!
    – Hippyjim
    Jul 13, 2012 at 12:53
  • Ok no joy. The main problem seems to be that yiiactiveform stores the state of the input and knows it hasn't changed. calling updateInput doesn't do much, as I can't seem to call it directly - I think that if I could figure out how to call the validate method on the whole form that'd work, but it can't find the syntax to call it manually from within an onchange - any clues?
    – Hippyjim
    Jul 13, 2012 at 13:31
  • Ok, i just realised something else - when validating only one field, the other field's value isn't always updated, unless we directly check the $_POST - it's not picking up the items_period field value anyway. I'm going to add a pseudo field that is the total value, and validate that instead.
    – Hippyjim
    Jul 13, 2012 at 14:11
5

I created the following javascript function, which I manually call when changing specific fields. It performs ajax validation on all form elements.

/**
 * @author marcovtwout
 * Force performing full ajax validation on given form.
 * @param Object $form jQuery form object
 */
performFullAjaxValidation = function($form){
    var settings = $form.data("settings");
    $.each(settings.attributes, function () {
        this.status = 2; // force ajax validation
    });
    $form.data("settings", settings);

    // trigger ajax validation
    $.fn.yiiactiveform.validate($form, function (data) {
        $.each(settings.attributes, function () {
            $.fn.yiiactiveform.updateInput(this, data, $form);
        });
        $.fn.yiiactiveform.updateSummary($form, data);
    });
}
1
  • I was trying to do this...I was missing the status change to force ajax validation.. You sir saved my day!
    – Felipe
    Dec 19, 2013 at 19:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.