Tuesday, February 14, 2012

MS CRM 2011: How to find Syntax to read different values

MS CRM 2011 syntax for common basic Jscript functions are following:
for more information read the blog

1) Get the GUID value of a lookup field:
function GetGUID() {
var primaryContactGUID = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].id;
alert(primaryContactGUID);
}

2) Get the Text value of a lookup field:
function GetText() {
var primaryContactName = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].name;
alert(primaryContactName);
}

3) Get the string value of a text field:
function GetTextField() {
var MainPhone = Xrm.Page.data.entity.attributes.get("telephone1").getValue();
alert(MainPhone);
}

4) Get the database value (i.e. the integer value) of an Option Set (pick list) field:
function GetOptionSetDatabaseValue() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressTypeDisplayValue = AddressType.getValue();
if (AddressTypeDisplayValue != null) {
alert(AddressTypeDisplayValue);
}
}

5) Get the display value (i.e. the text displayed in the drop down) of an Option Set (pick list) field:

function GetOptionSetDisplayValue() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressTypeDisplayValue = AddressType.getText();
if (AddressTypeDisplayValue != null) {
alert(AddressTypeDisplayValue);
}
}

6) Set the value of a string field:

function SetStringField() {
var Name = Xrm.Page.data.entity.attributes.get("name");
Name.setValue("ABC");
}

7) Set the value of an Option Set (pick list) field:

function SetOptionSetField() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressType.setValue(1);
}

8) Set the value of a Date field:

function SetDateField() {
var BirthDate = Xrm.Page.data.entity.attributes.get("birthdate");
var today = new Date();
var futureDate = new Date(today.setDate(today.getDate() + 1));
BirthDate.setValue(futureDate);
}

9) Set the value of a Lookup field:

// Set the value of a lookup field
function SetLookupValue(fieldName, id, name, entityType) {
if (fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}

var ExistingCase = Xrm.Page.data.entity.attributes.get("new_existingcase");
if (ExistingCase.getValue() != null) {
var ExistingCaseGUID = ExistingCase.getValue()[0].id;
var ExistingCaseName = ExistingCase.getValue()[0].name;
SetLookupValue("regardingobjectid", ExistingCaseGUID, ExistingCaseName, "incident");
}

10) Set the Requirement Level of a Field:

function SetRequirementLevel() {
var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
AddressType.setRequiredLevel("required");
}


11) Disable a field:
function SetEnabledState() {
var AddressType = Xrm.Page.ui.controls.get("address1_addresstypecode");
AddressType.setDisabled(true);
}

12) Hide a field:
function hideName() {
var name = Xrm.Page.ui.controls.get("name");
name.setVisible(false);
}

13) Hide a nav item:
Note: you need to refer to the nav id of the link, use F12 developer tools in IE to determine this

function hideContacts() {
var objNavItem = Xrm.Page.ui.navigation.items.get("navContacts");
objNavItem.setVisible(false);
}

14) Hide a Section:
function HideShowSection(tabName, sectionName, visible) {
Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(visible);
}

HideShowSection("tab_5", "tab_5_section_4", true);


15) Save the form:
function SaveAndClose() {
Xrm.Page.data.entity.save();
}

16) Save and close the form:
function SaveAndClose() {
Xrm.Page.data.entity.save("saveandclose");
}

17) Close the form:
Note: the user will be prompted for confirmation if unsaved changes exist

function Close() {
Xrm.Page.ui.close();
}

18) Determine the Form Type:
Note: Form type codes: Create (1), Update (2), Read Only (3), Disabled (4), Bulk Edit (6)

function AlertFormType() {
var FormType = Xrm.Page.ui.getFormType();
if (FormType != null) {
alert(FormType);
}
}

19) Determine the GUID of the current record:

function AlertGUID() {
var GUIDvalue = Xrm.Page.data.entity.getId();
if (GUIDvalue != null) {
alert(GUIDvalue);
}
}

20) Determine the GUID of the current user:

function AlertGUIDofCurrentUser() {
var UserGUID = Xrm.Page.context.getUserId();
if (UserGUID != null) {
alert(UserGUID);
}
}

21) Determine the CRM server URL:

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

22) Refresh a Sub-Grid:

var targetgird = Xrm.Page.ui.controls.get("target_grid");
targetgird.refresh();

23) Pop the lookup window associated to a Lookup field:

window.document.getElementById('new_existingcase').click();

24) Change the default entity in the lookup window of a Customer or Regarding field:

Note: this approach utilises my configuration data framework as described here. You will need to create the supporting configuration data entity and add a configuration record to house the GUID of the default view you wish displayed in the lookup window

function ChangeLookup() {
document.getElementById("from").setAttribute("defaulttype", "2");
var ConfigValue = GetConfigValue("ActiveContactsViewGUID");
Xrm.Page.getControl("from").setDefaultView(ConfigValue);
}



function GetConfigValue(ConfigParamName) {

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

// Specify the ODATA end point (this is the same for all CRM 2011 implementations)
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

// Specify the ODATA entity collection (this needs to be specific to your entity)
var ODATA_EntityCollection = "/new_configurationSet";

// Specify the ODATA filter
var ODATA_Query = "?$select=new_Value&$filter=new_name%20eq%20\'" + ConfigParamName + "\'&$top=1";

// Build the URL
var ODATA_Final_url = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Query;

//Calls the REST endpoint
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODATA_Final_url,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//This function will trigger asynchronously if the Retrieve was successful
return (data.d.results[0].new_Value);
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
//This function will trigger asynchronously if the Retrieve returned an error
//alert("ajax call failed");
}
});
}

25) Pop an existing CRM record:
Note: this example pops an existing Case record. The GUID of the record has already been established and is stored in the variable IncidentId.

//Set features for how the window will appear
var features = "location=no,menubar=no,status=no,toolbar=no";

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&id=" + encodeURIComponent(IncidentId), "_blank", features, false);

26) Force Submit value
Sets whether data from the attribute will be submitted when the record is saved.
function submitAllOptionsetData()
{
var attributes = Xrm.Page.data.entity.attributes.get(SDK.AttributeSamples.isOptionSet);
for (var i in attributes)
{
attributes[i].setSubmitMode("always");
}

alert(Xrm.Page.data.entity.getDataXml());
}

or

Xrm.Page.getAttribute("attribute Id").setSubmitMode("always");


27) Pop the Create form of a CRM record type:

Note: this example pops the Case form from the Phone Call form, defaulting the Case’s CustomerID based on the Phone Call’s SenderID and defaulting the Case Title to “New Case”

//Collect values from the existing CRM form that you want to default onto the new record
var CallerGUID = Xrm.Page.data.entity.attributes.get("from").getValue()[0].id;
var CallerName = Xrm.Page.data.entity.attributes.get("from").getValue()[0].name;

//Set the parameter values
var extraqs = "&title=New Case";
extraqs += "&customerid=" + CallerGUID;
extraqs += "&customeridname=" + CallerName;
extraqs += "&customeridtype=contact";

//Set features for how the window will appear
var features = "location=no,menubar=no,status=no,toolbar=no";

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

//Pop the window
window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);

Here is a little more info that will help you get your head around the general design of all this…

Depending upon what you want to do you will interact with one of the following:

Xrm.Page.data.entity.attributes – The data fields represented by fields on the form

Xrm.Page.ui.controls – The user interface controls on the form

Xrm.Page.ui.navigation.items – The navigation items on the form

28) SetFocus on MS CRM 2011 for tab, navigation and controls
To set the focus on tab, navigation or on fields afetr doing some validations.

Set Focus for Tab
Xrm.Page.ui.tabs.get('TabName').setFous();

Set Focus for Navigation
Xrm.Page.ui.navigation.items.get(0).set Focus();

Set Focus for Fields (Controls)
(Xrm.Page.ui.controls.get("attributeName")).setFocus();


for more information read the blog

MS CRM 2011: How to colorize grid rows based on some conditions

In CRM 2011, I found a way to add color to entities grids using the ribbon, even if there are still two limitations:

1) This is still not supported (as I browse and change DOM as you will see below) but does not required access to the filesystem
2) Ribbon element that helps me to colorize the grid view can’t be hidden and it is useful just to add color, it should then not be visible…

To accomplish this you need to perform three tasks
1) Add Ribbon Button

This button is added in the HomePageGrid of an case entity (but could also be added to SubGrid). It has an Enable rule that perform the grid colorization and returns always false to be deactivated. This is the last remaining difficulty, the SDK doesn’t allow to use a customRule to manage DisplayRule, so we can just deactivate the button.

<RibbonDiffXml>
<CustomActions>
<CustomAction Id="Mscrm.HomepageGrid.incident.MainTab.Actions" Location="Mscrm.HomepageGrid.incident.MainTab.Actions.Controls._children" Sequence="20">
<CommandUIDefinition>
<Button Id="Mscrm.HomepageGrid.incident.Colorization.Button" Command="Mscrm.HomepageGrid.incident.Colorization.Button.Command" CommandType="General" Image32by32="/_imgs/Ribbon/Actions_32.png" LabelText="Colorize" Sequence="22" TemplateAlias="o1" />
</CommandUIDefinition>
</CustomAction>
</CustomActions>
<Templates>
<RibbonTemplates Id="Mscrm.Templates"></RibbonTemplates>
</Templates>
<CommandDefinitions>
<CommandDefinition Id="Mscrm.HomepageGrid.incident.Colorization.Button.Command">
<EnableRules>
<EnableRule Id="ColorizeRule" />
</EnableRules>
<DisplayRules />
<Actions />
</CommandDefinition>
</CommandDefinitions>
<RuleDefinitions>
<TabDisplayRules />
<DisplayRules>
<DisplayRule Id="testRule">
<CrmClientTypeRule
Default="false"
InvertResult="false"
Type="Outlook" />
</DisplayRule>
</DisplayRules>
<EnableRules>
<EnableRule Id="ColorizeRule">
<CustomRule
Default="true"
InvertResult="false"
FunctionName="load"
Library="$webresource:mctools_/ColorView/jQuery_1_7_1.js" />
<CustomRule Default="true" InvertResult="false" FunctionName="load" Library="$webresource:new_jQuery_1_7_1" />
<CustomRule Default="false" InvertResult="false" FunctionName="load" Library="$webresource:new_case_colour_enabled">
<CrmParameter Value="SelectedControlAllItemReferences" />
<CrmParameter Value="SelectedControl" />
</CustomRule>
</EnableRule>
</EnableRules>
</RuleDefinitions>
<LocLabels />
</RibbonDiffXml>

2) jQuery library

Download the latest version from jQuery web site and add a new function to permit load of this script file from ribbon. jQuery will help us writing faster code…

3) A custom library

The custom library has a unique function with two parameters:
A list of entityReference that contains the grid elements displayed
The grid control itself

Script File we are using is

function load(items,grid)
{
try
{
if(items)
{
var index = $("#gridBodyTable").find("col[name=gendercode]").index();
/*//to colour a specific cell of grid row
var a = document.all['crmGrid'].InnerGrid.AllRecords;
alert(a);
alert(a.length);
for (var i=0; i <a.length; i++)
{
alert(a[i][a[i].length-1].cells[3].innerText);

if(a[i][a[i].length-1].cells[3].innerText=='Homme')
{
a[i][a[i].length-1].cells[3].style.backgroundColor='CCFF33';
}
if(a[i][a[i].length-1].cells[3].innerText=='Femme')
{
a[i][a[i].length-1].cells[3].style.backgroundColor='FF9966';
}

}*/

/*
$('table tr :nth-child(3)').css('background-color', 'red');
$('table tr :nth-child(3)').innerHtml();
var myValue = $(this).parents('tr:first').find('td:eq(4)').text();

*/
//To colour a grid row
for(var i=0;i<items.length;i++)
{
var id = items[i].Id;

$(grid._element).find("tr[oid='" + id + "']").each(function()
{
var theTr = $(this);

//alert(theTr);
//alert(theTr.find("td:nth-child(4)")[0].innerText);
//theTr.find("td:nth-child(" + (index/1 + 1/1) + ")")[0].innerText

if(theTr.find("td:nth-child(5)")[0].innerText.indexOf("Normal") >= 0)
{
theTr.find("td").css("background-color","lightblue");
}
else if(theTr.find("td:nth-child(5)")[0].innerText.indexOf("Low") >= 0)
{
theTr.find("td").css("background-color","pink");
}
else if(theTr.find("td:nth-child(5)")[0].innerText.indexOf("High") >= 0)
{
theTr.find("td").css("background-color","red");
}
});
}
}
}
catch(e)
{
alert(e.description);
}
}


5) Screenshot



For More Information please read the mscrmtools blog

Split the String values with a special character in MS Flow to convert this into Array

 Many times we have a requirement to prepare the Mailing address for some of the documents, suppose there are Address Line1, Address Line2, ...