Sage CRM Developers Course Validation Rules and Table and Entity Level Scripts
Looking ahead to the classes DP01: Introduction to the Development Partner Program DP02: Entities and the Data Model (Part 1 of 2) DP03: Entities and the Data Model (Part 2 of 2) DP04: Implementing Screen Based Rules (Part 1 of 2) DP05: Implementing Screen Based Rules (Part 2 of 2) DP06: Screen and User Independent Business Rules DP07: Workflow (Part 1 of 2) DP08: Workflow (Part 2 of 2) DP09: Using the API Objects in ASP Pages (Part 1 of 2) DP10 : Using the API Objects in ASP Pages (Part 2 of 2) DP11: Using the Component Manager DP12: Programming for the Advanced Email Manager DP13: Using the Web Services API DP14: Using the Web Services API (Part 2 of 2) DP15: Coding the Web Self Service COM API (Part 1 of 2) DP16: Coding the Web Self Service COM API (Part 2 of 2) DP17: Using the .NET API (Part 1 of 2) DP18: Using the .NET API (Part 2 of 2)
Agenda Validation Rules Screen and User Independent Business Rules Table Level and Entity Level Scripts including future change in support for Detached/Delayed Table Level scripts Objects Available Differences between Values() and FormValues() Collections Availability of Contextual Information Rollback behaviour
Validate Script What are the Objects Available? Core Jscript Objects Extensibility Module Objects ActiveX Objects What is the Scope of Effect? What are the limitations?
Complex Rules Validation Rules can support complex multi- row and inter-table rules Example Wave Budget Validation Rule var wavebudgetentered = Values('wave_budget'); var myRecordId = CRM.GetContextInfo('Campaigns','camp_campaignid'); var campaignsbudget = CRM.GetContextInfo('Campaigns','camp_budget'); var myRecord = CRM.FindRecord('Waves','wave_campaignid='+myRecordId); var totalwavesbudget = 0 var brokebudgetbyamount = 0; while (!myRecord.eof) { totalwavesbudget += Number(myRecord.wave_budget); myRecord.NextRecord(); } totalwavesbudget += Number(wavebudgetentered); if (totalwavesbudget >campaignsbudget) brokebudgetbyamount = totalwavesbudget - campaignsbudget; Valid = false; ErrorStr = 'You have broken the campaign budget by ' + brokebudgetbyamount; else Valid = true; Validation rules can make use of other Server objects. For example we might want to implement the following business rule: "Customer Care cases can only be entered for Companies that are of type 'Customer' & that have an agreed SLA." The rule has to be written with the screen which is used to enter the case. I'll put the rule on the case_referenceid field. This is for convenience as I am not interested in that field's data. Within Validation scripts (& table/entity & workflow scripts) this context is accessed via the eWare object. For example in our rule: var companyid = CRM.GetContextInfo('company','comp_companyid') The two parameters are the 'entity' & the 'entity primary key'. This can then allow us to retrieve more details about the company. We will use the eWareRecordBlock object for this. This data handling object will allow use to retrieve the correct company record. var companyRecord = CRM.FindRecord('company', 'comp_companyid='+companyid); The record is retrieved so we can check the properties: var companyid = CRM.GetContextInfo('Company', 'comp_companyid') var companyRecord = CRM.FindRecord('Company','comp_companyid='+companyid); if (companyRecord.comp_type == 'Customer' && companyRecord.comp_slaid >0) { Valid = true; } else Valid = false; ErrorStr = 'Cases can only be created for Companies that are Customers with an agreed SLA'
Validation Rules and onChange Rules The field may only contain letters and numbers var strRuleMessage = 'Field may only contain Letters and Numbers'; re =/[^A-Za-z0-9]/; r = this.value.match(re); if (r) { window.alert(strRuleMessage); } var strRuleMessage = "Field may only contain Letters and Numbers"; var strFieldData = Values("comp_customfield"); re =/[^A-Za-z0-9]/; r = strFieldData.match(re); if (r) { Valid = false; ErrorStr = strRuleMessage;} The field may only contain uppercase or lowercase letters. var strRuleMessage = 'The field may only contain uppercase or lowercase letters'; re =/[^A-Za-z]/; r = this.value.match(re); if (r) { window.alert(strRuleMessage); } if (r){ The field may only contain numeric characters. var strRuleMessage = 'The field may only contain numeric characters'; re =/[^0-9]/;
Using Validation Rules for other purposes Validation on Search Screens Validation rules are checked on submission of a search screen even though in this case no data is being inserted or updated. For example the code below on the comp_name will ensure that it can't be left blank when searching for companies. if (!Values("comp_name")) { Valid = false; ErrorStr = "you must fill in this field"; } Example Validation Log Script The example below only needs to log which fields have changed not every field in the screen so we first need to know what fields are in the screen and then examine each field in turn. To do this I've used the fact that the screen object (EntryGroup block) is an enumerable object. var ForReading = 1, ForWriting = 2, ForAppending = 8; var TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0; var mySystemObject = new ActiveXObject("Scripting.FileSystemObject"); var myFile = mySystemObject.GetFile("c:/customlogs/TEST.TXT"); var myFileTextStream = myFile.OpenAsTextStream(ForAppending, TristateUseDefault); var oldName = ""; var myBlock = CRM.GetBlock("CompanyBoxLong"); var myE = new Enumerator(myBlock); while (!myE.atEnd()) { oldName = CRM.GetContextInfo("company",myE.item()); if (oldName != Values(myE.item())) { myFileTextStream.WriteLine(oldName +"/"+Values(myE.item())+" changed by "+CurrentUser.user_logon); } myE.moveNext(); } myFileTextStream.Close();
Table and Entity Level Scripts
Four Types of Table/Entity Script Table Level Detached Table Level (Deprecated in Sage CRM v7.2) Developers should remove Detached Table Level scripts. Use Escalation rules and other scripts where possible. Entity Level Entity Level with Rollback Table Level Scripts can't block database actions but they are very useful for changing or inserting data. For example where data is being inserted by a third party system then table level scripts will still fire. Entity Level Scripts can be set to rollback if an error occurs. Entity Level Scripts with rollback work on Company Person Email Address
Objects used in Internal Scripting Main Objects Other Objects EntryGroup block is enumerable and it may provide us within a TableLevel script a simple way of checking if certain fields exist on the screen to see if they have changed value.
Entity Level Script Firing Points Screen System Action EntityScript Function New Company Newcompany Company InsertRecord() Change Company Companysummary UpdateRecord() Delete Company DeleteRecord() New Individual Newindividual Person Change Person PersonSummary Delete Person Personsummary Edit Phone/Email Phoneemail Email New Address Address Edit Address Delete Address
Values() Usage Values() FormValues() Reassign Values Access QueryString Create Script Can see data in form in View mode not Edit or Save Can see data in form in Save mode not View or Edit No both Values () – yes FormValues - no Validate Script All submitted data defined in blocks used in form Table level Script Only data in entity screen block e.g. company not address info Yes Values() No FormValues() -errors Values () – no
FormValues() and Values() The Values() collection Allows access the data within the fields associated with the EntryBlock (screen) used to build the edit screen for current record. E.g. editing a company record you would use the CompanyBoxLong screen. The FormValues() collection Allows access the data from within the whole of the HTML form submitted. This means in a screen like the new Company screen when you are actually inserting data to several tables (Company, Person, Address etc) then you can access any of the submitted data. E.g. So in an InsertRecord event function of an Company Entity script we could access the submitted address information: var strPostCode = FormValues("addr_postcode");
Validating Phone Numbers and Email Addresses We can use an "Entity Level script with Rollback". Entity Level with Rollback scripts can be used when we want to stop an action happening if there is a validation error or other error with the script. Need to consider Data Entry Data Update
Table Level Scripts Example Rule If the company is reassigned then reassign all opportunities for that company to that new personid. The GetContextInfo() method returns the originally assigned user and the Values() collection contains the inbound userid data. When they are different, the record has been reassigned. if (CRM.GetContextInfo('Company','comp_primaryuserid') != Values('comp_primaryuserid')) { var myCompRecordId = CRM.GetContextInfo('company','comp_companyid'); var strSQL = "oppo_status = 'In Progress' and oppo_primarycompanyid="+myCompRecordId; var myOppoRecord = CRM.FindRecord('opportunity', strSQL); while (!myOppoRecord.EOF) myOppoRecord.oppo_assigneduserid = Values('comp_primaryuserid') myOppoRecord.NextRecord(); } myOppoRecord.SaveChanges(); if (CRM.GetContextInfo('Company','comp_primaryuserid') != Values('comp_primaryuserid')) { var myCompRecordId = CRM.GetContextInfo('company','comp_companyid'); //This returns the primary key information var myOppoRecord = CRM.FindRecord('opportunity','oppo_primarycompanyid='+myCompRecordId); while (!myOppoRecord.EOF) myOppoRecord.oppo_assigneduserid = Values('comp_primaryuserid') myOppoRecord.NextRecord(); } myOppoRecord.SaveChanges(); Note This contains pre update values CRM.GetContextInfo('company','comp_primaryuserid') This contains the new passed in values Values('comp_primaryuserid') Also Table/Entity level scripts can chain. A script can cause change in table that will fire a script, that will fire a script....
Rollback & Table Level Scripts Only Entity Level Scripts can rollback Values() collection contains the new values CRM.GetContextInfo() returns the old value Therefore you are be able to do this... if (Values('data_whatever')==invalidValue) { Valid = false; ErrorStr = CRM.GetTrans('capt_family','capt_code'); Values('data_whatever') = CRM.GetContextInfo('mytable','data_whatever'); }
Update of Data not submitted from Screen The Values() collection can be extended to set a value for a field not in the screen. function UpdateRecord() { // Handle update record actions here var strCompany = Values("comp_name"); Values("comp_name") = strCompany.toUpperCase(); Values("comp_mailrestriction") = 'Y'; }
Insert & PostInsert functions Two 'Insert' event functions available to you within table level scripts. InsertRecord() InsertRecord() event fires as the record is created but before the database insert, therefore the new unique id for the record is unknown. PostInsertRecord(). Have access to the records newly created unique id. But can’t use CRM.GetContextInfo('datatable','data_dataid') Record is new and is not in context at that moment. Neither can we use Values() collection Id has not been passed into the system.
Use of the WhereClause In a PostInsertRecord() function To obtain the newly created record id. Use system variable called 'WhereClause'. Contains after the creation of the record the literal string 'dataid=value' e.g 'lead_leadid=507'.
Variables & Objects P O Field Level Scripts Create Change Validate Table/Entity Scripts CurrentUser P Valid O ErrorStr Values() & FormValues() WhereClause
External Triggering of Table Level scripts Possible to trigger any Table Level script event function Triggered by COM API calls ASP page extensions Self Service extensions Windows script Mail Manager Scripts SOAP Web Service calls .NET API calls Note: Table Level scripts may not be triggered by changes made by Exchange & ERP sync engines
ScriptCommonFunctions In registry ScriptCommonFunctions reg key value utils\myfunctions.js Put filename you want. Assumed to be in the custompages folder or use path to subfolder. Functions in the file will be added to every table level script at execution. Note: May clash with existing ERP integration e.g. Sage 300 ERP
Q&A
Looking ahead to the classes DP01: Introduction to the Development Partner Program DP02: Entities and the Data Model (Part 1 of 2) DP03: Entities and the Data Model (Part 2 of 2) DP04: Implementing Screen Based Rules (Part 1 of 2) DP05: Implementing Screen Based Rules (Part 2 of 2) DP06: Screen and User Independent Business Rules DP07: Workflow (Part 1 of 2) DP08: Workflow (Part 2 of 2) DP09: Using the API Objects in ASP Pages (Part 1 of 2) DP10 : Using the API Objects in ASP Pages (Part 2 of 2) DP11: Using the Component Manager DP12: Programming for the Advanced Email Manager DP13: Using the Web Services API DP14: Using the Web Services API (Part 2 of 2) DP15: Coding the Web Self Service COM API (Part 1 of 2) DP16: Coding the Web Self Service COM API (Part 2 of 2) DP17: Using the .NET API (Part 1 of 2) DP18: Using the .NET API (Part 2 of 2)
Visit the Sage CRM Ecosystem at www.sagecrm.com Facebook: Sage CRM Twitter: wwwsagecrmcom LinkedIn: Sage CRM (Official Group) YouTube: wwwsagecrmcom