jQWidgets Forums

jQuery UI Widgets Forums Grid add new blank row

This topic contains 12 replies, has 5 voices, and was last updated by  Peter Stoev 10 years, 11 months ago.

Viewing 13 posts - 1 through 13 (of 13 total)
  • Author
  • add new blank row #5954

    mr_putersmit
    Participant

    Hello

    Is it possible to add a new blank row so I can add a new entry and send to MySql? Thanks

    add new blank row #5956

    mr_putersmit
    Participant

    Cam I take it then that this is not possible? I am familiar with the technique for adding a row which updates grid from db, but i need to add new entry to db. If someone could just can confirm whether this is possible, I would be grateful. Thanks

    add new blank row #5958

    Peter Stoev
    Keymaster

    To add a blank row, you can do this:

    $("#jqxgrid").jqxGrid('addrow', null, []);

    I suggest you to take a look at this sample: createremoveupdatedata.htm.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

    add new blank row #5961

    mr_putersmit
    Participant

    Thank you peter. However, that example seems to be inserting data into the grid from either db or xml. What I am trying to achieve is, when I click add new row button, blank cells are inserted into the grid so I can enter data and save them to MySql. Thanks

    add new blank row #5962

    Peter Stoev
    Keymaster

    Ok, and this code inserts a blank row: $(“#jqxgrid”).jqxGrid(‘addrow’, null, []);. If you turn on the cells editing feature, you will be also able to edit the cells in the blank row.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

    add new blank row #5963

    mr_putersmit
    Participant

    Thank you Peter.

    add new blank row #6038

    mr_putersmit
    Participant

    Peter
    I am struggling to get this to work. I can include blank row but it is not getting the next id. How can I change my code to get next id (auto inc) and also save to db. Also, is there a way to confirm or cancel before I enter into db? Thanks

    $(document).ready(function () {
    // prepare the data
    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'id'},
    { name: 'type'},
    { name: 'service'},
    { name: 'quantity'},
    { name: 'department'},
    { name: 'date', type: 'date', format: 'yyyy-MM-dd HH:mm:ss'},
    ],
    url: 'data.php',
    updaterow: function (rowid, rowdata) {
    // synchronize with the server - send update command
    var data = "update=true&type=" + rowdata.type + "&service=" + rowdata.service + "&quantity=" + rowdata.quantity;
    data = data + "&department=" + rowdata.department + "&date=" + rowdata.date;
    data = data + "&id=" + rowdata.id;

    $.ajax({
    dataType: 'json',
    url: 'data.php',
    data: data,
    success: function (data, status, xhr) {
    // update command is executed.
    alert(data);
    }
    });
    }
    };

    var dataAdapter = new $.jqx.dataAdapter(source);

    $("#jqxgrid").jqxGrid(
    {
    source: source,
    theme: 'classic',
    width: 900,
    altrows: true,
    pageable: true,
    sortable: true,
    filterable: true,
    autoheight: true,
    pagesizeoptions: ['10', '20', '30', '40'],
    editable: true,
    ready: function () {
    var button = $("");
    button.jqxButton({ height: 20 });
    button.click(function () {
    $("#jqxgrid").jqxGrid('addrow', null, []);
    });
    $(".jqx-grid-pager > div:first").append(button);
    },

    columns: [
    { text: 'id', editable: false, datafield: 'id', width: 100 },
    { text: 'Type', datafield: 'type', width: 150},
    { text: 'Service', datafield: 'service', width: 150 },
    { text: 'Quantity', datafield: 'quantity', width: 180 },
    { text: 'Department', datafield: 'department', width: 90 },
    { text: 'Date', datafield: 'date', cellsformat: "dd/MM/yyyy HH:mm:ss", width: 230 }
    ]
    });
    });

    add new blank row #6046

    Peter Stoev
    Keymaster

    Hi mr_putersmit,

    You can use the ‘getdatainformation’ to retrieve the rows count and pass it to the ‘addrow’ method.

    For example:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
    <script type="text/javascript" src="../../scripts/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxcore.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxdata.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxbuttons.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxscrollbar.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxmenu.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxcheckbox.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxlistbox.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxdropdownlist.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
    // prepare the data
    var data = {};
    var firstNames =
    [
    "Andrew", "Nancy", "Shelley", "Regina", "Yoshi", "Antoni", "Mayumi", "Ian", "Peter", "Lars", "Petra", "Martin", "Sven", "Elio", "Beate", "Cheryl", "Michael", "Guylene"
    ];
    var lastNames =
    [
    "Fuller", "Davolio", "Burke", "Murphy", "Nagase", "Saavedra", "Ohno", "Devling", "Wilson", "Peterson", "Winkler", "Bein", "Petersen", "Rossi", "Vileid", "Saylor", "Bjorn", "Nodier"
    ];
    var productNames =
    [
    "Black Tea", "Green Tea", "Caffe Espresso", "Doubleshot Espresso", "Caffe Latte", "White Chocolate Mocha", "Cramel Latte", "Caffe Americano", "Cappuccino", "Espresso Truffle", "Espresso con Panna", "Peppermint Mocha Twist"
    ];
    var priceValues =
    [
    "2.25", "1.5", "3.0", "3.3", "4.5", "3.6", "3.8", "2.5", "5.0", "1.75", "3.25", "4.0"
    ];
    for (var i = 0; i < 10; i++) {
    var row = {};
    var productindex = Math.floor(Math.random() * productNames.length);
    var price = parseFloat(priceValues[productindex]);
    var quantity = 1 + Math.round(Math.random() * 10);
    row["firstname"] = firstNames[Math.floor(Math.random() * firstNames.length)];
    row["lastname"] = lastNames[Math.floor(Math.random() * lastNames.length)];
    row["productname"] = productNames[productindex];
    row["price"] = price;
    row["quantity"] = quantity;
    row["total"] = price * quantity;
    data[i] = row;
    }
    var source =
    {
    localdata: data,
    datatype: "local",
    addrow: function (rowid, rowdata) {
    // synchronize with the server - send insert command
    }
    };
    // initialize jqxGrid
    $("#jqxgrid").jqxGrid(
    {
    width: 500,
    height: 350,
    source: source,
    columns: [
    { text: 'First Name', datafield: 'firstname', width: 100 },
    { text: 'Last Name', datafield: 'lastname', width: 100 },
    { text: 'Product', datafield: 'productname', width: 180 },
    { text: 'Quantity', datafield: 'quantity', width: 80, cellsalign: 'right' },
    { text: 'Unit Price', datafield: 'price', width: 90, cellsalign: 'right', cellsformat: 'c2' },
    { text: 'Total', datafield: 'total', width: 100, cellsalign: 'right', cellsformat: 'c2' }
    ]
    });
    $("#addrowbutton").jqxButton({});
    // create new row.
    $("#addrowbutton").bind('click', function () {
    var id = $("#jqxgrid").jqxGrid('getdatainformation').rowscount;
    $("#jqxgrid").jqxGrid('addrow', id, []);
    });
    });
    </script>
    </head>
    <body class='default'>
    <div id='jqxWidget' style="font-size: 13px; font-family: Verdana; float: left;">
    <div style="float: left;" id="jqxgrid">
    </div>
    <div style="margin-left: 10px; float: left;">
    <div>
    <input id="addrowbutton" type="button" value="Add New Row" />
    </div>
    </div>
    </div>
    </body>
    </html>

    Synchronization with the DB depends on your implementation. jqxGrid only calls updaterow, addrow and deleterow functions when a row is updated, added or deleted in the client-side. Implementation of synchronization with the server is demonstrated in this help topic: php-server-side-grid-crud.htm.

    Hope this helps.

    Best Wishes,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

    add new blank row #56539

    sridhar.sethu
    Participant

    Hello Peter,

    i am trying to add new blank row. so i have put the following line:
    $(“#jqxgrid”).jqxGrid(‘addrow’, null, []);

    but, it is not displaying the row(new blank row) on the screen untill i refresh the page. how can i show the newly added row (blank row) without refreshing the page.

    plz help,

    thanks,
    Sridhar

    Ok, and this code inserts a blank row: $(“#jqxgrid”).jqxGrid(‘addrow’, null, []);. If you turn on the cells editing feature, you will be also able to edit the cells in the blank row.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

    add new blank row #56544

    Peter Stoev
    Keymaster

    Hi Sridhar,

    Live Demo for adding a blank row: http://jsfiddle.net/Sfgcw/

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

    add new blank row #56545

    stevewhite
    Participant

    I just got through struggling with this only my flow is a little different. First, I have the database assign the key, and I pre-save the record so that the edit does the updaterow. My solution places an add button on the statusbar, synchs in the addrow callback for the dataadapter and if successful updates the id of the new row.

          var renderStatusBar = function (statusbar) {
              // appends statusBar container to the status bar.
              statusbar.append($('statusbar'));
              $('#new').jqxButton({  width: 60, height: 20 });
              $('#delete').jqxButton({  width: 65, height: 20 });
              $('#save').jqxButton({  width: 65, height: 20 });
              $('#lookup').jqxButton({  width: 50, height: 20 });
              // add new row.
              $('#new').unbind('click').bind('click',function (event) {// bug causing dual click events work around is to unbind first
                  var rowscount = $("#jqxgrid").jqxGrid('getdatainformation').rowscount;
                  var contx = contextHistory[contextHistory.length -1];
                  var newRowData = {};
                  newRowData[contx.ctxPrefix + "_owner_id"] = 2;
                  newRowData[contx.ctxPrefix + "_visibility_ids"] = '{2}';
                  $("#jqxgrid").jqxGrid('addrow', null, newRowData, 'last');
                  $("#jqxgrid").jqxGrid('ensurerowvisible', rowscount);
                  return false;
              });
    ...
    

    Note that I was getting 2 rows for every click and applied an unbind work around (note the return false for bubbling). Also note that the I have a breadCrumb trail for my database table browser. The contx.ctxPrefix is the table prefix for the column you could simply replaces these with newRowData[‘yourcolumnname’]=yourdefaultvalue. You could use DB defaults except for the case where the default information is user specific.

              addrow: function (rowid, rowdata, position, commit) { //addrow callback in source of dataadapter
                var pkey = prefix+'_id',
                    data ='{"'+prefix+'":[{"'+prefix+'_id":"new"';
                for (colname in rowdata) {
                  if (colname == pkey || colname.substring(0,4) != prefix+'_') continue; //skip non record columns and the primary key
                  newVal = rowdata[colname];
                  oldVal = ((isNaN(rowid) || rowid >= this.originaldata.length)?null : this.originaldata[rowid][colname]);
                  if (newVal != oldVal) {
                    data += ',"' + colname + '":"' + newVal + '"';
                  }
                }//{"tok":[{"tok_id":355,"tok_grapheme_ids":"{594,595,596,597,598}"},...]}
                data += '}]}';
                $.ajax({
                    dataType: 'json',
                    url: 'http://localhost/services/saveEntityData.php',
                    data: 'data='+data,
                    success: function (data, status, xhr) {
                        var entity = entityInfo.entities[prefix].name;
                        // add record suceeded.
                        if (Object.size(data)) { // ensure we have a valid object
                          if (data[entity].columns &&
                              data[entity].records[0] &&
                              data[entity].columns.indexOf(prefix + "_id") > -1) {
                            newID = data[entity].records[0][data[entity].columns.indexOf(prefix + "_id")];
                            commit(true,newID); //tell grid about the new id.
                            rowid = $('#jqxgrid').jqxGrid('getrowboundindexbyid', newID);
                            $('#jqxgrid').jqxGrid('setcellvalue', rowid, prefix + "_id", newID); //update the cell with the new value
                            return;
                          }
                          if (data[entity].errors.length) {
                            alert("An error occurred saving while trying to add a record. Error: " + data[entity].errors.join());
                          }
                          if (data[error]) {
                            alert("An error occurred while trying to add a record. Error: " + data[error]);
                          }
                        }
                        commit(false);
                    },
    ...
    
    Hope this helps,
    
    Cheers,
    Steve
    
    add new blank row #58230

    nix
    Participant

    hi ,

    I have a grid containing dropdownlist and datetimeinput controls in their columns along with input text columns. While adding new row my controls are getting loaded but am not able to set default value of the dropdownlist as —-select—– in new blank row inserted

    Thanks in advance

    add new blank row #58236

    Peter Stoev
    Keymaster

    Hi nix,

    To set default value of an editor, you will have to implement the column’s initeditor callback function.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

Viewing 13 posts - 1 through 13 (of 13 total)

You must be logged in to reply to this topic.