In this recipe, we will be retrieving information from the Phone field of a Contact entity. We can work in the same fashion with any other default text fields on any entity form, or with custom fields.
If you have a solution created from the previous chapter, open that solution. If not, create a new solution package. We will be saving all configurations as part of a solution package.
In order to associate our script with a field on the Contact form, we will follow these steps:
OnChange
event of this field. The script will execute when the focus is moved off this field. This functionality is similar to capturing the OnBlur
standard JavaScript form event.OnChange
, and add a new function named ReadBusinessPhone. Make sure the enabled checkbox is selected, then click on OKfunction ReadBusinessPhone() { var myBusinessPhone; myBusinessPhone = Xrm.Page.getAttribute("telephone1").getValue(); alert("You have entered: " + myBusinessPhone); }
While our sample script does not really do much other than retrieve the input and return it in a pop-up window, from here on you can do more complex things, such as formatting and validation. Those are standard JavaScript string operations in most cases.
Once you have the value of the text field captured in your script, you can do more interesting processing. The following examples describe some of the common actions I use on regular basis.
Looking at the Field properties, as described in step 10, if we open the Details tab, the Name field holds the actual field name we have to use in JavaScript:
One common formatting I implement on all phone number fields is the formatting of the number. In order to make it readable and user friendly, we can check to make sure the length is either 10 or 11 characters, and then format it for North America in the following way:
+1-XXX-XXX-XXXX
Remove "-" before the count to make sure you are getting the correct length, and also check that all input is numeric.
Another common validation that can be implemented is the validation of Country/Region versus State/Province. Out of the box, the State/Province field comes before the Country/Region field, so we can read the value in State/Province, and based on that prepopulate the Country value.
Once we have processed the value retrieved from the text field, we can write it back to the same or another text field. The line of code to do so is as follows:
Xrm.Page.getAttribute("telephone1").setValue(myBusinessPhone);
This assumes that we will be writing the information to a field named telephone1, and the variable that stores the processed string is named myBusinessPhone
.
3.145.46.109