Monday, May 7, 2012

Microsoft Dynamics CRM Javascript

        Below are the few useful properties, commands in Microsoft Dynamics CRM 2011/2013/2015 javascript.

Click on the item below to go through the description about that.



Get the string value of a Text field:

Returns the string value in the text field.
var fieldValue = Xrm.Page.data.entity.attributes.get("fieldName").getValue();

Set the string value of a Text field:

Set the string value for Text field.
Xrm.Page.data.entity.attributes.get("fieldName").setValue("New Value");

Retrieve Optionset Value/Text:

Returns the Value/Text of Optionset.
var optionSet = Xrm.Page.data.entity.attributes.get("optionSetName");
var optionSetText = optionSet.getText();
var optionSetValue = optionSet.getValue();

Get the label name of the field:

Get the Label of the specified field.
var fieldLabel = Xrm.Page.ui.controls.get("fieldName").getLabel();

Get the Lookup field value:

Get the value in given Lookup field.
var lookupValue=Xrm.Page.data.entity.attributes.get("lookupFieldName").getValue()[0].name;

Get the Lookup field ID:

Returns the ID of the record to which the lookup pointing to.
var lookupFieldId=Xrm.Page.data.entity.attributes.get("lookupFieldName").getValue()[0].id;

Get current entity name:

Returns the logical name of the current entity.
var entityName = Xrm.Page.data.entity.getEntityName();

Get Type Code of lookup:

Returns the code type with respect to an entity the lookup pointing to.
var objectTypeCode = Xrm.Page.getAttribute("lookupFieldName").getValue()[0].type;

Get reference entity name of lookup:

Returns the logical name of an entity the lookup pointing to.
var entityName = Xrm.Page.getAttribute("lookupField").getValue()[0].entityType;

Check for Dirty:

Returns a Boolean value indicating if any fields in the form have been modified.
var formChanged = Xrm.Page.data.entity.getIsDirty();

Set Lookup field:

Set the lookup field value.
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = newId;
lookupValue[0].name = newName;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute("lookupName").setValue(lookupValue);


Get event generated field value:

Returns the value of the field which generates the event.

function fieldValue_onchange(obj) {
  var attribute = obj.getEventSource();
  alert(attribute .getValue());
  alert(Xrm.Page.ui.getCurrentControl().getAttribute().getValue());
}

Get Organization Name:

Returns the unique name of logged-in organization.
var orgName = Xrm.Page.context.getOrgUniqueName();

Get Organization Language Code:

Returns organization's language code(LCID).
var orgLanguage = Xrm.Page.context.getUserLcid();

Get Server URL:

Returns the base server URL.
var orgName = Xrm.Page.context.getServerUrl();

Get GUID of current record:

Returns GUID for the record.
var guid = Xrm.Page.data.entity.getId();

Whether the field is disabled or not:

Returns a Boolean value indicating whether the control is disabled.
var fieldDisabled = Xrm.Page.ui.controls.get("fieldName").getDisabled();

Get form type:

Returns an integer value, indicates the form type: 1-Create, 2-Update
var FormType = Xrm.Page.ui.getFormType();

Get required fields in the form:

Returns required field names in the form:
Xrm.Page.data.entity.attributes.forEach( function (attribute, index) { 
 if (attribute.getRequiredLevel() == "required" ) {
  requiredFields += attribute.getName()+"\n";
 }
} );
   

Form Save:

Save the current form.
Xrm.Page.data.entity.save();

Form Save and Close:

Save and Close the form.
Xrm.Page.data.entity.save("saveandclose");

Set Focus:

Set focus on the control.
Xrm.Page.ui.controls.get("fieldName").setFocus();

Hide a field:

Hide the specified control.
Xrm.Page.ui.controls.get("fieldName").setVisible(false);

Disable and Enable a field:

Set field as Read only.
Xrm.Page.ui.controls.get("fieldName").setDisabled(true);

Set field as editable(Enable).
Xrm.Page.ui.controls.get("fieldName").setDisabled(false);

Close window:

Close the current opened window.
Xrm.Page.ui.close();

Open New window:

Open a new browser window with specified URL.
window.open("http://google.com", 
  'name', 
  'width=900,height=800,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,modal=yes');

Get Logged-in User ID:

Get the Logged-in User ID.
var userID = Xrm.Page.context.getUserId();

Attach Event to Control:

As CRM 2011 does not supports some events like onclick and ondblclick, we can attach a particular event to the control on form load.
function onload_method() {
    var control = document.getElementById("fieldName");
    if (control) {
        control.attachEvent("onclick", control_clicked);
        control.attachEvent("oncdbllick", control_dblclicked);
    }
}

function control_clicked(){
    //This function fires on field click
    //onclick logic goes here
}

function control_dblclicked(){
   //This function fires on field double click
   //ondblclick logic goes here
}

Set Description field in E-mail entity:

The Description field in E-mail entity is inside an IFrame and since its made for text decoration, text inside this field is enclosed with html tags. So, we can't directly set the field value. Below is the solution to set this field OnLoad of the form.

function onload_method() {
    var descriptionFrame = document.getElementById('descriptionIFrame');
    descriptionFrame.attachEvent('onreadystatechange', setValue);
}

function setValue () {
    var descriptionFrame = document.getElementById('descriptionIFrame'); 
    if (descriptionFrame.readyState != 'complete')
        return; 
    var htmlTag = "<:html> Value for Description field...<:/html>";
    var descriptionWindow = document.frames['descriptionIFrame'];
    descriptionWindow.document.body.innerHTML = htmlTag; 
}

Set IFrame URL:

To change the URL of IFrame and can also pass values in query string.

function setIFrameURL() {
    var IFrame = Xrm.Page.ui.controls.get("IFRAME_GoogleMap");
    var countryName = Xrm.Page.data.entity.attributes.get("address1_country").getValue();
    var newTarget= "http://maps.google.com/maps?q="+countryName;
    IFrame.setSrc(newTarget);
}

Get Schema Names of the Attributes:

To get the Schema Names of all the attributes in given entity.

function getSchemaNamesList(entityName) {
 var request = "<Request xsi:type='RetrieveEntityRequest'>" +
               "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>" +
               "<EntityItems>IncludeAttributes</EntityItems>" +
               "<LogicalName>" + entityName + "</LogicalName>" +
               "<IsCustomizable>1</IsCustomizable>" +
               "<RetrieveAsIfPublished>true</RetrieveAsIfPublished>" +
               "</Request>";

 var result = queryMetadataService(request);
 var schemaNames = result.selectNodes("//EntityMetadata/Attributes/Attribute/SchemaName");
        var namesList = "";
        for (var i = 0; i < schemaNames.length; i++) {
  namesList += schemaNames[i].text +",";
        }
        alert("Schema Names: "+namesList)
}

function queryMetadataService(request) {
 var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 xmlhttp.open("POST", '/mscrmservices/2007/MetadataService.asmx', false);
 xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlhttp.setRequestHeader("SOAPAction", 'http://schemas.microsoft.com/crm/2007/WebServices/Execute');

 var soapMessage = "<?xml version='1.0' encoding='utf-8'?>" +
 "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
 "xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
 "<soap:Header>" +
 "<CrmAuthenticationToken xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
 "<AuthenticationType xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>" + AUTHENTICATION_TYPE +
 "</AuthenticationType>" +
 "<OrganizationName xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>" + ORG_UNIQUE_NAME +
 "</OrganizationName>" +
 "<CallerId xmlns='http://schemas.microsoft.com/crm/2007/CoreTypes'>00000000-0000-0000-0000-000000000000"+
 "</CallerId>" +
 "</CrmAuthenticationToken>" +
 "</soap:Header>" +
 "<soap:Body><Execute xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" + request +
 "</Execute></soap:Body>" +
 "</soap:Envelope>";

 xmlhttp.send(soapMessage);
 return xmlhttp.responseXML;
}


Get Teams of User:

Get all the Teams User belongs to.

var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 " <query xmlns:q1=\"http://schemas.microsoft.com/crm/2006/Query\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>team</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +
 " <q1:Attribute>name</q1:Attribute>" +
 " </q1:Attributes>" +
 " </q1:ColumnSet>" +
 " <q1:Distinct>false</q1:Distinct>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkCriteria>" +
 " <q1:FilterOperator>And</q1:FilterOperator>" +
 " <q1:Conditions>" +
 " <q1:Condition>" +
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +
 " <q1:Operator>EqualUserId</q1:Operator>" +
 " </q1:Condition>" +
 " </q1:Conditions>" +
 " </q1:LinkCriteria>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </query>" +
 " </RetrieveMultiple>" +
 " </soap:Body>" +
 "</soap:Envelope>";

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/RetrieveMultiple");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);
var resultXml = xmlHttpRequest.responseXML;
//alert(resultXml.xml);

// Save all entity nodes in an array.
var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

var teamnames = new Array();
var teamids = new Array();

for (var i = 0; i < entityNodes.length; i++) {

 var entityNode = entityNodes[i];
 var teamidNode = entityNode.selectSingleNode("q1:teamid");
 var teamNode = entityNode.selectSingleNode("q1:name");
 var teamid = (teamidNode == null) ? null : teamidNode.text;
 var team = (teamNode == null) ? null : teamNode.text;

 teamnames[i] = team;
 teamids[i] = teamid;
}

Filtered Lookup:

Filter the lookup view based the value selected in another lookup.

You can get fetchXml value from your CRM system by following the steps below.
Open Dynamics CRM
à Click Advanced Find on ribbon à Select Target(say) in "Look for:" list à Select Owning Team(Team) in list below à Select Team under Owning Team(Team) à Leave Equals as default filter à In Enter Value lookup select one record à Click Download Fetch XML on ribbon. You will get fetch XML string and put that code in variable 'fetchXml' in below code and replace GUID from 'value' property in <condition> tag with dynamic variable, here it is _teamId.

function changeCustomView() {
//new_targetvalue is a lookup to new_target entity which we are filtering present on new_test entity form
//new_team is a lookup to Team on new_test entity form by which new_targetvalue lookup filtering
//new_targetid is a primary key attribute in new_target entity
//teamid is a lookup to Team on new_target entity form
 
   var entityName = "new_target"; //Filtering lookup entity name
   var _team = Xrm.Page.data.entity.attributes.get("new_team"); //Team on which filtering depends on
   var viewDisplayName = "CustomTargetFilteredView";

   // If new_team contains a value, then filter the new_targetvalue lookup based on new_team selected
   if (_team.getValue() != null) {
      var _teamId = _team.getValue()[0].id;
      var viewId = "{1DFB2B35-B07C-44D1-868D-258DEEAB88E2}"; // Unique viewID
      var fetchXml = "<?xml version='1.0'?>" +
        "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
        "<entity name='new_target'> <attribute name='new_targetid'/>" +
        "<attribute name='new_name'/>" +
        "<attribute name='createdon'/>" +
        "<order descending='false' attribute='new_name'/>" +
        "<link-entity name='team' alias='aa' to='owningteam' from='teamid'>" +
        "<filter type='and'>"+ 
        "<condition attribute='teamid' value='" + _teamId + "' uitype='team' operator='eq'/>" +
        "</filter> " +
        "</link-entity> " +
        "</entity> " +
        "</fetch>";

      var layoutXml = "<grid name='resultset' " +
        "object='1' " +
        "jump='new_name' " +
        "select='1' " +
        "icon='1' " +
        "preview='1'>" +
        "<row name='result' " +
        "id='new_targetid'>" +
        "<cell name='new_name'/>" +
        "width='100' />" +
        "</row>" +
        "</grid>";

      var lookup = Xrm.Page.ui.controls.get("new_targetvalue");
      lookup.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
      lookup.setDefaultView(viewId);
      document.getElementById("new_targetvalue").setAttribute("disableViewPicker", "1");   
   }
}

Trigger the Workflow:

Trigger the workflow(process) using javascript.

Steps to be followed to implement javascript to trigger workflow:
à Download JQuery here.
à Crate one JScript webresource and upload this downloaded JQuery.
à Create one JScript webresource for the below code and register to the CRM form where you want to run this script.


function TriggerWorkflow() {

 // Get the Workflow ID
 var workflowId = GetProcessId();
 if (workflowId[0].results.length > 0) {
  var xml = "" +
  "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" +
  GenerateAuthenticationHeader() +
  "<soap:Body>" +
  "<Execute xmlns=\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
  "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
  "<EntityId>" + Xrm.Page.data.entity.getId() + "</EntityId>" +
  "<WorkflowId>" + workflowId[0].results[0].WorkflowId + "</WorkflowId>" +
  "</Request>" +
  "</Execute>" +
  "  </soap:Body>" +
  "</soap:Envelope>" +
  "";
  var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", true);
  xmlHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Execute");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);
 }
}

function GetProcessId() {
 // Pass the workflow name manually to get the Id of the workflow
 var processName = "My Workflow Name";

 // Get the server URL
 var serverUrl = Xrm.Page.context.getServerUrl();
 var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/WorkflowSet?$select=WorkflowId&$filter=Name eq '" + processName + "' and ActiveWorkflowId/Id ne null";
 var jSonArray = new Array();

 jQuery.ajax({
  type: "GET",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: oDataUri,
  async: false,
  beforeSend: function (XMLHttpRequest) {
   XMLHttpRequest.setRequestHeader("Accept", "application/json");
  },
  success: function (data, textStatus, XmlHttpRequest) {
   if (data && data.d != null) {
    jSonArray.push(data.d);
   }
  },
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   alert("Error :  has occured during retrieval of the workflowId");
  }
 });
 return jSonArray;
}

Set field value using query string parameter:

When we click on some ribbon button or on some event, the new Account window will open with setting the Account Name field by passing that value in query string parameter.

function openAccountWindow(value) {
 var windowProperties = 'width=900,height=800,toolbar=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,modal=yes';
 var encodedParam = encodeURIComponent("name = New Test Account");
 window.open("http://serverName/OrgName/main.aspx?etc=1&extraqs="+ encodedParam +"&pagetype=entityrecord",
'accountWindow',
windowProperties);
}

Change the Status and Status Reason of the record:

We can not change the Status and Status Reason of the record directly or by REST call. We can do so using SOAP request. And Status and Status Reason should be matched to perform this action.
function SetState(entityName, entityId, statusReason, state) {
   var serverURL = Xrm.Page.context.getServerUrl();
   var setStateRequest = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">' +
    '<s:Body>' +
       '<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' +
          '<request i:type="a:UpdateRequest" xmlns:a="http://schemas.microsoft.com/xrm/2011/Contracts">' +
             '<a:Parameters xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>EntityMoniker</b:key>' +
                   '<b:value i:type="a:EntityReference">' +
                      '<a:Id>' + entityId + '</a:Id>' +
                      '<a:LogicalName>' + entityName + '</a:LogicalName>' +
                      '<a:Name i:nil="true"></a:Name>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>State</b:key>' +
                   '<b:value i:type="a:OptionSetValue">' +
                      '<a:Value>' + state + '</a:Value>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>Status</b:key>' +
                   '<b:value i:type="a:OptionSetValue">' +
                      '<a:Value>' + statusReason + '</a:Value>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
             '</a:Parameters>' +
          '<a:RequestId i:nil="true"></a:RequestId>' +
          '<a:RequestName>SetState</a:RequestName>' +
          '</request>' +
       '</Execute>' +
    '</s:Body>' +
   '</s:Envelope>';

   var req = new XMLHttpRequest();
   req.open("POST", getServerUrlForSetState(), false);
   
   req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
   req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
   
   req.send(setStateRequest);
   
   if (req.status != 200) {
      getError(req.responseXML);
   }
}

Get the current form name:

Returns the name of the selected form in the record.
Xrm.Page.ui.formSelector.getCurrentItem().getLabel();

Form Switching:

To switch to the desired form.
var allForms = Xrm.ui.formSelector.getItems().getAll();
var currenFormName = Xrm.ui.formSelector.getCurrentItem().getLabel();    
var desiredFormName = isSalesUser ? "Sales" : "Information";

if (currenFormName != desiredFormName) {
for (var i = 0; i < allForms.length; i++) { if (allForms[i].getLabel() == desiredFormName)
allForms[i].navigate(); } }

Refresh the form:

Refresh the current form.
window.parent.location.reload();

Hide left navigation item:

Hide the left navigation item based on some condition.
var items = Xrm.Page.ui.navigation.items.get();

for (var i in items) {
   var item = items[i];

  if (item.getLabel() == "Accounts") {
    item.setVisible(false);
   }
}

Set field requirement level in run time:

Set the field requirement level to either Required or Recommended or NoConstraint in run time.
// No Constraint 
Xrm.Page.getAttribute("field_name").setRequiredLevel("none");   

// Business Required 
Xrm.Page.getAttribute("field_name").setRequiredLevel("required");   

// Business Recommended 
Xrm.Page.getAttribute("field_name").setRequiredLevel("recommended");

Get the CRM Organization URL:

Retrieve the CRM Organization URL with respect to the current domain name.
For example, if you are browsing the CRM instance with IP, then the return value would be like this: http(s)://<IP>/<OrgName>
If you are browsing with domain name, it would be like this: http(s)://<DomainName>/<OrgName>

function GetServerUrlRegExp(location) {
    var urlReg = new RegExp(/http[s]?:\/\/[0-9.:]+\/[^\/]+/);
    var ServerUrl = Xrm.Page.context.getServerUrl();
    if (window.location.href.match(urlReg) != null) {
        ServerUrl = window.location.href.match(urlReg).toString();
    }
    if (ServerUrl.match(/\/$/)) {
        ServerUrl = ServerUrl.substring(0, ServerUrl.length - 1);
    }
    return ServerUrl;
}

Set Form Notification:

We can show the notification message on CRM form using javascript. It works only in CRM 2013 and later versions.
There are three types of notification messages can be shown:
1. Information
2. Warning
3. Error

The syntax for setting the notification: Xrm.Page.ui.setFormNotification(<message>, <level>, <uniqueId>);
The syntax for clearing the notification: Xrm.Page.ui.clearFormNotification(<uniqueId>);

Below is the image of the CRM record with all three form notifications:

function SetNotification() {
    Xrm.Page.ui.setFormNotification('Error! Test error message.', 'ERROR', 'Error1');
    Xrm.Page.ui.setFormNotification('Warning! Test warning message', 'WARNING', 'Warning1');
    Xrm.Page.ui.setFormNotification('Information: Test information', 'INFORMATION', 'Information1');
}

function ClearNotification() {
    Xrm.Page.ui.clearFormNotification('Warning1');
}

Set Field Notification:

We can show the notification message for the particular field using javascript. It works only in CRM 2013 and later versions.
After setting the field notification, form save will not be succeeded until the field notification get cleared.

The syntax for setting the field notification: Xrm.Page.getControl("<fieldName>").setNotification(<message>);
The syntax for clearing the field notification: Xrm.Page.getControl("<fieldName>").clearNotification();


Below is the image of the field with notification set:

function SetFieldNotification() {
    Xrm.Page.getControl("fax").setNotification("Please enter valid Fax.");
}

function ClearFieldNotification() {
    Xrm.Page.getControl("fax").clearNotification();
}


Refresh Subgrid:

To refresh the subgrid on the form
Xrm.Page.ui.controls.get("subgridName").refresh();

Prevent Form Save:

Sometimes we need to prevent the form saving based on some validation. In such scenarios, we can achieve this by below script.
exeContext is a Execution Context parameter passed from the form while registering the On Save event. If this function returns false, form save will be aborted. IsValidForSave() is a sample function used in this example for on save validations. For more information, visit MSDN blog here.

function OnSave(exeContext) {

    if (!IsValidForSave()) {
        alert("Form validation is not met."); // Any user friendly message here
        exeContext.getEventArgs().preventDefault();
    }
}

23 comments:

  1. Hi, Great list. I have tried to find out how to set Status reason (statuscode) via JScript. Does anyone have a solution?

    ReplyDelete
    Replies
    1. Thanks.. You can use SOAP call to set State/Status(Status Reason) of the record. Let me post that code over here.. :)

      Delete
    2. Here is the code to change the status of the record: http://charanmandya.blogspot.in/2012/05/microsoft-dynamics-crm-2011-javascript.html#recordStatusChange

      Delete
  2. Hi Charan,
    This one is a good article. I need one help in the following context.
    In javascript, I know the current object name & type code value. How to get current entity's default view name? E.g for "account" entity, I want to get "AccontSet".

    Thanks,
    Ketan

    ReplyDelete
    Replies
    1. Hi Ketan,
      We can't get the ODATA name of an entity programmatically. We actually hard code the ODATA name based on our context. For all custom entities you can append "Set" to the entity name. But in case of system entities we can't do that. I will post you back if I get any ways to do this..

      Regards,
      Charan

      Delete
    2. This comment has been removed by the author.

      Delete
    3. Hi Charan,
      Thxs for the reply. But we can not always set OData name as entityname + "Set".
      Because in javascript, I am getting the entity name dynamically by using Xrm.Page.data.entity.getEntityName(); and that will be always be in lower case.
      I can set the first character of the entity name to Upper case as "Account" + "Set" = "AccountSet".
      But think a case I have entity name as OrderItem. In javascript i will get entity name as "orderitem". How will know to set the o & i to upper case?

      Regards,
      Ketan

      Delete
    4. That's what I told we can't get the ODATA name programmatically. My suggestion is, you just define a switch statement which will give you a ODATA name by checking the hard coded entity name as in below sample code.
      Ex:
      switch(entityName) {
      case "orderitem":
      entityODATAName = "OrderItem";
      break;
      case "account":
      entityODATAName = "Account";
      break;
      //......
      //......
      defeult:
      break;
      }

      Delete
    5. Hi Charan,
      I have a Xml file where user can specify the default view name & it is working fine. The reason behind getting it dynamically is to reduce the user's work.

      Thanks. :)

      Delete
  3. Hi,

    Get Schema Names of the Attributes: is not working for me.. Can you help me out.\

    Regards,
    Pavan.G

    ReplyDelete
    Replies
    1. Hi Pavan,
      Thanks for your valuable feedback. This javascript code has been updated now. Please check it out and let me know if any issues.

      Delete
  4. Hi Charan,
    I need your help for different issue. I want to show a view of an entity from javascript. I am using the following url
    window.parent.Xrm.Page.context.getServerUrl() + /userdefined/areas.aspx?security=852023&oid= + &oType=

    The issue here is it is not showing the view "All" by default. For example, for opportunity it will show "Lost Opportunity" view. What changes I can do to my url to show "All" view for all the entities?

    Thanks,
    Ketan

    ReplyDelete
    Replies
    1. Go to the specific entity through site map and select the required view. Then click on 'Copy a Link' button in the ribbon, select 'Of Current View'. Then paste or make use of that copied ULR in your javascript.

      Delete
  5. I'm very interested in the status reason changes via SOAP. In the code you posted, do I need to change anything to fit my status and status reason? And I'll have a custom ribbon button which will call the function SetState...any help or info is appreciated! Great list btw.

    ReplyDelete
    Replies
    1. You can directly call SetState method with no changes on ribbon button click (with matching State and Status Reason).

      Delete
  6. Hi,

    I need to know how to place users from a team in a text. I want to pick a team and automaticly populate a multitext box with the members of that team.

    ReplyDelete
    Replies
    1. What is the triggering point or event you want to capture the Team members' name?

      Delete
    2. A lookup will trigger it.

      Delete
    3. - First Download XrmServiceToolkit and create a webresource for it.
      - Create a new multiline text field in Team entity to capture all the team members name with comma delimited. Here it is new_teammembers
      - Register below code on change of the lookup(triggering event)

      function getMembers() {
      var teamId = Xrm.Page.data.entity.getId();
      var fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>"+
      "<entity name='systemuser'>"+
      "<attribute name='fullname' />"+
      "<attribute name='systemuserid' />"+
      "<order attribute='fullname' descending='false' />"+
      "<link-entity name='teammembership' from='systemuserid' to='systemuserid' visible='false' intersect='true'>"+
      "<link-entity name='team' from='teamid' to='teamid' alias='ab'>"+
      "<filter type='and'>"+
      "<condition attribute='teamid' operator='eq' uitype='team' value='" + teamId + "' />" +
      "</filter>"+
      "</link-entity>"+
      "</link-entity>"+
      "</entity>"+
      "</fetch>";
      var teamMembers = XrmServiceToolkit.Soap.Fetch(fetchXML);

      if (teamMembers.length > 0) {
      var membersName = "";
      var finalMembers = "";
      for (var i = 0; i < teamMembers.length; i++) {
      membersName = teamMembers[i].attributes.fullname.value + ",";
      }

      if (membersName.substr(-1) == ",")
      finalMembers = membersName.substring(0, membersName.length - 1);
      Xrm.Page.data.entity.attributes.get("new_teammembers").setValue(finalMembers);
      }
      }

      Delete
  7. Hi Charan,
    Please let me know how to disable HTML webresource control using javascirpt.

    ReplyDelete
    Replies
    1. Hi,
      We cannot disable the HTML WebResource directly. But there are two alternative ways of doing it.

      1. Run the javascript inside html webresource code and disable the html controls based on any fields on CRM form (Use parent.Xrm.Page.getAttribute("fieldName").getValue()).

      2. Access the html controls from CRM form onload javascript and disable each of them as in the below code.

      function DisableHTMLWebresouceControl()
      {

      var webRefCtrl = Xrm.Page.getControl('WebResource_Test').getObject();
      var htmlDoc=webRefCtrl.contentDocument;
      var htmlControls= htmlDoc.getElementsByTagName('input'); //Get all the controls to be disabled

      if(htmlControls[0]==null)
      {
      setTimeout(DisableHTMLWebresouceControl,1000)
      return;
      }

      for (var i = 0; i < htmlControls.length; i++){
      htmlControls [i].disabled = true;
      }
      }

      Delete