Aisell-day07

1.创建domain

产品表
@Entity
@Table(name = "product")
public class Product extends BaseDomain {

   private String name; //产品名称 
   private String color; //产品颜色
   private String pic; //大图片
   private String smallPic;//小图片
   private BigDecimal costPrice;//成本价
   private BigDecimal salePrice;//销售价
   
   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "types_id")
   private Producttype types;// 对应的二级产品类型
   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "unit_id")
   private Systemdictionarydetail unit;// 数据字典明细:单位
   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "brand_id")
   private Systemdictionarydetail brand;// 数据字典明细:品牌

    //getter,setter…
}
/**
 * 产品类型表
 * @author Administrator
 *
 */
@Entity
@Table(name="producttype")
public class Producttype  extends BaseDomain {

   private String name;//名称
   private String  descs;//描述
   //类型分两级,有一个自关联
   @ManyToOne(fetch=FetchType.LAZY)
   @JoinColumn(name="parent_id")
   private Producttype parent;

   //getter,setter…
}

ProductQuery

/**
 * 这是一个查询类(对象)
 * 接收前台传过来的查询数据
 */
public class ProductQuery extends BaseQuery {

    private String name;


    /**
     * 创建相应的查询规则并且返回这个规则
     * @return
     */
    @Override
    public Specification createSpecification(){
        Specification<Product> spec = Specifications.<Product>and()
                .like(StringUtils.isNotBlank(name),"name", "%"+name+"%")
                .build();
        return spec;
    }
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}


   
}

ProducttypeQuery

/**
 * 这是一个查询类(对象)
 * 接收前台传过来的查询数据
 */
public class ProducttypeQuery extends BaseQuery {

    private String name;


    /**
     * 创建相应的查询规则并且返回这个规则
     * @return
     */
    @Override
    public Specification createSpecification(){
        Specification<Producttype> spec = Specifications.<Producttype>and()
                .like(StringUtils.isNotBlank(name),"name", "%"+name+"%")
                .build();
        return spec;
    }
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}


   
}

ProductRepository

package cn.itsource.aisell.repository;

import cn.itsource.aisell.domain.Product;

public interface ProductRepository extends BaseRepository<Product,Long> {

}

ProducttypeRepository

package cn.itsource.aisell.repository;

import cn.itsource.aisell.domain.Producttype;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface ProducttypeRepository extends BaseRepository<Producttype,Long> {
    //查询子的选项
    @Query("select o from Producttype o where o.parent is not null")
    List<Producttype> findChildTypes();
}

IProductService

package cn.itsource.aisell.service;

import cn.itsource.aisell.domain.Product;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public interface IProductService extends  IBaseService<Product,Long> {
    /**
     * 保存产品,上传附件
     * @param product 产品对象
     * @param fileImage 附件
     * @param request 请求
     */
    void save(Product product, MultipartFile fileImage, HttpServletRequest request) throws IOException;
}

IProducttypeService

package cn.itsource.aisell.service;

import cn.itsource.aisell.domain.Producttype;

import java.util.List;

public interface IProducttypeService extends  IBaseService<Producttype,Long> {

    /**
     * 查询二级产品类型
     * @return
     */
    List<Producttype> findChildTypes();
}

ProductServiceImpl

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product,Long> implements IProductService {
    @Autowired
    private ProductRepository productRepository;

    @Override
    public void save(Product product, MultipartFile fileImage, HttpServletRequest request) throws IOException {
        //如果fileImage不为空就证明在上传
        if(fileImage.getSize() != 0L){
            //获取application上下文 四大作用域
            ServletContext servletContext = request.getServletContext();
            //获取upload的根路径
            String rootPath = servletContext.getRealPath("/");
            //如果产品类型不为空,证明是修改图片
            if(product.getId() != null && StringUtils.isNotBlank(product.getPic())){
                //删除大图
                File file = new File(rootPath, product.getPic());
                file.delete();
                //删除小图
                file = new File(rootPath, product.getSmallPic());
                file.delete();
            }
            //随机产生名字 UUID 当前时间毫秒数
            long name = System.currentTimeMillis();//3434543534534534
            //获取上传附件的名字
            String filename = fileImage.getOriginalFilename();//a.png
            //获取文件的后缀名
            String extension = FilenameUtils.getExtension(filename);//png
            //最终生成小图的名字
            String smallFileName = name + "_small." + extension;//3434543534534534_small.png
            //最终生成文件的名字(大图)
            String bigFileName = name + "." + extension;//3434543534534534.png
            //存储大图的路径
            String filePath = "/upload/" + bigFileName;//    /upload/3434543534534534.png
            //存储小图的路径
            String smallFilePath = "/upload/" + smallFileName;//  /upload/3434543534534534_small.png
            //大图的绝对路径
            File file = new File(rootPath, filePath);//   E:\ideaProject\target\aisell/upload/3434543534534534.png
            //如果图片的父文件夹不存在,则创建
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            //获取输出流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            //上传的核心代码
            IOUtils.copy(fileImage.getInputStream(),fileOutputStream);

            //大图上传完毕之后,则把路径设置到product中
            product.setPic(filePath);
            //压缩小图 --压缩小图 scale 压缩比例
            Thumbnails.of(fileImage.getInputStream()).scale(0.2f).toFile(new File(rootPath,smallFilePath));//E:\ideaProject\aisell\target/upload/3434543534534534_small.png
            //小图设置完毕之后,把路径设置到product中
            product.setSmallPic(smallFilePath);
            fileOutputStream.close();
        }
        super.save(product);
    }
}

ProducttypeServiceImpl

@Service
public class ProducttypeServiceImpl extends BaseServiceImpl<Producttype,Long> implements IProducttypeService {
    @Autowired
    private ProducttypeRepository producttypeRepository;

    @Override
    public List<Producttype> findChildTypes() {
        return producttypeRepository.findChildTypes();
    }
}

ProductController

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 跳到主页面
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "product/product";
    }

    /**
     * 获取列表
     * @return
     */
    @RequestMapping("/page")
    @ResponseBody
    public PageUi datagrid(ProductQuery query){
        Page page = productService.findPageByQuery(query);
        //把Page对象转为UIPage
        PageUi uipage = new PageUi(page);
        return uipage;

    }


    //当你在方法上面打上此注解之后,意思就是,在执行任何方法之前,都要先执行@ModelAttribute对应的方法
    @ModelAttribute("updateProduct")
    public Product beforeEdit(Product product,String cmd){
        if(product.getId()!= null && StringUtils.isNotBlank(cmd)){
            product = productService.findOne(product.getId());
            //凡是关联对象都必须清空,否则会报n2n问题
            product.setTypes(null);
            product.setUnit(null);
            product.setBrand(null);
        }
        return product;
    }

    /**
     * 保存数据
     * @param product
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public AjaxResult save(Product product, HttpServletRequest request){
        return saveOrUpdate(product,request);
    }
    @RequestMapping("/update")
    @ResponseBody
    public AjaxResult update(@ModelAttribute("updateProduct") Product product,HttpServletRequest request){
        return saveOrUpdate(product,request);
    }

    private AjaxResult saveOrUpdate(Product product, HttpServletRequest request){
        try {
            //下面是解决上传文件为空报错的问题
            MultipartFile fileImage = null;
            //如果获取值是true  说明表单里面添加 enctype="multipart/form-data"
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart){
                MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
                //获取前台传递的文件
                fileImage = multipartRequest.getFile("file");
            }
            productService.save(product,fileImage,request);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult( "操作失败" + e.getMessage());
        }
    }

    /**
     * 删除数据
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult delete(Long[] ids,HttpServletRequest request){
        try {
            for (Long id : ids) {
                Product product = productService.findOne(id);
                ServletContext servletContext = request.getServletContext();
                //获取upload的根路径
                String rootPath = servletContext.getRealPath("/");
                if(StringUtils.isNotBlank(product.getPic())){
                    //删除大图
                    File file = new File(rootPath, product.getPic());
                    file.delete();
                    //删除小图
                    file = new File(rootPath, product.getSmallPic());
                    file.delete();
                }
                //删除数据
                productService.delete(id);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return  new AjaxResult( "删除失败!" + e.getMessage());
        }
    }


}

ProducttypeController

@Controller
@RequestMapping("/producttype")
public class ProducttypeController {

    @Autowired
    private IProducttypeService producttypeService;

    /**
     * 跳到主页面
     * @return
     */
    @RequestMapping("/index")
    public String index(){
        return "producttype/producttype";
    }

    /**
     * 获取列表
     * @return
     */
    @RequestMapping("/page")
    @ResponseBody
    public PageUi page(ProducttypeQuery query){
        Page page = producttypeService.findPageByQuery(query);
        PageUi uipage = new PageUi(page);
        //把Page对象转为UIPage
        return uipage;
    }


    //当你在方法上面打上此注解之后,意思就是,在执行任何方法之前,都要先执行@ModelAttribute对应的方法
    @ModelAttribute("updateProducttype")
    public Producttype beforeEdit(Producttype producttype,String cmd){
        if(producttype.getId()!= null && StringUtils.isNotBlank(cmd)){
            producttype = producttypeService.findOne(producttype.getId());
            //凡是关联对象都必须清空,否则会报n2n问题
        }
        return producttype;
    }

    /**
     * 保存数据
     * @param producttype
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public AjaxResult save(Producttype producttype){
        return saveOrUpdate(producttype);
    }
    @RequestMapping("/update")
    @ResponseBody
    public AjaxResult update(@ModelAttribute("updateProducttype") Producttype producttype){
        return saveOrUpdate(producttype);
    }

    private AjaxResult saveOrUpdate(Producttype producttype){
        try {
            producttypeService.save(producttype);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult( "操作失败" + e.getMessage());
        }
    }

    /**
     * 删除数据
     * @param ids
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResult delete(Long[] ids){
        try {
            for (Long id : ids) {
                producttypeService.delete(id);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return  new AjaxResult("删除失败!" + e.getMessage());
        }
    }


}

UtilController

@Controller
@RequestMapping("/util")
public class UtilController {

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private ISystemdictionarydetailService systemdictionarydetailService;

    @Autowired
    private IProducttypeService producttypeService;
    @Autowired
    private IProductService productService;

    @RequestMapping("/queryDepartment")
    @ResponseBody
    public List<Department> queryDepartment(){
        return departmentService.findAll();
    }

    //findMenuByUserId
    @RequestMapping("/findMenuByUserId")
    @ResponseBody
    public List<Menu> findMenuByUserId() {
        //当前用户ID
        Employee employee = (Employee)UserContent.getUser();
        return menuService.findMenuByLoginUser(employee.getId());
    }

    /**
     * 查询所有品牌
     * @return
     */
    @RequestMapping("/findBrands")
    @ResponseBody
    public List<Systemdictionarydetail> findBrands(){
        return systemdictionarydetailService.findDetailsBySn(Systemdictionarytype.PRODUCT_BRAND);
    }

    /**
     * 查询所有单位
     * @return
     */
    @RequestMapping("/findUnits")
    @ResponseBody
    public List<Systemdictionarydetail> findUnits(){
        return systemdictionarydetailService.findDetailsBySn(Systemdictionarytype.PRODUCT_UNIT);
    }

    /**
     * 查询所有的产品类型
     * @return
     */
    @RequestMapping("/findTypes")
    @ResponseBody
    public List<Producttype> findTypes(){
        return producttypeService.findChildTypes();
    }

    /**
     * 查询所有的产品对象
     * @return
     */
    @RequestMapping("/findProduts")
    @ResponseBody
    public List<Product> findProduts(){
        return productService.findAll();
    }

}

前端部分 product.jsp

  <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%@include file="/WEB-INF/head.jsp" %>
    <script type="text/javascript" src="/js/product.js"></script>
    <script type="text/javascript" src="/easyui/plugin/tooltip/jeasyui.extensions.base.tooltip.js"></script>

</head>
<body>

<%--弹出框对应的按钮--%>
<div id="bb">
    <a href="javascript:void(0);" data-method="saveData" class="easyui-linkbutton c3" data-options="plain:true">保存</a>
    <a href="javascript:void(0);" onclick="$('#dlg').dialog('close')" class="easyui-linkbutton c4"
       data-options="plain:true">关闭</a>
</div>
<%--
        easyui的时候,查看默认属性与事件
       $.fn.{plugin}.defaults
        弹出框html代码
    --%>
<div id="dlg" class="easyui-dialog" data-options="width:300,height:310,buttons:'#bb',closed:true">
    <form id="ff" method="post" enctype="multipart/form-data">
        <input id="eid" type="hidden" name="id">
        <table cellpadding="5">
            <tr>
                <td>名称:</td>
                <td><input class="easyui-textbox" type="text" name="name"></input></td>
            </tr>
            <tr>
                <td>颜色:</td>
                <td>
                    <input class="easyui-textbox" type="color"   name="color"></input>
                </td>
            </tr>
            <tr>
                <td>成本价:</td>
                <td><input class="easyui-textbox" type="text" name="costPrice"></input></td>
            </tr>
            <tr>
                <td>销售价:</td>
                <td><input class="easyui-textbox" type="text" name="salePrice"></input></td>
            </tr>
            <tr>
                <td>单位:</td>
                <td>
                    <input class="easyui-combobox" name="unit.id"
                           data-options="
                        url: '/util/findUnits',
                        method: 'get',
                        valueField:'id',
                        textField:'name',
                        panelHeight:'auto'     <%--自适应高度--%>
                    ">
                </td>
            </tr>
            <tr>
                <td>品牌:</td>
                <td>
                    <input class="easyui-combobox" name="brand.id"
                           data-options="
                        url: '/util/findBrands',
                        method: 'get',
                        valueField:'id',
                        textField:'name',
                        panelHeight:'auto'     <%--自适应高度--%>
                    ">
                </td>
            </tr>
            <tr>
                <td>类型:</td>
                <td>
                    <input class="easyui-combobox" name="types.id"
                           data-options="
                        url: '/util/findTypes',
                        method: 'get',
                        valueField:'id',
                        textField:'name',
                        groupField:'group'
                    ">
                </td>
            </tr>
            <tr>
                <td>产品图片:</td>
                <td>
                    <input class="easyui-filebox" name="file" data-options="prompt:'图片', buttonText: '选择图片'">
                </td>
            </tr>


        </table>
    </form>
</div>


<%--查询工具栏--%>
<div id="tb" style="padding:10px;height:auto">
    <div>
        <form id="searchForm">
            姓名: <input name="name" class="easyui-textbox" style="width:120px">
            <a href="javascript:void(0);" data-method="search" class="easyui-linkbutton" iconCls="icon-search">搜索</a>
        </form>
    </div>
    <div style="margin-bottom:5px">
        <a href="javascript:void(0);" data-method="add" class="easyui-linkbutton" iconCls="icon-add" plain="true"></a>
        <a href="javascript:void(0);" data-method="edit" class="easyui-linkbutton" iconCls="icon-edit" plain="true"></a>
        <a href="javascript:void(0);" data-method="delete" class="easyui-linkbutton" iconCls="icon-remove"
           plain="true"></a>
    </div>
</div>

<table id="dg"  class="easyui-datagrid" title="员工管理"
           data-options="url:'/product/page',
           fit:true,
           pagination:true,
           rownumbers:true,
           toolbar:'#tb',
           onLoadSuccess:loadSuccess  <%-- 当页面渲染完毕之后才执行onLoadSuccess对应的函数--%>
        ">
        <thead>
        <tr>
            <th data-options="field:'id',checkbox:true,width:'2%'">ID</th>
            <th data-options="field:'name',width:'12%',align:'center'">名称</th>
            <th data-options="field:'color',width:'12%',align:'center',formatter:formatColor">颜色</th>
            <th data-options="field:'smallPic',width:'14%',align:'center',formatter:formatImg">图片</th>
            <th data-options="field:'costPrice',width:'12%',align:'center'">成本价</th>
            <th data-options="field:'salePrice',width:'12%',align:'center'">销售价</th>
            <th data-options="field:'types',width:'12%',align:'center',formatter:formatterTypes">类型</th>
            <th data-options="field:'unit',width:'12%',align:'center',formatter:formatterTypes">单位</th>
            <th data-options="field:'brand',width:'12%',align:'center',formatter:formatterTypes">品牌</th>
        </tr>
        </thead>
    </table>
</body>
</html>

producttype.jsp

<html>
<head>
    <title>Title</title>
    <%@include file="/WEB-INF/head.jsp"%>
    <script type="text/javascript" src="/js/producttype.js"></script>
</head>
<body>

    <%--弹出框对应的按钮--%>
    <div id="bb">
        <a href="javascript:void(0);" data-method="saveData" class="easyui-linkbutton c3" data-options="plain:true">保存</a>
        <a href="javascript:void(0);" οnclick="$('#dlg').dialog('close')" class="easyui-linkbutton c4"  data-options="plain:true">关闭</a>
    </div>

<%--
        easyui的时候,查看默认属性与事件
       $.fn.{plugin}.defaults
        弹出框html代码
    --%>
    <div id="dlg" class="easyui-dialog" data-options="width:300,height:310,buttons:'#bb'" >
        <form id="ff" method="post">
            <input id="eid" type="hidden" name="id">
            <table cellpadding="5">
                                                                                                                                
                                                                                                                        
                                                                                                                        
                                                                                
                                                    <tr>
                        <td>name:</td>
                        <td><input class="easyui-textbox" type="text" name="name" ></input></td>
                    </tr>
                                    <tr>
                        <td>descs:</td>
                        <td><input class="easyui-textbox" type="text" name="descs" ></input></td>
                    </tr>
                                    <tr>
                        <td>parentId:</td>
                        <td><input class="easyui-textbox" type="text" name="parentId" ></input></td>
                    </tr>
                                
  
            </table>
        </form>
    </div>

    <%--查询工具栏--%>
    <div id="tb" style="padding:10px;height:auto">
        <div>
            <form id="searchForm">
                姓名: <input name="name" class="easyui-textbox" style="width:120px">
                <a href="javascript:void(0);" data-method="search" class="easyui-linkbutton" iconCls="icon-search">搜索</a>
            </form>
        </div>
        <div style="margin-bottom:5px">
            <a href="javascript:void(0);" data-method="add" class="easyui-linkbutton" iconCls="icon-add" plain="true"></a>
            <a href="javascript:void(0);" data-method="edit" class="easyui-linkbutton" iconCls="icon-edit" plain="true"></a>
            <a href="javascript:void(0);" data-method="delete" class="easyui-linkbutton" iconCls="icon-remove" plain="true"></a>
        </div>
    </div>

    <table id="dg" class="easyui-datagrid" title="员工管理"
           data-options="url:'/producttype/datagrid',
           fit:true,
           pagination:true,
           rownumbers:true,
           toolbar:'#tb'
        ">
        <thead>
        <tr>
            <th data-options="field:'id',checkbox:true,width:'2%'">ID</th>
                                                                                                        
                                                                                                    
                                                                                                    
                                                                
                                        <th data-options="field:'name',width:'16%',align:'center'">name</th>
                            <th data-options="field:'descs',width:'16%',align:'center'">descs</th>
                            <th data-options="field:'parentId',width:'16%',align:'center'">parentId</th>
                    </tr>
        </thead>
    </table>
</body>
</html>

js部分


```javascript
/**
 * 格式化产品类型
 * @param v
 * @param r
 */
function formatterTypes(v,r){
    return v.name;
}
//图片展示
function formatImg(data) {
    return "<img src='"+data+"' width='50px' height='50px' alt='没有图片' />"
}
//转换颜色
function formatColor(data) {
    return "<div style='width: 20px;height: 20px;background-color: "+data+"'></div>"
}
function formatObj(data) {
    if(data){
        return data.name;
    }
}
//成功后进行加载
function loadSuccess(data) {
    //获取表格里面所有的行数据
    var rows = data.rows;
    for(var i=0;i<rows.length;i++){
        //取出每一行的数据
        var result = rows[i];
        $.easyui.tooltip.init($("img[src='"+result.smallPic+"']"), {
            position:"right",
            content: "<div style=\"width:100px;height:180px;\"><img src='"+result.pic+"'  /></div>"
        });
    }
}

$(function () {
    //给所有a标签都注册一个事件
    $("a").on("click", function () {
        //动态获取data-method属性对应的值
        var method = $(this).data("method");
        //method不能为空
        if(method){
            //动态触发事件

            itsource[method]();
        }
    });
    //datagrid对应的jquery对象
    var dg = $("#dg");
    //弹出框对应的jquery对象
    var dlg = $("#dlg");
    //form表单对应的jquery对象(弹出框)
    var ff = $("#ff");
    itsource = {
        //高级查询
        "search":function(){
            //把form表单元素,直接封装成一个json对象
            var jsonObj = $("#searchForm").serializeObject();
            //加载datagrid
            dg.datagrid('load',jsonObj);
        },
        //删除
        "delete":function(){
            //获取选中的行
            var rows = dg.datagrid("getSelections");
            //在js中认为false的值:0  false ""  null NaN  undefined
            if(!rows.length){
                $.messager.alert('操作错误','亲!请选中数据进行删除!','error');
                return;
            }
            //定义一个数组,该数组把所有的id都给装进来
            var ids = [];
            //循环数组中的所有数据
            $.each(rows, function (i, o) {
                //把id装进数组中
                ids.push(o.id);
            });
            $.messager.confirm('确认', '你确定要离我而去吗?', function(r){
                if (r){
                    $.get("/product/delete",{"ids":ids.toString()},function(result){
                        if(result.success){
                            //刷新界面
                            dg.datagrid("reload");
                        }else{
                            $.messager.alert('失败',result.msg,'error');
                        }
                    });
                }
            });

        },
        //添加按钮,弹出窗体
        "add":function(){
            //清空form表单中所有的值
            ff.form("clear");
            //弹出窗体,居中,并且设置标题,动态修改高度
            dlg.dialog("open").dialog("center").dialog("setTitle","添加产品").dialog("resize",{
                height:450
            });
        },
        //修改按钮,弹出窗体
        "edit":function(){
            //获取即将要修改的数据(单个对象)
            var row = dg.datagrid("getSelected");
            //没有选中就会返回null
            if(!row){
                $.messager.alert('操作错误','亲!请选中数据进行修改!','error');
                return;
            }
            //清空form表单
            ff.form("clear");
            //单位回显
            if(row.unit){
                row["unit.id"] = row.unit.id;
            }
            //品牌回显
            if(row.brand){
                row["brand.id"] = row.brand.id;
            }
            //产品类型回显
            if(row.types){
                row["types.id"] = row.types.id;
            }

            //回显操作
            ff.form('load',row);
            //弹出窗体,居中,设置标题  动态修改它的宽度和高度
            dlg.dialog("open").dialog("center").dialog("setTitle","修改员工").dialog("resize",{
                height:450
            });
        },
        //保存数据
        "saveData":function(){
            var url = "/product/save";
            if($("#eid").val()){
                url = "/product/update?cmd=update";
            }
            //提交form表单
            ff.form('submit', {
                url:url,
                onSubmit: function(){//提交之前先做验证
                    return ff.form("validate");//验证通过之后才返回true,否则返回false,false它会阻止你提交
                },
                success:function(data){
                    //把json字符串转为对象
                    var result = $.parseJSON(data);
                    if(result.success){
                        //关闭窗体
                        dlg.dialog("close");
                        //刷新界面
                        dg.datagrid("reload");
                    }else{
                        $.messager.alert('操作错误',result.msg,'error');
                    }
                }
            });
        }

    }
});
producttype.js
$(function () {
    //给所有a标签都注册一个事件
    $("a").on("click", function () {
        //动态获取data-method属性对应的值
        var method = $(this).data("method");
        //method不能为空
        if(method){
            //动态触发事件

            itsource[method]();
        }
    });
    //datagrid对应的jquery对象
    var dg = $("#dg");
    //弹出框对应的jquery对象
    var dlg = $("#dlg");
    //form表单对应的jquery对象(弹出框)
    var ff = $("#ff");
    itsource = {
        //高级查询
        "search":function(){
            //把form表单元素,直接封装成一个json对象
            var jsonObj = $("#searchForm").serializeObject();
            //加载datagrid
            dg.datagrid('load',jsonObj);
        },
        //删除
        "delete":function(){
            //获取选中的行
            var rows = dg.datagrid("getSelections");
            //在js中认为false的值:0  false ""  null NaN  undefined
            if(!rows.length){
                $.messager.alert('操作错误','亲!请选中数据进行删除!','error');
                return;
            }
            //定义一个数组,该数组把所有的id都给装进来
            var ids = [];
            //循环数组中的所有数据
            $.each(rows, function (i, o) {
                //把id装进数组中
                ids.push(o.id);
            });
            $.messager.confirm('确认', '你确定要离我而去吗?', function(r){
                if (r){
                    $.get("/producttype/delete",{"ids":ids.toString()},function(result){
                        if(result.success){
                            //刷新界面
                            dg.datagrid("reload");
                        }else{
                            $.messager.alert('失败',result.msg,'error');
                        }
                    });
                }
            });

        },
        //添加按钮,弹出窗体
        "add":function(){
            //清空form表单中所有的值
            ff.form("clear");
            //弹出窗体,居中,并且设置标题,动态修改高度
            dlg.dialog("open").dialog("center").dialog("setTitle","添加员工").dialog("resize",{
                height:350
            });
        },
        //修改按钮,弹出窗体
        "edit":function(){
            //获取即将要修改的数据(单个对象)
            var row = dg.datagrid("getSelected");
            //没有选中就会返回null
            if(!row){
                $.messager.alert('操作错误','亲!请选中数据进行修改!','error');
                return;
            }
            //清空form表单
            ff.form("clear");
            //回显操作
            ff.form('load',row);
            //弹出窗体,居中,设置标题  动态修改它的宽度和高度
            dlg.dialog("open").dialog("center").dialog("setTitle","修改员工").dialog("resize",{
                height:270
            });
        },
        //保存数据
        "saveData":function(){
            var url = "/producttype/save";
            if($("#eid").val()){
                url = "/producttype/update?cmd=update";
            }
            //提交form表单
            ff.form('submit', {
                url:url,
                onSubmit: function(){//提交之前先做验证
                    return ff.form("validate");//验证通过之后才返回true,否则返回false,false它会阻止你提交
                },
                success:function(data){
                    //把json字符串转为对象
                    var result = $.parseJSON(data);
                    if(result.success){
                        //关闭窗体
                        dlg.dialog("close");
                        //刷新界面
                        dg.datagrid("reload");
                    }else{
                        $.messager.alert('操作错误',result.msg,'error');
                    }
                }
            });
        }

    }
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值