0

sorry if my questions are simple , i'm totaly new to jqGrid :)

1- i want to use (add,edit,delete) feature of jqGrid , as you see there are buttons on the footer part of my grid but when i click just a dialog box comes and no fields to enter !! i want it just like this page see my screen picture of what happens !

2- what happens when i click on submit button ( after fixing part 1 ) , i want to know how datas post to server! no matter what language , i want to not for example they sent as object or sth , to know how to process them !

tnx alot

my source code :

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Index Page</title>
    <!-- external scripts -->

    <!-- jQuery & Bootstrap -->
    <script type="text/javascript" src="{% static "js/jquery.js" %}"/></script>
        <script type="text/javascript" src="{% static "js/jquery.jqGrid.min.js" %}"/></script>
    <link rel="stylesheet" type="text/css" media="all" href="{% static "css/bootstrap.min.css?id=1" %}"/>
    <script type="text/javascript" src="{% static "js/bootstrap.min.js" %}"/></script>
    <!-- jQuery & Bootstrap -->

    <!-- jqGrid -->
    <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/ui.jqgrid.css" %}" />
    <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/ui-lightness/jquery-ui.min.css" %}" />
    <script type="text/javascript" src="{% static "js/grid.locale-en.js" %}"/></script>
    <!-- jqGrid -->

    <!-- own implemented scripts -->
    <script type="text/javascript" src="{% static "js/script.js" %}"/></script>  
    <!-- own implemented scripts -->

    <!-- external scripts-->

    <script type="text/javascript">
    $(function () {
        $("#list").jqGrid({
            url: "http://localhost:8000/getdata",
            datatype: "json",
            mtype: "GET",
            colNames: ["شناسه", "کد","نام", "عنوان" ,"عنوان انگلیسی", "ظرفیت", "ظرفیت اضافه","قیمت روز"],
            colModel: [
                  { name: "id", index:"id", width: 60 , editable:true,editoptions: {readonly: "readonly"}},
            { name: "code", width: 60 , editable:true},
            { name: "name", width: 90 , editable:true},
            { name: "title", width: 90 ,editable:"true", editable:true},
            { name: "english_title", width: 100, align: "left", editable:true },
            { name: "capacity", width: 90, align: "left", editable:true },
            { name: "extra_capacity", width: 90, align: "left", editable:true },
            { name: "today_price", width: 80, align: "left" , editable:true},
            ],
            rowNum:10,
            rowList:[10,20,30],
            pager: '#pager',
            loadonce:true,
            sortname: 'id',
            viewrecords: true,
            sortorder: "desc",
            rownumbers: true,
            rownumWidth: 40,
            gridview: true,
            multiselect: false,
            caption: "اتاق ها",
            onSelectRow: function(ids) {
                if(ids == null) {
                    ids=0;
                    if(jQuery("#list_d").jqGrid('getGridParam','records') >0 )
                    {

                        jQuery("#list_d").jqGrid('setGridParam',{url:"getpricelist?q=1&id="+ids,page:1}).trigger('reloadGrid');

                    }
                } else {
                    jQuery("#list_d").jqGrid('setGridParam',{url:"getpricelist?q=1&id="+ids,page:1}).trigger('reloadGrid');
                jQuery("#list_d").jqGrid('setCaption',"لیست قیمت اتاق شماره : "+ids)
                }
            }
     });
    jQuery("#list").jqGrid('navGrid','#pager',{edit:true,add:true,del:true,search:false},
     /*   {
                    recreateForm: true,
                    beforeShowForm: function ($form) {
                        $form.find(".FormElement[readonly]")
                            .prop("disabled", true)
                            .addClass("ui-state-disabled")
                            .closest(".DataTD")
                            .prev(".CaptionTD")
                            .prop("disabled", true)
                            .addClass("ui-state-disabled")
                    },
        }, */
     //edit options
       { // Edit option (parameters of editGridRow method)
        recreateForm:true,
        reloadAfterSubmit:true,
        closeOnEscape:true,
        savekey: [true,13],
        closeAfterEdit:true,
        url:'/edit',
        ajaxEditOptions: {
            beforeSend: function(jqXHR) {
                var csrf_token = getCookie('csrftoken'); 
                jqXHR.setRequestHeader('X-CSRF-Token', csrf_token);
            }

        },
            afterSubmit: function () {
             jQuery("#list").jqGrid("setGridParam", {datatype: 'json'});
             console.log('changed data type');
             return [true];
         },
        editData: {
            csrfmiddlewaretoken: getCookie('csrftoken')
        }
    },
    //add options
    { 
        recreateForm:true,
        reloadAfterSubmit:true,
        closeOnEscape:true,
        savekey: [true,13],
        closeAfterAdd: true,
        url:'/add',
        ajaxEditOptions: {
            beforeSend: function(jqXHR) {
                var csrf_token = getCookie('csrftoken'); 
                jqXHR.setRequestHeader('X-CSRF-Token', csrf_token);
            }
        },
            afterSubmit: function () {
             jQuery("#list").jqGrid("setGridParam", {datatype: 'json'});
             console.log('changed data type');
             return [true];
         },
        editData: {
            csrfmiddlewaretoken: getCookie('csrftoken')
        }

    },
    //delete options
    { 
        recreateForm:true,
        reloadAfterSubmit:true,
        closeOnEscape:true,
        savekey: [true,13],
        url:'/delete',
        ajaxEditOptions: {
            beforeSend: function(jqXHR) {
                var csrf_token = getCookie('csrftoken'); 
                jqXHR.setRequestHeader('X-CSRF-Token', csrf_token);
            }
        },
        afterSubmit: function () {
             jQuery("#list").jqGrid("setGridParam", {datatype: 'json'});
             console.log('changed data type');
             return [true];
         },
        editData: {
            csrfmiddlewaretoken: getCookie('csrftoken')
        }
    }

    );
  jQuery("#list").jqGrid('filterToolbar',{stringResult: true,searchOnEnter : false});
    jQuery("#list_d").jqGrid({
        height: 100,
    width:345,
        url:'getpricelist?q=1&id=2',
        datatype: "json",
        colNames:['از','تا', 'قیمت'],
        colModel:[

    {name:'from',index:'from', width:100},
    {name:'to',index:'to', width:100},
    {name:'price',index:'price', width:80, align:"right"},



        ],
        rowNum:5,
        rowList:[5,10,20],
        pager: '#pager_d',
        sortname: 'item',
        viewrecords: true,
        sortorder: "asc",
        multiselect: false,
        caption:"لیست قیمت"
    }).navGrid('#pager_d',{add:false,edit:false,del:false});

        }); 

    </script>

    </head>
    <body>

        <table id="list"><tr><td></td></tr></table>
        <div id="pager"></div> 

        <table id="list_d"></table>
        <div id="pager_d"></div>
    </body>
</html>

views.py

from django.shortcuts import render
from django.utils import simplejson
from django.http import HttpResponse
from rooms.models import *
from django.db.models import Q
from django.core import serializers


def index(request):
    return render(request, 'index.html')

def getdata(request):
    data=room_type.objects.all()
    json=[]

    for o in data:
        json.append({'id':o.id, 'code':o.code,'name':o.name,'title':o.title, 
                     'english_title':o.english_title, 'capacity':o.capacity,
                     'extra_capacity':o.extra_capacity, 'today_price':o.today_price })

    return HttpResponse(simplejson.dumps(json), mimetype='application/json',content_type='application/json' )


def getpricelist(request):

    requested_room_id = request.GET.get('id', '')

    room = room_type.objects.get(id = requested_room_id)
    price_list_set = room.price_list_set.all()

    json=[]
    for price_list in price_list_set:
        json.append({'from':price_list.from_date, 'to':price_list.to_date, 'price':price_list.price})


    return HttpResponse(simplejson.dumps(json), mimetype='application/json',content_type='application/json' )

def edit(request):
    print "################ediit#################"
    return render(request, 'index.html')


def add(request):
    print "################addddddddddd#################"
    return render(request, 'index.html')


def delete(request):
    print "################deeeeeeeeeeeeeel#################"
    return render(request, 'index.html')
Iman Mirzadeh
  • 12,710
  • 2
  • 40
  • 44
  • Probably url:'/edit' etc URLs are wrong. You can use [Fiddler](http://www.telerik.com/fiddler) or Developer Tools of IE or Google Chrome (press F12 to start) to trace HTTP traffic. Try url:'edit' or other relative path. The URL `"http://localhost:8000/getdata"` works but I recommend you to change it to *relative* path too: "getdata", "getdata/", "/getdata/" etc. I recommend you 1) to use the same option for Add as for Edit or to change default options of form editing on the page (see [the answer](http://stackoverflow.com/a/10287508/315935)). Currently you don't set options for Add and Delete – Oleg Aug 01 '14 at 12:57
  • 1
    I recommend you additionally to use default `reloadAfterSubmit:true` and add reload the data inclusive the id of new added row from the server. You need still reset `datatype` to `"json"` inside of `afterSubmit` (see [the answer](http://stackoverflow.com/a/11273416/315935)) to reload the data **from the server**. I recommend to move `jquery.jqGrid.min.js` after `grid.locale-en.js`. – Oleg Aug 01 '14 at 13:09
  • no the urls are correct , i also updated my code to working version but 2 i have little problems : 1- when i submit add form , the form doesn't go away and list doesn't refresh ! :( 2-how can i **don't let users edit in edit form but add value in add form**(i want to do that for "today_price" col) ! if i add **editoptions: {readonly: "readonly"}** changes in both edit and add forms and is not suitable for me ! again thanks for saving my life :D @Oleg – Iman Mirzadeh Aug 01 '14 at 15:34
  • 1
    1) you should use `closeAfterAdd: true` in the list of Add options 2) you placed `afterSubmit` on the wrong place. It's not callback of jqGrid - it's callback of form editing (see near `ajaxEditOptions`). 3) I suppose you should use `csrfmiddlewaretoken: function () { return getCookie('csrftoken');}` instead of `csrfmiddlewaretoken: getCookie('csrftoken')`. 4) You can use `beforeShowForm` callback of form editing like in [the answer](http://stackoverflow.com/a/20498576/315935) and [this one](http://stackoverflow.com/a/6974432/315935) to disable some fields, set/remove readonly attribute etc... – Oleg Aug 01 '14 at 16:40
  • thanks alot , but theres a problem with delete option ? whats wrong with delete part (3rd part) ? i want to delete row but it seems its not working! @Oleg – Iman Mirzadeh Aug 02 '14 at 11:18
  • 1
    The "Delete" part of your code use wrong options. You should exactly examine [the documentation](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing#properties2). You example you need use `ajaxDelOptions` instead of `ajaxEditOptions`, `delData` instead of `editData`, some other Edit option not exist for Delete etc. – Oleg Aug 02 '14 at 11:46

1 Answers1

2

The first problem is very easy to solve. The editing form (Add and Edit) includes only the information about editable columns. So you need include editable: true property in every column of colModel which you want to allow the user to edit.

It's important to understand that there are default value for every known property of colModel. I recommend you to examine the last ("Default") column of the table on the place of the documentation. You will find that default value of align is "left", so you can remove align: "left" from all colModel items. In the same way you can see that default value of editable property is false. It way the reason why you had empty editing form. If you need to set editable: true to more as the half of columns of colModel I would recommend you to use cmTemplate option of jqGrid (see the answer for more details). After including cmTemplate: {editable: true} option for example you will need to include editable: false in all columns which you want don't make editable. All other columns will be editable.

If you need to include some column information in Add/Edit form, but don't permit the user to edit it you can use editable: true together with editoptions: {readonly: "readonly"} or editoptions: {disabled: "disabled"}. The option will include the information in the edit form, but set additional readonly="readonly" or disabled="disabled" attribute on the corresponding editing field. One can add additional "ui-state-disabled" class on such filed like described in the answer. In the way you can make some fields editable, but only for example in Add dialog and hold it disabled/readonly in Edit dialog. Don't forget to use recreateForm: true option.

To make editing successful it's very important to fill rowid of the grid correctly. If you have column with name: "id" or if some column have key: true property then the corresponding value will be used as rowid. The information which will be send to the server is described here (about Edit), here (about Add) and here (about Delele). The information contains always id=rowidvalue property. Add/Edit form post additionally information about all (inclusive hidden) editable columns in the form: name=value, where the name is the value of name property of the column definition in the colModel.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • @ImanMirzadeh: Probably `url:'/edit'` etc URLs are wrong. Try `url:'edit'` or other relative path. The URL `"http://localhost:8000/getdata"` works but I recommend you to change it to *relative* path too `"getdata"`, `"getdata/"`, `"/getdata/"` etc. I recommend you 1) to use the same option for Add as for Edit or to change default options of form editing on the page (see [the answer](http://stackoverflow.com/a/10287508/315935)). Currently you **don't set options for Add and Delete** – Oleg Aug 01 '14 at 12:33