What is the best way to prepopulate a new form entry with info from other most recent entries?

bcronrath
Kilo Guru

I was looking to make it so for a new table I created, if when a user first goes to enter a new entry, it prepopulates field info with info from the most recently created entry in that table.   Is the proper way to do this through dynamic defaults at the dictionary level?   If so I'm having trouble figuring out how to do this as the docs seem sparse to this functionality and it seems to want a filter only.   The other thing I was thinking was perhaps have a client script that populates the info onLoad, however I'm not sure how in this case I can do a check to make sure it's a new entry and not viewing an existing entry?

Best regards,

Brian

1 ACCEPTED SOLUTION

Brian,




In your onLoad client script add this condition


if(g_form.isNewRecord()){


write your code here


}


View solution in original post

7 REPLIES 7

Chuck Tomasi
Tera Patron

Hi Brian,



One option would be a before query business rule to set values in g_scratchpad, then (like you said) an onLoad client script to populate the fields. For your example, let's assume a table called u_table with fields u_bool, u_int, u_string, and u_ref.



The Before Query business rule would grab the latest created record. It might look something like this:



Name: Get Latest Values


Table: u_table


When: Before


Query: true


Advanced: true


Script:


var rec = new GlideRecord('u_table');


rec.orderByDesc('sys_created_on');


rec.setLimit(1);


rec.query();


if (rec.next()) {


        g_scratchpad.u_bool     = rec.u_bool;


        g_scratchpad.u_int       = rec.u_int;


        g_scratchpad.u_string = rec.u_string;


        g_scratchpad.u_ref       = rec.u_ref;


}



I know, I could have made an object within g_scratchpad, but for sake of simplicity...



Your onLoad client script would use those g_scratchpad values (within the default onLoad function wrapper).



g_form.setValue('u_bool', g_scratchpad.u_bool);


g_form.setValue('u_int', g_scratchpad.u_int);


g_form.setValue('u_string', g_scratchpad.u_string);


g_form.setValue('u_ref', g_scratchpad.u_ref);



This looks like it should accomplish what I'm trying to do, although I seem to be getting an error on the business rule saying g_scratchpad is undefined.   Is there anything special I need to do in order to declare the scratchpad?


Brian,



  That is beacuse, g_scratchpad object is only available for Display Business rule


ok it looks like I could resolve the scratchpad issue by changing the BR to run on display instead of before.   However, the only problem now here is it works and is pulling in the info, but is also doing it if I look at a past record since it doesn't really seem to have a way currently to limit the script to only run on new entries.  



Is there anything I might be able to add on the BR or client script to signify it should only run for new entries?