Advertisements

Archive

Posts Tagged ‘JScript’

D365 – Multi Select Option set JScript Syntax

November 21, 2017 4 comments

In this article I am going to provide JScript syntax’s to use in projects.

Refer my previous article on configuring Multi Select Option set fields.

// Read the values
var branches = Xrm.Page.getAttribute(“new_branches”).getValue();
Xrm.Utility.alertDialog(“Branches – ” + branches, null);

// Set the values (i.e., Hyderabad,Chennai)
Xrm.Page.getAttribute(“new_branches”).setValue([100000000, 100000001]);

// Determine if the option is selected

// Non-IE Browser
var isCitySelected = Xrm.Page.getAttribute(“new_branches”).getValue().includes(100000000);

// IE Browser

var isCitySelected = Xrm.Page.getAttribute(“new_branches”).getValue().indexOf(100000000)>=0;

Xrm.Utility.alertDialog(“Is City Selected – ” + isCitySelected, null);

// Clear the values
Xrm.Page.getAttribute(“new_branches”).setValue(null);

Create a web resource with these syntax’s and map to the form.

JScript - Multi select option set

🙂

Advertisements

Build Auto Complete Text Box using Jscript – CRM 2016

In CRM 2016, we got showAutoComplete and hideAutoComplete methods to configure the auto-completion experience in text controls in forms.

In this article, I am going to configure “Auto Complete” feature for my “Locality” text box on my Account form.

Auto Complete Localities

Auto Complete Localities

JScript:

function suggestLocality() {
// List of sample Locality names to suggest
accounts = [
{ name: ‘AA Street’, code: ‘A01’ },
{ name: ‘AB Street’, code: ‘A02’ },
{ name: ‘AC Street’, code: ‘A03’ },
{ name: ‘Benetten street’, code: ‘A04’ },
{ name: ‘Beverly Hills’, code: ‘A05’ },
{ name: ‘City Street’, code: ‘A06’ },
{ name: ‘City Power & Light’, code: ‘A07’ },
{ name: ‘Aruna Street’, code: ‘A08’ },
{ name: ‘Winery Street’, code: ‘A09’ },
{ name: ‘Coho Vineyard & Winery’, code: ‘A10’ },
{ name: ‘Zeebra Street.’, code: ‘A11’ }
];

var localityKeyPress = function (ext) {
try {
var userInput = Xrm.Page.getControl(“raj_locality”).getValue();
resultSet = {
results: new Array(),
commands: {
id: “sp_commands”,
label: “Explore CRM”, // Help link text
action: function () {
window.open(“http://rajeevpentyala.com”); // Help link URL
}
}
};

// Read the ‘Text’ entered in Locality field.
var userInputLowerCase = userInput.toLowerCase();
for (i = 0; i < localities.length; i++) {
if (userInputLowerCase === localities[i].name.substring(0, userInputLowerCase.length).toLowerCase()) {
resultSet.results.push({
id: i,
fields: [accounts[i].name]
//, icon:<url> — Its an option field. You can show icon next to the Auto populated text.
});
}
if (resultSet.results.length >= 10) break;
}

if (resultSet.results.length > 0) {
// If matches found; Show the Auto complete text area with matched localitites (i.e., Up to 10)
ext.getEventSource().showAutoComplete(resultSet);
} else {
// If no match found; Hide the Auto complete text area.
ext.getEventSource().hideAutoComplete();
}
} catch (e) {
alert(“Error while auto complete – ” + e.description);
}
};

// Attach Key Press event to ‘Locality’ text box
Xrm.Page.getControl(“raj_locality”).addOnKeyPress(localityKeyPress);
}

How do I use it:

  • Copy the “suggestLocality” function and create a web resource in CRM.
  • Register the “suggestLocality” function on onload event of Account form.
Auto Complete Onload Event

Auto Complete Onload Event

  • Publish the Customization’s.
  • Open an Account and start typing in “Locality” text box.
Auto Complete Localities

Auto Complete Localities

  • You can extend the script by instead of hard coding Localities, you can read from any existing entity and populate the list.

Important Notes on Auto Complete feature:

  • “Auto Complete” show up to 10 matching strings in a drop-down list as users press keys to type character in a specific text field.
  • These methods aren’t supported for the CRM mobile clients (phones or tablets).

🙂

Categories: CRM 2016 Tags: , ,

Script error with navigate() statement while navigate between forms – CRM Jscript

September 12, 2015 Leave a comment

We have a Custom entity with 3 forms and the requirement is to navigate to a different form based on a field value .

So we registered a script on form ‘load’ event to navigate to a specific form based on an option set value.

Navigation worked as expected except few user’s that too when application should take User to ‘Form 2’.

Reason and Fix

  • We configured new Security Roles recently.
  • Our forms were role based and we missed enabling newly added “Security Role” for ‘Form 2’.
Role Based Forms - Account

Role Based Forms Screen

  • By enabling newly added Security Role for ‘Form 2’ script started working.

🙂

Categories: CRM Tags: , , ,

CRM 2015 – Useful JScript Snippets and Syntaxes

Below are the list of useful scripts and syntax’s

Filter look up records

Let’s consider a scenario, “Primary Contact” lookup on Account form should display only Contacts with “Business Phone” (i.e., Contact.telephone1 != Null)

Steps :

  • Add PreSearch event for ‘Primary Contact’ lookup
  • In the event handler define Filter and set to the lookup using ‘addCustomFilter’ method

Script:

// Attach below ‘onload’ function to Form onload event

function onload() {

Xrm.Page.getControl(“primarycontactid”).addPreSearch(filterCustomerContacts);

}

function filterCustomerContacts() {

//Only show Contacts with ‘Business Phone’

var primaryContactFilter = “<filter type=’and’><condition attribute=’telephone1′ operator=’not-null’ /></filter>”;

Xrm.Page.getControl(“primarycontactid”).addCustomFilter(primaryContactFilter, “contact”);

}

Filter Primary Contact Lookup

Filter Primary Contact Lookup

Get fields of specific types

One of my blog follower asked this question “How to get list of all Option Set fields placed on the form?”.

Below is the Script to get Attributes based on Type or Requirement Level using “Xrm.Page.data.entity.attributes.forEach”

Script:

function onload() {

var requiredAttributeNames = [];

var optionsetAttributeNames = [];

Xrm.Page.data.entity.attributes.forEach(

function (attribute, index) {

if (attribute.getRequiredLevel() == “required”) {

requiredAttributeNames.push(attribute.getName());

}

if (attribute.getAttributeType() == “optionset”) {

optionsetAttributeNames.push(attribute.getName());

}

});

alert(“Required Attributes on the form are : ” + requiredAttributeNames.join());

alert(“Attributes of Type Optionset on the form are : ” + optionsetAttributeNames.join());

}

Callback functions on Save

Saves the record asynchronously with the option to set callback functions to be executed after the save operation is completed.

Script

Xrm.Page.data.save().then(successCallback, errorCallback);

successCallback() {

alert(“Form saved !!!”);

}

function errorCallback(saveErrorResponse) {

if (saveErrorResponse != null) {

if (saveErrorResponse.message != ‘undefined’ && saveErrorResponse.message != null) {

alert(“Error on Save – ” + saveErrorResponse.message);

}

}

}

Get control placed on Header

  • var nameControlInHeader = Xrm.Page.getControl(“header_{fieldname}”);

Get control placed in business process flow

  • var nameControlInBPF = Xrm.Page.getControl(“header_process_{fieldname}”);
  • We can get controls in the active stage.

Hide\Show time portion of Date Control

  • Page.getControl(“createdon”).setShowTime(true/false);

Syntaxes

  • getUserPrivilege – When field level security has been applied to an attribute, determine whether a user has privileges to perform create, read, or update operations on the attribute

Xrm.Page.getAttribute(“name”).getUserPrivilege().canUpdate;

  • getMin – Get the minimum allowed value for an attribute that contains a number

Xrm.Page.getAttribute(“creditlimit”).getMin()

  • getMax – Get the maximum allowed value for an attribute that contains a number

Xrm.Page.getAttribute(“creditlimit”).getMax()

  • getIsPartyList – Determines whether an attribute is a partylist.

Xrm.Page.getAttribute(“to”).getIsPartyList()

  • getAttributeType – Get the type of attribute (i.e., Option set,Text etc…)

Xrm.Page.getAttribute(0).getAttributeType()

  • getFormat- Get attribute’s format. (i.e., Text,URL,Email etc…)

Xrm.Page.getAttribute(0).getFormat()

  • getInitialValue – Get the initial value of a Boolean or Optionset attribute

Xrm.Page.getAttribute(“address1_addresstypecode”).getInitialValue()

  • getMaxLength – Get the maximum allowed length for an attribute that contains a string

Xrm.Page.getAttribute(“name”).getMaxLength()

  • alertDialog – Display a non-blocking alert dialog with a callback function.

var alertDisplayed = false;
Xrm.Utility.alertDialog(
“Showing Alert”,
function () { alertDisplayed = true; }
)

  • confirmDialog – Display a Non-blocking Confirm dialog with different callbacks depending on the button clicked by the user.

var agree = false;
Xrm.Utility.confirmDialog(
“Do you agree?”,
function () { agree = true;},
function () { agree = false; }
);

🙂

Categories: CRM 2015 Tags: ,

Exclude namespaces from XML using Jscript

In one of my requirement I had to parse XML and find node values.

 My XML looks as below

<NS1:Envelope xmlns:NS1=http://schemas.xmlsoap.org/soap/envelope/>

<QueryBalanceResult>

<NS1:AvailableCredit>17400</NS1:AvailableCredit>

</QueryBalanceResult>

</NS1:Envelope>

Since the XML has got namespaces I need to exclude namespaces before I find the node. 

Below is the logic to exclude namespaces

var xmlWithNamespaces={Your xml with namespaces};

var xmlWithNoNamespaces= xmlWithNamespaces.replace(/<(\/?)([^:>\s]*:)?([^>]+)>/g, “<$1$3>”);

🙂

 

 

Categories: Misc Tags: , , ,

Identify “Auto Save” in JScript onload & onsave events – CRM 2013

December 30, 2013 1 comment

CRM 2013 has got a new ‘Auto Save” feature which periodically saves the form after new data entered.

Problem with frequent auto save

  • The problem with this design is whenever auto-save fires, it causes  unwanted execution of the registered onload & onsave events.

To identify ‘Auto Save’ event in ‘onload & onsave’ below is useful approach

On Save 

  • Check  the ‘Save Mode’ of ‘Event Args’, If Save Mode is ‘70’ then save event is caused by ‘Auto Save’
  • Make sure to check ‘Pass execution context as first parameter’ while registering ‘onsave’ event
Passing execution context

Passing execution context

function onsave(eventArgs) {

var saveMode = eventArgs.getEventArgs().getSaveMode();

// 70 – AutoSave

if (saveMode == 70) {

alert(“Save caused by AutoSave”);

// By setting Form dirty, we will make sure the traditional save event executes when you click on ‘Save’ button

Xrm.Page.data.setFormDirty(true);

}

else {

alert(“Traditional Save event”);

}

}

Note

  • Since the ‘AutoSave’ periodically saves the form data, you might not get traditional ‘onsave’ event fired.
  • If you want your logic to be executed in traditional ‘onsave’ event, set form dirty to ‘true’ in ‘AutoSave’ save mode.

On Load 

‘onload’ event caused by ‘AutoSave’ does not clears the global variables. So use below steps to check ‘AutoSave’ event on ‘onload’

  • Declare and set a global variable
  • Check the variable on onload event

var formLoaded = false;

function onload() {

if (!formLoaded) {

alert(“Traditional form load happend !!!”);

}

formLoaded = true;

}

  • Above function the ‘If’ block executes only first time when you open the form

🙂

Categories: CRM 2013 Tags: , ,

Xrm.Utility is undefined error – CRM 2011

Other day when I deployed my solution on a new CRM server, I was getting “Xrm.Utility is undefined” script error.

I refered“Xrm.Utility” JScriptin my code to open forms which was causing script issue.

Reason & Fix

  • The CRM server is not having UR 8
  • Since Xrm.Utility object was added in CRM 2011 Update Rollup 8, installing UR 8 on server solved the issue

🙂