jQuery UI Widgets Forums Grid addrow in popup window

This topic contains 5 replies, has 2 voices, and was last updated by  andy 12 years ago.

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
  • addrow in popup window #13246

    andy
    Member

    Hi I am trying to combine the grid examples of the add button in the statusbar with the popup edit window. I just want to be able to add a new record with a popup modal window by pressing an Add button on the status bar. I’m using php with a Mysql db.

    It’s not quite happening for me.

    The grid renders correctly; the popup window opens and closes correctly but it’s not saving any data.

    In my simple example there are two fields: year_id (autoincrement integer primary key) and year (integer). As it’s an autoincrement primary key, I only need to save the “year” field.

    Here’s my code:

    <head>
    <link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
    <link rel="stylesheet" href="../../jqwidgets/styles/jqx.classic.css" type="text/css" />
    <link rel="stylesheet" href="../../jqwidgets/jqwidgets/styles/opmaakeditform.css" type="text/css" />
    <script type="text/javascript" src="../../scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxcore.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/jqxdata.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.sort.js"></script> 
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.pager.js"></script> 
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.selection.js"></script> 
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.grouping.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.filter.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxgrid.edit.js"></script> 
    <script type="text/javascript" src="../../jqwidgets/jqxwindow.js"></script>
    <script type="text/javascript" src="../../jqwidgets/jqxnumberinput.js"></script>
    <script type="text/javascript" src="../../jqwidgets/globalization/jquery.global.js"></script>
    <script type="text/javascript" src="../../jqwidgets/scripts/gettheme.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
    // prepare the data
    data = {};
    var theme = 'classic';
    var addrow = function () {
    var offset = $("#jqxgrid").offset();
    $("#AddWindow").jqxWindow({ position: { x: parseInt(offset.left) + 60, y: parseInt(offset.top) + 60} });
    // get the clicked row's data and initialize the input fields.
    //var dataRecord = $("#jqxgrid").jqxGrid('getrowdata', addrow);
    //$("#year_id").val(dataRecord.year_id);
    //$("#year").val(dataRecord.year);
    // show the popup window.
    $("#AddWindow").jqxWindow('show');
    //var datarow = generatedata(1); //FAIL ADD FUNCTION TO BE INCLUDED!!
    var datarow = {};
    }
    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'year_id', type: 'number' },
    { name: 'year', type: 'number' },
    ],
    //id: 'year_id',
    url: 'data.php',
    
    addrow: function (rowid, rowdata, commit) {
    var data = "insert=true&" + $.param(rowdata);
    $.ajax({
    dataType: 'json',
    url: 'data.php',
    data: data,
    success: function (data, status, xhr) {
     // update command is executed.
     commit(true);
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
     commit(false);
    }
    });
    }
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    // initialize jqxGrid
    $("#jqxgrid").jqxGrid(
    {
    width: 440,
    //height: 600,
    autoheight: true,
    theme: theme,
    source: dataAdapter,
    //editable: true,
    pageable: true,
    pagesize: 30,
    //statusbar start
    showstatusbar: true,
    renderstatusbar: function (statusbar) {
    // appends buttons to the status bar.
    var container = $("<div style='overflow: hidden; position: relative; margin: 5px;'></div>");
    var addButton = $("<div style='float: left; margin-left: 0px;'><img style='position: relative; margin-top: 2px;' src='../../images/add.png'/><span style='margin-left: 4px; position: relative; top: -3px;'>Add</span></div>");
    container.append(addButton);
    statusbar.append(container);
    addButton.jqxButton({ theme: theme, width: 60, height: 20 });
    // add new row.
    addButton.click(function (event) {
    // open the Add Record popup window when the user clicks a button.. EXPERIMENTAL
    addrow = addrow();
    $("#jqxgrid").jqxGrid('addrow', null, newrow);
    });
    },
    //statusbar end
    //columns start
    columns: [
    { text: 'ID', datafield: 'year_id', width: 100 },
    { text: 'Year', datafield: 'year' },
    ]
    //columns end
    });
    
    // initialize the Add popup window and buttons. EXPERIMENTAL
    $("#AddWindow").jqxWindow({ width: 400, resizable: false, theme: theme, isModal: true, autoOpen: false, cancelButton: $("#Cancel"), modalOpacity: 0.5, keyboardCloseKey: 'esc', title: 'Add Year', showAnimationDuration: 600, closeAnimationDuration: 200 });
    $("#Cancel").jqxButton({ theme: theme });
    $("#Save").jqxButton({ theme: theme });
    // update the added row when the user clicks the 'Save' button. EXPERIMENTAL
    $("#Save").click(function () {
    //if (editrow >= 0) {
    var newrow = { 
    year_id: $("#year_id").val(), 
    year: $("#year").val()
    };
    //$('#jqxgrid').jqxGrid('addrow', null, newdata);
    //commit(true);
    $("#AddWindow").jqxWindow('hide');
    //}
    });
    
    });
    </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 id="AddWindow">
    <div>Add</div>
    <div style="overflow: hidden;">
    <div class="formeditgroup2">
    <div class="formeditgroup1">
    <div class="formedittext">Id:</div>
    <div class="formeditinput"><input disabled="disabled" size="4" id="year_id" /></div>
    <div class="formedittext">Year:</div>
    <div class="formeditinput"><input size="10" id="year" /></div>
    </div>
    <div class="formeditgroup1">
    <div style='margin-top:15px;'>
    <input style="margin-right: 5px;" type="button" id="Save" value="Save" />
    <input id="Cancel" type="button" value="Cancel" />
    </div>
    </div>
    </div>
    </div> 
    </div>
    
    </body>

    Here’s the data processing file:

    #Include the connect.php file
     include('../../common/connect.php');
     #Connect to the database
     //connection String
     $connect = mysql_connect($hostname, $username, $password)
     or die('Could not connect: ' . mysql_error());
     //Select The database
     $bool = mysql_select_db($database, $connect);
     if ($bool === False){
     print "can't find $database";
     }
     // get data and store in a json array
     $query = "SELECT * FROM year";
    if (isset($_GET['insert']))
     {
     // INSERT COMMAND
     $insert_query = "INSERT INTO year (year) VALUES ('".$_GET['year']."')";
    $result = mysql_query($insert_query) or die("SQL Error 1: " . mysql_error());
     //mysql_close($connect);
     echo $result;
     }
     else if (isset($_GET['update']))
     {
     // UPDATE COMMAND
     // disable foreign key checks.
     //mysql_query("SET foreign_key_checks = 0");
     $update_query = "UPDATE year SET year='".$_GET['year']."' WHERE year_id='".$_GET['year_id']."'";
     $result = mysql_query($update_query) or die("SQL Error 1: " . mysql_error());
     // enable foreign key checks.
     //mysql_query("SET foreign_key_checks = 1");
     //mysql_close($connect);
     echo $result;
     }
     else if (isset($_GET['delete']))
     {
     // DELETE COMMAND
     $delete_query = "DELETE FROM year WHERE year_id='".$_GET['year_id']."'";
     $result = mysql_query($delete_query) or die("SQL Error 1: " . mysql_error());
     //mysql_close($connect);
     echo $result;
     }
     else
     {
     // SELECT COMMAND
     $result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
     while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
     $year[] = array(
     'year_id' => $row['year_id'],
     'year' => $row['year']
     );
     }
    header("Content-type: application/json");
     echo json_encode($year);
     }

    Can anyone advise where I’m going wrong?
    I suspect it’s something to do with the “addrow” parameters…?

    addrow in popup window #13260

    Peter Stoev
    Keymaster

    Hi Andy,

    Do you see the new row added visually to the client-side i.e to the Grid? If yes, then the commit(true) function is called. Otherwise, the server call has failed and the commit(false) function is called. If you see a row visually added, then the server synchronization with your Database fails in the PHP, MySQL code.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

    addrow in popup window #13273

    andy
    Member

    Thanks, Peter, for your advice.
    I now understand better and have got it working.
    There is only one thing that doesn’t work:
    The autoincremented id field (not set via the popup form or grid but by the database) does not display after adding the new row.
    It’s there and displays if you manually refresh the page.

    A couple of interesting attempts to find a workaround didn’t work either.

    For anyone trying to achieve the same thing, here’s the code (same data processing file as above):

    $(document).ready(function () {
    // prepare the data
    data = {};
    var theme = 'classic';
    
    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'year_id', type: 'number' },
    { name: 'year', type: 'number' },
    ],
    //id: 'year_id', //IF ENABLED DISPLAYS IN THE GRID AFTER ADD, BUT INCORRECT VALUE!
    url: 'data.php',
    
    
    addrow: function (rowid, rowdata, position, commit) {
    var data = "insert=true&" + $.param(rowdata);
    $.ajax({
    dataType: 'json',
    url: 'data.php',
    data: data,
    success: function (data, status, xhr) {
    	commit(true);
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
    	commit(false);
    }
    });
    }
    };
    
    var dataAdapter = new $.jqx.dataAdapter(source);
    // initialize jqxGrid
    $("#jqxgrid").jqxGrid(
    {
    width: 440,
    //height: 600,
    autoheight: true,
    theme: theme,
    source: dataAdapter,
    //editable: true,
    pageable: true,
    pagesize: 30,
    
    //STATUSBAR START
    showstatusbar: true,
    renderstatusbar: function (statusbar) {
    // appends buttons to the status bar.
    var container = $("
    "); var addButton = $("
    Add
    "); container.append(addButton); statusbar.append(container); addButton.jqxButton({ theme: theme, width: 60, height: 20 }); // add new row. addButton.click(function (event) { // open the Add Record popup window when the user clicks a button.. EXPERIMENTAL //addrow = addrow(); //$("#jqxgrid").jqxGrid('addrow', null, newrow); //$("#AddWindow").jqxWindow('open'); //$("#AddWindow").jqxWindow('move', offset.left + 30, offset.top + 30); $("#AddWindow").jqxWindow('show'); $("#year").focus(); }); }, //STATUSBAR END //COLUMNS START columns: [ { text: 'ID', datafield: 'year_id', width: 100 }, { text: 'Year', datafield: 'year' }, ] //COLUMNS END }); // INITIALIZE THE ADD POPUP WINDOW AND BUTTONS. $("#AddWindow").jqxWindow({ width: 400, resizable: false, theme: theme, isModal: true, autoOpen: false, cancelButton: $("#Cancel"), modalOpacity: 0.5, keyboardCloseKey: 'esc', title: 'Add Year', showAnimationDuration: 600, closeAnimationDuration: 200 }); var offset = $("#jqxgrid").offset(); $("#AddWindow").jqxWindow({ position: { x: parseInt(offset.left) + 60, y: parseInt(offset.top) + 60} }); $("#Cancel").jqxButton({ theme: theme }); $("#Save").jqxButton({ theme: theme }); // UPDATE THE ADDED ROW WHEN THE USER CLICKS THE 'SAVE' BUTTON. $("#Save").click(function () { var newrow={}; //REINITIALISE OTHERWISE SUBSEQUENT POPUPS WILL HAVE PREVIOUS VALUE. var newrow = { //year_id: $("#year_id").val(), // autoincrement - not to be saved year: $("#year").val() }; $("#jqxgrid").jqxGrid('addrow', null, newrow); $("#AddWindow").jqxWindow('hide'); //$("#jqxgrid").jqxGrid('refreshdata'); //DOESN'T REFRESH GRID DATA //$("#jqxgrid").jqxGrid('refresh'); //DOESN'T REFRESH GRID DATAVIEW }); });

    My attempts at manually rereshing the grid were unsuccessful:

    $("#Save").click(function () {
    var newrow={}; //REINITIALISE OTHERWISE SUBSEQUENT POPUPS WILL HAVE PREVIOUS VALUE.
    var newrow = {
    //year_id: $("#year_id").val(), // autoincrement - not to be saved
    year: $("#year").val()
    };
    $("#jqxgrid").jqxGrid('addrow', null, newrow);
    $("#AddWindow").jqxWindow('hide');
    //$("#jqxgrid").jqxGrid('refreshdata'); //DOESN'T REFRESH GRID DATA
    //$("#jqxgrid").jqxGrid('refresh'); //DOESN'T REFRESH GRID DATAVIEW
    });

    Also, if I specified the id in the source, it then successfully displayed the id after being added via the popup window, but displayed an incorrect value!!

    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'year_id', type: 'number' },
    { name: 'year', type: 'number' },
    ],
    //id: 'year_id', //IF ENABLED DISPLAYS IN THE GRID AFTER ADD, BUT INCORRECT VALUE!
    url: 'data.php',

    HOW DO YOU REFRESH THE GRID DATA / GRID VIEW?

    addrow in popup window #13276

    Peter Stoev
    Keymaster

    Hi andy,

    The “refreshdata” method refreshes the Grid(View + DataView) using the loaded data via the dataAdapter. The “refresh” method just invalidates the view, not the data. In case you wish the Grid to make a server call and to re-render, use the ‘updatebounddata’ method.

    Best Regards,
    Peter Stoev

    jQWidgets Team
    http://www.jqwidgets.com

    addrow in popup window #13278

    andy
    Member

    Thanks Peter for the quick feedback.

    Got it working now. 🙂

    For anyone else facing the same here is the code extract based on the above:

    Do NOT specify the id field for autoincrement fields in the source:

    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'year_id', type: 'number' },
    { name: 'year', type: 'number' },
    ],
    //id: 'year_id', //IF ENABLED DISPLAYS IN THE GRID AFTER ADD, BUT INCORRECT VALUE!
    url: 'data.php',
    addrow: function (rowid, rowdata, position, commit) {
    var data = "insert=true&" + $.param(rowdata);
    $.ajax({
    dataType: 'json',
    url: 'data.php',
    data: data,
    success: function (data, status, xhr) {
    commit(true);
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
    commit(false);
    }
    });
    }
    };

    After closing (hiding) the popup window, call “updatebounddata” and then “refresh” methods (not “refreshdata”). Seems to work:

    $("#Save").click(function () {
    var newrow={}; //REINITIALISE OTHERWISE SUBSEQUENT POPUPS WILL HAVE PREVIOUS VALUE.
    var newrow = {
    //year_id: $("#year_id").val(), // autoincrement - not to be saved
    year: $("#year").val()
    };
    $("#jqxgrid").jqxGrid('addrow', null, newrow);
    $("#AddWindow").jqxWindow('hide');
    $("#jqxgrid").jqxGrid('updatebounddata');
    $("#jqxgrid").jqxGrid('refresh');
    });
    addrow in popup window #13298

    andy
    Member

    PLEASE IGNORE MY LAST POST. I HADN’T TESTED IT PROPERLY AND THERE WERE ACTUALLY SOME PROBLEMS!! Sorry about that.

    DO specify the id field for autoincrement fields in the source:

    var source =
    {
    datatype: "json",
    datafields: [
    { name: 'year_id', type: 'number' },
    { name: 'year', type: 'number' },
    ],
    id: 'year_id', //ENABLE
    url: 'data.php',
    addrow: function (rowid, rowdata, position, commit) {
    var data = "insert=true&" + $.param(rowdata);
    $.ajax({
    dataType: 'json',
    url: 'data.php',
    data: data,
    success: function (data, status, xhr) {
    commit(true);
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
    commit(false);
    }
    });
    }
    };

    After closing (hiding) the popup window, call “updatebounddata” refreshes the gridview in synch with the database:

    $("#Save").click(function () {
    var newrow={}; //REINITIALISE NOT WORKING !!??
    var newrow = {
    //year_id: $("#year_id").val(), // autoincrement - not to be saved
    year: $("#year").val()
    };
    $("#jqxgrid").jqxGrid('addrow', null, newrow);
    $("#AddWindow").jqxWindow('hide');
    $("#jqxgrid").jqxGrid('updatebounddata');
    //$("#jqxgrid").jqxGrid('refresh'); // ONLY USE 'updatebounddata'!
    });

    The only unresolved issue is how to reinitialise the popup field values to null as they are currently set to the previous new entry.
    Anyone know how to reinitilise values in a popup? Thanks.

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

You must be logged in to reply to this topic.