clicksor

Monday, August 13, 2012

MS CRM 4.0 & 2011: Javascript with examples.



CRM 2011: JAVASCRIPT



Xrm.Page.context Methods

1. getAuthenticationHeader: 
Returns the encoded SOAP header necessary to use MSCRM 4.0 Web service calls.
2. getCurrentTheme:
Returns the current Outlook theme chosen by the user.
3.getOrgLcid:
Returns the LCID value for the base language of the organization.
4.getOrgUniqueName:
Returns the unique text value of the organizations name.
5.getQueryStringParameters:
Returns an array of key value pairs representing the query string arguments that were passed to the page.
6.getServerUrl:
Returns the base server URL. When a user is working offline, the URL is to the local MSCRM Web services.
7. getUserId:
Returns the current user’s SystemUser id.
8. getUserLcid:
Returns the LCID value that the user selected as their preferred language.
9.getUserRoles:
Returns an array of strings representing the GUID values of each of the security roles that the user is associated with.
10. isOutlookClient:
Returns a Boolean value indicating if the user is using MSCRM for Outlook client.
11. isOutlookOnline:
Returns a Boolean value indicating whether the user is connected to the MSCRM server while using the MSCRM for Outlook with Offline Access client.
12.prependOrgName
Prepends the organization name to the specified path.


Xrm.Page.data.entity Methods

1.addOnSave
Sets a function to be called when the record is saved.
2.getDataXml
Returns a string representing the xml that will be sent to the server when the record is saved.
3.getEntityName
Returns a string representing the logical name of the entity for the record.
4.getId
Returns a string representing the GUID id value for the record.
5.getIsDirty
Returns a Boolean value that indicates if any fields in the form have been modified.
6.removeOnSave
Removes a function from the OnSave event hander.
7.save
Saves the record. This method has three possible parameters.
8.Xrm.Page.data.entity Methods
9.close
Closes the form.
10.getCurrentControl
Returns the control object that currently has focus on the form.
11.getFormType
Indicates the form context for the record.
12.getViewPortHeight
Returns the height of the viewport in pixels.
13.getViewPortWidth
Returns the width of the viewport in pixels.
14.refreshRibbon
Causes the ribbon to re-evaluate data that controls what is displayed in it.
Returns the number of tabs in the collection.



Xrm.Page

The Xrm.Page object provides a hierarchy of objects that can be used to interact
with Microsoft Dynamics CRM 2011 forms in the following ways:

• Show and hide user interface elements.
• Support multiple controls for each attribute.
• Support multiple forms for each entity.
• Manipulate form navigation items.


Xrm.Page.context

Xrm.Page.context provides methods that are used to retrieve information that is
specific to an organization, a user, or parameters that were passed to the form in a
query string.

Xrm.Page.data.entity
Xrm.Page.data provides an entity object that provides collections and methods to
manage data within the entity form.

Xrm.Page.ui
Xrm.Page.ui provides collections and methods that are used to manage the user
interface of the form.


Shortcuts

The Xrm.Page object includes two shortcut methods that are used to provide
direct access to commonly used controls.

Xrm.Page.getAttribute

This shortcut provides direct access to the Xrm.Page.data.entity.attributes.get
method. The following example uses the Xrm.Page.getAttribute shortcut method
to get the accountnumber attribute.

var accountnumber = Xrm.Page.getAttribute("accountnumber");

Xrm.Page.getControl

This shortcut provides direct access to the Xrm.Page.ui.controls.get method. The
following example uses the Xrm.Page.getControl to get the accountnumber
control.

var accountnumber = Xrm.Page.getControl("accountnumber");


User-defined Shortcuts

User-defined shortcuts can be created by using JScript. For example, to interact
with the controls found in a specific section of a form, a shortcut variable can be
created to enable easy access to those controls.

var myControls =
Xrm.Page.ui.tabs.get(2).sections.get(0).controls.get();







CRM 4.0: Javascript Examples:


.
Disabling the time selection of a date/time field
You can dynamically enable or disable the time selection box of a date/time field using the following syntax:
var dateField = crmForm.all.<name of datetime field>;

//Check the existence of the time field. It is null if the control is setup to only display the date.
if (dateField.all.time != null) {

    //Disable the time field
    dateField.all.time.disable();

    //Enable the time field
    dateField.all.time.enable();
}
CRM automatically enables the time selection box if the date value changes to a non-null value, so in order to always disable the time selection box, you need to add the following OnChange event script to the datetime field:
var dateField = crmForm.all.<name of datetime field>;

//Check the existence of the time field. It is null if the control is setup to only display the date.
if (dateField.all.time != null) {
    //Disable the time field
    dateField.all.time.disable();
}
To initially disable the time field, put the following into the form OnLoad event:
var dateField = crmForm.all.<name of datetime field>;

//Check the existence of the datetime field. It may not be included in a quick create form!
if (dateField != null) {

    //Call the OnChange event handler
    dateField.FireOnChange();
}
Changing the time interval in date/time fields
The time selection box of a date/time field uses a 30 minute interval. You can change it to a different interval using the following code in an OnLoad event:
var dateField = crmForm.all.<name of datetime field>;

//Check the existence of the datetime field. It may not be included in a quick create form!
if (dateField != null) {

    var timeField = dateField.all.time;

    //Check the existence of the time field. It is null if the control is setup to only display the date.
    if (timeField != null) {

        //The new interval in minutes.
        var interval = 15;
        var tables = timeField.getElementsByTagName("table");

        if ((tables != null) && (tables.length > 0)) {

            var table = tables[1];

            //Remove all existing values from the selection box
            while (table.firstChild != null) {
                table.removeChild(table.firstChild);
            }

            //Add the new values
            for (hour = 0; hour < 24; hour++) {
                for (min = 0; min < 60; min += interval) {

                    var row = table.insertRow();
                    var cell = row.insertCell();
                    var time = ((hour < 10) ? "0" : "") + hour + ":" + ((min < 10) ? "0" : "") + min;

                    cell.setAttribute("val", time);
                    cell.innerText = time;
                }
            }
        }
    }
}
Getting the quote id inside a quotedetail form
There's a hidden field in the quotedetail form storing the quote id. You can access it using
alert("Quote ID = " + crmForm.all.quoteid.DataValue);
How to know which button triggered the OnSave event
You can use the event.Mode property in the OnSave event. It will tell you which button was used to save an entity. Not all values are documented in the SDK, e.g the "Save as completed" in a phone call has a value of 58. As it's not documented, this number may change in future releases.
To get started enter the following into your OnSave script:
alert ("event.Mode = " + event.Mode);
event.returnValue = false;
return false;
This codes makes it impossible to save the entity, but allows you to write down all of the values passed to OnSave. You will see 1 for a normal save operation and 2 for Save and Close. Most but not all constants are defined in /_common/scripts/formevt.js.
Accessing the CRM database from JavaScript
To access the CRM database from JavaScript, use the following as a template:
var connection = new ActiveXObject("ADODB.Connection");
var connectionString = "Provider=SQLOLEDB;Server=STUNNWARECRM;Database=stunnware_mscrm;Integrated Security=sspi";

connection.Open(connectionString);

var query = "SELECT name FROM FilteredAccount";
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open(query, connection, /*adOpenKeyset*/1, /*adLockPessimistic*/2);
rs.moveFirst();

var values = "";

while (!rs.eof) {
    values += rs.Fields(0).Value.toString() + " ";
    rs.moveNext();
}

connection.Close();

alert(values);
You may need to adjust your security settings in IE in order to run this code.
Modifying the Quick Create Form
Allthough the quick create form isn't listed in the forms and views dialog, it uses the same scripts entered in the main application form. You can use the following in the OnLoad script to run code when inside of a quick create form:
if (crmForm.FormType == 5 /* Quick Create Form */) {
    //modify the form using DHTML
}
Forcing the selection of an account in the potential customer field of an opportunity
Put the following into the opportunity's OnLoad event:
crmForm.all.customerid.setAttribute("lookuptypes", "1");
This tells the customer lookup to only include the account (object type code 1). A value of 2 forces the lookup to only display contacts.
Hiding and showing fields dynamically based on other field values
You can do this in client-side JavaScript. Let's say you have a picklist named "new_category" and you have assigned the following options to it:
1 - Business
2 - Private
3 - Unspecified
Let's further assume that you want to hide the fields "new_a" and "new_b" whenever a user selects "Private", but they should be visible if a different option is selected in the picklist. Your OnChange event script of the new_category field will be:
var hideValues = (crmForm.all.new_category != null) && (crmForm.all.new_category.DataValue == "2");
var displayStyle = hideValues ? "none" : "";

crmForm.all.new_a.style.display = displayStyle;
crmForm.all.new_b.style.display = displayStyle;
To run the code when the form is initially loaded, put the following into the OnLoad event:
if (crmForm.all.new_category != null) {
    crmForm.all.new_category.FireOnChange();
}
The test for a null value of crmForm.all.new_category is included to avoid errors if the field is not available on a form. This is true for quick create forms if the field required level is not set to business required or business recommended.
Removing the value from a lookup field
crmForm.all.<lookupField>.DataValue = null;
Hiding tabs at runtime
You can hide and show entire tabs dynamically using the following code:
//Add your condition here, usually a field comparison in an OnChange event
if (condition == true) {
    //hide the second tab
    crmForm.all.tab1Tab.style.display = "none";
}

else {
    //show the second tab
    crmForm.all.tab1Tab.style.display = "";
}
The tabs are named "tab0Tab", "tab1Tab", "tab2Tab" and so on.
Setting the active tab
From the SDK docs:
SetFocus: Sets the focus, changes tabs, and scrolls the window as necessary to show the specified field. Example:
// Set focus to the field.
crmForm.all.SOME_FIELD_ID.SetFocus();
Displaying related entities instead of the form when opening a record
To open a related entity view of the left navigation bar (like contacts in an account entity), you can use the following:
loadArea("areaContacts");
Each entry in the navigation bar has a unique area name (areaContacts is just a sample). If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the entry you're after. Some instructions on how to use it are in http://www.stunnware.com/crm2/topic.aspx?id=CrmLookAndFeel1; though it is a different topic, I included some screenshots using the developer toolbar in CRM.
Modifying the color of disabled form fields
Disabled form fields are sometimes hard to read. Making the color a little bit darker greatly helps to read all of the content without loosing the information that a field is read-only.
Open the following file in your CRM web: /_forms/controls/controls.css. Then find the following style:
INPUT.ro,TEXTAREA.ro,DIV.ro,SPAN.ro
{
background-color: #ffffff;
color:    #808080;
border-color:  #808080;
}
The color attribute is the light gray you're seeing by default. You may change it to #404040 to get a slightly darker gray. If you don't see the new colors in IE, hit CTRL-F5 to reload the source files, including the updated css file.
Removing a navigation bar entry at runtime.
To remove a navigation bar entry dynamically, you can use the following code:
var navigationBarEntry = document.getElementById("navProds");

if (navigationBarEntry != null) {
   
    var lbArea = navigationBarEntry.parentNode;

    if (lbArea != null) {
        lbArea.removeChild(navigationBarEntry);
    }
}
If you haven't already done it, download and install the Internet Explorer Developer Toolbar to find the name of the navigation bar entry.
Changing the color of a label
var label = crmForm.all.<field name>_c;
label.innerHTML = "<font color='#FF0000'>" + label.innerText + "</font>";



1 comment:

  1. hi,

    i have req. of "when i click on tabs from navigation pane..sepcific field in that tab should be focused".
    can u pls help ?

    Thank you..!

    ReplyDelete