Javascript

Update parent after children new windows closed

14 Apr , 2015  

Here is a snippet to update parent after new window getting closed :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Start trigger pop-up new window
var createUrl = $(this).data('url') + selectedUUID;
newwindow = window.open(createUrl, 'Some Page, 'scrollbars=yes,resizable=yes,height=600,width='+screen.width/2);

// Set focus on windows
if (window.focus) {
    newwindow.focus();
}

// Update parent once children window already closed
// Reload jqgrid table to get latest data
var monitor = setInterval(function() {
    if (newwindow.closed) {
         // Update children table
         $selectorFarmfield.setGridParam({url: 'someurl' + selectedUUID});
         $selectorFarmfield.trigger("reloadGrid");
         clearInterval(monitor);
    }
}, 1000);

Django

JqGrid inline editing integration with DJango send csrf token

3 Apr , 2015  

Here is a quick snippet to send csrf_token in POST data from inline edit JqGrid to Django:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var tableGrid = $(selector).jqGrid({
   ....
   onSelectRow: function(id){
         if(id && id!==lastSel){
            $(selector).restoreRow(lastSel);
            lastSel=id;
         }

         var editparameters = {
            extraparam: {csrfmiddlewaretoken: $('.token-data').data('token')},
            keys: true,
          };
         $(selector).jqGrid('editRow', id, editparameters);

    }
};

Javascript

Example Jquery Plugin to filtering input value real-time with Regex validation

3 Apr , 2015  

We try to add real-time input validation for dynamic element with some regex. Let say, user allowed only to type “numeric” and disallow any others alphabet and symbols.

Then, we can write a small plugin, at this example, i use https://github.com/akzhan/jquery-keyfilter for Regex validation.

Then, we just need to write this simple and easy plugin :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
(function($) {
    $.fn.validNumber = function(selector) {

        /**
         * Attach key filter with regex int only for dynamic element
         */
        $(document).on('click', selector, function() {
            $(this).keyfilter(/[\dA-F]/);
        });

        /**
         * When input have more than 1 digit but leading with 0
         * Remove the leading zero
         */
        $(document).on('keyup', selector, function() {
            if($(this).val().length > 1 && $(this).val()[0] == "0") {
                 $(this).val($(this).val().substring(1));
            }
        });
    };
})(jQuery);

Then, we just need to use this libraries by :

1
$(document).validNumber('input');

Django

Handle error form.save() with model validation

2 Apr , 2015  

Here is a quick snippet to avoid form.save() error because model validation :

1
2
3
4
5
6
7
8
# handle form save with model validationerror
# http://stackoverflow.com/questions/8771029/django-raise-a-validation-error-in-a-models-save-method
try:
    form.save()
except ValidationError, e:
    form._errors = {}
    for _, v in e.message_dict.items():
        form._errors.setdefault(NON_FIELD_ERRORS, []).extend(v)

Uncategorized

Inline edit jqgrid with select2

2 Apr , 2015  

Here is a quick snippet for inline edit JqGrid with Select2

First, we need to bind colModel with select2 in dataInit :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var colModel = [
     // always put uuid and id
     {name:'id', hidden: true},
     {name:'uuid', hidden: true},
     {name:'youroption', label:'yourlabel',editable: true,
      edittype: "select", editrules: { required: true }, width:450,
      editoptions: {
        value: [[1, ],
        dataInit: function (elem) {
            $(elem).width(450).select2();
            $(elem).addClass("select2box");
        }
      }},
 ...

Second, we need to fix select2 “enter key” to hide search box and execute inline edit save.

1
2
3
4
5
6
7
$(document).on('keyup', '.select2-search > input.select2-input', function (e) {
  // Close select2 if enter key
   if(e.keyCode === 13) {
      $('select.select2box').select2("enable", false);
      $(selector).jqGrid('saveRow', lastSel, false, 'clientArray');
      }
  });

Javascript

Jqgrid for Dummies

1 Apr , 2015  

Here is a quick snippet of how to using JqGrid for dummies, like get data, delete data, access data or data manipulation.

Setup JQGrid:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
$(document).ready(function() {
    // Enable tooltips
$("body").tooltip({
    selector : '[data-toggle="tooltip"]'
});
$(".chosen").chosen();

var permission = $('.permission');

// Define ID for table
var selector = "#table-index";
var pager = '#table-pager';

// Setup url ajax for loading data in table
var url = $(selector).data('url');

// Define last sel for edit
var lastSel;

var colModel =  [
     {name:'id', hidden: true, key:true, editable:true},
     {name:'uuid', hidden: true},
     {name:'hybrid', label:'Hybrid', editable: true, editrules:{number: true}, classes: 'numberonly'},
     {name:'some_date', label:'Date Selection', editable: true,  editoptions:{size:20,
          dataInit:function(el){
                $(el).datepicker({dateFormat:'dd-mm-yy'});
          },
          defaultValue: function(){
            var currentTime = new Date();
            var month = parseInt(currentTime.getMonth() + 1);
            month = month < = 9 ? "0"+month : month;
            var day = currentTime.getDate();
            day = day <= 9 ? "0"+day : day;
            var year = currentTime.getFullYear();
            return day+"-"+month + "-"+year;
          }
        }
      },
 ];

/**
 * Setup Table GRID
 *
 * We need to define colModel with editable and edittype
 * Check to load pager and bind keys
 */
var tableGrid = $(selector).jqGrid({
    url : url,
    datatype : "json",
    colModel : colModel,
    rowNum : 100,
    rowList : [100, 500, 1000],
    pager : pager,
    sortname : 'id',
    sortorder : "desc",
    height: 300,
    jsonReader : {
        repeatitems: false,
        id: "0"
    },
    editurl: $(selector).data('edit-url'),
    viewrecords: true,
    multiselect: true,
    onSelectRow: function(id){
         if(id && id!==lastSel){
            $(selector).restoreRow(lastSel);
            lastSel=id;
         }
   },
});

More…

Javascript

JqGrid save inline editing callback

1 Apr , 2015  

Here is a quick snippet for callback when saving inline editing in JqGrid:

1
2
3
4
5
6
7
8
9
10
11
12
// http://stackoverflow.com/questions/13303698/total-of-amount-in-jqgrid
ondblClickRow: function (rowid, name, val, iRow, iCol) {
    $(selector).jqGrid("editRow", rowid, {
        keys: true,
        aftersavefunc: function (rowid) {
            var $grid = $(selector);
            var colSum = $grid.jqGrid('getCol', 'debit', false, 'sum');
            $grid.jqGrid('footerData', 'set', { 'debit': colSum });
           
        }
    });
},

In this example, we do calculation after inline edit save.

Django,Javascript

JqGrid delete multiple select rows

1 Apr , 2015  

There is an issue if we delete rows using :

1
2
3
4
5
6
7
8
9
10
// Get all selected row
var rows = $(selector).jqGrid("getGridParam", "selarrrow");
console.log(rows);

// Iterate and delete
for (var i in rows) {
      console.log(i);
      console.log(rows[i]);
      $(selector).jqGrid('delRowData', rows[i]);
}

Only a few records will deleted.

The solution :

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * Delete data button handler
 * There is a bug if we delete by forloop, solution
 * http://www.trirand.com/blog/?page_id=393/bugs/delrowdata-bug-on-grid-with-multiselect
 */
$("a.delete-data").click(function(e) {
    e.preventDefault();

    var rowids = $(selector).jqGrid('getGridParam', 'selarrrow');
    for (var i = rowids.length - 1; i >= 0; i--) {
        $(selector).jqGrid('delRowData', rowids[i]);
    }
});