代码之家  ›  专栏  ›  技术社区  ›  TheStoryCoder

yii2:有没有一种简单的方法可以用javascript中的值加载现有的activeform?

  •  0
  • TheStoryCoder  · 技术社区  · 7 年前

    我在一个单页应用程序上有一个现有的yii2活动表单(如下所示),我想通过ajax将新值加载到其中。是否已经有了一个简单的方法,或者我需要自己的javascript函数来做到这一点?

    <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>
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Chux    7 年前

    所以,如果我理解正确,您希望您的控制器通过Ajax保存您的模型数据吗?

    如果是这样的话,你应该看看 ActiveControllers .

    基本上,你会有:

    • 索引:模型列表
    • 视图:返回模型的详细信息
    • 创建:创建新模型
    • 更新:更新现有模型
    • 删除:删除现有模型
    • 选项:返回允许的HTTP方法

    通过不同的动词公开以用作API。

        2
  •  0
  •   TheStoryCoder    7 年前

    我最终创建了自己的javascript函数。欢迎改进。

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