Form Properties and Methods
Either inside formulas or when writing javascript to accomplish complex requirements, you can use the client-side API provided by PowerForms – HTML.
A global variable named “form” is available wherver you can use script :
- In form events (Load, Validation, etc)
- Inside Enabled and Visibility formulas
- In control Value-Change events
- In custom events provided by specific controls (like grids)
DataItem
Type : Object
Represents the record data. Each property of the object represents a list column.
The internal names of columns have been used to build this object.
MaintainTabSelection
Type : Bool
In case that the form contains more than one tab selections, after the save action, the last selected tab will maintain selected if it is set true.
Loaded
Type : Bool
This property is true while the form is loading and becomes false as soon as the user starts editing the data in the form.
The is useful when you want to change the value of controls during the Value-Change event of another control.
Since the Value-Change events are raised even when the form is initialized, that may have unwanted results.
For example :
You want every time the user selects a specific customer from a combobox, to automatically set the priority combo to “High”. This should act as a default value for that control, but the user may change it afterwards. So we apply this rule only when the value of the combo is changed by a user action.
Example:
// Code inside the Value-Change event of the Customer combo
var customer = form.GetControl(“c_Customer”).GetValue_Name();
if (customer == “BPC”) form.GetControl(“c_Priority”).SetValue(“High”);
// The above code is incorrect, since it would also run during form initialization
// when the form applies values from the list item to controls.
// The correct way would be the following :
var customer = form.GetControl(“c_Customer”).GetValue_Name();
if (form.Loaded) {
if (customer == “BPC”) form.GetControl(“c_Priority”).SetValue(“High”);
}
FieldValue(controlName)
Return type : string
Used to retrieve the current value of a control on the form.
The value is always retrieved as a string.
For date values, ANSI format is used.
For numeric values, US locale is used.
For lookup values, the ID;#TITLE format is used.
For boolean values, 1 or 0 is returned.
Example :
form.FieldValue(“c_Title”);
Enabled formula example :
form.FieldValue(“c_Status”) != “Open”
FieldValue_Name(controlName)
Return type : string
This method is used for lookup controls only and it returns the TITLE part of the control value (ID;#TITLE)
For example, a combobox lookup control has the value : 2;#Open
var a = form.FieldValue(“c_Status”);
// returns “2;#Open”
var b = form.FieldValue_Name(“c_Status”);
// returns “Open”
FieldValue_Value(controlName)
Return type : string
This method is used for lookup controls only and it returns the ID part of the control value (ID;#TITLE)
For example, a combobox lookup control has the value : 2;#Open
var a = form.FieldValue(“c_Status”);
// returns “2;#Open”
var b = form.FieldValue_Value(“c_Status”);
// returns “2”
FieldValues(controlName, separator)
Return type : string
This method is used for multi-lookup controls only.
The FieldValue(controlName) method for multi-lookup controls returns the value in the ID1;TITLE1;#ID2;#TITLE2;#… format.
This method returns all the ID parts inside the value, concatenated by the separator provided as a parameter.
For example:
var value = form.FieldValue(“c_Multi”);
// returns “1;#Open;#2;#Closed”
var value2 = form.FieldValues(“c_Multi”, “,”);
// returns “1,2”
FieldNames(controlName, separator)
Return type : string
This method is used for multi-lookup controls only.
The FieldValue(controlName) method for multi-lookup controls returns the value in the ID1;TITLE1;#ID2;#TITLE2;#… format.
This method returns all the TITLE parts inside the value, concatenated by the separator provided as a parameter.
For example:
var value = form.FieldValue(“c_Multi”);
// returns “1;#Open;#2;#Closed”
var value2 = form.FieldNames(“c_Multi”, “,”);
// returns “Open,Closed”
UserID()
Return type : string
This method returns the ID of the current SharePoint user.
Example :
var id = form.UserID();
UserFullName()
Retutn type : string
Returns the name of the current user
Example :
var name = form.UserFullName();
LoginName()
Retutn type : string
Returns the login name of the current user
Example :
var name = form.LoginName();
UserInGroup(idOrName)
Return type : bool
Retutns true if the current user belongs to a group having the provided id or name.
Example :
var granted = (form.UserInGroup(“Administrators”) || form.UserInGroup(“2”));
CurrentUser()
Return type : object
Returns a structure containing information about the current user.
User Properties :
ID, FullName, LoginName, Email, Groups (array of groups)
Group Properties
ID, Name
Example :
var user = form.CurrentUser();
var userId = user.ID;
for (var i=0;i<user.Groups.length;i++) {
var group = user.Groups[i];
var groupName = group.Name;
}
IsNewRecord()
Return type : bool
Returns true if we are currently in a new record, otherwise it retuns false.
Example :
if (form.IsNewRecord() && form.FieldValue(“c_Title”) == “”)
alert(“Title must be provided for new records”);
ViewMode()
Return type : bool
Returns true if the form is in view mode. This is important to know specially when dealing with script that enables controls.
Example :
A script like the following written inside the LoadCompleted script of the form, would have the result that the specific control would be enabled even when the form is in ViewMode.
var status = form.DataItem.Status;
var control = form.GetControl(“c_Title”);
// Wrong
if (status == “Open”) control.SetEnable(true);
else control.SetEnable(true)
// Correct
if (form.ViewMode() == false) {
if (status == “Open”) control.SetEnable(true);
else control.SetEnable(false);
}
ShowMessage(message)
Return type : None
Displays a short message in a placeholder between the toolbar and the form.
It may be used to provide alerts and instructions to the end user.
Example :
form.ShowMessage(“Password must be at least 6 characters long”);
MessageForm(message, title, callback)
Return type : None
Shows a modal popup message form to the user.
The message and title parameters are used to set the body and title of the dialog.
If a callback method is specified, the callback is executed when the users closes the form.
Example :
form.MessageForm(“There has been an error saving data”, “Error”, function(e) {
form.CancelRecord();
});
CloseMessageForm()
Return type : None
Closes the above message form programmatically.
Example :
form.CloseMessageForm();
ShowButton(buttonName)
Return type : None
Shows a toolbar button.
In order for this method to work, the user must first have the appropriate rights to press that button and the designer of the form must have allowed this button to be available on the form.
Example :
form.ShowButton(“delete”);
Available button names (Case Insensitive) : “New”, “Save”, “SaveAndExit”, “Delete”, “Cancel”, “Edit”, “Help”, “Design”, “Print”
HideButton(buttonName)
Return type : None
Hides a button from the toolbar.
Available button names (Case Insensitive) : “New”, “Save”, “SaveAndExit”, “Delete”, “Cancel”, “Edit”, “Help”, “Design”, “Print”
Example :
form.HideButton(“Save”);
form.HideButton(“SaveAndExit”);
RequestValue(key)
Return type : string
Searches inside the window querystring to find a key matching the specified parameter.
It returns the value of the querystring parameter.
For example (assuming a page with the url : “http://servername/Lists/EditPage.aspx?IsDlg=1”)
var value = form.RequestValue(“IsDlg”);
// returns “1”
SendEmail(to, subject, body, callback)
Return type : None
Uses the SharePoint infrastructure to send an email. The callback (optional) will be executed as soon as the operation completes.
Example :
var sub = form.GetControl(“c_EmailSubject”).GetValue();
var to = form.GetControl(“c_EmailTo”).GetValue();
var body = form.GetControl(“c_EmailBody”).GetValue();
form.SendEmail(to, sub, body, function(e) {
var ok = e.Success;
if (!ok) alert(“Error sending email : ” + e.ErrorMessage);
});
The variable that will be passed to the callback will have the following properties :
Success : Type = bool
ErrorMessage : Type = string
CallWebService(wsName, callback)
Return type : None
Used to manually execute a predefined web service.
Example :
In the following example we call a predefined web service targeting the _vti_bin/Lists.asmx default service of SharePoint. Inside the callback, it checks for any errors and then loops all the results to create a single <a> hyperlink for each list retrieved.
function callback(e) {
var c = form.GetControl(“c_WSResult”);
var s = “”;
if (pf.IsEmpty(e.ErrorMessage)) {
for (var i=0;i<e.ListItems.length;i++) {
if (i>0) s+=”, “;
s += “<a href=\”#\” onclick=\”w = window.open(‘http://wssdev1/Lists/” + e.ListItems[i].Title + “‘,”,’width=800, height=600, resizable=yes, scrollbars=yes’);\” style=\”color:#cc6600\”>” + e.ListItems[i].Title + “</a>”;
}
c.SetValue(s);
}
else { c.SetValue(e.ErrorMessage); }
form.GetControl(“c_WSButton”).SetEnable(true);
}
form.GetControl(“c_WSButton”).SetEnable(false);
form.CallWebService(“All Lists”, callback);
ExecuteSQLQuery(queryName, callback)
Return type : None
Used to manually execute a predefined SQL query.
Example :
function callback(e) {
var c = form.GetControl(“c_SQLResult”);
var s = “”;
if (pf.IsEmpty(e.ErrorMessage)) {
for (var i=0;i<e.ListItems.length;i++) {
if (i>0) s+=”, “;
s += e.ListItems[i].NAME;
}
c.SetValue(“<strong>” + s + “</strong>”);
}
else {
c.SetValue(e.ErrorMessage);
}
}
form.ExecuteSQLQuery(“Products”, callback);
LoadListQuery(listQueryName,callback)
Return type: None
Used to manually execute a predefined list query.
Example:
LoadRecords(listUrl, listIdOrName, viewIdOrName, criteria, fieldsToRetrieve, sortField, sortAscending, rowLimit, callback)
Return type : None
Used to manually load an array of list items based on specified criteria. The criteria is an array of pf.SearchSpec objects. The “fieldsToRetrieve” parameter is a string array of field names; if null then all fields are returned. If row is greater than zero then all rows are returned.
Example:
criteria = [];
LoadRecord(listUrl, listIdOrName, itemId, callback)
Return type : None
Used to manually load a list item through script based on its ID.
function callback(e)
DeleteRecords(listUrl, listIdOrName, viewIdOrName, specs, sortField, sortAscending, rowLimit, callback)
Return type : None
Used to delete an array of list items based on specified criteria.
The url of the list, the list title or the view id of the records must be passed as parameters. The criteria (specs) is an array of pf.SearchSpec objects.
Example:
criteria = [];
DeleteRecord(listUrl, listIdOrName, itemId, callback)
Return type : None
Used to delete a record inside a list.
The url of the list, the list title and the id of the record must be passed as parameters.
Example :
form.DeleteRecord(“http://servername”, “Customers”, “2”, function(e) {
if (!pf.IsEmpty(e.ErrorMesage)) alert(“Error occurred : ” + e.ErrorMessage);
});
DeleteCurrentRecord(confirm)
ReturnType : None
Used to delete the current record. It takes a parameter to force or ommit the confirmation message presented to the end user.
Example :
form.DeleteCurrentRecord(false);
CancelRecord()
Return type : None
It has the same effect with that when the user presses the Cancel button in the toolbar.
Example :
form.CancelRecord();
SaveRecord() or SaveCurrentRecord()
Return type : None
Saves the current record. The method has the same effect with that when the users press the “Save” button.
Validations are applied to the form data (either required fields or custom validation code from script)
Example :
form.SaveRecord();
SaveRecord(url, listIdOrName, listItem, callback)
Saves the provided list item. The item should be a javascript object having properties named after the column names we want to update.
Example :
var item = new Object();
item.Title = “New Item”;
item.Status = “Open”;
item.Category = “1;#Category A”;
form.SaveRecord(“http://servername”, “listA”, item, function (e) {
var error = e.ErrorMessage;
var newItem = e.ListItem;
});
SaveAndExit()
Return type : None
Performs the same action which is performed by the Save-and-Close button of the toolbar.
Example :
form.SaveAndExit();
GetSectionByKey(key)
Return type : FormSection object
Returs a section object that matches the key provided.
Each section in a form may have an identifier key (you can set this up using the appropriate section-properties form inside the run-time designer)
Example
var section = form.GetSectionByKey(“Main”);
if (section != null) section.Collapse();
ExpandSection(sectionKey)
Return type : None
Expands a form section.
Example :
form.ExpandSection(“SectionA”);
CollapseSection(sectionKey)
Return type : None
Collapses a form section
Example :
form.CollapseSection(“SectionA”);
HideSection(sectionKey)
Return type : None
Hides a form section
Example :
if (!form.UserInGroup(“Administrators”))
form.HideSection(“SectionA”);
ShowSection(sectionKey)
Return type : None
Shows a form section that is hidden
Example :
if (form.UserID() == “1”) form.ShowSection(“SectionA”);
else form.HideSection(“SectionA”);
GetControl(controlName)
Return type : FormControl object
Searches the form for a control with the name passed as a parameter.
Returns the control object found or null if no control matches the specified name.
The control object returned has its own methods described here :
Control Properties and Methods
Example:
var c = form.GetControl(“c_Status”);
var value = c.GetValue();
if (value == “Closed”) form.GetControl(“c_Priority”).SetValue(“Low”)
GetControlByTargetFieldName(columnName)
ReturnType : FormControl object
Searches inside the form controls to find one that is bound to the specified list column name.
Example :
var c = form.GetControlByTargetFieldName(“Title”);
if (c != null) c.SetValue(“”);
HideTab(index)
ReturnType : None
Hides a tab item by its index (the index is zero based).
Example :
form.HideTab(1);
ShowTab(index)
ReturnType : None
Shows a tab item by its index (the index is zero based).
Example :
form.ShowTab(1);
SetSectionBorderThickness(key, thickness)
Return Type : None
Changes the thickness of a section border.
Parameters :
key : The section key
thickness : The border thickness
Example :
form.SetSectionBorderThickness(“main”, “3px”);
SetSectionBorderColor(key, color)
Return Type : None
Changes the color of a section border.
Example :
form.SetSectionBorderColor(“main”, “#336699”);
SetSectionBackColor(key, color)
Return Type : None
Changes the background color of a section.
Example :
form.SetSectionBackColor(“main”, “#F5F5A5”);
SetSectionCellSpacing(key, spacing)
Return Type : None
Changes the cell spacing of the table inside a section.
Example :
form.SetSectionCellSpacing(“main”, 3);
SetSectionCellPadding(key, padding)
Return Type : None
Changes the cell padding of the table inside a section.
Example :
form.SetSectionCellPadding(“main”, 3);
SetSectionHeader(key,content)
Return Type : None
Changes the contents of a section’s header.
Example :
form.SetSectionHeader(“A0”, “<span class=’title’>Companies</span>”);
Attachments() and AttachmentsLoaded event
The Attachments method returns an array of the loaded attachment objects.
Each attachment includes the Filename and FullPath properties.
Example script written inside the LoadCompleted event of the form that produces thumbnails for all the image attachments of the current list item:
var s = “”;
var c = form.GetControl(“c_Attachments”);
for (var i=0;i<files.length;i++) {
var name = files[i].FullPath;
var suf = name.substring(name.length – 3, name.length).toLowerCase();
s = s + “<span style=’padding:10px’><a href='” + files[i].FullPath + “‘ target=’_blank’ style=”><img src='” + files[i].FullPath + “‘ width=’32’ height=’32’ style=’border:0px’ /></a></span>”
}
c.SetValue(s);
SetTabHeader(Tab Ident Number, an HTML span containing the text which also sets the visual properties)
Return Type : None
Changes a tab’s header properties.
Example :
form.SetTabHeader(0, “<span style=’font-size:19px;padding:5px;cursor:pointer;color:#3399FF;’>My Best Form</span”);
Url()
Return Type : String
Returns the form’s list Url. Can be used in script and formulas.
Example :
var mySiteUrl = form.Url();
LoadCurrentUser(Web site Url, callback function)
Return Type : Object
Returns the current user’s information in a User object.
User Object:
– LoginName (string)
– ID (string)
– FullName (string)
– IsSiteAdmin (boolean)
– Email (string)
– Groups (object)
Example :
CopyFile(sourceUrl, sourceList, docID, targetUrl, targetList, targetFolder, targetFileName, attributes, overwrite, callback)
Return Type : None
Copies a document from one document library to another.
Example :
alert(“Document Copied”);
});
SetAttachmentGridHeight(height)
Return Type : None
Adjusts the height of the grid containing item attachments.
Example :
form.SetAttachmentGridHeight(“400px”);
GetTab(Tab Number)
Return Type: Object
Returns the selected tab’s object. The parameter Number is zero-based, meaning that if you want to select the first tab appearing on form, you have to do the following:
form.GetTab(0);
SetDisplayMode(mode)
Return Type: None
Accepts two parameters: Flat and Normal
Flat mode turns the form into a single page, with every control listed beneath each other, meant to be used for easier page printing.
form.SetDisplayMode(“Flat”);
ToggleDisplayMode()
Return Type: None
Switches between Flat and Normal page mode.
form.ToggleDisplayMode();
Log(string message)
Return Type: None
This command is meant to be used with the debugging form (_log=1), allowing you to print a message in the debugging box.
form.Log(“Test message!”);
OpenUrl(url, caption, width, height, x, y, callback)
Return Type: None
You can use this command to open a new pop-up window, which will navigate to the appointed URL path. You can also include a callback function, which will fire, once the form finishes loading.
SelectedTabIndex()
Return Type: Integer
You can use this command to find out the index number of the currently selected Tab. The selected tab index is zero-based, meaning the first tab will return 0, the second tab will return 1 etc.
HideInnerTab(key, index)
Return Type: None
You can use this command to hide a specific Inner Tab. The inner tab index is zero-based, meaning the first tab will be 0 and the key is the name of it.
ShowInnerTab(key, index)
Return Type: None
You can use this command to show a specific Inner Tab. The inner tab index is zero-based, meaning the first tab will be 0 and the key is the name of it.
SelectInnerTab(key, index)
Return Type: None
You can use this command to select a specific Inner Tab. The inner tab index is zero-based, meaning the first tab will be 0 and the key is the name of it.
SelectedInnerTabIndex(key)
Return Type: Integer
You can use this command to find out the index number of the currently selected Inner Tab. The selected inner tab index is zero-based, meaning the first tab will return 0, the second tab will return 1 etc.
DisableInnerTab(key, index)
Return Type: None
You can use this command to disable a specific Inner Tab. The inner tab index is zero-based, meaning the first tab will be 0 and the key is the name of it.
EnableInnerTab(key, index)
Return Type: None
You can use this command to enable a specific Inner Tab. The inner tab index is zero-based, meaning the first tab will be 0 and the key is the name of it.
SetInnerTabHeader(key, index, text)
Return Type: None
You can use this command to set a new header text to a specific Inner Tab. The inner tab index is zero-based, meaning the first tab will be 0, the key is the name of it and the text is the new header.
LoadGroupsInSite(url, callback)
Return Type: Array of Objects
You can use this command to load a site’s SharePoint groups. The command accepts two parameters, the site url and a callback function which you can use to retrieve any information you require.
The returned objects contain the following group information:
– ID [number]
– IsGroup [boolean]
– Name [string]
– LoginName [object]
– Email [object]
– IsSiteAdmin [boolean]
– Type [object]
– uid [string]
Since this is a complicated function, we will use an example to explain its usage. Our example contains a Combobox control, which we will use to load the Group names, called c_Groups and a button, which will use the following script to load every group in the site.
Use the following script in the button’s Action property to load the c_Groups Combobox with the group names:
LoadUsersInGroup(url, groupName, callback)
Return Type: Array of Objects
You can use this command to load a SharePoint group’s Users. The command accepts three parameters, the site url, the group’s name and a callback function which you can use to retrieve any information you require.
The returned objects contain the following group information:
– LoginName [string]
– ID [string]
– FullName [string]
– IsSiteAdmin [boolean]
– Email [string]
– Groups [object]
– uid [string]
Again, since this is a complicated function, we will continue using the above example to explain its usage. Our example above contained a Combobox control, which we used to load every group name in the site. Following this, we will add a DataGrid called c_UsersInGroup, which we will use to show the login name and the full name of every user in the selected group. We will also add another button, which will call the LoadUsersInGroup function.
Use the following script in the button’s Action property to populate the datagrid:
AddUserInGroup(url, groupName, username, callback)
Return Type: none
You can use this command to add a user to a SharePoint group. The command accepts four parameters, the site url, the group’s name, the user’s name and a callback function which you can use to retrieve the success or failure of the operation.
DeleteUserFromGroup(url, groupName, username, callback)
Return Type: none
You can use this command to remove a user from a SharePoint group. The command accepts four parameters, the site url, the group’s name, the user’s name and a callback function which you can use to retrieve the success or failure of the operation.
SetAttachmentTabHeader(theHeaderText)
Return Type: none
You can use this command to change the header in the Attachments tab. The command accepts one parameter, a string value.
You can use the following code in the form’s Load Completed script:
form.SetAttachmentTabHeader(“My Attchments”);
AddToolbarButton(icon, text, style, position)
Return Type: none
You can use this command to create a custom button on the form’s toolbar section. You can also set the button in such a way, that it performs various actions. The command accepts four parameters:
– icon: The icon’s path, as a string value.
– text: The text to appear beneath the icon.
– style: Defines the button’s style. Possible values can be:
– An empty string, which will create a default button, with an icon and a text underneath.
– “tiny” will create a button with a small icon.
– “tinynotext” will create a button with a small icon and no text underneath.
– “notext” will create a button with a normal-sized icon and no text underneath.
– position: Use form.TOOLBAR to place it next to the other form toolbar buttons.
As an example, we will create a custom button, place it at the end of the toolbar section and make sure that each time you press it, the form will save all data.
You can use the following code in the form’s Load Completed script:
GetTabHeader(index)
Return Type: string
You can use this command to retrieve the header text from a tab. The command accepts one parameter, an index number representing the tab’s order of appearance. The index is zero based, meaning that the first tab is 0, the second is 1 etc.
You can use the following code in the form’s Load Completed script:
SetTranslation(key, value)
Return Type: none
You can use this command to change the textual representation of any standard control on the form. You normally would do this using the Localization section in the designer form, but you can also do the same programmatically using this function.
The function accepts two parameters, the Key part will be the key part from the Localization section and the value would be the textual representation you wish to use.
For example, we will change the text part of the form’s New Record button.
You can use the following code in the form’s Form Design Loaded script:
form.SetTranslation(“Form_NewRecord”, “Something irrelevant”);
DisableAttachments()
Return Type: none
You can use this command to disable the use of the Attachments tab.
form.DisableAttachments();
EnableAttachments()
Return Type: none
You can use this command to enable the use of the Attachments tab.
form.EnableAttachments();
Leave a Reply
Want to join the discussion?Feel free to contribute!