Пользовательский диалог в под-подсетке, скрытой за сеткой

Как мой первый вопрос здесь, возможно, я делаю что-то не так. Пожалуйста, не стесняйтесь сказать мне - мы все учимся с первого раза :)

Контекст моей проблемы:

У меня есть база данных с 2 таблицами: Scales и Items. 1 Шкала может иметь разные связанные Шкалы (отношение, которое я назвал Родителем Шкалы - Дочерними Шкалами). Дочерние элементы масштаба могут иметь предметы. Масштаб Родители не делают.

Поэтому я решил работать на границах своих знаний с Grids и создать Sub-SubGrid для этого случая:

Сетка масштабных родителей. - SubGrid с дочерними элементами шкалы для каждого родителя шкалы. -- SubGrid с элементами для каждого дочернего элемента шкалы.

Работает. И это хорошо: добавление, редактирование, пользовательские диалоги работают для масштабирования родителей и масштабирования дочерних элементов.

Но не для Item. Пользовательские диалоги, открытые в Sub-SubGrid (я добавляю «Добавить», «Редактировать» и «Удалить» как настраиваемые действия в столбце «Действие элемента»), работают в контексте Sub-SubGrid, который очень ограничен, поэтому он не подходит и скрывается за строками сетки.

Я прикрепил скриншот к этому для лучшего понимания того, что я говорю. Вы можете увидеть имя масштаба вверху, за которым следует имя дочернего элемента масштаба, а третий дочерний элемент имеет SubSubGrid с идентификатором элемента масштаба вверху. В середине внизу диалоговое окно «Новый элемент», а нижняя часть сетки имени шкалы блокирует диалоговое окно.

Ссылка на изображение, так как я слишком новичок, чтобы публиковать изображения... http://imageshack.us/photo/my-images/703/subsubgriddialogopened.png/

Теперь мой вопрос:

Как я могу избежать плавающего атрибута диалога, чтобы он не прятался за сеткой? Некоторые исследования привели меня к этой ссылке: Неправильный Z-порядок - экран добавления/редактирования jqgrid отображается сзади, если сетка находится в диалоговом окне пользовательского интерфейса jquery

... что хорошо для стандартных кнопок добавления, редактирования и удаления, но не работает для пользовательских диалогов.

Всем спасибо за прочтение моей проблемы. Поскольку это не проблема с кодом (все работает), я его не выкладывал, но если кто-то думает, что это поможет решить проблему, я добавлю его сюда.

РЕДАКТИРОВАТЬ: Код.

jQuery(document).ready(function(){
      var $Grid_scaleParent = jQuery("#scaleOverviewList");
    $Grid_scaleParent.jqGrid({
    url:'/scaleoverview/scaleParentsData/',    
    datatype: 'json',
    mtype: 'POST',
    colNames:[
        //Colnames is the visual name of the column, which appears at the top.
        'Scale Id',
        'Scale Name',
        'Completed Scale',
        'Childs related',
        'Childs with Items related',
        'Scale Actions'
    ],
colModel :[
        //ColModel defines the columns and its names.
        //Name is the key of the column. Index is needed for sorting the grid.
        {name:'scaleId', index:'sPId', sortable:true, hidden:true},
        {name:'scaleName', index:'sPName', sortable:true, align:'left', required: true, editable:true, edittype:'text'},
        {name:'completedScale', sortable:false},
        {name:'childsRelated', sortable:false},
        {name:'childsItemsRelated', sortable:false},
        {name:'scaleActions', sortable:false}
    ],
    //Toppager adds the pagination to the top of the form.
toppager: true,
height: "100%",
    rowNum:10,
    rowList:[10,40,100],
    pager: '#gridpager',
    sortname: 'sPName',
    sortorder: "asc",        
    viewrecords: true,
    // Options to enable subGrid.
    subGrid: true,
    subGridRowExpanded: function(Grid_scaleChild, rowId_scaleParent) {            
        ////////////////////////////////////
        //  Starting Scale Child SubGrid  //
        ////////////////////////////////////

        var Table_scaleChild, Pager_scaleChild;
        Table_scaleChild = Grid_scaleChild+"_t";
        Pager_scaleChild = "p_"+Table_scaleChild;
        $('#'+Grid_scaleChild).html("<table id='"+Table_scaleChild+"' class='scroll'></table><div id='"+Pager_scaleChild+"' class='scroll'></div>");
        jQuery('#'+Table_scaleChild).jqGrid({
            url:'scaleoverview/scaleChildsData/'+rowId_scaleParent+'/',
            datatype: "json",
            mtype: 'POST',
            colNames: [
                'Scale Child Id',
                'Scale Child Name',
                'Items Related',
                'Scale Child Actions'
            ],
            colModel: [
                {name:"scaleChildId",index:"sCId", sortable:true, hidden:true},
                {name:"scaleChildName",index:"sCName", width:600, sortable:true, align:'left', required: true, editable:true, edittype:'text'},
                {name:"itemsRelated", sortable: false, width:300},
                {name:"scaleChildActions", sortable:false, width:200}
            ],
            autowidth:false,
            rowNum:20,
            pager: Pager_scaleChild,
            sortname: 'sCId',
            sortorder: "asc",
            height: '100%',
            subGrid: true,
            subGridRowExpanded: function(Grid_scaleItems, rowId_scaleChild) {            
                ////////////////////////
                //  Starting Scale Items SubSubGrid  //
                ////////////////////////

                var Table_scaleItems, Pager_scaleItems;
                Table_scaleItems = Grid_scaleItems+"_t";
                Pager_scaleItems = "p_"+Table_scaleItems;
                $('#'+Grid_scaleItems).html("<table id='"+Table_scaleItems+"' class='scroll'></table><div id='"+Pager_scaleItems+"' class='scroll'></div>");
                jQuery('#'+Table_scaleItems).jqGrid({
                    url:'scaleoverview/scaleItemsData/'+rowId_scaleChild+'/',
                    datatype: "json",
                    mtype: 'POST',
                    colNames: [
                        'Scale Item Id',
                        'Min.Amount',
                        'Max.Amount',
                        'Percentage',
                        'Start Date',
                        'End Date',
                        'Scale Item Actions'
                    ],
                    colModel: [
                        {name:"scaleItemId",index:"sIId", sortable:true},
                        {name:"minAmount", sortable:false, align:'left', required: true, editable:true, edittype:'text'},
                        {name:"maxAmount", sortable:false, align:'left', required: true, editable:true, edittype:'text'},
                        {name:"percentage", sortable:false, align:'left', required: true, editable:true, edittype:'text'},
                        {name:"startDate", sortable:false, align:'left', required: true, editable:true, edittype:'text'},
                        {name:"endDate", sortable:false, align:'left', required: true, editable:true, edittype:'text'},
                        {name:"scaleItemActions", sortable:false, width:100}
                    ],
                    autowidth:false,
                    rowNum:20,
                    pager: Pager_scaleItems,
                    sortname: 'sIId',
                    sortorder: "asc",
                    height: '100%',
                    loadComplete: function(){
                        //Getting the ID array of the list.
                        var scaleItemIds = jQuery('#'+Table_scaleItems).getDataIDs();

                        //Constructing action buttons.
                        for(var scaleItemAuxId=0;scaleItemAuxId< scaleItemIds.length;scaleItemAuxId++){
                            var scaleItemId = scaleItemIds[scaleItemAuxId];
                            //Construction of the custom option for each row.
                            //Note that we need to pass to the function the subGrid for the correct form construction.
                            var scaleItemActions = '<button class="scaleItemEdition" onclick="scaleItemEdition(\'' + scaleItemId + '\', \''+ Table_scaleItems +'\');"></button>';

                            //Constructing property management buttons.
                            scaleItemActions += '<button class="scaleItemDeletion" onclick="scaleItemDeletion(\'' + scaleItemId + '\', \''+ Table_scaleItems +'\');"></button>';

                            //Adding options to the Action Column
                            jQuery('#'+Table_scaleItems).setRowData(scaleItemIds[scaleItemAuxId],{"scaleItemActions":scaleItemActions});
                        }

                        //Construction of the visual features of the buttons.
                        $(".scaleItemEdition").button({
                            icons: {
                                primary: 'ui-icon-pencil'
                            },
                        text: false
                        });           
                        $(".scaleItemDeletion").button({
                            icons: {
                                primary: 'ui-icon-close'
                            },
                        text: false
                        });                            
                    }
                });
                jQuery("#"+Table_scaleItems).jqGrid('navGrid',"#"+Pager_scaleItems,{edit:false,add:false,del:false}, {multipleSearch:true, overlay:false});
                jQuery("#"+Table_scaleItems).navButtonAdd(Pager_scaleItems,{
                    caption: 'New Item',
                    title:'New Item',
                    buttonicon :'ui-icon-plus', 
                    onClickButton:function(){
                        //Definition of the columns to be shown.
                        jQuery('#'+Table_scaleItems).jqGrid('editGridRow', 'new', {
                            zIndex:2000,
                            addCaption: 'New Item',
                            reloadAfterSubmit:true,
                            closeAfterAdd:true,
                            recreateForm:true,
                            beforeShowForm: function (form) 
                            {
                                var $grid = $('#'+Table_scaleItems);
                                var dlgDiv = $("#editmod" + $grid[0].id);
                                var parentDiv = dlgDiv.parent();
                                var dlgWidth = dlgDiv.width();
                                var parentWidth = parentDiv.width();
                                dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";

                            },
                            url: '/scaleoverview/addItem/'+rowId_scaleChild+'/'
                        });
                    }
                });                     

                /////////////////////////////////////
                //  Ending Scale Items SubSubGrid  //
                /////////////////////////////////////

            },
            loadComplete: function(){
                //Getting the ID array of the list.
                var scaleChildIds = jQuery('#'+Table_scaleChild).getDataIDs();

                //Constructing action buttons.
                for(var scaleChildAuxId=0;scaleChildAuxId< scaleChildIds.length;scaleChildAuxId++){
                    var scaleChildId = scaleChildIds[scaleChildAuxId];
                    //Construction of the custom option for each row.
                    //Note that we need to pass to the function the subGrid for the correct form construction.
                    var scaleChildActions = '<button class="scaleChildEdition" onclick="scaleChildEdition(\'' + scaleChildId + '\', \''+ Table_scaleChild +'\');"></button>';

                    //Constructing property management buttons.
                    scaleChildActions += '<button class="scaleChildDeletion" onclick="scaleChildDeletion(\'' + scaleChildId + '\', \''+ Table_scaleChild +'\');"></button>';

                    //Adding options to the Action Column
                    jQuery('#'+Table_scaleChild).setRowData(scaleChildIds[scaleChildAuxId],{"scaleChildActions":scaleChildActions});
                }

                //Construction of the visual features of the buttons.
                $(".scaleChildEdition").button({
                    icons: {
                        primary: 'ui-icon-pencil'
                    },
                text: false
                });           
                $(".scaleChildDeletion").button({
                    icons: {
                        primary: 'ui-icon-close'
                    },
                text: false
                });
            }
        });
        jQuery("#"+Table_scaleChild).jqGrid('navGrid',"#"+Pager_scaleChild,{edit:false,add:false,del:false});

        // SubGrid Adding Scale
        jQuery("#"+Table_scaleChild).navButtonAdd(Pager_scaleChild,{
            caption: 'New Child',
            title:'New Child',
            buttonicon :'ui-icon-plus', 
            onClickButton:function(){
                //Definition of the columns to be shown.
                jQuery('#'+Table_scaleChild).jqGrid('editGridRow', 'new', {
                    addCaption: 'New Child',
                    reloadAfterSubmit:true,
                    closeAfterAdd:true,
                    recreateForm:true,
                    beforeShowForm: function (form) 
                    {
                        // Styling the editing form to the center of the page
                        var $grid = $('#'+Table_scaleChild);
                        var dlgDiv = $("#editmod" + $grid[0].id);
                        var parentDiv = dlgDiv.parent();
                        var dlgWidth = dlgDiv.width();
                        var parentWidth = parentDiv.width();
                        var dlgHeight = dlgDiv.height();
                        var parentHeight = parentDiv.height();
                        dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
                        dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";

                    },
                    url: '/scaleoverview/addScale/'+rowId_scaleParent+'/'
                });
            }
        });            

        //////////////////////////////////
        //  Ending Scale Child SubGrid  //
        //////////////////////////////////

    },
loadComplete: function(){
        //Resizing grid in order to make it 100% width.
        resize_the_grid($Grid_scaleParent);

        //Getting the ID array of the list.
        var ids = $Grid_scaleParent.getDataIDs();

        //Constructing action buttons.
    for(var i=0;i< ids.length;i++){
    var cl = ids[i];

            //Construction of the custom option for each row.
            var scaleActions = '<button class="edit" onclick="parentScaleEdition(\'#scaleOverviewList\', \'' +  cl + '\');"></button>';
            scaleActions += '<button class="delete" onclick="parentScaleDeletion(\'#scaleOverviewList\', \'' +  cl + '\');"></button>';

            //Construction of the custom option for new Tab and the name of the tab.
            //var nameOfTheTab = jQuery('#siteOverviewList').getCell(cl,'Client') + '::' + jQuery("#siteOverviewList").getCell(cl,'Name');
            //siteActions += '<button class="seeGames" onclick="createtab(\''+ nameOfTheTab +'\', '+ cl +');"></button>';

            //Adding options to the Action Column
            $Grid_scaleParent.setRowData(ids[i],{'scaleActions':scaleActions});
        }

        //Construction of the visual features of the buttons.
        $(".edit").button(
        {
            text: false,
            label: 'Edit Scale',
            icons: {
                primary: 'ui-icon-pencil',
                secundary: null
            }
        });            
        $(".delete").button(
        {
            text: false,
            label: 'Delete Scale',
            icons: {
                primary: 'ui-icon-close',
                secundary: null
            }
        });
        /*
        $(".seeGames").button(
        {
            text: false,
            label: 'Open tab with Games related to this Site',
            icons: {
                primary: 'ui-icon-folder-open',
                secundary: null
            }
        });
         */
        setHighlightedRows();
}
});

// 2 - Adding aditional options to the grid    
$Grid_scaleParent.navGrid('#gridpager',{edit:false,add:false,del:false,search:false,refresh:true,cloneToTop: true},
{}, // edit options
{}, // add options
{}, //del options
{} // search options
);

// 3 - Adding a custom option to the grid.
//      It is important to declare this custom button after the standard ones. Otherwise it will not appear.
$Grid_scaleParent.navButtonAdd("#gridpager",{
    caption:'New Parent',
    buttonicon :'ui-icon-plus', 
    onClickButton:function(){
        $Grid_scaleParent.jqGrid('editGridRow', 'new', {
            addCaption: 'New Parent',
            reloadAfterSubmit:true,
            closeAfterAdd:true,
            recreateForm:true,
            beforeShowForm: function (form) 
            {
                // Styling the editing form to the center of the page
                var $grid = $Grid_scaleParent;
                var dlgDiv = $("#editmod" + $grid[0].id);
                var parentDiv = dlgDiv.parent();
                var dlgWidth = dlgDiv.width();
                var parentWidth = parentDiv.width();
                var dlgHeight = dlgDiv.height();
                var parentHeight = parentDiv.height();
                dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
                dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";

            },
            beforeInitData: function() {
                //Redefine of the cols that need to be set for adding.
            },
            afterShowForm: function () {
                //Redefine of the cols, so other actions will not see them.
            },
            url: '/scaleoverview/addScale/'
        });
    }
});
});

function scaleItemEdition (scaleItemId, subSubGridId)
{
  //Declaring subGrid in which the form has to be inserted.
var $subSubGrid = jQuery('#'+subSubGridId);

$subSubGrid.jqGrid('editGridRow', scaleItemId, {
    editCaption:'Edit Scale Item',
    beforeShowForm: function(form) 
    {
        // Styling the editing form to the center of the page
        var $grid = $subSubGrid;
        var dlgDiv = $("#editmod" + $grid[0].id);
        var parentDiv = dlgDiv.parent();
        var dlgWidth = dlgDiv.width();
        var parentWidth = parentDiv.width();
        var dlgHeight = dlgDiv.height();
        var parentHeight = parentDiv.height();
        dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
    },
width:400,
recreateForm:true,
reloadAfterSubmit:true,
closeAfterEdit:true,
url:'/scaleoverview/scaleItemEdition'
});
resize_the_grid(jQuery('#scaleOverviewList'));
}

function scaleItemDeletion (scaleItemId, subSubGridId)
{
//Declaring subGrid in which the form has to be inserted.
var $subSubGrid = jQuery('#'+subSubGridId);

$subSubGrid.jqGrid('delGridRow', scaleItemId,
{
    caption:'Delete Scale Item',
    msg:'Delete this Scale Item.',
    beforeShowForm: function(form) 
    {
        // Styling the editing form to the center of the page
        var $grid = $subSubGrid;
        var dlgDiv = $("#delmod" + $grid[0].id);
        var parentDiv = dlgDiv.parent();
        var dlgWidth = dlgDiv.width();
        var parentWidth = parentDiv.width();
        var dlgHeight = dlgDiv.height();
         var parentHeight = parentDiv.height();
        dlgDiv[0].style.top = Math.round((parentHeight-dlgHeight)/2) + "px";
        dlgDiv[0].style.left = Math.round((parentWidth-dlgWidth)/2) + "px";
    },
    reloadAfterSubmit:true,
    url:'/scaleoverview/scaleItemDeletion'
});
}

person Hector Ordonez    schedule 02.05.2012    source источник


Ответы (2)


Добро пожаловать в stackoverflow! Без скриншота сложно понять ваш вопрос. Это примерно то же самое, что пытаться понять вкус какого-нибудь блюда, не попробовав его. Вы также не публикуете код JavaScript. Код может помочь понять, как вы создаете «настраиваемый диалог», который будет плохо отображаться вместе с jqGrid.

Тем не менее, если вы предполагаете, что проблема в неправильном z-порядке диалога, вы, вероятно, можете решить эту проблему очень легко. Например, если вы используете диалоговое окно пользовательского интерфейса jQuery, вам следует добавить параметр zIndex. Если вы создаете пользовательский диалог вручную в отношении <div>, вам необходимо добавить 'z-Index' к стилям div. Важно, чтобы div имел absolute, relative или fixed значение position. Обычно для диалогов используется position: absolute.

person Oleg    schedule 02.05.2012
comment
Привет, мистер Олег :) Во-первых, спасибо за все ваши другие посты о jqGrid, вы уже очень помогли мне раньше. Во-вторых, я добавил изображение в качестве ссылки (отредактируйте пост за мгновение до этого). Дело не в неправильном z-порядке, он работает так, как должен, но дело в том, что это нехорошее поведение, когда это подсетка. Я собираюсь добавить код в исходный пост, предварительно убрав ненужные строки. - person Hector Ordonez; 02.05.2012
comment
Я все еще борюсь с этой проблемой. Изображение в моем посте может помочь понять это (это ссылка на imageshack, так как у меня нет прав на загрузку изображений). - person Hector Ordonez; 03.05.2012

Я все еще борюсь с этой проблемой. Изображение в моем посте может помочь понять это (это ссылка на imageshack, так как у меня нет прав на загрузку изображений).

Выяснил, что проблема связана с Overflow: auto для классов '.ui-jqgrid .ui-jqgrid-bdiv'. Пробовал с Firebug избегать этой строки, а затем ВСЕ диалоги «летают» по всем сеткам, что ИМЕННО то, что я хочу.

Однако это скорее HACK, чем решение, поэтому я все еще ищу правильный ответ. Где-то в jqGrid должна быть опция, чтобы включить «летающие» диалоги, не заставляя их прятаться за пределы сетки.

Я собираюсь поставить обе ссылки на изображения моей сетки.

Первое изображение: Диалог НЕ летает по сетке, поэтому он прячется за сеткой.

http://imageshack.us/photo/my-images/703/subsubgriddialogopened.png/

Второе изображение: Диалог ЛЕТАЕТ в сетке, чего я и хочу.

http://imageshack.us/photo/my-images/221/screenshot20120503at845.png

Если нужно, могу загрузить больше скриншотов.

person Hector Ordonez    schedule 03.05.2012