jQuery UI Widgets Forums Grid Edit Grid doesn't update grid -but does update DB

This topic contains 5 replies, has 3 voices, and was last updated by  Dimitar 8 years, 10 months ago.

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

  • atrumm
    Participant

    Hi guys! I’ve got another one for you! 🙂

    I’m doing something similar to this post: http://www.jqwidgets.com/community/topic/popup-editing-option-in-row-click/

    My grid is simple, and it pulls from a MySql db. it works great, the popup works, etc. I can add a record fine. But when I edit the behavior is strange. The change hits the database, but the row becomes blank. If I click edit again, the edit form is populated with the new data. But say instead I click edit on another record, and then cancel (or save), then go back and click edit on the record I edited (which is now a blank row) – the form is populated with the previous data. If I refresh the page, everything’s right. The weirdest part is, we have another grid that I copied and edited the code for to make this grid…and that grid does fine (with this part – it has another bug I may post about separately LOL)

    This is in an MVC – I’ll go ahead and paste the code of the three files involved since they’re not too huge

    The main page with the grid:

    <script type="text/javascript">
        $(document).ready(function () {
            var theme = '<?php echo $theme; ?>';
    
            // Create a jqxMenu
            $("#appMenu").jqxMenu({ theme: theme, width: '99%'});
    
            var editrow = -1;
            var CancelButton = $("#Cancel");
            $("#rigID").jqxInput({ theme: theme, width: 120,  disabled: true });
            $("#rigName").jqxInput({ theme: theme, width: 120 });
            CancelButton.jqxButton({ theme: theme});
            $("#Save").jqxButton({ theme: theme});
    
            var rigs =
            {
                datatype: "json",
                datafields: [
                    { name: 'RigIDRig' },
                    { name: 'Rig' }
                ],
                id: 'rig_id',
                url: '<?php echo URL; ?>rig/fillRigGrid',
                updaterow: function (rowid, rowdata, commit) {
                    // synchronize with the server - send update command
                    var data = "update=true&RigName=" + rowdata.RigName;
                    data = data + "&RigID=" + rowdata.RigID;
                    $.ajax({
                        dataType: 'json',
                        url: '<?php echo URL; ?>rig/update',
                        data: data,
                        success: function (data, status, xhr) {
                            // update command is executed.
                            commit(true);
                        },
                        error: function () {
                            // cancel changes.
                            commit(false);
                        }
                    });
                },
                addrow: function (rowid, rowdata, commit) {
                    // synchronize with the server - send add command
                    var data = "update=true&RigName=" + rowdata.RigName;
                    $.ajax({
                        dataType: 'json',
                        url: '<?php echo URL; ?>rig/add',
                        data: data,
                        success: function (data, status, xhr) {
                            // add command is executed.
                            commit(true);
                        },
                        error: function () {
                            // cancel changes.
                            commit(false);
                        }
                    });
                }
            };
    
            var rigsAdapter = new $.jqx.dataAdapter(rigs, {
                autoBind: true
            });
            // initialize jqxGrid
            $("#jqxgrid").jqxGrid(
                {
                    width: '99%',
                    height: '99%',
                    selectionmode: 'singlerow',
                    source: rigsAdapter,
                    theme: theme,
                    editable: false,
                    columnsresize: true,
                    columns:
                        [
                            { text: 'Rig ID', editable: false, datafield: 'RigIDRig', width: '5%' },
                            // do we need to show the rig assignments in this? or have a rig assignments button?
                            { text: 'Rig Name', datafield: 'Rig', width: '15%' },
                            { text: 'Edit', datafield: 'Edit', width: '5%', columntype: 'button', cellsrenderer: function () {
                                return "Edit";
                            }, buttonclick: function (row) {
                                // open the popup window when the user clicks edit button.
                                editrow = row;
                                $("#rigEntryWindowTitle").text("Edit Rig");
                                var offset = $("#jqxgrid").offset();
                                $("#rigEntryWindow").jqxWindow({ position: { x: parseInt(offset.left) + 60, y: parseInt(offset.top) + 60},width: "500px"});
                                // get the clicked row's data and initialize the input fields.
                                var dataRecord = $("#jqxgrid").jqxGrid('getrowdata', editrow);
                                $("#rigID").val(dataRecord.RigIDRig);
                                $("#rigName").val(dataRecord.Rig);
                                // show the popup window.
                                $("#rigEntryWindow").jqxWindow('open');
                            }
                            }
                        ]
                });
            // initialize the popup window and buttons.
            $("#rigEntryWindow").jqxWindow({
                width: 250, resizable: false, theme: theme, isModal: true, autoOpen: false, cancelButton: CancelButton, modalOpacity: 0.01
            });
    
            // update the edited row when the user clicks the 'Save' button.
            $("#Save").click(function () {
                if (editrow >= 0) {
                    var row = { RigID: $("#rigID").val(), RigName: $("#rigName").val()};
    
                    var rowID = $('#jqxgrid').jqxGrid('getrowid', editrow);
                    $('#jqxgrid').jqxGrid('updaterow', rowID, row);
                    $("#rigEntryWindow").jqxWindow('hide');
                }
                else
                {
                    var row = { RigName: $("#rigName").val()};
    
                    $('#jqxgrid').jqxGrid('addrow', null, row);
                    rigsAdapter.dataBind();
    
                    $("#rigEntryWindow").jqxWindow('hide');
                }
            });
    
            // open the userEntryWindow with no data in it
            $("#AddRigMenuItem").click(function () {
                $("#rigEntryWindowTitle").text("Add User");
                var offset = $("#jqxgrid").offset();
                $("#rigEntryWindow").jqxWindow({ position: { x: parseInt(offset.left) + 60, y: parseInt(offset.top) + 60},width: "500px"});
                $("#rigID").val("");
                $("#rigName").val("");
                $("#rigEntryWindow").jqxWindow('open');
            });
        });
    </script>
    </head>
    <body>
    <div id='jqxWidget'>
        <div id='appMenu'>
            <ul>
                <?php require VIEWS_PATH . '_templates/tabs.php'; ?>
                <li id="AddRigMenuItem">Add Rig</li>
            </ul>
        </div>
        <div id="jqxgrid">
        </div>
        <div id="rigEntryWindow">
            <div id="rigEntryWindowTitle">
                Edit
            </div>
            <div style="overflow: hidden;">
                <table>
                    <tr>
                        <td align="right" nowrap>Rig ID:</td>
                        <td align="left" nowrap><input type="text" id="rigID" /></td>
                    </tr>
                    <tr>
                        <td align="right" nowrap>Rig Name:</td>
                        <td align="left" nowrap><input type="text" id="rigName" /></td>
                    </tr>
                    <tr>
                        <td align="right" nowrap></td>
                        <td style="padding-top: 10px;" align="right" nowrap>
                            <input style="margin-right: 5px;" type="button" id="Save" value="Save" />
                            <input id="Cancel" type="button" value="Cancel" />
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>

    The model:

    <?php
    /**
     * WellModel
     * Handles data for wells (pages that show well headers / lists)
     */
    
    class RigModel {
        /**
         * Constructor, expects a Database connection
         * @param Database $db The Database object
         */
        public function __construct(Database $db)
        {
            $this->db = $db;
        }
        
        /**
         * Gets an array that contains all the rigs in the database. 
         * @return json encoded array of rigs
         */
        public function getAllrigs()
        {
            $sth = $this->db->prepare("SELECT rig_id, rig_name FROM rig ORDER BY rig_name");
            $sth->execute();
            foreach ($sth->fetchAll() as $rig) {
                $all_rigs[] = array(
                    'RigIDRig' => $rig->rig_id,
                    'Rig' => $rig->rig_name
                );
            }
    
            return json_encode($all_rigs);
        }
        
        public function updateRig()
        {
            $sql = "UPDATE rig SET rig_name = :rig_name WHERE rig_id = :rig_id;";
                                    
            file_put_contents("application/log/error.log","\n".$sql."\n", FILE_APPEND | LOCK_EX);
            $sth = $this->db->prepare($sql);
            $sth->execute(array(':rig_name' => $_GET['RigName'], ':rig_id' => $_GET['RigID']));
                
            $count =  $sth->rowCount();
            if ($count == 1) {
                return true;
            } else {
                $_SESSION["feedback_negative"][] = FEEDBACK_USER_EDITING_FAILED;
            }
            // default return
            return false;
        }
    
        public function addRig()
        {
            $sql = "INSERT INTO rig (rig_name) VALUES (:rig_name)";
            file_put_contents("application/log/error.log","\n".$sql."\n", FILE_APPEND | LOCK_EX);
    
            $sth = $this->db->prepare($sql);
            $sth->execute(array(':rig_name' => $_GET['RigName']));
    
            $count =  $sth->rowCount();
            if ($count == 1) {            
                return true;
            } else {
                $_SESSION["feedback_negative"][] = FEEDBACK_USER_EDITING_FAILED;
            }
            // default return
            return false;
        }
    
    } 

    The controller:

    <?php
    /**
     * Class Overview
     * This controller shows the data of one or all well(s)
     */
    
    class Rig extends Controller
    {
        private $model = null;
    
        /**
         * Construct this object by extending the basic Controller class
         */
        function __construct()
        {
            parent::__construct();
            Auth::handleLogin();
            $this->model = $this->loadModel('Rig');
        }
    
        /**
         * This method controls what happens when the application first initiates on the desktop in your app
         * beginning the rendering process.
         */
        function index()
        {
            $this->view->render('rig/index');
        }
    
        
        /**
         * Fills the rig drop down in the wellheader grid.
         */
        function fillRigGrid()
        {
            echo $this->model->getAllrigs();
        }
        
        /**
         * Adds a rig.
         */
        function add()
        {
            echo $this->model->addRig();
        }
        
        /**
         * Updates a rig.
         */
        function update()
        {
            echo $this->model->updateRig();
        }
        
    } 

    Thanks in advance guys! I’ll post if I fix it before anybody responds!

    — Aaron


    atrumm
    Participant

    Oh.
    my.
    god.

    just needed to add this line:

    rigsAdapter.dataBind();

    do the save button function, update case. *headdesk* 🙂


    drv232
    Participant

    Hi…Thanks for the code…Was really helpful..

    Can you post the file in
    <?php require VIEWS_PATH . '_templates/tabs.php'; ?>

    I’m trying to create the function to add new rows by checking your code out…I believe I need this file as well if I’m not mistaken


    Dimitar
    Participant

    Hello drv232,

    You may also take a look at our Build CRUD Web App with jqxGrid using PHP and MySQL tutorial which shows how to add rows to the database through jqxGrid, among other functionalities.

    Best Regards,
    Dimitar

    jQWidgets team
    http://www.jqwidgets.com/


    drv232
    Participant

    Hi Dimitar,
    it uses the generaterow() function. I don’t want to use static data. can you provide an example without using generate row


    Dimitar
    Participant

    Hi drv232,

    Here is how to add a new row without the use of generaterow. You can set whatever values you wish to the fields of the datarow object (static or dynamic):

    $("#addrowbutton").bind('click', function() {
        var rowscount = $("#jqxgrid").jqxGrid('getdatainformation').rowscount;
        var datarow = {
            EmployeeID: rowscount + 1,
            FirstName: 'Lars',
            LastName: 'Peterson',
            Title: 'CEO',
            Address: '35 Bishop St.',
            City: 'Boston',
            Country: 'USA'
        };
        $("#jqxgrid").jqxGrid('addrow', null, datarow);
    });

    Best Regards,
    Dimitar

    jQWidgets team
    http://www.jqwidgets.com/

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

You must be logged in to reply to this topic.