BPC-Components

Home > Products > BPC PowerForms - Silverlight > Knowledge Base > Scripting and Formulas > Using Iron Python Scripting in PowerForms

Iron Python Scripting in PowerForms

Python scripting is a powerful tool for your customizations.

You can find here some common scripts you can use in your forms. 

IMPORTANT: Python uses "Significant Whitespace", meaning that whitespaces in front of commands are important for the interpreter to identify code blocks.  

You can apply scripting to either Control Value Change events, or to handle the Form Validation and the completion of Form loading.

VALUE CHANGE EVENTS

For Value Change events, you can apply the script in the control properties window, in the Scripts tab.

Variables :

control : this variable points to the control that raised the event.

template : this variable references the current form

Code

value = control.GetValue()

if value == "Resolved" :

  template.GetControl("c_Priority").SetValue("Normal")

IMPORTANT :

Value Change events are raised when controls value change. This happens both by user interaction or during form loading.

When the form initializes to display an existing record, it sets the appropriate record values to controls, one by one.

This also raises the ValueChange event so users should be carefull when writing scripts because some actions should only happen on user action.

For example you may want when the STATUS control of your form is set to "CLOSED", to set a value to the "ClosedBy" control. Since the ValueChange event would also be raised when editing an existing record, this script should only be executed when a user makes that change.

For that reason, a property exists in the "template" object called "Loaded" which indicates if the form has finished loading or not.

Code

# Form is still loading

template.Loaded == False

# Form has completed loading

template.Loaded == True

So for our example you should write something like the following :

Code

# Get the value from the current control raising the event

value = control.GetValue()

# Check control value

if value == "Closed" :

# Enable the Progress control (this happens every time)

  template.GetControl("c_Progress").SetEnable(False)

# Setting the value should NOT be executed during form loading

  if template.Loaded :

    template.GetControl("c_ClosedBy").SetValue(template.CurrentUser.FullName)

else :

  template.GetControl("c_Progress").SetEnable(True)

FORM VALIDATION EVENT

The form Validation event is raised just before submitting the record for save.

Variables :

template : this variable references the current form

result : boolean variable that should be returned according to the validation result. Return False when validation fails

error : string variable that should contain the error messagee that should be displayed to the user.

Example :

Code

result = True

error = ""

method = template.GetControl("c_PayMethod").GetValue()

card = template.GetControl("c_CreditCard").GetValue()

if method == "CreditCard" and card == "" :

  result = False

  error = "You should type your credit card number"

IMPORTANT :

You should always define the "result" and "error" variables for validation to work as expected.

You should initialize the "result" to True and the "error" variable to a blank string, and then perform validations. In case validation fails, you should set False to the "result" variable and fill the "error" variable with the error message you want to display to the end user.

FORM LOAD COMPLETED EVENT

This event is raised after the controls have been placed on the form and before the data item values are applied.

Variables :

template : this variable references the current form

dataitem : this variable contains the fieldName/fieldValue pairs of the actual data from the record.

Available methods for the dataitem :

dataitem.GetValue("ColumnName")

returns the value from the record

dataitem.GetValue_Value("ColumnName")

returns the ID part of a lookup column value

dataitem.GetValue_Name("ColumnName")

returns the TITLE part of a lookup column value

Example :

Code

if dataitem.GetValue_Value("Customer") == "1" :

  template.DisableTab(2)

 

Control Methods

control.SetValue(string) 

Sets the value to a control

Code

template.GetControl("c_Title").SetValue("This is the Title")

# FOR LOOKUP COLUMN CONTROLS

template.GetControl("c_Country").SetValue("4;#England")

control.GetValue()

Retrieves the current value of the control (string). 

Code

# DISABLE A CONTROL IF THE VALUE OF THE CURRENT CONTROL IS BLANK

if control.GetValue() == "" :

  template.GetControl("c_Control1").SetEnable(False)

else :

  template.GetControl("c_Control1").SetEnable(True)

GetValue_Value()

Retrieves the "value" portion of the control value in case of lookup columns where the value is in the ID;#NAME format

Code

c = template.GetControl("c_Country")

# RETURNS : 34;#France

value = c.GetValue()

# RETURNS : 34

id = c.GetValue_Value()

# RETURNS : France

name = c.GetValue_Name() 

GetValue_Name()

Retrieves the "name" portion of the control value 

GetDisplayValue()

Some controls return a user-friendly representation of their value. 

SetFontBold(bool)    (For boolean operations you should use "True" or "False")

Code

template.GetControl("c_Title").SetFontBold(True)

SetForeColor(string)

Sets the foreground color of a control. You can use named colors ("White", "Red", etc) or hexadedimal colors (i.e. "#AB557D") 

Code

if control.GetValue() == "4" :

  control.SetForeColor("Red")

else :

  control.SetForeColor("Black")

SetBackColor(string)

Sets the background of the control

Code

teplate.GetControl("c_OrderNo").SetBackColor("#CC6600")

SetBorderThickness(int)

Set a control to look required under conditions using script

Code

countryValue = template.GetControl("c_Country").GetValue()

stateControl = template.GetControl("c_State")

if countryValue == "USA" :

  stateControl.SetBorderThickness(2)

  stateControl.SetBorderColor("Red")

else :

  stateControl.SetBorderThickness(1)

  stateControl.SetBorderColor("Gray")

SetBorderColor(string) 

SetEnable(bool)

Code

template.GetControl("c_City").SetEnable(False)

SetVisible(bool)

GetVisible()

Returns if the control is visible or not 

Code

if template.GetControl("c_Country").GetVisible() :

  template.GetControl("c_City").SetVisible(True)

else :

  template.GetControl("c_City").SetVisible(False)

SetReadOnly(bool)

 

Template Methods

 

GetControl(name)

Retrieves a control from the form

Code

customer_control = template.GetControl("c_Customer")

customer_control.SetValue("")

Loaded

The "Loaded" property is readonly and returns True if the form initialization has completed. Otherwise it returns False.

Code

if template.Loaded :

  template.GetControl("c_Status").SetValue("Closed")

SaveRecord(), SaveAndExit()

Saves the current record. Can be used inside Action Buttons to apply Save operations to the form without using the default toolbar buttons.

Code

template.SaveRecord()

DeleteRecord()

Deletes the current record

Code

template.DeleteRecord()

CancelRecord()

Cancels the record editing

Code

template.DeleteRecord()

GetListId(), GetListName(), GetListUrl()

Retrieves list metadata

ReloadValue(controlName)

Reloads the value of a control

Code

template.ReloadValue("c_Customer")

EnableTab(int index)

Enables a form tab. The index is zero based. (0 for first tab, 1 for the second, etc)

Code

if template.GetControl("c_ID") != "" :

  template.DisableTab(1)

else :

  template.EnableTab(1)

DisableTab(int index) 

Disables a form tab

ShowTab(int index) 

Shows a (hidden) form tab. Index is zero based.

Code

template.ShowTab(2)

HideTab(int index) 

Hides a form tab

ExecuteJavascript(string script)

Executes javascript command(s).

Code

template.ExecuteJavascript("document.location.href='http://www.bpc-components.com';")

SaveRecord(url, listName, data) 

Saves a record (Insert or Update depends on the ID value provided)

Code

# CREATE AN ARRAY OF FIELD_NAME/FIELD_VALUE PAIRS

data = ["ID", "1", "Title", "Tom Parker", "Age", "34"]

template.SaveRecord(http://serverName, "Contacts", data)

SaveRecord(url, listName, data, callback) 

Saves a record and calls a callback method when complete

DeleteRecord(url, listName, id, callback) 

Deletes a record

LoadRecord(url, listName, id, callback) 

Loads an existing record.

Example : LoadRecord("http://servername/sitename, "TestList", "1", callback)

where "callback" is a method defined inside script

SetDataItemValue(fieldName, value)

You can use this method to set values to the current record. If you set values to fields bound to controls, the values will be overriden before record update. So it can normally be used for columns that do not have a bound control on the form.

Code

template.SetDataItemValue("ColumnName", "1")

GetDataItemValue(fieldName)

 Retrieves a value from the underlying record (this value may be different from the current value inside the bound control)

Code

# LOAD COMPLETED SCRIPT

CID = 15

def Add(x, y) :

  return x+y

# VALUE CHANGE SCRIPT

value = Add(CID, CID)

# THE FOLLOWING COMMAND WILL SET THE VALUE 30 (15 + 15) TO THE "CID" GLOBAL BARIABLE

template.SetGlobalVariable("CID", value)

SetSectionBackColor(index, color)

Changes the background color of a section on the form.

Code

template.SetSectionBackColor(2, "Red")

SetSectionBorderColor(index, color)

Changes the border color of a section on the form.

Code

template.SetSectionBorderColor(2, "#C2C2C2")

SetSectionBorderThickness(index, thickness)

Chages the border thickness of a section on the form

Code

template.SetSectionBorderThickness(2, 3)

SetSectionHeader(index, headerText)

Changes the header/caption of a section

Code

template.SetSectionHeader(2, "Item Details")

 

ReloadRecord()

Reloads the current record from the SharePoint list

Code

template.ReloadRecord()

 

ExpandSection(index)

Expands the form section

Code

template.ExpandSection(1)

 

CollapseSection(index)

Collapses the form section

Code

template.CollapseSection(0)

 

HideButton(string)

Hides a toolbar button. Available values are : "New", "Save", "SaveAndExit", "Delete", "Cancel", "Edit", "Help", "Design", "Customizations"

Code

template.HideButton("Save")

template.HideButton("SaveAndExit")

 

ShowButton(string)

Shows a (hidden) toolbar button. Available values are : "New", "Save", "SaveAndExit", "Delete", "Cancel", "Edit", "Help", "Design", "Customizations"

Code

template.HideButton("Save")

template.HideButton("SaveAndExit")

 

SetGlobalVariable(string, object)

Sets the value for a global variable. Global variables are created inside the "LoadCompleted" script.

Code

template.SetGlobalVariable("ItemCount", 20)

ExecuteSQLQuery(string queryListUrl, string queryListName, string queryName, FieldValue[] parameters, callback)

Executes a SQL Query defined in the specified list. Read more about how to define a sql query here.

Code

import clr
clr.AddReferenceToFile("BPC.PowerForms.Core.dll")
from BPC.PowerForms.Core import FieldValue
from System import Array

def callback(e) :
  if e.Error != None :
    template.GetControl("c_SQLQueryCount").SetValue(e.Error.Message)
  else :
    template.GetControl("c_SQLQueryCount").SetValue(e.DataItems.Count.ToString())

values = []
fv = FieldValue("ID", "")
values.Add(fv)
template.ExecuteSQLQuery(http://serverName, "BPC PowerForms Sql Queries", "GetProducts", values, callback)

ExecuteSQLQuery(string queryName, callback)

Executes a predefined sql qeury (from the Sql Queries section of the designer)

Code

import clr

def callback(e) :
  if e.Error != None :
    template.GetControl("c_SQLQueryCount").SetValue(e.Error.Message)
  else :
    template.GetControl("c_SQLQueryCount").SetValue(e.DataItems.Count.ToString())

template.ExecuteSQLQuery("Products", callback)

CallWebService(string wsName, callback)

Executes a predefined web service (from the web services section of the designer)

Code

def callback(e) :
  c = template.GetControl("c_WSResult")
  txt = ""
  for li in e.DataItems :
    txt = txt + li.GetValue("ows_ID") + ". " + li.GetValue("ows_Title") + "\r"

  c.SetValue(txt)

template.CallWebService("GetCustomers", callback)

 

EXAMPLES:

Change Control Appearance depending on control value 

Code

value = control.GetValue()

owner = template.GetControl("c_Title")

if value == "Error" : 

  owner.SetBackColor("#F15200") 

  owner.SetBorderColor("Red") 

  owner.SetBorderThickness(2)

else : 

  owner.SetBorderThickness(1) 

  owner.SetBackColor("White") 

  owner.SetBorderColor("DarkGray")

Import a .Net namespace

Code

import clr

from System.Windows import MessageBox

if control.GetValue() == "1" : 

  MessageBox.Show("Value provided is invalid")

Show a confirmation dialog

Code

from System.Windows import MessageBox

from System.Windows import MessageBoxButton

result = False

res = MessageBox.Show("Are you sure?", "Confirm", MessageBoxButton.OKCancel)

if res.ToString() == "OK" :

  result = True

if res.ToString() == "Cancel" :

  result = False

Exception Handling

Code

import clr

from System.Windows import MessageBox

from System import Convert

value = control.GetValue()

try : 

  d = Convert.ToDouble(value) 

  if (d>100) : 

    MessageBox.Show("Value out of bounds") 

    control.SetValue("0")

except Exception, e : 

  control.IInputControl.UpdateLayout()

Asynchronous Methods / Save a new list item

Code

# callback method that is executed as soon as saving the record is complete

label = template.GetControl("c_SaveResult")

def Callback(result) :

  label.SetValue("Save Completed")

# prepare the data (Target list columns : Title, Project (lookup)

data = ["Title", "This is the Title", "Project", "2;#Project2"]

# Insert the record inside the specified list

template.SaveRecord("http://servename/sitename", "ProjectTasks", data, Callback)

Load Records using criteria from the form / Perform Calculations

Code

T = template

# DEFINE THE CALLBACK METHOD TO CALCULATE THE AVERAGE RATE FOR RETRIEVED RECORDS

def callback(e) :

  if e.DataItems.Count>0 :

    total = 0

    avg = 0

    for record in e.DataItems :

      rate = e.DataItems[0].GetValue("Rate")

      if rate != "" :

        total = total + float(rate)

    avg = total / e.DataItems.Count\

    T.GetControl("c_Avg").SetValue(avg)

# CLEAR THE TARGET CONTROL

T.GetControl("c_Avg").SetValue("")

# GET THE ID OF THE CURRENT RECORD

id = T.GetControl("c_ID").GetValue()

# LOAD THE RATE FIELD FROM CASES LIST, THAT MATCH THE SPECIFIC CUSTOMER

template.LoadRecords("http://servername", "Cases", "Customer", "Equals", id, "Lookup", ["Rate"], callback)

 

Instead of using scripting in various form events, scripting may be applied with the ActionButton control.

For extensive language reference use the following links :

http://ironpython.net

http://en.wikipedia.org/wiki/IronPython