Re-usability of Web Resources by referencing the Execution context

What’s my problem statement?

I want to create a resusable web resource that I can use to validate and format the phone numbers for accuracy on any entity that contains a phone number field.

My options

  1. To create a web resource that references each phone number field on each entity that includes a phone number i.e. Contact, Account, lead  and call this web resource on the onchange event of each field.
  2. Create one web resource and pass in the execution context, call the web resource on the on change event for each phone number field on my entities

So with option one I could improve the code by using a function and calling the function based on the field that has changed passing in the phone number and validating it, but I have to create multiple web resources for each entity and thus maintain the same code in multiple places.

With option two, on the other hand my code is in one place and is ressuable. So how do I do option two?

The Solution – using the execution context

  1. The first step is to create a web resource with the code to validate the phone number but referring to the context of the execution to pass in the variable to be used to validate the number. To do this we add the parameter context to the function i.e.  function <<Insertfunctionname>>(context). We can then reference this context as follows var oField = context.getEventSource().getValue();
  2. We now need to write our simple phone number validation and format script as below.Phone Number Format Code
  3. Save and Publish the web resource.
  4. Open the first form to add the phone number validation and format script.
  5. Click on the Form Properties and add the new web resource as a new library
  6. Select the field to add the control to using the drop down and the event will default to On Change.
  7. Click on Add and select the new library and enter the function name of the script in my case “validatephonenumber”.
  8. Critical to the process is to select the Enabled check box and the “Pass execution context as first parameter” validatephonenumber2
  9. Click ok and save and publish
  10. Repeat for each phone field on each entity
  11. Now when you open the entity and update the phone number the script is run and the number is validated, without hardcoding any field value.

End Result

You can now use this same concept to script other resusable functions using the context of the call, great for any on change common validation of formatting function.

I hope this helps to simplify your development and time to deliver critical common functions.