2009/04/16

More CRM Jscript Code Snips!

Replacing the content of an IFRAME
If you really want to do some funny things in your CRM form, you can create an IFRAME serving as a placeholder for your real HTML code. Create an IFRAME in an entity and name it "IFRAME_TEST". In the Onload event put the following code:
crmForm.all.IFRAME_TEST_d.innerHTML ="Some HTML text";
Note the "_d" at the end of IFRAME_TEST. This single line replaces the whole IFRAME element with your own HTML.


Adding additional values to duration fields



The following script adds the new option "42 Minutes" to the actualdurationminutes field in a task:

var duration = crmForm.all.actualdurationminutesSelect;

var tables = duration.getElementsByTagName("table");
var table = tables[1];
var row = table.insertRow();
var newOption = row.insertCell(-1);
var newValue = "42 Minutes";
newOption.setAttribute("val", newValue);
newOption.innerText = newValue;


Changing the title of a CRM

formdocument.title = "Hello World!";

Changing the Link of a Ticker Symbol from MSN Money to Yahoo Finances

This is an unsupported solution as it requires modifications to server files!Open the following directory on your CRM server:
C:\Inetpub\wwwroot\_forms\controls (may vary depending on your installation)
Open the following file: INPUT.text.ticker.htc
Search the following function:

function Launch()
{
if(value.length > 0)
{
Parse();
window.open("

http://go.microsoft.com/fwlink?linkid=8506&Symbol=" + encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) + ",width=" + (screen.availWidth * .75) + ,scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
}}Replace it with the following:function Launch()
{
if(value.length > 0)
{ Parse();
//window.open("http://go.microsoft.com/fwlink?linkid=8506&Symbol=" + encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) + ",width=" + (screen.availWidth * .75) + ,scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
window.open("http://finance.yahoo.com/q?s=" + encodeURIComponent(value), "", "height=" + (screen.availHeight * .75) + ",width=" + (screen.availWidth * .75) + ",scrollbars=1,resizable=1,status=1,toolbar=1,menubar=1,location=1");
}}

Save the file.On your client machine: Open Internet Explorer and remove all temporary internet files, so that the new htc source is retrieved. Navigate to any ticker symbol, enter a valid value and double click it.


Counting the number of backslashes in a string

Of course you can use the two code snippets with any character you like.
Solution 1

var text = "hardware\\printers\\Epson";var paths = text.split("

\\");alert(paths.length -1);

Solution 2

var text = "hardware\\printers\\Epson";
var numBs = 0;
var index = 0;while(index != -1)
{
index = text.indexOf("\\", index);
if (index != -1)
{
numBs++; index++; }}alert(numBs);


Changing the label of a field at runtime

Lets say you want to change the label of the revenue field, then you simply write:

crmForm.all.revenue_c.innerText = "Amount Euro";

Simply append the "_c" to the field name. This should work for most labels.

Changing the colour of a single option in a picklist

You can change the colour and background colour of an option element using the following syntax:
//TODO:
Replace with the schema name of the picklist in question.
var list = crmForm.all.;
//using the first option here, you need to find the one you need.
var option = list.options[0];
//Set the background colour to red.
option.style.backgroundColor = "#FF0000";
//Set the text colour to white.
option.style.color = "#FFFFFF";

Opening a new window without the IE menu and status bars

The following is a sample HTML page that you can use to test. Replace the link with the URL of your web page.

return false">Domain

Retrieving the text of a lookup control

var lookup = crmForm.all..DataValue;
if (lookup[0] != null)
{
var theText = lookup[0].name;
}

Disabling a form at runtime

document.body.disabled = true;

This will disable all controls except the Notes tab, where you still can enter new notes.
Automatically changing the value of a text field to capitalsPut the following script in the OnChange event of the text field:
crmForm.all..DataValue = crmForm.all..DataValue.toUpperCase();

Getting notified when the user selects a another tab on a form

Put the following in the OnLoad event of your form:

crmForm.all.tab0Tab.onclick = function()
{

alert("Tab 0 clicked");
}crmForm.all.tab1Tab.onclick = function()
{
alert("Tab 1 clicked");
}

It seems that the tab pages are always named "tabxTab", where x is a number starting from 0 (first tab) to (n-1), where n is the total number of tabs. Maybe you find better events that handle the activation instead of a click, but that's the general way it should work.
The current record idThe primary key is always available in crmForm.ObjectIdIt is set to null, if the record hasn't been saved yet. There are some other useful properties. Look at the "Form Object Model" in the SDK docs for more information.
The current object type codeThe type code of the entity being displayed in a CRM form is available through
crmForm.ObjectTypeCode
There are some other useful properties. Look at the "Form Object Model" in the SDK docs for more information.

Initializing a date field with the current date

crmForm.all..DataValue = new Date();

Changing the URL of an IFRAME at runtime

Set the initial URL of the IFRAME to about:blank and execute the following line:

document.all.IFRAME_.src =
http://domain/file;

Displaying a picture in a CRM form,
Using a text field to store the data source ,
Let's say you have a custom field storing the image name called new_pictureName. Then in the OnLoad event do the following:

if ((crmForm.all.new_pictureName != null) && (crmForm.all.new_pictureName.DataValue != null))
{
document.all.IFRAME_.src =
http://server/dir/images/ + crmForm.all.new_pictureName.DataValue;
}
In the OnChange event of the new_pictureName place the following:
if (crmForm.all.new_pictureName.DataValue != null)

{
document.all.IFRAME_.src = http://server/dir/images/ + crmForm.all.new_pictureName.DataValue;
}
else
{ document.all.IFRAME_.src = "about:blank"
}

Checking crmForm.all.new_pictureName for null in the OnLoad event is a sanity check. Bulk edit forms will not display all fields and if it is not contained in the form, it will be null. This check is not required in the OnChange event, as this event will never fire if the field does not exist.

Changing the default lookup type

When opening a lookup that can select from multiple entity types, you may want to use a different default entity in the lookup dialog. The following script changes the default entity of the regardingobjectid field in an activity to contacts:if (crmForm.all.regardingobjectid != null) { crmForm.all.regardingobjectid.setAttribute("defaulttype", "2");}Checking if a field is present in a formif (crmForm.all. != null) { //do your JavaScript processing here}
You should always check if a field is present before accessing it, because your script may throw an exception if it is not included in a form (like in quick create forms if your field is not required or recommended).
Calculating a date field based upon the selection of a picklistThe following script assumes that you have a picklist with three values: "1 year", "2 years" and "3 years".

var years = 0;
switch(crmForm.all..DataValue)
{
//You need to check the picklist values if they have the values 1, 2 and 3. Look at the attribute in the entity customization and note the option values.
case "1": years = 1;
break;
case "2": years = 2;
break;
case "3": years = 3; b
reak;
}if (years != 0) {var date = new Date();
date.setYear(date.getYear() + years);
crmForm.all..DataValue = date;
}
Creating a new email when double-clicking a standard text field
if (crmForm.all. != null)

{
crmForm.all..ondblclick = function()
{
var email = crmForm.all..DataValue;
if ((email != null) && (email.length > 0))
{
window.navigate("mailto:" + email);
}
}}

Resetting a field value if validation fails

In the OnLoad event, place the following code:

crmForm.all..setAttribute("lastKnownGood", crmForm.all..DataValue);

This adds a new attribute to field for later access.
In the OnChange event put the following:

//checkFailed contains either true or false and must be set to the result of your validation routineif (checkFailed)
{
crmForm.all..DataValue = crmForm.all.fieldToCheck.getAttribute("lastKnownGood");
else
{
crmForm.all..setAttribute("lastKnownGood", crmForm.all.fieldToCheck.DataValue);
}

Inserting line breaks in a text area control

Put the following in the OnLoad event:

crmForm.all..style.whiteSpace = "pre";

Hiding an entire row of a CRM form

//the field you want to hidevar field = crmForm.all.name;
//search the enclosing table rowwhile ((field.parentNode != null) && (field.tagName.toLowerCase() != "tr"))
{
field = field.parentNode;}//if we found a row, disable itif (field.tagName.toLowerCase() == "tr")
{
field.style.display = "none";
}

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.;
//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.;
//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.;
//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.;
//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 <>
{
for (min = 0; min <>
{
var row = table.insertRow();
var cell = row.insertCell();
var time = ((hour <>
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 usingalert("Quote ID = " + crmForm.all.quoteid.DataValue);How to know which button triggered the OnSave eventYou 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..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 colour of a label

var label = crmForm.all._c;label.innerHTML = "" + label.innerText + "";

Hide a section on a form

crmForm.all.new_attribute_c.parentElement.parentElement.parentElement.style.display = 'none'

To show the section again:

crmForm.all.new_attribute_c.parentElement.parentElement.parentElement.style.display = 'block'