ExtJS DataGrid如何展示Student关联Course的一对多多条课程记录
ExtJS DataGrid展示关联多行课程数据的实现方案
你当前仅能展示第一条课程的原因是renderer中调用了first()方法,仅取了关联课程store的第一条记录。可以根据业务需求选择以下三种方案实现:
方案1:平铺数据集,每行对应一门课程(最符合你期望的多行展示需求)
思路:不直接绑定Student模型的store到Grid,先将学生数据按关联课程展开,每门课程生成一条独立的Grid行记录,同时保留学生基础字段。
数据处理代码:
// 假设studentStore为加载学生数据的源store,grid为目标表格组件 let gridDataSource = []; studentStore.each(studentRecord => { // 取当前学生的所有关联课程 const allCourses = studentRecord.course().getRange(); allCourses.forEach(courseRecord => { // 拼接学生+课程字段生成单条行数据 gridDataSource.push({ name: studentRecord.get('name'), studentid: studentRecord.get('studentid'), address: studentRecord.get('address'), courseid: courseRecord.get('courseid'), coursename: courseRecord.get('coursename'), coursecode: courseRecord.get('coursecode') }); }); }); // 将处理后的数据加载到Grid绑定的store grid.getStore().loadData(gridDataSource);
Grid列配置(无需自定义renderer):
columns: [ {dataIndex: 'name', text: '学生姓名', flex: 1}, {dataIndex: 'studentid', text: '学号', flex: 1}, {dataIndex: 'coursecode', text: 'COURSECODE', flex: 1}, {dataIndex: 'coursename', text: 'COURSENAME', flex: 1} ]
配置后即可实现每门课程单独占一行的展示效果。
方案2:使用RowExpander行扩展插件(适合以学生行为主,点击查看课程的场景)
如果不需要平铺所有课程,仅需每个学生显示一行,点击行后展开查看关联课程,可使用ExtJS自带的RowExpander插件:
Grid配置:
plugins: [{ ptype: 'rowexpander', rowBodyTpl: new Ext.XTemplate( '<table style="width:100%;padding-left: 20px;">', '<tr><th style="width: 120px;text-align:left;">COURSECODE</th><th style="text-align:left;">COURSENAME</th></tr>', '<tpl for="course">', '<tr><td>{coursecode}</td><td>{coursename}</td></tr>', '</tpl>', '</table>' ) }], columns: [ {dataIndex: 'name', text: '学生姓名', flex: 1}, {dataIndex: 'studentid', text: '学号', flex: 1}, {dataIndex: 'address', text: '地址', flex: 2} ]
方案3:单元格内多行展示(适合单学生行内展示所有课程的场景)
如果不需要拆分学生行,可修改renderer将所有课程用换行符拼接,在单个单元格内多行展示:
列配置:
viewConfig: { getRowClass: function() { return 'multi-line-cell'; } }, columns:[ { xtype: 'gridcolumn', renderer: function(value, metaData, record) { // 提取所有课程代码,用<br>换行拼接 return record.course().getRange().map(item => item.get('coursecode')).join('<br>'); }, dataIndex: 'course.coursecode', text: 'COURSECODE', flex: 1 }, { xtype: 'gridcolumn', renderer: function(value, metaData, record) { // 提取所有课程名称,用<br>换行拼接 return record.course().getRange().map(item => item.get('coursename')).join('<br>'); }, dataIndex: 'course.coursename', text: 'COURSENAME', flex: 1 }, {dataIndex: 'name', text: '学生姓名', flex: 1}, {dataIndex: 'studentid', text: '学号', flex: 1} ]
配套CSS:
.multi-line-cell .x-grid-cell { white-space: normal !important; vertical-align: top; }
内容的提问来源于stack exchange,提问作者ngjiajun
相关产品推荐
相关产品推荐

