RSS

Jscript Reference for Microsoft CRM 2011

16 Apr

Most common tasks javascript in CRM 2011

Index:

Get GUID value from lookup

var primaryContactGUID = Xrm.Page.getAttribute("primarycontactid").getValue()[0].id;

Get Text value from lookup field

var primaryContactName = Xrm.Page.getAttribute("primarycontactid").getValue()[0].name;

Set value in 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 LookupControlItem(id, entityType, name);
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}

Get value from text field

var MainPhone = Xrm.Page.getAttribute("telephone1").getValue();

Set value in text field

var Name = Xrm.Page.getAttribute("name");
Name.setValue("mytext");

Split Full Name into First and Last Names

function PopulateNameFields() {
    var ContactName = Xrm.Page.getAttribute("customerid").getValue()[0].name;
    var mySplitResult = ContactName.split(" ");
    Xrm.Page.getAttribute("firstname").setValue(mySplitResult[0]);
    Xrm.Page.getAttribute("lastname").setValue(mySplitResult[1]);
}

Get the numeric value from Option Set

var AddressType = Xrm.Page.getAttribute("address1_addresstypecode").getValue();

Get the text value from Option Set field

var AddressType = Xrm.Page.getAttribute("address1_addresstypecode").getSelectedOption().text;

Set value in Option Set

var AddressType = Xrm.Page.getAttribute("gender").setValue(1);

Remove value from Optionset

Xrm.Page.getControl("fieldName").removeOption(Option_Value);

Get value from Bit field

Xrm.Page.getAttribute(fieldname).getValue();

Get value fro Date field

return Xrm.Page.getAttribute("createdon").getValue();

Get the day, month and year parts from a Date field

function FormatDate(fieldname) {
    var d = Xrm.Page.getAttribute(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;
}

Set date into Date field

//Today's date
Xrm.Page.getAttribute("new_date1").setValue(new Date());

//Next week
Xrm.Page.getAttribute("new_date2").setValue(new Date(today.setDate(today.getDate() + 7)));

//Set the Time portion of a Date Field
Xrm.Page.getAttribute(attributeName).setValue(new Date().setHours(8, 30, 0)) //today at 8:30

Change Requirement Level to fields

Xrm.Page.getAttribute("description").setRequiredLevel("required");
Xrm.Page.getAttribute("description").setRequiredLevel("none");

Disable a field

Xrm.Page.getControl("ownerid").setDisabled(true);

Force Submit the Save of a Disabled Field

// Save the Disabled Field
Xrm.Page.getAttribute("new_date1").setSubmitMode("always");

Show/Hide a field

Xrm.Page.getControl("name").setVisible(false);

Show/Hide a field based on a Bit field

var ExistingCustomerBit = Xrm.Page.getAttribute("new_existingcustomer").getValue();
if (ExistingCustomerBit == false)
   Xrm.Page.getControl("customerid").setVisible(false);
else
   Xrm.Page.getControl("customerid").setVisible(true);

Show/Hide a nav item

Xrm.Page.ui.navigation.items.get("navContacts").setVisible(false);

Show/Hide a Section

Xrm.Page.ui.tabs.get("tab0").sections.get("general").setVisible(false);

Show/Hide a Tab

Xrm.Page.ui.tabs.get("tab0").setVisible(visible);

Determine which fields on the form are dirty

var attributes = Xrm.Page.data.entity.attributes.get()
for (var i in attributes)
{
   var attribute = attributes[i];
   if (attribute.getIsDirty())
      alert("attribute dirty: " + attribute.getName());

}

Refresh a Sub-Grid

Xrm.Page.getControl("target_grid").Refresh();

Add OnChange to field

Xrm.Page.getAttribute("target_field").addOnChange(MyFunction);

Fire OnChange on field

Xrm.Page.getAttribute("target_field").fireOnChange();

Remove OnChange to field

Xrm.Page.getAttribute("target_field").removeOnChange(MyFunction);

Change the default entity in the lookup window of a Customer or Regarding field
Note: I am setting the customerid field’s lookup window to offer Contacts (entityid 2) by default (rather than Accounts). I have also hardcoded the GUID of the default view I wish displayed in the lookup window.

document.getElementById("customerid").setAttribute("defaulttype", "2");
var ViewGUID= "A2D479C5-53E3-4C69-ADDD-802327E67A0D";
Xrm.Page.getControl("customerid").setDefaultView(ViewGUID);

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

var FormType = Xrm.Page.ui.getFormType();

Get the GUID of the current record

var GUIDvalue = Xrm.Page.data.entity.getId();

Get the GUID of the current user

var UserGUID = Xrm.Page.context.getUserId();

Get Security Roles from the current user

Xrm.Page.context.getUserRoles()

Determine the CRM server URL

var serverUrl = Xrm.Page.context.getServerUrl();

Save the form

Xrm.Page.data.entity.save();

Save and close the form

Xrm.Page.data.entity.save("saveandclose");

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

Xrm.Page.ui.close();

Pop existing lookup window from field

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

Pop an existing CRM record

//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);

Pop the Create form of a CRM record type

//Collect values from the existing CRM form that you want to default onto the new record
var parententity = Xrm.Page.getAttribute("from").getValue();

//Set the parameter values
var extraqs = "&title=New Case";
extraqs += "&customerid=" + parententity.id;
extraqs += "&customeridname=" + parententity.name;
//if you need to send parameters from personal entities this parameter send it without type
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);

Pop Dialog from a ribbon button

var DialogGUID = "128CEEDC-2763-4FA9-AB89-35BBB7D5517D";
var serverUrl = "https://avanademarchdemo.crm5.dynamics.com/";
serverUrl = serverUrl + "cs/dialog/rundialog.aspx?DialogId=" + "{" + DialogGUID + "}" + "&EntityName=lead&ObjectId=" + sLeadID;
PopupCenter(serverUrl, "mywindow", 400, 400);
window.location.reload(true);

function PopupCenter(pageURL, title, w, h) {
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);
    var targetWin = window.showModalDialog(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}

Original Post:

http://gtcrm.wordpress.com/2011/03/16/jscript-reference-for-microsoft-crm-2011/

 
7 Comments

Posted by on April 16, 2012 in CRM 2011, Javascript

 

Tags: , ,

7 responses to “Jscript Reference for Microsoft CRM 2011

  1. Gareth Tucker

    April 16, 2012 at 3:02 pm

    Please do not copy my blog content in full, can you please just include a link.

     
    • Isaac Sultan

      April 17, 2012 at 6:45 am

      Sorry man, I will change it.

       
      • Gareth Tucker

        May 17, 2012 at 5:20 am

        Can you please remove this post. This is all my original content.

         
  2. sandeep

    June 26, 2012 at 10:12 pm

    how to move the Xrm object from one form to another form by using javascript for acessing feild in child form from parent form javascript

     
  3. C30Boy

    October 17, 2012 at 10:14 am

    Great post!!
    What is the difference between get a fiel value with crmForm.all.myfield.value and Xrm.Page.data.entity.attributes.get(“myfield”).getValue() ?

     
    • Isaac Sultan

      October 30, 2012 at 7:22 am

      crmForm.all.myfield is the older way used in crm4. Xrm.Page.data.entity.attributes.get(“myfield”).getValue() is the new implementation for crm2011. But crmForm.all.myfield is still working. If you have installed the JScript IntelliSense for Form Script Libraries you can use full intellisense in visual studio 😉

       
  4. Suresh Kumar VC

    June 13, 2013 at 12:23 pm

    Hi Gareth,
    Thanks for your post. All the best.
    Suresh Kumar VC

     

Leave a comment