Script Example : Using Script to Save List Items
There are cases when the complexity of your business cases require that you need to take over and save list items manually.
Besides controlling how data are saved through a normal PowerForms designed form, or by using the ListAndForm control to save "related" items to connected lists, saving through script is now available (v.2.4)
The "template" object provided to most of scripts in PowerForms supports a SaveRecord method.
The SaveRecord method accepts the following parameters:
URL (string) : represents the url of the target list
LIST (string) : the title of the target list
DATA (list of objects) : represents an array of the data to be saved. the array should follow the FIELD1, VALUE1, FIELD2, VALUE2, ... pattern.
CALLBACK : the callback method that will be invoked as soon as saving is complete (saving list items is asynchronous)
The callback method should accept 2 parameters (the template and the result of the save-action).
We want use a button to manually save a list item in a list and inform the user of the result.
We should add an ActionButton (which supports script) and add the following script :
T = template
def Callback(e) :
c = T.GetControl("c_Result")
if e.Error != None :
url = "http://servername/site1"
list = "Clients"
value = template.GetControl("c_Source").GetValue()
data = ["Title", value, "Status", "Open"]
template.SaveRecord(url, list, data, Callback)
In order to handle the asynchronous call we must define a callback method that will be invoked as soon as the action completes. The is acchieved by the def Callback(e) part of the script. If no handling is required, None should be passed for that parameter.
The "e" result contains an "Error" variable that contains the Error if any otherwise it is empty (None for python)
The SaveRecord method performs an INSERT action if no "ID" field is provided otherwise it performs an UPDATE action.
The "e" parameter in INSERT actions contains a property named "NewId" which contains the ID of the newly inserted record.
The T = template command, enables the callback function to have access to the template variable.
To actually insert a new list item we should use the template.SaveRecord method passing the URL, the ListName and an array of FieldName/FieldValue pairs.