Reusable Jscript Library of Common Functions for CRM 2011

I find myself needing the same jscript over and over again when I build out demos.  To make life easier I decided to create a function library that I can attach to any CRM form.  Here it is.  I will add to this over time. 

If you have any useful functions that should be included post them in the comments and I’ll incorporate them.  The jscript is available here and below.   At the end of this post you will see some examples demonstrating the use of these functions.

Warning: these functions are of a ‘demo’ standard, and should be hardened and tested before used in a production setting.

p.s. my older jscript reference post has been updated recently as well, check it out.

// Determine Form Type
// example: GetFormType();
function GetFormType() {
    var FormType = Xrm.Page.ui.getFormType();
    if (FormType != null) {
        switch (FormType) {
            case 1:
                return "create";
                break;
            case 2:
                return "update";
                break;
            case 3:
                return "readonly";
                break;
            case 4:
                return "disabled";
                break;
            case 6:
                return "bulkedit";
                break;
            default:
                return null;
        }
    }
}

// Show/Hide a TAB
// example: HideShowTab("General", false);   // "false" = invisible
function HideShowTab(tabName, visible) {
    try {
        Xrm.Page.ui.tabs.get(tabName).setVisible(visible);
    }
    catch (err) { }
}

// Show/Hide a SECTION
// example: HideShowSection("General", "Customers", false);   // "false" = invisible
function HideShowSection(tabName, sectionName, visible) {
    try {
        Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(visible);
    }
    catch (err) { }
}

// Get GUID value of Lookup Field
// example GetGUIDofLookup("primarycontactid");
function GetGUIDofLookup(fieldname) {
    if (Xrm.Page.data.entity.attributes.get(fieldname).getValue() != null) {
        return Xrm.Page.data.entity.attributes.get(fieldname).getValue()[0].id;
    }
    else return null;
}

// Get Name value of Lookup Field
// example GetNameofLookup("primarycontactid");
function GetNameofLookup(fieldname) {
    if (Xrm.Page.data.entity.attributes.get(fieldname).getValue() != null) {
        return Xrm.Page.data.entity.attributes.get(fieldname).getValue()[0].name;
    }
    else return null;
}

// Get Value of Text Field
// example GetTextField("telephone1");
function GetTextField(fieldname) {
    return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}

// Get Integer value of Option Set Field
// example GetOptionsetInteger("address1_addresstypecode");
function GetOptionsetInteger(fieldname) {
    return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}

// Get Text value of Option Set Field
// example GetOptionsetText("address1_addresstypecode");
function GetOptionsetText(fieldname) {
    if (Xrm.Page.data.entity.attributes.get(fieldname).getValue() != null) {
        return Xrm.Page.data.entity.attributes.get(fieldname).getSelectedOption().text;
    }
    else return null;
}

// Get Database Value of a Bit Field
// example GetBitValue("telephone1");
function GetBitValue(fieldname) {
    return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}

// Get Database Value of a Date Field
// example GetDate("createdon");
function GetDate(fieldname) {
    return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}

// Sets the time portion of a date field (and sets the date to today if blank)
// Example: SetTime('new_date2', 8, 30);
function SetTime(attributeName, hour, minute) {
        var attribute = Xrm.Page.getAttribute(attributeName);
        if (attribute.getValue() == null) {
            attribute.setValue(new Date());
        }
        attribute.setValue(attribute.getValue().setHours(hour, minute, 0));
}

// Converts a CRM date value into dd-mm-yyyy
// Example:     
//              var ReviewDate = Xrm.Page.data.entity.attributes.get(new_date2).getValue(); 
//              alert(FormatDate(ReviewDate));
function FormatDate(fieldname) {
    var d = Xrm.Page.data.entity.attributes.get(fieldname).getValue();
    if (d != null) {
        var curr_date = d.getDate();
        var curr_month = d.getMonth();
        curr_month++;  // getMonth() considers Jan month 0, need to add 1
        var curr_year = d.getFullYear();
        return curr_date + "-" + curr_month + "-" + curr_year;
    }
    else return null;
}

// Compares a date to today's date
// Example:     
//              var ReviewDate = Xrm.Page.data.entity.attributes.get(new_date2).getValue(); 
//              alert(DateCompare(ReviewDate));
// Returns:  "future date", "date is in the past", or "date is today"
function DateCompare(dateinput) {
    var today = new Date();
    var today_date = today.getDate();
    var today_month = today.getMonth();
    today_month++;
    var today_year = today.getFullYear();

    var dateinput_date = dateinput.getDate();
    var dateinput_month = dateinput.getMonth();
    dateinput_month++;
    var dateinput_year = dateinput.getFullYear();

    if (dateinput != null && dateinput_year > today_year) {  // future year
        return "future date";
    }
    else if (dateinput != null && dateinput_year < today_year) {  // prior year
        return "date is in the past";
    }
    else if (dateinput != null && dateinput_year == today_year && dateinput_month > today_month) { //current year, future month
        return "future date";
    }
    else if (dateinput != null && dateinput_year == today_year && dateinput_month < today_month) { //current year, prior month
        return "date is in the past";
    }
    else if (dateinput != null && dateinput_year == today_year && dateinput_month == today_month && dateinput_date > today_date) { //current year, current month, future date
        return "future date";
    }
    else if (dateinput != null && dateinput_year == today_year && dateinput_month == today_month && dateinput_date < today_date) { //current year, current month, prior date
        return "date is in the past";
    }
    else if (dateinput != null && dateinput_year == today_year && dateinput_month == today_month && dateinput_date == today_date) { //same date
        return "date is today";
    }
    else {
        return null;
    }
}

/////////////////////////////////////////////////////////////////////////////
// Here's a few more courtesy of Paul Kreeck
/////////////////////////////////////////////////////////////////////////////
///Gets the Attributes by its Name.
 GetAttributeByName: function (attributeName)
 {
 return Xrm.Page.getAttribute(attributeName);
 } 

///Sets the attributes required level.
 ///
 ///Values: ‘none’, ‘required’, ‘recommended’
SetAttributeRequiredLevel: function (attributeName, level)
 {
 var attribute = GetAttributeByName(attributeName);
 if (attribute != null)
 {
 return attribute.setRequiredLevel(level);
 }
 return null;
 }
 
///Sets whether data from the attribute will be submitted when the record is saved.
 ///
 ///Values: ‘always’, ‘never’, ‘dirty’
SetAttributeSubmitMode: function (attributeName, submitMode)
 {
 var attribute = GetAttributeByName(attributeName);
 
if (attribute != null)
 {
 if (submitMode == “always” || submitMode == “never” || submitMode == “dirty”)
 {
attribute.setSubmitMode(submitMode);
 }
 else
 {
 throw “Invalid Submit Mode parameter”;
 }
 }
 }

 

Here are some examples where I utilise the above functions:

function AccountFormOnLoad() {
    var FormType = GetFormType();
    alert("Form type: " + FormType);

    alert(GetDate("createdon"));
    alert(FormatDate("createdon"));

    SetTime('new_date2', 8, 30);

    var FieldDate = GetDate("new_date2");
    alert(DateCompare(FieldDate));
    
    if(FormType == "update") {
        alert("hiding General tab");
        HideShowTab("general", false);

        alert("UNhiding General tab");
        HideShowTab("general", true);

        alert("hiding address section on general tab");
        HideShowSection("general", "address", false);

        alert("UNhiding address section on general tab");
        HideShowSection("general", "address", true);

        alert("getting GUID of primary contact");
        alert(GetGUIDofLookup("primarycontactid"));

        alert("getting name of primary contact");
        alert(GetNameofLookup("primarycontactid"));

        alert("getting value of telephone1");
        alert(GetTextField("telephone1"));

        alert("getting integer value of address type");
        alert(GetOptionsetInteger("address1_addresstypecode"));

        alert("getting text value of address type");
        alert(GetOptionsetText("address1_addresstypecode"));
    }
}

 

To reference the jscript library on a CRM form add the shared function library web resource to the Form and then add a form-specific jscript library web resource after that.  It is in this second jscript file that your form logic will sit and where you will make function calls against the shared functions library:

image

 

To reference the jscript library within a  custom Ribbon button’s definition either;

simply reference the library on the form:

image

or, you can reference the library within the ribbon definition:

        <CommandDefinitions>
          <CommandDefinition Id="ActivityFeeds.Form.account.MainTab.ExportData.Test.Command">
            <EnableRules />
            <DisplayRules />
            <Actions>
				<JavaScriptFunction Library="$WebResource:new_shared_functions.js" FunctionName="NaN" />
				<JavaScriptFunction Library="$WebResource:new_account_form_examples.js" FunctionName="AccountFormOnLoad" />
            </Actions>
          </CommandDefinition>
        </CommandDefinitions>

 

Note: you have to specify a Function name when you reference a jscript library so just use some dummy value like “NaN”

Advertisements

9 thoughts on “Reusable Jscript Library of Common Functions for CRM 2011

  1. Paul

    Here are 3 functions that we use a lot in the common javascript library where I work.

    ///Gets the Attributes by its Name.
    GetAttributeByName: function (attributeName)
    {
    return Xrm.Page.getAttribute(attributeName);
    }

    ///Sets the attributes required level.
    ///
    ///Values: ‘none’, ‘required’, ‘recommended’
    SetAttributeRequiredLevel: function (attributeName, level)
    {
    var attribute = GetAttributeByName(attributeName);
    if (attribute != null)
    {
    return attribute.setRequiredLevel(level);
    }
    return null;
    }

    ///Sets whether data from the attribute will be submitted when the record is saved.
    ///
    ///Values: ‘always’, ‘never’, ‘dirty’
    SetAttributeSubmitMode: function (attributeName, submitMode)
    {
    var attribute = GetAttributeByName(attributeName);

    if (attribute != null)
    {
    if (submitMode == “always” || submitMode == “never” || submitMode == “dirty”)
    {
    attribute.setSubmitMode(submitMode);
    }
    else
    {
    throw “Invalid Submit Mode parameter”;
    }
    }
    }

    Reply
  2. Pingback: Did you know, Dynamics CRM & xRM #9 « North 52

  3. Diego Santos

    Hello,

    I’m using these functions and they are very cool.

    The only question I have is about the SetAttributeSubmitMode function. When I let this function in my reusable script I can’t use any other function.

    I think has a scripting error, but I’m not able to identify what is.

    Do you have any information about that?

    Thanks

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s