JavaScript Web Resources with Microsoft Dynamics 365 | JavaScript
Microsoft Dynamics 365 provide many opportunities to use JavaScript. All JavaScript used in Microsoft Dynamics 365 is added by creating JavaScript web resources.
Why and when to use JavaScript in Dynamics 365:
We can use JavaScript to perform actions in form scripts, command bar (ribbon) commands, and web resources.
Form Scripts: The most common use of JavaScript in Microsoft Dynamics 365 is to add functions as event handlers for entity form events. Tasks frequently performed by using form programming include the following:
- Data Validation: perform validation of data while the data is being edited.
- Automation: use form scripting to automate common tasks such as copy data from one filed to another or from another entity.
- Process enhancement and enforcement: You can customize what data to display in the form or the layout. You can use form programming to show or hide specific form elements, or to open different forms. You can control which fields are required based on data present in the form or in related records.
Command bar (ribbon) commands: When you customize the Microsoft Dynamics 365 command bar, you can configure commands for controls that you add. These commands contain rules that control whether the control is enabled and what action is performed when the control is used. Such as:
- Display/Hide ribbon buttons based on some logic
- Enable/Disable ribbon buttons based on some logic
- Handle what happens when you click a certain ribbon button
JavaScript Xrm.Page Object Model:
(Xrm.Page depricated by Microsoft, instead use formcontext/ executioncontext)
Microsoft Dynamics CRM uses the Xrm.Page object’s hierarchy JavaScript model showing the available namespaces, objects, and their collections.
The Xrm.Page object serves as a namespace object to consolidate three objects on the form:
1. Context: Xrm.Page.context: Provides methods to retrieve context-specific information such as organization details, logged-in user details, or parameters that were passed to the form in a query string.
2. Data: Xrm.Page.data: Provides access to the entity data and methods to manage the data in the form as well as in the business process flow control.
3. UI: Xrm.Page.ui: Contains methods to retrieve information about the user interface, in addition to collections for several sub-components of the form.
Collections:
The following describes the Xrm.Page object model collections:
Ø Attributes: The Xrm.Page.data.entity.attributes collection provides access to each entity attribute that is available on the form. Only those attributes that correspond to fields added to the form are available.
Ø Controls: Three objects contain a controls collection:
· ui.controls: The Xrm.Page.ui.controls collection provides access to each control present on the form.
· attribute.controls: Because an attribute may have more than one control on the form, this collection provides access to each of them. This collection will contain only one item unless multiple controls for the attribute are added to the form.
· section.controls: This collection only contains the controls found in the section.
Ø Navigation.items: The Xrm.Page.ui.navigation.items Collection provides access to navigation items that are visible on the left side of the form.
Ø FormSelector.items: When multiple forms are provided for an entity, the Xrm.Page.ui.formSelector.items collection provides access to each form definition available to that user.
Ø Tabs: You can organize each form by using one or more tabs. The Xrm.Page.ui.tabs collection provides access to each of these tabs.
Ø Sections: You can organize each form tab by using one or more sections. The tab Xrm.Page.ui tab.sections collection provides access to each of these sections.
Xrm.Page.context Properties and Methods:
· getUserId: Returns the GUID of the SystemUser.id value for the currently logged in user.
var userGUID = Xrm.Page.context.getUserId();
· getUserName: Returns the name of the current user.
var userName = Xrm.Page.context.getUserName();
· getUserRoles: Returns an array of strings representing the GUID values of each of the security roles that the user is associated with.
var currentUserRoles = Xrm.Page.context.getUserRoles();
· getClientUrl: Returns the base URL that was used to access the application.
var clientUrl = Xrm.Page.context.getClientUrl();
· getIsAutoSaveEnabled: Returns whether Autosave is enabled for the organization.
This method was introduced with Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update.
var isAutoSaveEnabled = Xrm.Page.context.getIsAutoSaveEnabled();
Xrm.Page.data properties and methods:
· refresh: Asynchronously refreshes and optionally saves all the data of the form without reloading the page.
Xrm.Page.data.refresh(true); true if the data should be saved after it is refreshed, otherwise false.
Xrm.Page.data.refresh(save).then(successCallback, errorCallback);
· save: Saves the record asynchronously with the option to set callback functions to be executed after the save operation is completed.
Xrm.Page.data.save();
Xrm.Page.data.save(saveOptions).then(successCallback, errorCallback); //saveOptions is optional
Another way to save entity.save: Saves the record synchronously with the options to close the form or open a new form after the save is completed.
Xrm.Page.data.entity.save(null | "saveandclose" | "saveandnew");
Xrm.Page.data.entity Properties and Methods:
· getId: Returns a string representing the GUID id value for the record.
var currentRecordGUID = Xrm.Page.data.entity.getId();
· getIsDirty: Returns a Boolean value that indicates if any fields in the form have been modified.
var isIdDirty = Xrm.Page.data.entity.getIsDirty();
Xrm.Page.data.entity.attribute OR Xrm.Page.getAttribute:
Xrm.Page.getAttribute: shortcut method to access a collection of attributes.
· Value:
Use the getValue and setValue methods of attributes are the most commonly performed actions in form scripts.
var myValue = Xrm.Page.getAttribute("CRMFieldSchemaName").getValue();
Xrm.Page.getAttribute("CRMFieldSchemaName").setValue("New Value");
· Required Level:
Use the setRequiredLevel and getRequiredLevel to set an attribute requirement level.
Xrm.Page.getAttribute("CRMFieldSchemaName").setRequiredLevel("none" | "required" | "recommended");
Xrm.Page.ui Properties and Methods:
Xrm.Page.ui contains properties and methods to retrieve information about the user interface as well as collections for several subcomponents of the form.
Xrm.Page.ui.control:
· Visible: Determine which controls are visible and show or hide them using the getVisible and setVisible methods.
Xrm.Page.getControl(arg).setVisible(true); Boolean: true if the control should be visible; otherwise, false.
· Disabled: Detect the state and enable or disable controls using the getDisabled and setDisabled methods.
Xrm.Page.getControl(arg).setDisabled(true); Boolean: true if the control should be disabled, otherwise false.
Supported Events in Form Programming
The Form Programming using Xrm.Page model allows you to handle the following form events −
· onLoad
· onSave
· onChange
· TabStateChange
· OnReadyStateComplete
· PreSearch
· Business Process Flow control events
Form Programming Example:
In this example, we will put some validations on the Contact form based on the Preferred Contact that the user selects. If the user selects Preferred Method of Contact= Email/ Phone then Email/ Business Phone should become mandatory.
Step 1 − Create a JavaScript file named ContactScripts.js and copy the following code.
// JavaScript source code –Ganesh Chowhan
function validatePreferredContact() {
//get the value of 'Preferred Method of Contact' field
var varPreferredContactValue = Xrm.Page.getAttribute("preferredcontactmethodcode").getValue();
//if Preferred Method of Contact = 'Email', make Email as mandatory
//else if Preferred Method of Contact = 'Phone' make 'Business Phone' field as mandatory
//and for all other value Email/ Phone is non-mandatory
if (varPreferredContactValue == 2) //Email
{
Xrm.Page.getAttribute("emailaddress1").setRequiredLevel("required");
Xrm.Page.getAttribute("telephone1").setRequiredLevel("none");
}
else if (varPreferredContactValue == 3) //Phone
{
Xrm.Page.getAttribute("telephone1").setRequiredLevel("required");
Xrm.Page.getAttribute("emailaddress1").setRequiredLevel("none");
}
else {
Xrm.Page.getAttribute("emailaddress1").setRequiredLevel("none");
Xrm.Page.getAttribute("telephone1").setRequiredLevel("none");
}
}
Step 2 − Open the Contact entity
form by navigating to Microsoft Dynamics
365 -> Settings -> Customizations -> Customize the System ->
Contact entity -> Forms -> Main Form.
Step 3 − Click Form Properties.
Step 4 − From the Form Properties window, click Add under Form Libraries.
Step 5- Then in the next Look Up Record Web Resource window, click New since we are creating a new web resource.
- OR -
Alternative to step 2-5 navigate to:
Microsoft Dynamics 365 > Settings > Solutions > click on your work solution and from solution explorer under Components, click Web Resources click New.
Step 6 − In the New Web Resource window, enter the following details −
Name − ContactScripts.js
Display Name − ContactScripts.js
Type – Script(Jscript)
Upload File − Upload the JavaScript file that you created from your local machine. OR directly copy-paste in the text editor.
Step 7 − Click Save and then Publish.
Step 8 − Here, you can now see the demo1_ContactScript.js web resource (demo1 is my publisher prefix). Select it and click Add. You have now successfully added a new web resource and registered it on the form.
Step 9 − Now we will add an event handler on the change of 'Preferred Method of Contact' field. This event handler will call the JavaScript function that we just wrote. Select the following options from the Event Handlers section.
Control − Preferred Method of Contact
Event − OnChange
Then, click the Add button, as shown in the following screenshot.
Step 10 − in the following window of Handler Properties, we will specify the method name to be called when the change event occurs.
Select Library as demo1_ContactScript.js and Function as validatePreferredContact. Click OK.
Note: No Brackets/ Parentheses and Enable checkbox is ticked to enable the event to be triggered. Also here we can pass Comma separated list of parameters that can be passed to the function if needed.
Step 11 − you will now be able to see the Form Library (Web Resource) and events registered on it. Click OK.
Step 12 − Click Save followed by Step 12 − Click Save followed by Publish.
Step 13 − Now open any Contact form and set the Preferred Method of Contact as Email. This will make the Email field as mandatory. If you now try to save this contact without entering any Email address, it will give you an error saying "You must provide a value for Email".
Note: any change in script edited you must reload it again by clearing temp or Ctrl+F5.
CRM JavaScript Best Practices:
· Avoid using unsupported code
· Try to not to access the DOM
· Use Asynchronous data access method
· Keep it simple
· Use safe and efficient logic
· Define unique names for your JavaScript functions
Debugging JavaScript in Microsoft Dynamics 365:
Each browser provides some kind of debugging extension. Internet Explorer, Google Chrome provides developer tools you can use to debug scripts in Microsoft Dynamics 365. The Internet Explorer/ Google Chrome developer tools can be opened by pressing F12 when viewing a page using browser.
IE: On the Debugger tab click on Folder Icon (or Ctrl+P to search)and look for your script and put breakpoint and you are ready to debug the JavaScript Code. Trigger the event from CRM by changing the field value.
No comments:
Post a Comment