简体   繁体   中英

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>

So, if I understand you correctly, you want your controllers to save your model data via ajax?

If that's the case, you should take a look at ActiveControllers .

Basically, you will have:

  • index: list of models
  • view: return the details of a model
  • create: create a new model
  • update: update an existing model
  • delete: delete an existing model
  • options: return the allowed HTTP methods

exposed via different verbs to use them as an API.

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);
            }
        })
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM