In earlier article we discussed about new scripting methods introduced in CRM 2016 to implement AutoComplete feature. In last example we used hard coded option to show over autocomplete list, but in this post we are going to demonstrate how we can bring these options from a custom configuration entity to populate under autocomplete list.
We have setup a custom entity named Configuration, where we have not created any custom fields so we are just using default primary attribute field to store possible options for salutations.
Using this custom entity CRM admin can create/delete required salutations easily, so it is easy to configure list options without any coding changes. We will write OData query to get list of our configuration entity records and will utilize here retrievemultiple method of CRM organization service to get data based on the character enter by the user, so our query filter will be like the following,
- function ContactOnLoad() {
- Xrm.Page.getControl("salutation").addOnKeyPress(LoadAutoComplete);
- }
-
- function LoadAutoComplete() {
- var salutationtxt = Xrm.Page.getControl("salutation").getValue();
- var entitySchemaName = "him_configuration";
- var odataQuery = "?$select=him_name&$top=10&" +
- "$filter=startswith(him_name,'" + salutationtxt + "')";
- if (typeof(SDK) != "undefined") {
- SDK.REST.retrieveMultipleRecords(entitySchemaName, odataQuery, Callback, function(error) {
- alert(error.message);
- }, function() {});
- } else {
- alert("Not able to load REST.SDK library");
- }
- }
-
- function Callback(entityresultSet) {
- if (entityresultSet.length > 0) {
-
- var salutationtxt = Xrm.Page.getControl("salutation").getValue();
- resultSet = {
- results: new Array(),
- commands: {
- id: "salutationcmd",
- label: "Search in Google",
- action: function() {
- window.open("http://google.com");
- }
- }
- };
- var salutationtxtLowerCase = salutationtxt.toLowerCase();
- for (i = 0; i < entityresultSet.length; i++) {
- if (salutationtxtLowerCase === entityresultSet[i].him_name.substring(0, salutationtxtLowerCase.length).toLowerCase()) {
- resultSet.results.push({
- id: i,
- fields: [entityresultSet[i].him_name]
- });
- }
- }
-
- if (resultSet.results.length > 0) {
- Xrm.Page.getControl("salutation").showAutoComplete(resultSet);
- } else {
- Xrm.Page.getControl("salutation").hideAutoComplete();
- }
- }
- }
Now we need to add our SDK script web resource to contact entity form and need to call ContactOnLoad method on contact form OnLoad like the following,
Make sure to keep SDK.Rest.js first in order.
Save and publish your changes and now try to modify salutation field for existing or new contact record, it will load list from configuration entity like the following,