Difference between revisions of "Form Scripts"

From AgileApps Support Wiki
imported>Aeric
Β 
(57 intermediate revisions by 2 users not shown)
Line 12: Line 12:
::*At this event, optionally perform custom front-end validations before sending the data to the server
::*At this event, optionally perform custom front-end validations before sending the data to the server
::*Return false to cancel the save
::*Return false to cancel the save
:*;Resusable Script Functions:
:*;Reusable Script Functions:
::*Available to be called from the On Load or On Save event form scripts
::*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
::*Also available to be called from the On Change and On Focus event field scripts
Line 21: Line 21:


===Working with Form Scripts===
===Working with Form Scripts===
{{Note| Please note that all the examples listed in this page are limited to the legacy AgileApps UI and not the new runtime AgileApps UI.}}


====Editing Form Scripts====
====Editing Form Scripts====
Follow these steps to add or change scripting in a form:
Follow these steps to add or change scripting in a form:
{{Note|To run the JavaScript in the LongJump UI and the legacy AgileApps UI, enter the script in the '''Legacy UI Script''' tab. To run the JavaScript in the New AgileApps UI, enter the script in the '''New UI Script''' tab.}}
# Click '''[Form Script]'''
# Click '''[Form Script]'''
# Click '''[Edit]'''
# Click '''[Edit]'''
Line 41: Line 42:
====Add a Help Button to an Arbitrary Form====
====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.
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.
Β 
For information about adding a help button to a form, see the tech community article [https://tech.forums.softwareag.com/t/adding-a-custom-button-to-an-arbitrary-form-using-form-script/237542 Adding a Custom Button to an Arbitrary Form using Form Script].
In general, it puts a '''[Help]''' button in the upper right corner of a form:
:[[File:HelpButtonScriptExample.png]]
Β 
Here is the code:
:<syntaxhighlight lang="javascript" enclose="div">
</syntaxhighlight>
Β 
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.
:: This option requires special-case code for the Cases object. Note that the placement isn't perfect (the case-description is pushed down). But here, the button is always visible:
:::[[File:HelpButtonCaseRecord.png]]
Β 
--Targeting options:
:* [[Knowledgebase articles]] (if you have a ServicePortal running)
<!--:* JSP pages (requires some magic to get links to work)-->
:* Externally-hosted help pages
Β 
{{Tip|If you don't currently have a server you can use to host web pages, there are some free hosting services, these days. You could also consider using one of the free Wiki services, like WebHost, WebHub, or WebBot. (Those are some of the most widely used services at the time of this writing. They are very different from each other, so do an in-depth comparison to choose the one that will work best for you.}}
Β 
=====Invoke the Script from a Static Resource=====
To use the code in multiple forms, in multiple objects:
# Turn it into a function and store it in a <tt>.js</tt> file:
#:<syntaxhighlight lang="javascript" enclose="div">
/**
* Usage:
*Β  addHelpButton("target-page-URL");
*/
function addHelpButton(targetURL) {
Β  ...code goes here...
}
</syntaxhighlight>
#:
# Use the REST static resource API to get the resource ID
# Put the following javascript into the form to read the file, use the JavaScript <tt>eval</tt> 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);
Β  Β  helpButton("YOUR HELP PAGE URL");
});
</syntaxhighlight>
Β 
''Learn more:'' [[Static Resources#Accessing a JavaScript Resource from an Object Form]]
Β 
====Add a Button Next to a Field in an Object Form====
This example adds a button to a standard object [[Form]], as shown here:
:[[File:FormLookupButtonAdded.png]]
Β 
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 <div>. The
Β  Β  *Β  .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:
# <tt>_sdform</tt> - A pointer to the current form
# <tt>form.find("#orderNum")</tt> - Find the order number field, using it's ID.
# <tt>.css</tt> - Define new [[CSS Styling]] for the field.
# <tt>.removeclass</tt> - 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.)
# <tt>.parent.append</tt> - 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.
# <tt>Lookup Order</tt> - The label displayed on the button.
# <tt>find("#orderNum").parent</tt> - Find the button again, and go to the div that contains it.
# <tt>#lookup_order</tt> - Find the button we added.
# <tt>.click</tt> - jQuery function to define an "on click" event handler.
# <tt>function()</tt> - Define an unnamed ("anonymous") function that contains the combination of JavaScript and jQuery functions to execute when the click event occurs on the button.
# <tt>return false</tt> - Prevent the input button from causing the form to be submitted.
# <tt>catch (e)</tt> - 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 [[Java Code Samples#Invoke Web Services Programmatically|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:
:[[File:CaseFormButtonAdded.png]]
Β 
:<syntaxhighlight lang="javascript" enclose="div">
var html = "<div style='float:left'>"
Β  Β  Β  Β  + "<input type='button' id='customButton' value='Button Label'"
Β  Β  Β  Β  + " class='lj-button fg-button ui-state-default ui-corner-all'"
Β  Β  Β  Β  + "/></div>";
Β 
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:
# <tt>html</tt> - Define a string that contains the HTML code to insert.
# <tt>div...float:left<tt> - Create a div that floats to the left, to contain the button.
# <tt>class</tt> - These CSS classes make the button appear the same as other platform buttons.
# <tt>.case_details_forms</tt> - Find the details form by it's CSS class. (Only item uses that class.)
# <tt>.case_submit_button</tt> - Find the [Save] button at the bottom of that form using it's CSS class. (Only one item uses that class.)
# <tt>.parent().parent()</tt> - Find the div that contains the button, then find the div that contains ''that'', so we can add our div to it.
# <tt>prepend</tt> - Insert our float-left div before the one that contains the buttons
# <tt>#custom_button</tt> - Find the button we just added, using it's ID.
# <tt>.click</tt> - jQuery function to define an "on click" event handler.
# <tt>function()</tt> - Define an unnamed ("anonymous") function that contains the combination of JavaScript and jQuery functions to execute when the click event occurs on the button.
# <tt>catch (e)</tt> - Report JavaScript errors. (They occur in the browser, so they don't appear in the platform's Debug Log.)


====Convert a Date====
====Convert a Date====
Line 199: Line 59:
====Trigger on a Specific Action====
====Trigger on a Specific Action====
To invoke a script On Load + Action (View, Update, Add or Clone a record):
To invoke a script On Load + Action (View, Update, Add or Clone a record):
{{Note|For new UI, see the section '''Variables and Methods Introduced in the Revamped UI ''' in [[JavaScript Field Type Reference for New AgileApps User Interface]]}}


Trigger on record ''View'':
Trigger on record ''View'':
Line 234: Line 95:
===On Save Examples===
===On Save Examples===


These examples perform operations when a form is saved.
For examples related to the On Save action, see the tech community article [https://tech.forums.softwareag.com/t/perform-custom-validations-using-form-script-in-agileapps/237545 Perform Custom Validations using Form Script in AgileApps].
Β 
====Create a Contact====
Make sure there is a contact when creating a record in a "Leads" object.
:{|
<pre>
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
Β  Β  }
}
</pre>
|}
Β 
====Set a Date Field====
If a user checked the "Done" radio button in a radio button group named <tt>technical_spec_completed</tt>, set the <tt>spec_date</tt> field with the current date formatted as month number, day number, and year.
:{|
<pre>
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);
Β  Β  }
}
</pre>
|}
Β 
====Change a Checkbox Field====
{{:Change Checkbox Value Script}}
Β 
====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.
:{|
<pre>
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;
Β  Β  }
}
</pre>
|}


===Learn More===
===Learn More===
:* [[JavaScript Field Type Reference for New AgileApps User Interface]]
:* [[Referencing Form Fields in JavaScript]]
:* [[Referencing Form Fields in JavaScript]]
:* [[Field Name|Field Name and Field Value]] syntax
:* [[Field Name|Field Name and Field Value]] syntax

Latest revision as of 05:12, 17 May 2024

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
  • Reusable 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:

Working with Form Scripts

Notepad.png

Note: Please note that all the examples listed in this page are limited to the legacy AgileApps UI and not the new runtime AgileApps UI.

Editing Form Scripts

Follow these steps to add or change scripting in a form:

Notepad.png

Note: To run the JavaScript in the LongJump UI and the legacy AgileApps UI, enter the script in the Legacy UI Script tab. To run the JavaScript in the New AgileApps UI, enter the script in the New UI Script tab.

  1. Click [Form Script]
  2. Click [Edit]
  3. Enter or change the JavaScript in On Load Script, On Save Script, and/or Reusable Script Functions
  4. Click [Save]

Writing JavaScript

Using JavaScript, you can

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. For information about adding a help button to a form, see the tech community article Adding a Custom Button to an Arbitrary Form using Form Script.

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):

Notepad.png

Note: For new UI, see the section Variables and Methods Introduced in the Revamped UI in JavaScript Field Type Reference for New AgileApps User Interface

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

For examples related to the On Save action, see the tech community article Perform Custom Validations using Form Script in AgileApps.

Learn More