javascriptmodel-view-controlleryii2active-form

Yii2: Is there an easy way to load an existing ActiveForm with values from Javascript?


I have an existing Yii2 ActiveForm (like the one below) on a Single-Page-App where I want to load new values into it via AJAX. Is there already a simple way to do that, or do I need to make my own Javascript function to do that?

<form>
    <input type="text" name="Conversation[cv_timestamp]">
    <input type="text" name="Conversation[cv_type]">
    <input type="text" name="Contact[ct_firstname]">
    <input type="text" name="Contact[ct_lastname]">
</form>

Solution

  • I ended up making my own Javascript function. Improvements are welcome.

     // Load ActiveForm with new model attributes via Javascript
     //
     // Form fields must have been named like this: <input name="Contact[firstname]"> <input name="Contact[lastname]">
     //
     // @param {(string|jQuery object)} formSelector - String with selector or a jQuery object
     // @param {object} models : Object where keys match the 1st level form field names and the values are the model attributes that match the 2nd level, eg.: {Contact: {firstname: 'John', lastname: 'Doe'}, }
    
    function loadActiveForm(formSelector, models) {
        if (!(formSelector instanceof jQuery)) {
            formSelector = $(formSelector);
        }
    
        $.each(models, function(modelName, model) {
            $.each(model, function(attributeName, attributeValue) {
                $input = formSelector.find(':input[name="'+ modelName +'['+ attributeName +']"]');
                if ($input.length > 1) {
                    if ($input.first().is(':radio')) {
                        $input.each(function() {
                            if ($(this).val() == attributeValue) {
                                $(this).prop('checked', true).click();
                                if ($(this).closest('.btn').length > 0) {
                                    $(this).closest('.btn').button('toggle');
                                }
                            }
                        });
                    } else {
                        alert('In loadActiveForm an input had multiple tags but they are not radio buttons.');
                    }
                } else {
                    $input.val(attributeValue);
                }
            })
        });
    }