Difference between revisions of "Form Scripts"
imported>Aeric |
imported>Aeric |
||
Line 97: | Line 97: | ||
::: ''Learn more:'' [[URL Addresses#KnowledgeBase Article]] | ::: ''Learn more:'' [[URL Addresses#KnowledgeBase Article]] | ||
:* | :* An [[Application Help Tab]] | ||
:: For that option, the | :: For that option, the JavaScript needs to find the Help tab element, and "click" on it. | ||
:::<syntaxhighlight lang="javascript" enclose="div"> | :: ''Learn more:'' [[HowTo:Creating Application-Specific Help]] | ||
:* A JSP [[Page]] | |||
::<syntaxhighlight lang="javascript" enclose="div"> | |||
<script> | <script> | ||
onclick="window.open(\'/networking/page/PAGENAME.jsp\')" | |||
</syntaxhighlight> | |||
:* A JSP [[Page]] hosted in a platform [[Site]] | :* A JSP [[Page]] hosted in a platform [[Site]] | ||
:* An externally-hosted web page | :* An externally-hosted web page | ||
Revision as of 21:46, 13 August 2015
About Form Scripts
Form Scripting lets you specify JavaScript code to execute when a Form is loaded or saved.
JavaScript code can be invoked at these form-level events:
- On Load
- This event happens when the form loads
- By default, the On Load scripts are triggered on any record action (View, Add, Update)
- Optionally, invoke the script on a specific action (View or Add or Update)
- Learn more: Trigger on a Specific Action
- On Save
- This event happens when a user clicks the [Submit] button on a form
- At this event, optionally perform custom front-end validations before sending the data to the server
- Return false to cancel the save
- Resusable Script Functions
- Available to be called from the On Load or On Save event form scripts
- Also available to be called from the On Change and On Focus event field scripts
- Learn more:
- Compare to Post Selection JavaScript and Field Scripting
- Using AJAX and REST to communicate with the platform
Working with Form Scripts
Editing Form Scripts
Follow these steps to add or change scripting in a form:
- Click [Form Script]
- Click [Edit]
- Enter or change the JavaScript in On Load Script, On Save Script, and/or Reusable Script Functions
- Click [Save]
Writing JavaScript
Using JavaScript, you can
- Reference Fields in the current form.
- Use AJAX and REST to communicate with the platform.
On Load Examples
These examples perform operations when a form is loaded.
Add a Help Button to an Arbitrary Form
This code works for forms in all objects, including Cases, Tasks, and custom objects. And it works when adding a new record, as well as when viewing an existing record.
In general, it puts a [Help] button in the upper right corner of a form:
Note that when viewing a record, there are two options, depending on which code you enable:
- Put the button in the details area. (The button is only visible when details are shown, but the short block of code works for all objects.)
- Put the button above the details area.
In either case, the code below opens the target page in a separate window.
(To open the page in the Help tab, see HowTo:Creating Application-Specific Help.)
- <syntaxhighlight lang="javascript" enclose="div">
var targetURL = "http://google.com"; var action = _sdForm.get(0).a.value; // Is this an add-record or view-record form? var button =
'
<input type="button" value=" Help " onclick="window.open(\+targetURL+'\')"> \
';
if (action == "add") {
// POPUP DIALOG. PUT HELP BUTTON IN THE NEW-RECORD FORM. _sdForm.parent('div').parent('div').parent('div') .find('.assigned_title .row-fluid').append(button);
} else {
// RECORD VIEW. PUT HELP BUTTON IN DETAILS AREA. // The simplest code. Works for all objects: custom objects, cases, and tasks. // The button shows only when the details section is open // Ideal when Company Info > Application Settings > Expand Details" is TRUE _sdForm.parent('div').parent('div').prepend(button);
// OR (choose the else-clause above, or the one below)
// PUT THE HELP BUTTON ABOVE THE DETAILS AREA, so it is always visible // This code pushes the case summary down by the height of the button. // Help button appears even when record details are hidden. // Look for the special case-record banner that shows priority and status var banner = _sdForm.parent('div').parent('div').parent('div') .find('.case-priority-status-header'); if (banner.length == 0) { // NORMAL RECORD VIEW (custom objects and tasks)--BUTTON IN TITLE AREA. _sdForm.parent('div').parent('div').parent('div').find('h5').append(button); } else { // CASE-RECORD VIEW--BUTTON UNDER THE BANNER. banner.after(button); }
} </syntaxhighlight>
Help Page Target Options
As for the help page to point to, you have the following options:
- A Knowledge Base article (if you have a ServicePortal running).
- Use the link-target pattern:
-
- For that option, the JavaScript needs to find the Help tab element, and "click" on it.
- Learn more: HowTo:Creating Application-Specific Help
- A JSP Page
- <syntaxhighlight lang="javascript" enclose="div">
<script> onclick="window.open(\'/networking/page/PAGENAME.jsp\')" </syntaxhighlight>
- An externally-hosted web page
Add a Help Button Using a Static Resource Script
A useful piece of code tends to be useful in multiple forms, in multiple objects. To make the code available to every form in your system:
- Turn it into a function and store it in a .js file:
- <syntaxhighlight lang="javascript" enclose="div">
/**
* Usage: addHelpButton("target-page-URL"); */
function addHelpButton(targetURL) {
...code goes here...
} </syntaxhighlight>
- Load the file as a Static Resource.
- Use the REST static resource API to get the resource ID
- Put the following code into the form to read the file, use the JavaScript eval function to make the function available, and invoke it:
- <syntaxhighlight lang="javascript" enclose="div">
$.get("https://{YOURDOMAIN}/networking/rest/staticResource/{RESOURCEID}?getFile=true",
function( data ) { eval(data); addHelpButton("YOUR HELP PAGE URL");
}); </syntaxhighlight>
Add a Button Next to a Field in an Object Form
This example adds a button to a standard object Form, as shown here:
The standard form is shown on the left. ON LOAD JavaScript added to it injects the button, producing the form on the right.
- <syntaxhighlight lang="javascript" enclose="div">
// Get a pointer to the current form var form = _sdForm
try {
/* * Find the order number field, modify it's CSS properties, * and add a search button to the element it's contained in.
* (Each label and field is contained in it's own
* .parent() function accesses it, and the button is added at the end.) */ form.find("#orderNum").css( {'width': '50%',"margin-bottom":"0px"}); form.find("#orderNum").removeClass("text_box_case"); form.find("#orderNum").parent().append( "<input type='button' id='lookup_order' name='lookup_order' value='Lookup Order'" + "style='background: none repeat scroll 0 0 #EBEBEB;box-shadow: 0 0 0 0 #888888 inset;" + " height: 26px;margin-top:-0px; padding: 0 8px 0 6px;" + " margin-right:5px;margin-left:5px;' >" ) ;
/* * Add an anonymous function to the button to invoke the WebServiceProxy method. */ form.find("#orderNum").parent().find("#lookup_order").click( function() { // Perform some operation alert("jQuery/Javascript placed here gets executed");
// Don't submit the input form when this particular button is clicked. return false; } );
} catch (e) {
// Report JavaScript errors alert(e);
}; </syntaxhighlight>
- How it works
- _sdform - A pointer to the current form
- form.find("#orderNum") - Find the order number field, using it's ID.
- .css - Define new CSS Styling for the field.
- .removeclass - Remove the reference to the CSS class currently used by the field. In this case, the field is a text field, so the class associated with that kind of field is removed. (For other field types, inspect the page to see what class is used.)
- .parent.append - Go to the div that contains the field and it's label. Append a new button to the end of it. Specify CSS styling for the button that fits into the form.
- Lookup Order - The label displayed on the button.
- find("#orderNum").parent - Find the button again, and go to the div that contains it.
- #lookup_order - Find the button we added.
- .click - jQuery function to define an "on click" event handler.
- function() - Define an unnamed ("anonymous") function that contains the combination of JavaScript and jQuery functions to execute when the click event occurs on the button.
- return false - Prevent the input button from causing the form to be submitted.
- catch (e) - Report JavaScript errors. (They occur in the browser, so they don't appear in the platform's Debug Log.)
Learn more:
- For a fully worked-out example that uses this technique to access an external web service, see Invoke Web Services Programmatically. (The first part of that section defines a class to access the service. The last part adds a button to a form to access it.)
Add a Button to a Case Form
This example adds a button to a Case details form. In this case, the button appears on the same line as the Save and [Cancel] buttons, but it is floated over to the left, as shown here:
- <syntaxhighlight lang="javascript" enclose="div">
+ "<input type='button' id='customButton' value='Button Label'" + " class='lj-button fg-button ui-state-default ui-corner-all'"+ "/>
try {
$(".case_details_forms").find(".case_submit_button").parent().parent().prepend(html); $("#customButton").click( function() { alert("jQuery/JavaScript code placed here executes when the button is clicked"); });
} catch (e) {
alert(e);
}; </syntaxhighlight>
- How it works
- html - Define a string that contains the HTML code to insert.
- div...float:left - Create a div that floats to the left, to contain the button.
- class - These CSS classes make the button appear the same as other platform buttons.
- .case_details_forms - Find the details form by it's CSS class. (Only item uses that class.)
- .case_submit_button - Find the [Save] button at the bottom of that form using it's CSS class. (Only one item uses that class.)
- .parent().parent() - Find the div that contains the button, then find the div that contains that, so we can add our div to it.
- prepend - Insert our float-left div before the one that contains the buttons
- #custom_button - Find the button we just added, using it's ID.
- .click - jQuery function to define an "on click" event handler.
- function() - Define an unnamed ("anonymous") function that contains the combination of JavaScript and jQuery functions to execute when the click event occurs on the button.
- catch (e) - Report JavaScript errors. (They occur in the browser, so they don't appear in the platform's Debug Log.)
Convert a Date
Create readable date string from the current date for display in the order_date field.
var v1 = new Date(); var v2 = new Array('Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat'); var v3 = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); date_string = v2[v1.getDay()] + " " + v3[v1.getMonth()] + " " + v1.getDate(); setTextFieldValue(_sdForm, "order_date", date_string);
Trigger on a Specific Action
To invoke a script On Load + Action (View, Update, Add or Clone a record):
Trigger on record View:
var action = _sdForm.get(0).a.value; if ( action == "view") { // java script to be triggered on the view of the record only ... }
Trigger on record Update:
var action = _sdForm.get(0).a.value; if ( action == "update") { // java script to be triggered on the update of the record only ... }
Trigger on record Add or Clone:
var action = _sdForm.get(0).a.value; if ( action == "add") { //java script to be triggered on the add or clone of the record only ... }
On Save Examples
These examples perform operations when a form is saved.
Create a Contact
Make sure there is a contact when creating a record in a "Leads" object.
var form = document.mainForm; if (form.reference_type[form.reference_type.selectedIndex].value == 'Lead') { if (form.contact_id.value == "") { alert("Please enter Contact Name"); return false; // cancel the save operation } }
Set a Date Field
If a user checked the "Done" radio button in a radio button group named technical_spec_completed, set the spec_date field with the current date formatted as month number, day number, and year.
var form = document.mainForm; function formatDate(value) { return value.getMonth()+1 + "/" + value.getDate() + "/" + value.getFullYear(); } for (var i=0; i<form.technical_spec_completed.length; i++) { if(form.technical_spec_completed[i].checked && form.technical_spec_completed[i].value == 'Done' && form.spec_date.value == '') { t = new Date(); form.spec_date.value = formatDate(t); } }
Change a Checkbox Field
Change the value of a checkbox field to true when the request amount is large enough.
- <syntaxhighlight lang="javascript" enclose="div">
if(_sdForm[0].request_amount.value > 10000) {
setCheckboxState(_sdForm, "approval_required", true);
} </syntaxhighlight>
Confirm that a Field is Intentionally Blank
The email address field on a form is not mandatory, but you want to encourage users to enter it. If the user clicks OK in the confirm dialog, it cancels the save so they can then enter the email address. If they click cancel, the save proceeds.
var form = document.mainForm; if(form.email.value=="") if (confirm("While the field is optional, we recommend entering a value")) { //User clicked OK: do not proceed with save return false; else { //User clicked cancel: let save happen return true; } }
Learn More
- Referencing Form Fields in JavaScript
- Field Name and Field Value syntax
- Use AJAX and REST to communicate with the platform in JavaScript code.
- JavaScript Functions
- Accessing Additional Lookup Variables in a Form