jqGrid应用--销售管理

  1. 管理界面,jsp页面

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>销售信息管理</title>
    <meta name="decorator" content="default"/>
    <%@include file="/WEB-INF/views/include/dialog.jsp" %>
    <style type="text/css">.sort{color:#0663A2;cursor:pointer;}</style>
      <link rel="stylesheet" type="text/css" href="${ctxStatic}/assets/css/jquery-ui-1.11.4.custom.css" />
    <link rel="stylesheet" type="text/css" href="${ctxStatic}/assets/css/uncompressed/ui.jqgrid-bootstarp.4.8.2.css" />
    <link rel="stylesheet" type="text/css" href="${ctxStatic}/assets/css/uncompressed/ui.jqgrid.4.8.2.css" />
    <link rel="stylesheet" type="text/css" href="${ctxStatic}/assets/css/uncompressed/ui.multiselect.4.8.2.css" />
    <script src="${ctxStatic}/assets/js/uncompressed/jqGrid/jquery.jqGrid.4.8.2.js" type="text/javascript"></script>
    <script src="${ctxStatic}/assets/js/jqGrid/i18n/grid.locale-cn.js" type="text/javascript"></script>
    <script src="${ctxStatic}/assets/js/uncompressed/jqGrid/jquery.tablednd.js" type="text/javascript"></script>
    <script type="text/javascript" src="${ctxStatic}/jquery-jbox/2.3/jquery.jBox-2.3.min.js"></script>
    <script type="text/javascript" src="${ctxStatic}/jquery-jbox/2.3/i18n/jquery.jBox-zh-CN.min.js"></script>
  
    <link rel="stylesheet" href="${ctxStatic}/print/css/print.css" type="text/css" media="print" />
    <link rel="stylesheet" href="${ctxStatic}/print/css/print-preview.css" type="text/css" media="screen">
    <link rel="stylesheet" href="${ctxStatic}/print/css/print-preview.css" type="text/css" media="screen" />
    <script src="${ctxStatic}/print/js/jquery.print-preview.js" type="text/javascript" charset="utf-8"></script>

    <script type="text/javascript">

        var saleId = "${saleId}";
        jQuery("#jqGrid").tableDnD({scrollAmount:0});

        function name_input(value, options) {//弹出框选择
            return $("<input type='text' value='"+value+"' onClick='relationDetectTask(this)'/>");
        }
        function name_value(value) {
            return value.val();
        }

        function batch_input(value, options) { //弹出框选择
            //return $('<input type="text" value="'+value+'" onClick="relationObj(this,"batch", "es/batch", "生产批次")"/>');
            return $('<input type="text" value="'+value+'" onClick="relationObj(this,\'batch\', \'es/batch\', \'生产批次\')"/>');
        }

        function quantity_input(value, options) {
            return $("<input type='text' value='"+value+"' onChange='countAmount(this)' />");
        }
        function quantity_value(value) {
            return value.val();
        }


          $(document).ready(function () {
            var template = "";

            $("#jqGrid").jqGrid({
                url: '${ctx}/es/saleDetail/findListBySale?saleId=' + saleId,
                // we set the changes to be made at client side using predefined word clientArray
                //editurl: '${ctx}/es/saleDetail/save',
                editurl: 'clientArray',//行内编辑时不提交
                datatype: "json",
                colModel: [
                    {
                        label: 'goodsId',
                        name: 'goodsId',
                        width: 10,
                        hidden:true,
                        editable: true // must set editable to true if you want to make the field editable
                    },
                    {
                        label: 'saleDetailId',
                        name: 'id',
                        width: 10,
                        hidden:true,
                        editable: true // must set editable to true if you want to make the field editable
                    },
                    {
                        label: '商品名称',
                        name: 'goodsName',
                        width: 140,
                        editable: true, // must set editable to true if you want to make the field editable
                        edittype:'custom',
                        editoptions:{
                            custom_element:name_input,
                            custom_value:name_value
                        }
                    },
                    {
                        label: '单价',
                        name: 'price',
                        width: 30,
                        align:"right",
                        editable:true,
                        editrules:{number:true},
                        edittype:'custom',
                        editoptions:{
                            custom_element:quantity_input,
                            custom_value:quantity_value
                        }
                    },
                    {
                        label: '单位',
                        name: 'unit',
                        width: 30,
                        align:'right',
                        editable:true,
                        edittype:'text'
                    },
                    {
                        label : '数量',
                        name: 'quantity',
                        width: 30,
                        align:"right",
                        editable:true,
                        edittype:'custom',
                        editoptions:{
                            custom_element:quantity_input,
                            custom_value:quantity_value
                        }
                    },
                    {
                        label: '金额',
                        name: 'amount',
                        width: 60,
                        align:"right",
                        editable:true,
                        editrules:{number:true} //editrules:{custom:true, custom_func:mypricecheck}自定义验证
                    },
                    {
                        label: 'reportId',
                        name: 'reportId',
                        width: 10,
                        hidden:true,
                        editable: true // must set editable to true if you want to make the field editable
                    },
                    {
                        label: 'batchId',
                        name: 'batchId',
                        width: 10,
                        hidden:true,
                        editable: true // must set editable to true if you want to make the field editable
                    },
                    {
                        label: '生产批次',
                        name: 'batchNo',
                        width: 80,
                        editable:true,
                        edittype:'custom',
                        editoptions:{
                            custom_element:batch_input,
                            custom_value:name_value
                        }
                    },
                    {
                        label: '备注',
                        name: 'remarks',
                        width: 80,
                        align:'left',
                        editable: true,
                        edittype:'text'
                    }
                ],
                rownumbers:true,//添加左侧行号  
                rownumWidth:10, 
                sortname: 'goodsName',//排序
                sortorder : 'asc',
                loadonce: true,
                viewrecords: true,
                //width: auto,
                autowidth:true,//自动宽
                height: 200,
                rowNum: 10,
                pager: "#jqGridPager",
                viewrecords : true,
                footerrow : true,
                userDataOnFooter : true,
                altRows : true,
                gridComplete: function() {
                    //$("#_empty","#listdnd").addClass("nodrag nodrop");
                    //jQuery("#listdnd").tableDnDUpdate();
                    setFooterData();//设置表格页脚
                }
            });
            $('#jqGrid').navGrid("#jqGridPager", {edit: false, add: false, del: true, refresh: true, view: false});
            $('#jqGrid').inlineNav('#jqGridPager',
                // the buttons to appear on the toolbar of the grid
                { 
                    edit: true, 
                    add: true, 
                    del: true, 
                    cancel: true,
                    editParams: {
                        keys: true,
                        aftersavefunc: function( rowid, response ){
                            setFooterData();//编辑完成后设置表格页脚
                            return true;
                        }
                    },
                    addParams: {
                        addRowParams: {
                            url: 'clientArray',
                            key: true,
                            restoreAfterError: false,
                            aftersavefunc: function(rowId) {
                               setFooterData();//编辑完成后设置表格页脚
                            }
                        }
                    },
                    delParams: {
                        keys: true,
                        aftersavefunc: function( rowid, response ){
                            setFooterData();//删除完成后设置表格页脚
                            return true;
                        }
                    },
                    refresh: true
                });

            
            /*
             * Initialise print preview plugin
             */
            // Add link for print preview and intialise
            //$('#aside').prepend('<a class="print-preview">打印</a>');
             $('a.print-preview').printPreview();
            
            // Add keybinding (not recommended for production use)
            $(document).bind('keydown', function(e) {
                var code = (e.keyCode ? e.keyCode : e.which);
                if (code == 80 && !$('#print-modal').length) {
                    $.printPreview.loadPrintPreview();
                    return false;
                }            
            });
        });

        function countPreferenceSum(){//表格页脚计算
            var amountSum = parseFloat($("#jqGrid").getCol("amount",false,'sum')).toFixed(2);
            var preferenceAmount =  $("#preferenceAmount").val();
            if("" != preferenceAmount){
                 amountSum = amountSum - parseFloat(preferenceAmount).toFixed(2);
            }
            $("#preferenceSum").val(amountSum);
        }

        function relationDetectTask(obj){//弹出框选择
            top.$.jBox.open("iframe:${ctx}/sale/selectList?pageSize=8", "选择一项商品",$(top.document).width()-620,$(top.document).height()-300,{
                buttons:{"确定":true}, loaded:function(h){
                    $(".jbox-content", top.document).css("overflow-y","hidden");
                },submit:function(v, h, f){
                   if (v == true){
                        var cwd =h.find("iframe")[0].contentWindow; 
                        var ids = cwd.document.getElementsByName("id");
                        if (ids.length > 0) {
                            for (var i = 0; i < ids.length; i++){
                                if (ids[i].checked == true){
                                    var _trobj = $(ids[i]).parent().parent();
                                    var selectRow = jQuery("#jqGrid").jqGrid('getGridParam','selrow');
                                    $("#"+selectRow+"_goodsId").val($(_trobj.find("#id")).val());
                                    $("#"+selectRow+"_goodsName").val($(_trobj.find("#name")).val());
                                    $("#"+selectRow+"_price").val($(_trobj.find("#price")).val());
                                    $("#"+selectRow+"_unit").val($(_trobj.find("#unit")).val());
                                    top.$.jBox.tip.mess="";
                                    return true;
                                }
                            }
                        }
                        top.$.jBox.info('请选择一项商品!');
                        return false;
                    }
                }
            });
        }
        
        function relationObj(obj, colName, url, msg){//弹出框选择,公共方法
            top.$.jBox.open("iframe:${ctx}/"+url+"/selectList?pageSize=8", "选择一项"+msg,$(top.document).width()-620,$(top.document).height()-300,{
                buttons:{"确定":true}, loaded:function(h){
                    $(".jbox-content", top.document).css("overflow-y","hidden");
                },submit:function(v, h, f){
                   if (v == true){
                        var cwd =h.find("iframe")[0].contentWindow; 
                        var ids = cwd.document.getElementsByName("id");
                        if (ids.length > 0) {
                            for (var i = 0; i < ids.length; i++){
                                if (ids[i].checked == true){
                                    var _trobj = $(ids[i]).parent().parent();
                                    var selectRow = jQuery("#jqGrid").jqGrid('getGridParam','selrow');
                                    $("#"+selectRow+"_"+colName+"Id").val($(_trobj.find("#id")).val());
                                    $("#"+selectRow+"_"+colName+"No").val($(_trobj.find("#"+colName+"No")).val());
                                    top.$.jBox.tip.mess="";
                                    return true;
                                }
                            }
                        }
                        top.$.jBox.info('请选择一项'+msg+'!');
                        return false;
                    }
                }
            });
        }
        function countAmount(obj){//总金额计算
             var selectRow = jQuery("#jqGrid").jqGrid("getGridParam","selrow");
             var amount = parseFloat($("#"+selectRow+"_price").val()).toFixed(4) * parseFloat($("#"+selectRow+"_quantity").val()).toFixed(4);
             $("#"+selectRow+"_amount").val(amount);
        }

        function setFooterData(){{//表格页脚计算
            var records =   parseInt(jQuery("#jqGrid").jqGrid('getGridParam','records'),10);
            if(records>0){
                $(".ui-jqgrid-sdiv").show();
                var quantitySum=parseFloat($("#jqGrid").getCol("quantity",false,'sum')).toFixed(2);
                var amountSum=parseFloat($("#jqGrid").getCol("amount",false,'sum')).toFixed(2);
                $("#amountSum").val(amountSum);
                $("#quantitySum").val(quantitySum);
                $("#jqGrid").footerData('set',{price:"合计:",quantity:quantitySum,amount:amountSum});
            }else{
                $(".ui-jqgrid-sdiv").hide();
            }
        }

        function saveSale(){//提交
            var ids = $("#jqGrid").getDataIDs();
            var re;
            var type;
            var mty_num=0;
            var strparm="{";

            //jQuery('#rowed2').saveRow();
            var selectRow = jQuery("#jqGrid").jqGrid("getGridParam","selrow");
            if(null != selectRow){
                if(document.all) {
                    document.getElementById("jqGrid_ilsave").click();
                }
                // 其它浏览器
                else {
                    var e = document.createEvent("MouseEvents");
                    e.initEvent("click", true, true);
                    document.getElementById("jqGrid_ilsave").dispatchEvent(e);
                }
            }
            
            var validator = $("#inputForm").validate();
            if(!validator.form()){
                return;
            }
            var obj = new Array();

            $.each(ids,function(i,id){
                re=$("#jqGrid").jqGrid("getRowData",id);

                var id = re.id;
                var goodsId = re.goodsId;
                var quantity = re.quantity;
                var amount = re.amount;
                var price = re.price;
                var unit = re.unit;
                var batchId = re.batchId;
                var remarks = re.remarks;
                var saleDetail = {
                    id:id,
                    quantity:quantity,
                    amount:amount,
                    price:price,
                    unit:unit,
                    batchId:batchId,
                    remarks:remarks
                }
                obj.push(saleDetail);
            });
            var json = JSON.stringify(obj);
            var options = {    
                //target:        '#output1',   // target element(s) to be updated with server response    
                //beforeSubmit:  showRequest,  // pre-submit callback    
                success:function(data) {
                    $.jBox.tip(data, 'info');
                },  // post-submit callback    
                error:function(data){
                    $.jBox.info('操作失败!');
                },
                // other available options:    
                url:"${ctx}/sale/saveSale?saleDetailListJson=" + json,// override for form's 'action' attribute    
                type:"post",        // 'get' or 'post', override for form's 'method' attribute    
                //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)    
                //clearForm: true       // clear all form fields after successful submit    
                resetForm: false        // reset the form after successful submit    

                // $.ajax options can be used here too, for example:    
                //timeout:   3000    
            };
            $('#inputForm').ajaxSubmit(options);

        }
    </script>
    
    <style>

    .bs-docs-example {
        position: relative;
        margin: 15px 0;
        padding: 39px 19px 14px;
        *padding-top: 19px;
        background-color: #fff;
        border: 1px solid #ddd;
        -webkit-border-radius: 4px;
         -moz-border-radius: 4px;
              border-radius: 4px;
    }

    .bs-docs-example:after {
        content: "";
        position: absolute;
        top: -1px;
        left: -1px;
        padding: 3px 7px;
        font-size: 12px;
        font-weight: bold;
        background-color: #f5f5f5;
        border: 1px solid #ddd;
        color: #9da0a4;
        -webkit-border-radius: 4px 0 4px 0;
         -moz-border-radius: 4px 0 4px 0;
              border-radius: 4px 0 4px 0;
    }

    .prettyprint.linenums {
      -webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
         -moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
              box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
    }

    .prettyprint {
      padding:0px 0px 0px 0px;
      background-color: #f7f7f9;
      border: 1px solid #e1e1e8;
    }
    .prettyprint2 {
      padding:5px 5px 5px 15px;
      background-color: #f7f7f9;
      border: 1px solid #e1e1e8;
    }
    
    .prettyprint.linenums {
      -webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
         -moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
              box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
    }

    /* Specify class=linenums on a pre to get line numbering */
    ol.linenums {
      margin: 0 0 0 33px; /* IE indents via margin-left */
    }
    ol.linenums li {
      padding-left: 12px;
      color: #bebec5;
      line-height: 20px;
      text-shadow: 0 1px 0 #fff;
    }
    </style>
</head>
<body>
    <form:form id="inputForm" modelAttribute="sale" action="${ctx}/sale/saveSale" method="post" class="viewprint form-horizontal">
        <form:hidden path="id"/>
        <form:hidden path="quantitySum"/>
        <form:hidden path="amountSum"/>
        <tags:message content="${message}"/>
        <div class="pull-right">
            <table border="0" cellspacing="0" cellpadding="0">   
                <tr>
                    <!--<td align="left"><div><h3>销售订单</h3></div></td>-->
                    <td><label>录单日期  </label></td>
                    <td align="left">
                        <input id="recordDate" name="recordDate" type="text" readonly="readonly" maxlength="10" style="height:14px" class="input-small Wdate"
                            value="<fmt:formatDate value="${sale.recordDate}" pattern="yyyy-MM-dd"/>"
                            onclick="WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:true});"/>
                    </td>
                    <td><label> 编号  </label></td>
                    <td align="left"><form:input path="saleNo" htmlEscape="false" maxlength="30" style="height:14px" class="input-medium required"/></td>
                </tr>
            </table>
        </div>
        <br/><br/>
        <div class="prettyprint2">
            购买单位  
            <form:input path="purchaseCompany" htmlEscape="false" maxlength="100" class="input-large required"/>
              采购人  <form:input path="purchaser" htmlEscape="false" maxlength="30" class="input-small required"/>
              采购人电话  <form:input path="purchaserTel" htmlEscape="false" maxlength="32" class="input-small required"/>
        </div>
        <p></p>
        <!--<table id="list4"  border="0" cellspacing="0" cellpadding="0" class="clearfix" ></table>-->
        <table id="jqGrid"></table>
        <div id="jqGridPager"></div>
        <p></p>
        <div class="pull-left">
            制单人: <shiro:principal property="name"/>
        </div>
        <br/><br/><br/><br/>
        <div class="clearfix pull-right">
            <a class="btn" href="${ctx}/sale/form?id=${sale.id}&type=print">打印</a>
            <shiro:hasPermission name="es:sale:edit"><input id="btnSubmit" class="btn btn-primary" type="button" value="保存" onClick="saveSale()"/> </shiro:hasPermission>
            <input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
        </div>
    </form:form>
</body>
</html>

 
 

2. 保存

</pre><pre name="code" class="java">    @ResponseBody
    public String saveSale(Sale sale, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, 
            HttpServletResponse response) {
        response.setContentType("application/json; charset=UTF-8");
        String requestMsg = ApiUtils.getRequestURL(request);
        String saleDetailListJson = StringUtils.trimToNull(request.getParameter("saleDetailListJson"));
        JsonMapper jsonMapper = JsonMapper.getInstance();
        JavaType javaType = jsonMapper.createCollectionType(List.class, SaleDetail.class);
        List<SaleDetail> saleDetailList = jsonMapper.fromJson(saleDetailListJson, javaType);

        saleService.save(sale);
        saleDetailService.save(saleDetailList);
        return "保存销售成功";
    }


你可能感兴趣的:(jqGrid)