Microsoft Dynamics CRM 2013/2015 选项集的多选

         CRM中的选项集多选一直是客户需求中的必选项,但从CRM进国内的3.0时代开始到目前的2015版本均没有提供该功能,但既然客户要了就得想办法满足,既然CRM本身的功能上不支持,那我们只有使用非官方支持的方法了,操作DOM。

      之前在2011中做过类似的功能,但最新无意中看到这篇博文:http://www.cnblogs.com/gnile/p/3429909.html,思路上要比我之前实现的要精简的多,顾决定重新实现下该功能,废话不多说,直接上代码。

      

function LoadOptions() {
    var fieldSchema = "optionlist";
    var optionSetValueList = Xrm.Page.getAttribute("new_optionlist").getOptions();
    var picklistValue = Xrm.Page.getAttribute("new_optionvalue").getValue();

    //step1:开始构建多选所需的html
    var appendHtml = "";
    //border:1px solid #f3f1f2;
    appendHtml += "<div style=\"padding-top:0px;padding-left:0px;padding-bottom:20px;padding-right:20px; margin-left:15px;\">";
    appendHtml += "<ul style=\"list-style:none;\">";

    for (var i = 0; i < optionSetValueList.length - 1; i++) {
        var checkboxId = "cb_" + fieldSchema + "_" + i;
        appendHtml += "<li style=\"float:left;display:block;padding-left:5px;\">";
        appendHtml += "<input type=\"checkbox\" value=\"" + optionSetValueList[i].value + "\" style=\"width:auto;\" class=\"" + fieldSchema + "\" id=\"" + checkboxId + "\" ";

        //step2:加载已经保存的选项
        if (picklistValue != null && picklistValue.indexOf(optionSetValueList[i].value + ":" + optionSetValueList[i].text + ";") > -1) {
            appendHtml += "checked=\"checked\"";
        }

        appendHtml += "/>";

        appendHtml += "<label for=\"" + checkboxId + "\">" + optionSetValueList[i].text + "</label>";
        appendHtml += "</li>";
    }

    appendHtml += "</ul>";
    appendHtml += "</div>";

    //step3:用构建好的html替换原先的picklist的html
    $("#new_optionlist_d").html(appendHtml);   
}

function OnSave()
{
    var saveValues = "";
    $(".optionlist").each(function () {
        if (this.checked) {
            saveValues += this.value + ":" + this.nextSibling.innerText + ";";
        }
    });

    Xrm.Page.getAttribute("new_optionvalue").setValue(saveValues);
}

      代码主要由两个方法组成,一个是formload的时候执行的LoadOptions方法,该方法即构造多选框,新建的时候新建多选框,编辑的时候呈现多选框的checked状态。其中用到两个字段,一个new_optionlist即选项集字段,一个new_optionvalue即保存复选框选中后的值,new_optionvalue中存值得格式为"value:text;",主要中在代码中的step2中。save方法中名为optionlist的即是我前面动态生成的type为checkbox的input的class,通过该方式取所有的checkbox来判断是否checked,如果是checked则取出它的value进行值得拼接。

      具体效果如下图,实际使用过程中需将下拉值也就是new_optionvalue字段隐藏,我这里显示出来主要是让你看下我前面所说的保存格式。

IE11效果图


Chrome效果图

Microsoft Edge效果图


IE9效果图


      这里需要说明下上述代码是拷贝的前面所提的博文并在他的基础上进行了些改进,并且我用的是getOptions这一API获取的选项集而非soap的方式,上面的截图提供了4种浏览器环境均OK没遇到他博文中说的情况,一时也找不到IE8所以没试应该也是OK的。

posted on 2015-11-06 15:06  代码王子  阅读(231)  评论(0编辑  收藏  举报

导航