0

I am trying to make a Dynamic jqgrid which consists subgrid. So it means subgrid should load data from database according to main jqgrid.So i am not able to get the logic for loading subgrid dynamically according to main jqgrid. Here I am posting my code for my js file

var InstructorsTabSc = function() 
{
var that = {};
var _parent = null;
var _instructorDlgMgrC = null;  
var _view = null;
var _panel = null;
var _path = null;
var BEGIN = "BEGIN";
var STARTING = "STARTING";
var READY = "READY";
var END = "END";
var _state = BEGIN;
var _transition = function(newState) {
    _state = newState;
    switch(_state) {
        case STARTING: _enterStarting(); break;
        case END: _enterEnd(); break;
    }
};
that.create = function(parent, path, panel) {

    _parent = parent;
    _path = path;
    _panel = panel;
    _transition(STARTING);
};      
that.destroy = function() {

    _transition(END);
};  
var _enterStarting = function() {

    var path = _path + '/InstructorsDlgMgrC';
    modelMgr.loadInclude( path + '/InstructorsDlgMgrC.js', function() {
        modelMgr.getHTML( _path + '/InstructorsTabSc.html', function(html) {

            _instructorDlgMgrC = InstructorsDlgMgrC();
            _instructorDlgMgrC.create(that, path);

            var req = {
                    programId :$('#programsList').val()
            };
            var fnSuccess = function(res) {
                _view = InstructorsTabV();
                _view.create(that, _panel, html, res);
            };
            serviceMgr.loadInstructor(req, fnSuccess, fnFailOrError, fnFailOrError);        
        });
    });
};      
var _enterEnd = function() {

    if (_view != null) {
        _view.destroy();
        _view = null;
    }

    _path = null;
    _parent = null;
};
return that;    
};      
var InstructorsTabV = function() 
{

var that = {};
var _sc = null; 
var _panel = null;      
that.create = function(sc, panel, html, res) {  
    _sc = sc;
    _panel = panel;
    that.layoutUi(html, res);
};      

that.layoutUi = function(html, res) {
    $(_panel).html(html);
    that.initInstructorGrid(res);
};

that.destroy = function() {
    $(_panel).html('');
    _sc = null;
};

that.initInstructorGrid = function(data) {      

    var grid = $("#instructorGrid");
        grid.jqGrid({
        data: data.instructors,
        datatype: "local",
        colNames:['Name','User ID', 'Is Active'],
        colModel:[
            {name:'firstName',index:'id', key: true, width:300},
            {name:'email',index:'Sname', width:370, formatter:'email'},
            {name:'isActive',index:'name',width:170,align:'center',editable: true, formatter: 'checkbox',formatoptions:{disabled:false}}
        ],
        pager:false,
        pgbuttons: false,
        pgtext: null,
        toppager:false,
        sortname: 'id',
        sortorder: 'asc',
        viewrecords: false,
        autowidth: true,
        height: "100%",
        subGrid: true,
        subGridOptions: { "plusicon" : "ui-icon-triangle-1-e",
                          "minusicon" :"ui-icon-triangle-1-s",
                          "openicon" : "ui-icon-arrowreturn-1-e",
                          "reloadOnExpand" : false,
                          "selectOnExpand" : true },
        subGridRowExpanded: function(subgrid_id, row_id) {
            var subgrid_table_id, pager_id; subgrid_table_id = subgrid_id+"_t";
            pager_id = "p_"+subgrid_table_id;
            $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
        $("#"+subgrid_table_id).jqGrid({

            data: data.subjects,
            datatype: "local",
            colNames: ['Subject','Is Active','Sessions'],
            colModel: [ {name:"subjectName",index:"num", key: true, width:270},
                        {name:"sessionCount",index:"item",width:160,align:'center',editable: true, formatter: 'checkbox',formatoptions:{disabled:false}},
                        {name:"programUserId",index:"qty",width:380}], 

            pager: false,
            pgbuttons: false,
            pgtext: null,
            sortname: 'num',
            sortorder: "asc",
            autowidth: true,
            height: '100%' });

            $("#gview_"+subgrid_table_id).attr("style","border-left:1px solid #666;");
            $("#"+pager_id).attr("style","height:40px");
            $("#"+"pg_"+pager_id +" table"+" tbody" +" tr").attr("style","background:#FFF");
        }
    });

};
return that;    
};

And here is code for servlet

 @WebServlet("/app/LoggedInSc/AdminSc/AdminTabsetSc/PeopleSc/InstructorsSc/getInstructors")
public class GetInstructors extends JSONServlet {

private static final long serialVersionUID = 1L;

@Override
protected JsonResponse action(TransactionHandler th, JSONObject json)  throws JSONException, CustomExceptionInvalidInput, Exception {       

    int programId = json.getInt("programId");

    List<Map<String, String>> instructorList = new ArrayList<Map<String, String>>();
    List<Map<String, String>> subjectList = new ArrayList<Map<String, String>>();

    for(ProgramUsersDetailDao daoProgramUser : ProgramUsersDetailDao.getProgramUsersByRole(th, programId, ProgramRoles.Instructor)) {

        instructorList.add(daoProgramUser.toMap());

        for(InstructorSubjectSessionsDao daoSubjectSessions : InstructorSubjectSessionsDao.getSubjectAndSessions(th, daoProgramUser.id))
        {
            subjectList.add(daoSubjectSessions.toMap());
        }
    }
    RESULT_OK.addDataParam("instructors", instructorList);
    RESULT_OK.addDataParam("subjects", subjectList);        
    return RESULT_OK;       
}
}

Please tell me how to load data in subgrid according to main grid dynamically according to database

Vikas Gupta
  • 1,530
  • 5
  • 21
  • 34

1 Answers1

1

If you need to load data in subgrid dynamically why you don't use subGridUrl? You can load JSON data from the server directly instead of usage datatype: "local".

In any way if you prefer to load all the data from the server as once you can place all data for all subgrids in the server response. It looks like serviceMgr.loadInstructor has fnSuccess callback which will be called at the end of data loading and the res parameter of fnSuccess get the data returned from the server.

Currently you use data.instructors in both grid and subgrid. You can format the data so that data.subgridData[rowid] will get you the subgrid data for the row with id attribute rowid. In the case you will need just replace the line

data: data.subjects,

in the subgrid to

data: data.subjects[row_id],
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • thanks for reply, you got it exactly right about service manager thing. But u read it wrong i am using data.subjets for subgrid data. – Vikas Gupta Jun 06 '12 at 09:01
  • And i want data of subgrid should be according to main grid. so i think there should be some loop, which will compare both id's and will provide me the content. But again that's what i think. If you have any better and optimize solution please share – Vikas Gupta Jun 06 '12 at 09:02
  • 1
    @VikasGupta: Sorry, I wrote not quite correct, but what I wanted to say is that you use **the same data** `data: data.subjects` in all subgrids independent from the row in which it will be opened. Now about the "loop". I think you don't full understand how subgrid will be created. Only if the user click on "+" (expand) button in the row the next row with subgrid will be created. If you use default setting `reloadOnExpand: true` the row will be deleted if the user close the subgrid. Because grid will be created with collapsed subgrids no subgrids exists initially so no "loop" can be done. – Oleg Jun 06 '12 at 09:23
  • 1
    @VikasGupta: Look at the demo from [the answer](http://stackoverflow.com/a/10178440/315935) to understand better what I mean with `data: data.subjects[row_id]`. [Another answer](http://stackoverflow.com/a/9165978/315935) have very close code too. – Oleg Jun 06 '12 at 09:25
  • Sorry but i am new to jquery, so how can i get this rowID. And can i use it just like 'data:data.subjects[rowID]' ? – Vikas Gupta Jun 06 '12 at 09:35
  • @VikasGupta: You create subgrid inside of `subGridRowExpanded` and get `row_id` (the value of id attribute of the row (``) which was clicked by the user). So you need just create `subjects` as array or as object *on the server*. The indexes (or the property names) should be the same which you use as ids or rows in the main grid. – Oleg Jun 06 '12 at 09:41
  • sorry oleg, but i didn't get it. can you give any example of that ? – Vikas Gupta Jun 06 '12 at 09:51
  • @VikasGupta: Because you need generate different sungrids for every row you should change `List> subjectList` to `Map>> subjectList`. One more thing: you should don't use different `name` and `index` values for local grids (`datatype: "local"`). So you should rename `{name:'email', index:'Sname'...}` to either `{name:'email', index:'email'...}` or `{name:'Sname', index:'Sname'...}`. – Oleg Jun 06 '12 at 09:54
  • @VikasGupta: I posted you before two links with examples. [The demo](http://www.ok-soft-gmbh.com/jqGrid/LocalSubgrid.htm) is from one from the references. You should generate on the server the data with the close structure to be able to use in the client code. – Oleg Jun 06 '12 at 09:57
  • Helped me to load static data in your way, now changing servlet according to your way. but still thanks a lot man. great work. Keep it up.. :) :) :) – Vikas Gupta Jun 07 '12 at 07:28