CRUD with cfgrid html format

On March 18, 2008, in ColdFusion, by Anuj Gakhar

After looking at Dan Vega’s series of posts on CFGRID usage, I decided to put together an example of CFGRID with a full CRUD functionality. ColdFusion 8 has introduced the new HTML format CFGRID which uses AJAX behind the scenes. I quite like the features it offers and I think with EXT framework behind the scenes, there are some nice things that can be done with it. Dan has already covered a lot of these areas and is doing a great job I think in writing these posts up.

My example is basically a “put together” kinda thing where I add custom buttons to the CFGRID toolbar for Add and Delete. The Editing can be done inline in the grid simply by double clicking the field you want to edit. I have used CFWINDOW for bringing up Add and Delete Screens. Its worth mentioning that, the delete functionality is inbuilt in the CFGRID tag and is one of the attributes but I could not find a way to bring up a confirmation window before the actual delete action was done, so I decided to add a custom button to the toolbar to first bring up a confirmation window and then fire off an AJAX call for the delete action. Its also worth mentioning that I have mostly taken the example from Dan’s post
and then modified it to add the add/delete functionality. I thought it was worth putting a full working example together.

Bear in mind that I am not good at design at all, so feel free to change the cfwindow styles I have used to something more pleasing for the eye. It would be really cool to have an automatic detection of the fields you want to be able to display in the ‘Add Window’ from the grid columns, as opposed to hardcoding the form (like I have done), but I would leave that exercise for later, mainly because of lack of time.

The example uses the built-in datasource cfartgallery so should work if you simple copy paste the code in a folder under your webroot.

Here are some screenshots of how it looks and you can download the full code from here including the cfm and cfc.

initial grid

add to grid

delete in grid

P.S. I had to set display=false for some of the columns in there for the screenshots to fit in there but feel free to change that.

Tagged with:  

94 Responses to CRUD with cfgrid html format

  1. Scott says:

    I have a simple HTML cfgrid that was works fine on FF and suddenly stopped working on IE6. Here’s the deal, I had added the cumulative 8.01 hotfix patch AND the hf801-71634 patch. That’s when I started getting a blank grid and a “‘ColdFusion.Grid.Actions’ is null or not an object” message in the IE6 error console. I’m going to remove the 71634 patch to see if that makes a difference.

  2. Scott says:

    Removal of the .jar file in that patch appears to have corrected the problem.

  3. Jay says:

    Has anyone had success using a cfwindow to *edit* existing db records (as opposed to just adding a new record…)?

    I have my code creating the window with my update form (without values for the inputs) fine. I then remotely call my cfc method to query the record details (by id), and then in the result handler for that remote call, I try to set the values of the form inputs. Unfortunately there’s where I run into a problem.

    The result handler seems to run…I can alert() from it just fine, and even alert values from the result object of the remote cfc method call.

    However the form input values won’t update – UNLESS I add an alert in the remote handler.

    So to put this another way, I have (code shortened for brevity…):

    updateWin = function() {
    // code to instantiate new proxy, set callbackhandler, etc. and invoke the remote cfc method
    }

    updateWin_resultHandler = function(r) {
    document.getElementById(‘uf_title’).value = r.DATA.TITLE[0];
    }

    …but the form inputs (i.e. title) values do not get set. However if I add an alert (any alert) to the result handler, then the form input values *do* get set, so if I change that result handler to the following, it will work:

    updateWin_resultHandler = function(r) {
    alert(‘foo’);
    document.getElementById(‘uf_title’).value = r.DATA.TITLE[0];
    }

    Any ideas?

    I’ve left a lot out to keep the post short – I have the correct ajaximport and ajaxproxy tags, window attributes, etc all set, and updateWin() is called from a button that passes a bound id from a grid row selection etc.

    I just can’t figure out why the .value set won’t work unless I add an alert there…seems really straing.

    Thanks in advance for any help/suggestions.

  4. Jono says:

    Hi guys, I’m new in cf, I already have a cfgrid load (bind to a data base table ) in html from a table releated to another one, with foreign key, but I dont wanna show the id of the key, I want to show the value or description of the foreign key, how do i do this? how can I take a cfgridcolumn and show the value or make a bind of the value of other table?

  5. Bud Hines says:

    Anuj,

    When I copy this code inside an empty cfm – it works great. When I copy the code inside my template, the add and delete buttons disappear? Any thoughts on how to correct this problem. Also, as a note, the grid shows up empty until I commend out this call in my application cfc: On a separate note, I needed to comment out this call in my application cfc to get the data to show up:

    Any thoughts on how to resolve these two issues?

    thanks,
    Bud

  6. Anuj Gakhar says:

    @Jono, you would have to manage that in your query I guess if I am not mistaken.

    @Bud, your comment missed out the code that you wanted to show. And add and delete buttons must be disappearing because of some css that could be overwritten, needs to be checked.

  7. […] else.  For instance, some time ago, I was searching for CFGRID samples when I came across “CRUD with cfgrid html format“.  I thought, I would share it it with you.  I am curius to see what you guys stumble […]

  8. Trent says:

    Cool demo. Any chance of adding a “modify” button next to the add and delete buttons? Thanks.

  9. Trent says:

    Cool demo. Any chance of adding a “modify” button next to the add and delete buttons? Thanks

  10. Anuj Gakhar says:

    @Trent, you can modify a record by double clicking any row and you should be able to edit inline. However, it shouldnt be too hard to add a Modify button and populate the form with selected row as well.

  11. E.Jones says:

    This is fantastic. I have one problem: the grid does not refresh after I add a record. (If I manually refresh the page from the browser, the grid reloads and the new record is indeed there.) I have spent a great deal of time troubleshooting this and would appreciate any help.

  12. gaver says:

    Howdy Anuj!
    Thanks for the great article on using the CFGrid element.

    I have a quick question for you…

    I would like to be able to pass a dynamic variable to the CFC to construct a where clause that would only return a set of values corresponding to the value that is passed to it.

    For example.
    If I wanted to pass a variable that limited the selection of the data returned to only those individuals with the last name of Johnson.

    How would I go about constructing or modifying the existing CFC declaration and what other changes might be required to facilitate the modification?

    I hope you can help me figure this out…

    Gaver

  13. Chris Bowyer says:

    As a thought, why not pass the variable in your database query…

    WHERE lastName = ‘#lastName#’

  14. gaver says:

    Dang…

    I always do my best thinkin right after I click the submit button 😉

    I found the solution to my question – amazingly simple, I guess I was looking for a more difficult solution..

    anyway… I stored the var in a SESSION variable and dropped it into a where clause in the CFC for the intial grid load query.

    Works like a charm

    G

  15. gaver says:

    Thanks Chris, I probably should have hit the refresh button before I posted my last response… 🙂

    I was stumped trying to pass a variable inside the cfc declaration – spent most of the day trying to figure out why the orderID value was getting double posted orderID:44,44 instead of a single value. orderID:44

    I don’t know why – but I thought I “had” to move variables into the CFC in the delcaration of the function.

    Which obviously (now I can say that) is not true.

    Thanks again,

    G

  16. Gianluca says:

    Firt of all thi exapmle is fantastic !!

    I’ve resolved problem with IE8 about dataproxy error moving line “” the line before ”
    // create a new JS proxy object for the CFC” now works fine.
    Thanks Anuj Gakhar

  17. Anuj Gakhar says:

    @Gianluca, Glad you like it. thanks.

  18. Adam says:

    I think I figured out the issue with dataproxy object not found, simply First: change the jsclassname to “DataProxy” and Second: change the variable from dataproxy to Aproxy. it seems the there is confusion between the class name and the variable name?

  19. Phillip Senn says:

    I’m not sure what’s supposed to happen when you add or delete a row. Is the grid suppose to refresh?
    You forgot to include a body tag and to close your table tag.
    I added this example as garden #034 to http://www.cfmzengarden.com.
    If you would like to polish it, I’d be glad to send you the code that I’ve got.

  20. Robert Gravel says:

    I’m having the same problem as per Phillip. The grid is not refreshing. Any idea?

  21. James Lamar says:

    Great post, but I have been unable to reproduce. I am using CF9, bt here is my error: Error invoking CFC /data.cfc : error executing database query.

    Any help would be much appreciated. Thanks!

  22. Anuj Gakhar says:

    @James, is your data.cfc in the same folder. Read the comments in this post, a few people had this issue.

  23. James Lamar says:

    Actually, I did make some progress yesterday, but still no cigar. I ended up installing cf8 and cf9 side by side. Sure enough the code worked flawlessly in 8, but gave me the same error in 9. I added a cfajaximport reference to the old Ajax folder from cf8 and I at least got the data to show, but still will not update. Also, I cannot view the content inside the cfwindows. I stripped the styling out to no avail. I have also tried replacing the JavaScript with the updated versions in Extjs 3, but it just broke it as before. Thanks.

  24. Chiru says:

    Hi,

    I am using cf8 unix version and I am getting this error. I think the args.bind is not returning any data. The data.cfc location is /datalayer/data.cfc.
    I am calling the ajaxproxy as .

    Here is the error message I am getting. Please help. Thanks
    The specified CFC data could not be found.
    The path to the CFC must be specified as a full path, or as a relative path from the current template, without the use of mappings.

    The error occurred in /vob/parts/grid.cfm: line 88

    86 :
    87 :
    88 :
    89 :
    90 :

  25. Chiru says:

    How to fix this error? Please help

    The specified CFC data could not be found.
    The path to the CFC must be specified as a full path, or as a relative path from the current template, without the use of mappings.

    The error occurred in /vob/parts/grid.cfm: line 88

    86 :
    87 :
    88 :
    89 :
    90 :

  26. KJ says:

    I have a bindable cfgrid in cf8 that updates just fine (I see the red triangle in the cell). What I need to know is how to refresh the grid after the update so the original cfc that fills the grid runs again to show new updated information. I found these commands but not sure where to put them or how to call them. Should they be in the page or the cfc? ColdFusion.Grid.refresh(‘mygrid’, true) ColdFusion.Grid.getGridObject(‘MyGrid’).render();

  27. prims says:

    Anuj, I read so many articles to get the simple example on how to make use of cfgrid functionality. Finally I am happy that I ended up this site. Great job and thanks for you and all those CF’ers commenting solutions on this page.

    Is there a easy way to get related select using cfgrid and which is editable.

    Finally I would like to know how to get refresh work on the example you are showing. Thanks in advance.

  28. jy says:

    will this cfgrid work on cf7 too?
    thanks

  29. Fabio B. says:

    Sorting does not work!

    SELECT * FROM xxx
    ORDER BY

    This is my function, the query is good and works but the json returned isn’t good! 🙁 It lose sorting.

    How can I do? What can I check??

  30. Brian says:

    I am having some problems with the delete function. When I click yes to confirm on the modal it doesnt do anything. Firebug says grid.getSelections(); is not a function

  31. Erol says:

    grid is null or not an object error in line :
    —> var gridHead = grid.getView().getHeaderPanel(true);

    any ideas?

    // add the 3 custom buttons to the toolbar
    function init() {
    grid = ColdFusion.Grid.getGridObject(“ServiceCategoryGrid”);
    —> var gridHead = grid.getView().getHeaderPanel(true);

    gridE = ColdFusion.Grid.getGridObject(“EstimateGrid”);
    var gridHeadE = gridE.getView().getHeaderPanel(true);

    var tbar = new Ext.Toolbar(gridHead);
    tbar.addButton({text:”Add”, handler:onAdd });
    tbar.addSeparator();
    tbar.addButton({ text:”Update”, handler:onUpdate });
    tbar.addSeparator();
    tbar.addButton({ text:”Delete”, handler:onDelete });

    var tbarE = new Ext.Toolbar(gridHeadE);
    tbarE.addButton({text:”Add”, handler:onAddE });
    tbarE.addSeparator();
    tbarE.addButton({ text:”Edit”, handler:onEditE });
    tbarE.addSeparator();
    tbarE.addButton({ text:”Delete”, handler:onDeleteE });
    }

  32. Mike Collins says:

    I like it. Need cfqueryparam inside the data.cfc editartist method though.

  33. This no longer works in cf9. The underlying architecture was changed. I had implemented the version the Dan Vega had blogged but as soon as I upgraded from 8 to 9 it all broke. No work around as far as I am aware of.

  34. Personally I never understood the data.cfc full functionality, with regards to the handling in Cf8 and Cf9. My code is working ok in CF8 but seems to fall over in Cf9??

  35. Lisa Walker says:

    applied cf 8.0.0 security patch and now cfgrid doesn’t work in production site.
    error:http: Error invoking CFC Source/4/volunteer_maintenance/committeeproductlinking.cfc : Not Found

    info:widget: Created grid, id: committees

    info:http: HTTP GET Source/4/volunteer_maintenance/committeeproductlinking.cfc?method=getproducts&returnFormat=json&argumentCollection=%7B%22page%22%3A1%2C%22pageSize%22%3A20%2C%22gridsortcolumn%22%3A%22%22%2C%22gridsortdir%22%3A%22%22%7D&_cf_nodebug=true&_cf_nocache=true&_cf_clientid=332BB39BD6A314C17468DBFDD869B034&_cf_rc=0

    info:http: Invoking CFC: Source/4/volunteer_maintenance/committeeproductlinking.cfc , function: getproducts , arguments: {“page”:1,”pageSize”:20,”gridsortcolumn”:””,”gridsortdir”:””}

    info:LogReader: LogReader initialized

    info:global: Logger initialized

    Worked before the patch was applied and still works in my test site on the same server as long as the cfc file is in the production folder.
    I’ve tried moving the cfc to a separate folder and creating a mapping for it, etc.. The CFIDE is a VD. Without it the grid doesn’t come up at all.

  36. rAMESH says:

    When i delete the grid is not refreshing, could you please tell me what should i do to fix this.
    My environment is
    CF8 and Sqlserver

  37. egemen says:

    hello, i have some issue about coldfusion grid,i try grid example but cold fusion given this error “The tag handler grid does not have a setter for the attribute checkBoxSelection specified in the Tag Library Descriptor.”,please can you help me?
    my code is very simple

    SELECT id, name, surname,email
    FROM egemen_deneme

    cfgrid Example
    Currently available courses

    .

  38. sam says:

    I am getting aproxy is undefind or not an object in IE not in firefox. any idea?

    Thanks

  39. deneme says:

    I’m not positive where you are getting your info, however good topic. I needs to spend some time finding out much more or working out more. Thank you for excellent info I was searching for this info for my mission.

  40. I am having the same problem that Fabio B. is having I think. I also cannot sort for some reason.

    I am getting a good query but it is not returning a good json. Then the sorting gets all messed up and I don’t know what to do. How can I fix this?

    Thanks
    Shelly

  41. Wendy says:

    Cannot get the grid to bind (display). Any ideas? I am getting no output even just returning a string from the function.

    CFC:

    SELECT *
    FROM PTS_Work
    WHERE PersonnelID = #PID# AND
    ProjectID = #URL.PROJECTID#

    order by #ARGUMENTS.gridsortcolumn# #ARGUMENTS.gridsortdirection#

    <!— —>


    You’ve Thrown a Database Error


    #cfcatch.message#
    Caught an exception, type = #CFCATCH.TYPE#
    The contents of the tag stack are:

    #i# #sCurrent[“ID”]#
    (#sCurrent[“LINE”]#,#sCurrent[“COLUMN”]#)
    #sCurrent[“TEMPLATE”]#

    update PTS_Work set #colname# =
    ‘#value#’
    where workid = #ARGUMENTS.gridrow.workid#

    delete from PTS_Work where workid = #ARGUMENTS.gridrow.workid#

    INSERT INTO PTS_Work
    (
    projectid,
    hours,
    date1,
    workcompleted,
    personnelid
    )
    VALUES
    (
    #URL.ProjectID#,
    ,
    ,#now()#
    ,
    ,#pid#
    )

    DELETE FROM PTS_Work
    WHERE
    workid =

    CFGRID:

    !——>

    select * from IBIS.PTS_Work
    where ProjectID = #URL.ProjectID# and
    PersonnelID = #PID#

    select Short_Title from IBIS.PTS_Project
    where ProjectID = #URL.ProjectID#

    #WorkMode# Work Item

    // create a new JS proxy object for the CFC
    var dataproxy = new cfcproxy();
    dataproxy.setCallbackHandler(handleResult);

    // this function recieves the response from CFC whenever a CFC function is called.
    // we are simply alerting the response but we could do more if we had to.
    function handleResult(response)
    {
    alert(response);
    }

    // the init()
    function init(){
    grid = ColdFusion.Grid.getGridObject(“Work_Grid”);

    // get the header and fotoer objects
    var gridHead = grid.getView().getHeaderPanel(true);
    var tbar = new Ext.Toolbar(gridHead);
    var gridFoot = grid.getView().getFooterPanel(true);
    var ds = grid.getDataSource();

    // add the 2 custom buttons to the toolbar
    tbar.addButton({text:”Add Work Item”, handler:onAdd });
    tbar.addSeparator();
    tbar.addButton({ text:”Delete Work Item”, handler:onDelete });

    // add a row double click event for the grid rows.
    // the double click will open a popup window for editing the row.
    var sm = grid.getSelectionModel();
    grid.on(‘rowdblclick’,function(grid, rowIndex, record){
    var rec = ds.getAt(rowIndex); // get the clicked row
    populateForm(rec); // populate the form with values
    ColdFusion.Window.show(‘addWorkWin’); // display the window
    });

    // this shows the display message by default
    var paging = new Ext.PagingToolbar(gridFoot,ds,{
    pageSize:10, //number of records displayed in grid
    displayInfo:true, // change this to false, if you dont want info displayed
    displayMsg:’Displaying records {0} – {1} of {2}’,
    emptyMsg:”No records to display”
    });

    // add a custom combobox to the grid header – this combobox lets you choose the number of rows you want to see
    cb = new Ext.form.ComboBox({
    id:”pagingCombo”,
    emptyText:”Rows per page”,
    mode:”local”,
    triggerAction:”all”,
    displayField:”text”,
    valueField:”value”,
    store:new Ext.data.SimpleStore({
    fields: [“value”, “text”],
    data: [
    [“5″,”5 rows per page”],
    [“10″,”10 rows per page”],
    [“15″,”15 rows per page”],
    [“20″,”20 rows per page”]
    ]
    })
    });

    // add event listener to combobox
    // this code will update the grid pageSize
    cb.addListener(“select”,function(combo,record,index){
    // the new pageSize from combobox – it needs to have parseInt() else it starts acting weird
    var numRows = parseInt(record.data.value);
    paging.pageSize = parseInt(numRows);
    paging.onClick(“refresh”);
    });

    // add the paging combo to right side of the toolbar
    Ext.fly(tbar.addSpacer().getEl().parentNode).setStyle(‘width’, ‘100%’);
    tbar.add(cb);

    }

    function populateForm(record){
    // gets the selected row from double click event and populates the form
    // could also use ColdFusion.getElementValue() here which gets the bound grid row but I find this method better

    // the form
    var frm = document.forms[“frmWork”];

    // default values if using the “add artist” mode
    var hours = “dummy”;
    var workcompleted = “dummy”;
    var email = “dummy@dummy.com”;
    var address = “dummy”;
    var city = “dummy”;
    var state = “CA”;
    var postalcode= “754”;
    var artistid = “0”;
    var btntext = “Add Work Item”;

    if(record)
    {
    // values for the selected row
    if(record.data.HOURS.length != 0) hours = record.data.HOURS;
    if(record.data.WORKCOMPLETED.length != 0) workcompleted = record.data.WORKCOMPLETED;
    // if(record.data.EMAIL.length != 0) email = record.data.EMAIL;
    // if(record.data.ADDRESS.length != 0) address = record.data.ADDRESS;
    // if(record.data.CITY.length != 0) city = record.data.CITY;
    // if(record.data.STATE.length != 0) state = record.data.STATE;
    // if(record.data.POSTALCODE.length != 0) postalcode = record.data.POSTALCODE;
    // if(record.data.ARTISTID != ‘0’) artistid = record.data.ARTISTID;
    // if(record.data.ARTISTID != ‘0’) ; btntext = “Update Artist”;
    }
    //populate the form, finally
    frm.hours.value = hours;
    frm.txtWorkCompleted.value = workcompleted;
    // frm.txtLastName.value = lname;
    // frm.txtEmail.value = email;
    // frm.txtAddress.value = address;
    // frm.txtCity.value = city;
    // frm.txtPostalCode.value= postalcode;
    // frm.txtState.value = state;
    // frm.artistid.value = artistid;
    frm.btnAction.value = btntext;
    }

    function onAdd(button,event){
    populateForm(false);
    ColdFusion.Window.show(‘addWorkWin’);
    }
    function onDelete(){
    ColdFusion.Window.show(‘deleteWorkWin’);
    }

    function savework()
    {
    //send data to CFC to add artist, the result will be handled by handleResult function above
    var f = document.frmArtist;
    dataproxy.saveArtist(
    f.artistid.value
    ,f.txtFirstName.value
    ,f.txtLastName.value
    ,f.txtEmail.value
    ,f.txtAddress.value
    ,f.txtCity.value
    ,f.txtState.value
    ,f.txtPostalCode.value
    );
    ColdFusion.Grid.refresh(‘Work_Grid’, true);
    ColdFusion.Window.hide(‘addWorkWin’);
    }

    function deleteWork(s)
    {
    // if user choose to delete, then send the CFC call, otherwise just sit back!
    if (s == ‘yes’)
    {
    var grid = ColdFusion.Grid.getGridObject(“Work_Grid”);
    var record = grid.getSelections();
    // remember, CF makes column names to all UPPERCASE, so dont forget to do that
    dataproxy.deleteWork(record[0].data.WORKID);
    }
    ColdFusion.Grid.refresh(‘Work_Grid’, true);
    ColdFusion.Window.hide(‘deleteWorkWin’);
    }

    a:link {text-decoration: underline}
    a:visited {text-decoration: underline}
    a:active {text-decoration: underline}
    a:hover {text-decoration: underline}
    .normal2 {font-size: 9px;}
    a {font-family: Geneva, Arial, Helvetica, sans-serif;}

    #WorkGrid .x-grid-row td {white-space:normal;}

    function checkForm(form) {

    var ok = “yes”;

    if ((form.Hours.value == null) || (form.Hours.value == “”)) {
    alert(“Please enter hours worked on this task.”);
    form.Hours.focus();
    ok = “no”;
    }
    else if (form.Hours.value.length > 10) {
    alert(“Hours is limited to 10 characters”);
    form.Hours.focus();
    ok = “no”;
    }
    else if ((form.WorkCompl.value == null) ||(form.WorkCompl.value == “”)) {
    alert(“Please enter a description of the work completed for this project.”);
    form.WorkCompl.focus();
    ok = “no”;
    }
    else if (form.WorkCompl.value.length > 500) {
    alert(“Description of work completed is limited to 500 characters”);
    form.WorkCompl.focus();
    ok = “no”;
    }

    if (ok == “no”) {
    return false;
    }
    else {
    return true;
    }
    }

    function init(){
    //get the grid component
    grid=ColdFusion.Grid.getGridObject(“work_grid”);
    }

     

    Work Performed – #FormTitle#

    Hours: *

    Work Completed: *

    #WorkCompl#

      

    <!—

    —>

    <!—

    —>

    Please Confirm this action.

    Hours:

    Work Completed:
    #WorkCompl#

    • Wendy says:

      UPDATE on CODE:

      Somehow my copy/paste skills went awry!!! Here is my code:

      CFC:

      SELECT *
      FROM PTS_Work
      WHERE PersonnelID = #PID# AND
      ProjectID = #URL.PROJECTID#

      order by #ARGUMENTS.gridsortcolumn# #ARGUMENTS.gridsortdirection#

      <!— —>


      You’ve Thrown a Database Error


      #cfcatch.message#
      Caught an exception, type = #CFCATCH.TYPE#
      The contents of the tag stack are:

      #i# #sCurrent[“ID”]#
      (#sCurrent[“LINE”]#,#sCurrent[“COLUMN”]#)
      #sCurrent[“TEMPLATE”]#

      update PTS_Work set #colname# =
      ‘#value#’
      where workid = #ARGUMENTS.gridrow.workid#

      delete from PTS_Work where workid = #ARGUMENTS.gridrow.workid#

      INSERT INTO PTS_Work
      (
      projectid,
      hours,
      date1,
      workcompleted,
      personnelid
      )
      VALUES
      (
      #URL.ProjectID#,
      ,
      ,#now()#
      ,
      ,#pid#
      )

      DELETE FROM PTS_Work
      WHERE
      workid =

      GRID:

      <!——>

      select * from IBIS.PTS_Work
      where ProjectID = #URL.ProjectID# and
      PersonnelID = #PID#

      select Short_Title from IBIS.PTS_Project
      where ProjectID = #URL.ProjectID#

      #WorkMode# Work Item

      // create a new JS proxy object for the CFC
      var dataproxy = new cfcproxy();
      dataproxy.setCallbackHandler(handleResult);

      // this function recieves the response from CFC whenever a CFC function is called.
      // we are simply alerting the response but we could do more if we had to.
      function handleResult(response)
      {
      alert(response);
      }

      // the init()
      function init(){
      grid = ColdFusion.Grid.getGridObject(“Work_Grid”);

      // get the header and fotoer objects
      var gridHead = grid.getView().getHeaderPanel(true);
      var tbar = new Ext.Toolbar(gridHead);
      var gridFoot = grid.getView().getFooterPanel(true);
      var ds = grid.getDataSource();

      // add the 2 custom buttons to the toolbar
      tbar.addButton({text:”Add Work Item”, handler:onAdd });
      tbar.addSeparator();
      tbar.addButton({ text:”Delete Work Item”, handler:onDelete });

      // add a row double click event for the grid rows.
      // the double click will open a popup window for editing the row.
      var sm = grid.getSelectionModel();
      grid.on(‘rowdblclick’,function(grid, rowIndex, record){
      var rec = ds.getAt(rowIndex); // get the clicked row
      populateForm(rec); // populate the form with values
      ColdFusion.Window.show(‘addWorkWin’); // display the window
      });

      // this shows the display message by default
      var paging = new Ext.PagingToolbar(gridFoot,ds,{
      pageSize:10, //number of records displayed in grid
      displayInfo:true, // change this to false, if you dont want info displayed
      displayMsg:’Displaying records {0} – {1} of {2}’,
      emptyMsg:”No records to display”
      });

      // add a custom combobox to the grid header – this combobox lets you choose the number of rows you want to see
      cb = new Ext.form.ComboBox({
      id:”pagingCombo”,
      emptyText:”Rows per page”,
      mode:”local”,
      triggerAction:”all”,
      displayField:”text”,
      valueField:”value”,
      store:new Ext.data.SimpleStore({
      fields: [“value”, “text”],
      data: [
      [“5″,”5 rows per page”],
      [“10″,”10 rows per page”],
      [“15″,”15 rows per page”],
      [“20″,”20 rows per page”]
      ]
      })
      });

      // add event listener to combobox
      // this code will update the grid pageSize
      cb.addListener(“select”,function(combo,record,index){
      // the new pageSize from combobox – it needs to have parseInt() else it starts acting weird
      var numRows = parseInt(record.data.value);
      paging.pageSize = parseInt(numRows);
      paging.onClick(“refresh”);
      });

      // add the paging combo to right side of the toolbar
      Ext.fly(tbar.addSpacer().getEl().parentNode).setStyle(‘width’, ‘100%’);
      tbar.add(cb);

      }

      function populateForm(record){
      // gets the selected row from double click event and populates the form
      // could also use ColdFusion.getElementValue() here which gets the bound grid row but I find this method better

      // the form
      var frm = document.forms[“frmWork”];

      // default values if using the “add artist” mode
      var hours = “dummy”;
      var workcompleted = “dummy”;
      var email = “dummy@dummy.com”;
      var address = “dummy”;
      var city = “dummy”;
      var state = “CA”;
      var postalcode= “754”;
      var artistid = “0”;
      var btntext = “Add Work Item”;

      if(record)
      {
      // values for the selected row
      if(record.data.HOURS.length != 0) hours = record.data.HOURS;
      if(record.data.WORKCOMPLETED.length != 0) workcompleted = record.data.WORKCOMPLETED;
      // if(record.data.EMAIL.length != 0) email = record.data.EMAIL;
      // if(record.data.ADDRESS.length != 0) address = record.data.ADDRESS;
      // if(record.data.CITY.length != 0) city = record.data.CITY;
      // if(record.data.STATE.length != 0) state = record.data.STATE;
      // if(record.data.POSTALCODE.length != 0) postalcode = record.data.POSTALCODE;
      // if(record.data.ARTISTID != ‘0’) artistid = record.data.ARTISTID;
      // if(record.data.ARTISTID != ‘0’) ; btntext = “Update Artist”;
      }
      //populate the form, finally
      frm.hours.value = hours;
      frm.txtWorkCompleted.value = workcompleted;
      // frm.txtLastName.value = lname;
      // frm.txtEmail.value = email;
      // frm.txtAddress.value = address;
      // frm.txtCity.value = city;
      // frm.txtPostalCode.value= postalcode;
      // frm.txtState.value = state;
      // frm.artistid.value = artistid;
      frm.btnAction.value = btntext;
      }

      function onAdd(button,event){
      populateForm(false);
      ColdFusion.Window.show(‘addWorkWin’);
      }
      function onDelete(){
      ColdFusion.Window.show(‘deleteWorkWin’);
      }

      function savework()
      {
      //send data to CFC to add artist, the result will be handled by handleResult function above
      var f = document.frmArtist;
      dataproxy.saveArtist(
      f.artistid.value
      ,f.txtFirstName.value
      ,f.txtLastName.value
      ,f.txtEmail.value
      ,f.txtAddress.value
      ,f.txtCity.value
      ,f.txtState.value
      ,f.txtPostalCode.value
      );
      ColdFusion.Grid.refresh(‘Work_Grid’, true);
      ColdFusion.Window.hide(‘addWorkWin’);
      }

      function deleteWork(s)
      {
      // if user choose to delete, then send the CFC call, otherwise just sit back!
      if (s == ‘yes’)
      {
      var grid = ColdFusion.Grid.getGridObject(“Work_Grid”);
      var record = grid.getSelections();
      // remember, CF makes column names to all UPPERCASE, so dont forget to do that
      dataproxy.deleteWork(record[0].data.WORKID);
      }
      ColdFusion.Grid.refresh(‘Work_Grid’, true);
      ColdFusion.Window.hide(‘deleteWorkWin’);
      }

      a:link {text-decoration: underline}
      a:visited {text-decoration: underline}
      a:active {text-decoration: underline}
      a:hover {text-decoration: underline}
      .normal2 {font-size: 9px;}
      a {font-family: Geneva, Arial, Helvetica, sans-serif;}

      #WorkGrid .x-grid-row td {white-space:normal;}

      function checkForm(form) {

      var ok = “yes”;

      if ((form.Hours.value == null) || (form.Hours.value == “”)) {
      alert(“Please enter hours worked on this task.”);
      form.Hours.focus();
      ok = “no”;
      }
      else if (form.Hours.value.length > 10) {
      alert(“Hours is limited to 10 characters”);
      form.Hours.focus();
      ok = “no”;
      }
      else if ((form.WorkCompl.value == null) ||(form.WorkCompl.value == “”)) {
      alert(“Please enter a description of the work completed for this project.”);
      form.WorkCompl.focus();
      ok = “no”;
      }
      else if (form.WorkCompl.value.length > 500) {
      alert(“Description of work completed is limited to 500 characters”);
      form.WorkCompl.focus();
      ok = “no”;
      }

      if (ok == “no”) {
      return false;
      }
      else {
      return true;
      }
      }

      function init(){
      //get the grid component
      grid=ColdFusion.Grid.getGridObject(“work_grid”);
      }

       

      Work Performed – #FormTitle#

      Hours: *

      Work Completed: *

      #WorkCompl#

        

      <!—

      —>

      <!—

      —>

      Please Confirm this action.

      Hours:

      Work Completed:
      #WorkCompl#

  42. Wendy says:

    Lets try it one more time – it appears that I can’t include the entire code for the CFGRID so – here is the snippet that was used:

    <!—

    —>

    Please Confirm this action.

    Hours:

    Work Completed:
    #WorkCompl#

  43. Wendy says:

    Not sure what is happening – my code is getting replaced by something else. If this doesn’t work – I will try again later. Sorry for clogging up this forum.

    Please Confirm this action.

    Hours:

    Work Completed:
    #WorkCompl#

Leave a Reply to Phillip Senn Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: