Showing posts with label Java Script. Show all posts
Showing posts with label Java Script. Show all posts

Tuesday, December 13, 2011

Retrieve OptionSet Text in CRM 2011 using C#

Hi All, In CRM 2011 we have two types of Option Sets. one will be normal Option set Filed and the other one will be Global Option Set. Lets see how to retrieve Option Set Text for both types.

Retrieve Normal(Local) Option Set Text


// Get Normal option set Text
string optionsetText = entity.FormattedValues["new_optionset"];

or

string optionsetText = entity.GetFormattedAttributeValue("new_optionset");

Retrieve Global Option Set Text

int OptionsetValue = ((Microsoft.Xrm.Sdk.OptionSetValue)entity["new_localoptionset"]).Value;
string GlobaloptionsetText= GetOptionsetText(entity, service, "new_globaloptionset", OptionsetValue );



  // Retrieves Global Option set Selected Text
        // Parameters: 1. Entity Name   2. Service  3. Global Option Set Name   4. optionset selected value
        public string GetOptionsetText(Entity entity, IOrganizationService service,string  optionsetName,int optionsetValue)
        {
            string optionsetSelectedText = string.Empty;
            try
            {


                RetrieveOptionSetRequest retrieveOptionSetRequest =
                    new RetrieveOptionSetRequest
                    {
                        Name = optionsetName
                    };

                // Execute the request.
                RetrieveOptionSetResponse retrieveOptionSetResponse =
                    (RetrieveOptionSetResponse)service.Execute(retrieveOptionSetRequest);

                // Access the retrieved OptionSetMetadata.
                OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

                // Get the current options list for the retrieved attribute.
                OptionMetadata[] optionList = retrievedOptionSetMetadata.Options.ToArray();
                foreach (OptionMetadata optionMetadata in optionList)
                {
                    if (optionMetadata.Value == optionsetValue)
                    {
                        optionsetSelectedText = optionMetadata.Label.UserLocalizedLabel.Label.ToString();
break;
                    }
                }
            }
            catch (Exception)
            {


                throw;
            }
            return optionsetSelectedText;
        }

===========================================


// Gets Local/Normal optionset Lable using Metadata Service
         public static string GetoptionsetText(string entityName, string attributeName, int optionSetValue, IOrganizationService service)
         {
             string AttributeName = attributeName;
             string EntityLogicalName = entityName;
             RetrieveEntityRequest retrieveDetails = new RetrieveEntityRequest
             {
                 EntityFilters = EntityFilters.All,
                 LogicalName = EntityLogicalName
             };
             RetrieveEntityResponse retrieveEntityResponseObj = (RetrieveEntityResponse)service.Execute(retrieveDetails);
             Microsoft.Xrm.Sdk.Metadata.EntityMetadata metadata = retrieveEntityResponseObj.EntityMetadata;
             Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata picklistMetadata = metadata.Attributes.FirstOrDefault(attribute => String.Equals

(attribute.LogicalName, attributeName, StringComparison.OrdinalIgnoreCase)) as Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata;
             Microsoft.Xrm.Sdk.Metadata.OptionSetMetadata options = picklistMetadata.OptionSet;
             IList<OptionMetadata> OptionsList = (from o in options.Options
                                                     where o.Value.Value == optionSetValue
                                                     select o).ToList();
             string optionsetLabel = (OptionsList.First()).Label.UserLocalizedLabel.Label;
             return optionsetLabel;
         }




happy coding :) 

Wednesday, November 30, 2011

Phone Number Validation using java script in CRM 2011

Hi All, Here is the logic to format Phone Number field into '(xxx) xxx-xxxx' format. It only allows user to enter only numeric characters, up to 10 char's.

function Bindevents() {
   // Binding the events to crm field, which needs to be validated
    crmForm.all.telephone1.onkeypress = isvalidPhone;
    crmForm.all.telephone1.onblur = function () { formatPhoneNumber("telephone1"); };
}




// Allows to enter only Numbers & upto 10 char's
function isvalidPhone() {
 
    var charCode = event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;


    var phnum = event.srcElement.value.replace(/[^0-9]/g, "");
    if (phnum.length >= 10)
         return false;


    return true;
}


// Formats Phone Number to '(xxx) xxx-xxxx' format
function formatPhoneNumber(phnum) {
 
    var phone = Xrm.Page.getAttribute(phnum).getValue();
    var tmp = phone.replace(/[^0-9]/g, "");
    phoneRegex = /^\d{10}$/;


    if (!tmp.match(phoneRegex)) {
            event.returnValue = false;        
            Xrm.Page.data.entity.attributes.get(phnum).controls.get(0).setFocus();
         
        }
        else {
            var formtedphn = "(" + tmp.substr(0, 3) + ") " + tmp.substr(3, 3) + "-" + tmp.substr(6, 4);
            Xrm.Page.getAttribute(phnum).setValue(formtedphn);
        }  
}

Hope it helps!!!!

Tuesday, September 20, 2011

Update Optionset, lookup data using OData service, JSON

Here I am going to update Optionset and Lookup fields using Odata Service in CRM 2011. In the SDK sample you will find only to update Text fields. After spending some time on Odata service, i got the solution to update Option set and Lookup fields.

        Here i am going to update Account information using Odata service.

function updateOptionset() {
    // Gets the record Guid
    var id = Xrm.Page.data.entity.getId();    
    var changes = {
      // Text field
        Telephone1: "123456789",
     // Option set field    
       Address1_AddressTypeCode: {  Value: 3 },
      // Lookup field
       ParentAccountId: {         
           Id: "8F8338A9-9AB2-E011-9E6D-000C29B0167C", // Guid of the parent account
           LogicalName: "account"
       }
    };
  
    //updateRecord exists in JQueryRESTDataOperationFunctions.js
    updateRecord(id, changes, "AccountSet", updateAccountCompleted, null);
}

function updateRecord(id, entityObject, odataSetName, successCallback, errorCallback) {
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();

    //The XRM OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //id is required
    if (!id) {
        alert("record id is required.");
        return;
    }
    //odataSetName is required, i.e. "AccountSet"
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }

    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(entityObject);

    //Asynchronous AJAX function to Update a CRM record using OData
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        data: jsonEntity,
        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.             
            XMLHttpRequest.setRequestHeader("Accept", "application/json");

            //Specify the HTTP method MERGE to update just the changes you are submitting.             
            XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            //The MERGE does not return any data at all, so we'll add the id 
            //onto the data object so it can be leveraged in a Callback. When data 
            //is used in the callback function, the field will be named generically, "id"
            data = new Object();
            data.id = id;
            if (successCallback) {
                successCallback(data, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}


function errorHandler(xmlHttpRequest, textStatus, errorThrow) {  
    alert("Error : " + textStatus + ": " + xmlHttpRequest.statusText);
}

//Called upon successful Account update.
function updateAccountCompleted(data, textStatus, XmlHttpRequest) {   
    //Get back the Account JSON object
    var account = data;
    alert("Account updated: id = " + account.id);
}

Hope it helps!!!!

Tuesday, July 12, 2011

Maximizing CRM Form using javascript in CRM 2011

Hi All, Maximizing CRM Form script has been changed slightly in CRM 2011. use the following code to maximize CRM Forms using javascript

window.top.moveTo(0,0);
window.top.resizeTo(screen.width, screen.height);

Monday, July 11, 2011

Retrieving optionset Lable data using Metadata service in CRM 2011

Hi All, Using OData service we are not able to get the option set selected text of an entity. Its providing only value field, but not the text. so I have used Metadata service to retrieve Option set text for the selected value.
 Here I am retrieving State option set text from country entity and assigning that option text to text field.

function RetrieveOptionsetLabel()
{
     // Entity schema name 
     var entityLogicalName = "new_country";
     // option set schema name
     var RetrieveAttributeName = "new_state";
     // Target Field schema name to which optionset text needs to be assigned
     var AssignAttributeName = "new_state";

// Option set value for which label needs to be retrieved
        var stateValue = optionValue;
     
        // Calling Metadata service to get Optionset Label
        SDK.MetaData.RetrieveEntityAsync(SDK.MetaData.EntityFilters.Attributes, entityLogicalName, null, false, function (entityMetadata) { successRetrieveEntity(entityLogicalName, entityMetadata, RetrieveAttributeName, stateValue, AssignAttributeName); }, errorDisplay);

}

// Called upon successful metadata retrieval of the entity
function successRetrieveEntity(logicalName, entityMetadata, RetrieveAttributeName, OptionValue, AssignAttributeName) {
    ///<summary>
    /// Retrieves attributes for the entity 
    ///</summary>

    var success = false;
    for (var i = 0; i < entityMetadata.Attributes.length; i++) {
        var AttributeMetadata = entityMetadata.Attributes[i];
        if (success) break;
        if (AttributeMetadata.SchemaName.toLowerCase() == RetrieveAttributeName.toLowerCase()) {
            for (var o = 0; o < AttributeMetadata.OptionSet.Options.length; o++) {
                var option = AttributeMetadata.OptionSet.Options[o];
                if (option.OptionMetadata.Value == OptionValue) {
                    Xrm.Page.getAttribute(AssignAttributeName).setValue(option.OptionMetadata.Label.UserLocalizedLabel.Label);
                    success = true;
                    break;
                }
            }
        }

    }


}


 function errorDisplay(XmlHttpRequest, textStatus, errorThrown) {

     alert(errorThrown);
 }

Note: Dont forget to add "sdk.metadata.js" resource to form before calling these methods. you can find this library in sdk "sdk\samplecode\js\soapforjscript\soapforjscript\scripts".



Saturday, July 9, 2011

Custom Lookup Filter Lookup in CRM 2011 using javascript

Hi All, Some times we will get requirement to set filterlookup using java script. CRM 2011 provides OOB Filter Lookups, but it has some limitations. For Activities they did not provided filter lookup facility. Recently i came accross Letter activity to set filter lookup. Here is the way to set filter lookup  using java script.

Here I am going to set contact lookup with selected account as parent.


function customfilterlookup(AccoundID)
{
//Show Contacts which has selected parent Account
    //build fetchxml, use Advance Find to get Fetchxml
    var viewId = "{a76b2c46-c28e-4e5e-9ddf-951b71202c9d}"; //view Guid
    var entityName = "contact"; // Entity to be filtered
    var viewDisplayName = "Active Contacts"; // Custom name for the lookup window.
    var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                  "<entity name='contact'>" +
                    "<attribute name='fullname' />" +
                    "<attribute name='parentcustomerid' />" +                  
                    "<attribute name='emailaddress1' />" +
                    "<attribute name='address1_telephone2' />" +
                    "<attribute name='new_city' />" +
                    "<attribute name='address1_stateorprovince' />" +
                    "<attribute name='address1_telephone1' />" +
                    "<attribute name='ownerid' />" +
                    "<attribute name='contactid' />" +
                    "<order attribute='fullname' descending='false' />" +
                    "<filter type='and'>" +
                      "<condition attribute='parentcustomerid' operator='eq'  uitype='account' value='"+AccoundID+"' />" +
                      "<condition attribute='statecode' operator='eq' value='0' />" +
                    "</filter>" +
                  "</entity>" +
                "</fetch>";
    // Build Grid Layout. building a custom view for the Lookup
    //building grid layout with the columns which needs to be displayed in the lookup view
    var layoutXml = "<grid name='resultset' " +
                    "object='1' " +
                    "jump='name' " +
                    "select='1' " +
                    "icon='1' " +
                    "preview='1'>" +
                    "<row name='result' " +
                    "id='contactid'>" + // Id/key attribute of the entity to be filtered
                    "<cell name='fullname' " +
                    "width='250' />" +
                    "<cell name='new_city' " +
                    "width='70' />" +
                    "<cell name='address1_telephone1' " +
                    "width='100' />" +
                    "</row>" +
                    "</grid>";
    // add new view to the lookup
    Xrm.Page.getControl("contact").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
}

keep smiling.. :)

Wednesday, July 6, 2011

Retrieving Customer Address from parent Account on Contact Form using ODATA

Hi All, Here I am going to retrieve Parent Account Address on contact form using Odata in crm 2011

// Populate Customer Address from Parent Account
function PopulateCustomerAddress(ParentAccount) {

    if (ParentAccount != null) {
        var AccountId = ParentAccount.getValue()[0].id;

        // Pass odataQuery
        var odataQuery = "AccountSet?$select=Address1_Fax,Address1_Line1,Address1_Line2,Address1_StateOrProvince,Address1_Telephone1,Address1_Telephone2,new_regionid&$filter=AccountId eq guid'" + AccountId + "'";

        retrieveRecord(odataQuery, retrieveCustomerAddressCompleted, null);
    }
 
}


// Retrieve Record Details based on the odataQuery
function retrieveRecord(odataQuery, successCallback, errorCallback) {
    var context = Xrm.Page.context;
    //Retrieve the server url,
    serverUrl = context.getServerUrl();
    //The XRM OData end-point
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //odataQuery is required, i.e. "AccountSet/guid('')"
    if (!odataQuery) {
        alert("odataQuery is required.");
        return;
    }

    //Asynchronous AJAX function to Retrieve a CRM record using OData
    $.ajax({
        type: "GET",
        async: false,      
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + "/" + odataQuery,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.             
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            if (successCallback) {
                successCallback(data.d, textStatus, XmlHttpRequest);
            }
        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            if (errorCallback)
                errorCallback(XmlHttpRequest, textStatus, errorThrown);
            else
                errorHandler(XmlHttpRequest, textStatus, errorThrown);
        }
    });
}

//Called upon successful Retrieval of Customer Address.
function retrieveCustomerAddressCompleted(data, textStatus, XmlHttpRequest) {

    //Get back the Account JSON object
    var Account = data.results[0];
    if (Account != null) {
        Xrm.Page.getAttribute("address1_fax").setValue(Account.Address1_Fax);
        Xrm.Page.getAttribute("address1_line1").setValue(Account.Address1_Line1);
        Xrm.Page.getAttribute("address1_line2").setValue(Account.Address1_Line2);
        Xrm.Page.getAttribute("address1_stateorprovince").setValue(Account.Address1_StateOrProvince);
        Xrm.Page.getAttribute("address1_telephone1").setValue(Account.Address1_Telephone1);
        Xrm.Page.getAttribute("address1_telephone2").setValue(Account.Address1_Telephone2);
        
             // setting lookup field
               if (Account.new_regionid != null && Account.new_regionid .Id != null)
            SetLookupValue("new_region", Account.new_regionid .Id, Account.new_regionid .Name, Account.new_regionid .LogicalName);
    }
    
}

// Set lookup value to a field
function SetLookupValue(fieldName, id, name, entityType) {
    if (fieldName != null) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;

        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}

Dont forget to add JSON and JQuery libraries to the form. you can find it in my previous posts click here

Retrieving Entity Object Type code

// Retrieving Entity Object Type code based on entity schema name

function getObjectTypeCode(entityName) {
 
 try {

        var lookupService = new RemoteCommand("LookupService", "RetrieveTypeCode");
        lookupService.SetParameter("entityName", entityName);
        var result = lookupService.Execute();

        if (result.Success && typeof result.ReturnValue == "number") {
            return result.ReturnValue;
        } else {
            return null;
        }
    }
    catch (ex) {
        throw ex;
    }
}

Tuesday, June 7, 2011

Force submit in CRM 2011

Hi, I got a requirement to update CRM Field data on a Ribbon Button click. I will be calling the following java script method from ribbon button. Here we will set value to the CRM Field and then set force submit to the field. After that we will call the save method, it will save the crm Form Data.

function SaveData() {

    Xrm.Page.getAttribute("new_field").setValue("100");

     // setting Force Submit to the field, This must be set to save the data
    Xrm.Page.getAttribute("new_field").setSubmitMode("always");

    // Call Form save method
    crmForm.Save();
    
} 

Happy coding.. :)

Wednesday, April 13, 2011

Retrieve using ODATA and JSON in CRM 2011

In this example i am trying to retrieve Account entity information in  form load script using ODATA  and JSON in CRM 2011

To use ODATA service you need two resource files
  JSON and JQuery


you can download these popular resource in web...
Now write following java script in the new web resource file

function init()
{
// write required ODATA query
var odataSelect = "http://server/orgname/XRMServices/2011/OrganizationData.svc/AccountSet(guid'6C2EFF37-BD39-E011-91D1-000C2971AF13')";

$.ajax({
       type: "GET",
       contentType: "application/json; charset=utf-8",
       datatype: "json",
       url: odataSelect,
       beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
       success: function (data, textStatus, XmlHttpRequest) 
           { 
               
                
// Use this method for a selection that  return single entitie
               RetrieveEntityData(data.d);

             
              // Use this method for a selection that may return multiple entities
               RetrieveMultipleEntities(data.d.results);
           
           },
       error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
   });
}



function RetrieveEntityData(Entity)
{  
    // get the fields from the Entity object
     var accountNumber = Entity.AccountNumber;
     var AccountName = Entity.Name;
    
alert(Entity.Name);   
}


function RetrieveMultipleEntities(ManyEntities)
{


  for( i=0; i< ManyEntities.length; i++)
  {
// get the fields from the Entity object
     var Entity = ManyEntities[i];
     var accountNumberAttribute = Entity.AccountId;    
     var AccountName = Entity.Name;
     
alert(Entity.Name);   
  }
}


Just call the init method from the CRM form events, but make sure you have to add JSON and JQuery web resources to the event library before adding this web resource. It has to follow the sequence JSON,JQuery and Custom web Resource.


To get the Required entity ODATA set use the following url




Wednesday, March 16, 2011

Override Add Existing ISV Button functionality in CRM

To override "Add Existing" button default functionality. An Iframe displays accounts assoiciation view. Here I will be adding an confirm alert message to the "Add Existing" button, if the user confirms it will opens the lookup window, otherwise no action will happen.






     Add the following java script code in page load of the entity



getAlertForAddExistingAccountButton = function(lookupUrl) {  
    var iframe = crmForm.all.IFRAME_Accounts; //  IFRAME_Accounts  ID  
    var crmGrid = iframe.contentWindow.document.all['crmGrid'];  
      


  // If it's not N:N lookup dialog, we skip it.   
    if (lookupUrl.toLowerCase().match(/\/_controls\/lookup\/lookupmulti.aspx/i) == null)  
        return lookupUrl;  
      
    // If the lookup window is not concerned with the entity that we are interested in, we skip as well  
    if (GetQueryString(lookupUrl, 'objecttypes') !== crmGrid.GetParameter('otc'))  
        return lookupUrl;  
  
    
    return lookupUrl;  
};

(function replaceCrmLookups() {  


    window.oldOpenStdDlg = window.oldOpenStdDlg || window.openStdDlg;  


    window.openStdDlg = function() {  
    
var cnf = confirm("Are you sure to open Account lookup? ");
if(!cnf)
return;



        arguments[0] = getAlertForAddExistingAccountButton(arguments[0]);  
        
        return oldOpenStdDlg.apply(this, arguments);  


    };  
})();


Now you will get confirm alert on add existing button click before opening the account lookup page.


Wednesday, February 23, 2011

using ODATA to retrieve data from a custom Entity in CRM2011

In this example i am going to retrieve related custom entity attributes information in a CRM form load script using ODATA feature of CRM2011


To use ODATA you need two resource files
  JSON and JQuery




you can download these popular resource in web...
Now write following java script in the new web resource file


var ODataPath;
var serverUrl;


// here lid is the parameter that we will be passing while calling this method in crm form
function getCity(lid) {
    // Set Global Variables

    var context = Xrm.Page.context;
    serverUrl = context.getServerUrl();
    ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
    startTime = new Date();
     var locid = lid[0].id;
// here i'm passing lookup guid as parameter to retrieve that lookup entity related information   
 retrieveCity(locid );


}


function retrieveCity(Id) {



 var retrieveCityReq = new XMLHttpRequest();


// here is the entityset value you can get from the ODATA organization service
 retrieveCityReq.open("GET", ODataPath + "/new_entitySet(guid'" + Id + "')", true);
 retrieveCityReq.setRequestHeader("Accept", "application/json");
 retrieveCityReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
 retrieveCityReq.onreadystatechange = function () {
  retrieveCityReqCallBack(this);
 };
 retrieveCityReq.send();


}


function retrieveCityReqCallBack(retrieveCityReq ) {
 if (retrieveCityReq.readyState == 4 /* complete */) {
  if (retrieveCityReq.status == 200) {
   //Success
   var retrievedCity = JSON.parse(retrieveCityReq.responseText).d;
// here i'm retrieving pick list data
  alert("Retrieved City = " + retrievedCity.new_City.Value+ "");
  
// Assigning retrieved pick list  value to form element
Xrm.Page.getAttribute("new_city").setValue(retrievedCity.new_city.Value); 


     }
  else {
   //Failure
   errorHandler(retrieveBrandtReq);
  alert("retrieve Brand ReqCallBack function failure ");
  }
 }
}


Just call the getCity method from the CRM form events, but make sure you have to add JSON and JQuery web resources to the event library before adding this web resource. It has to follow the sequence JSON,JQuery and Custom web Resource.




To get the Required entity ODATA set use the following url
http://server/XRMServices/2011/OrganizationData.svc/new_enitityset





"The only reward of virtue is virtue; the only way to have a friend is to be one."
- Ralph Waldo Emerson


Monday, February 21, 2011

CRM2011 java script samples

Here are few basic CRM2011 java script samples

Get the value from a CRM field
var varMyValue = Xrm.Page.getAttribute(“CRMFieldSchemaName”).getValue() ;

Set the value of a CRM field
Xrm.Page.getAttribute(“po_CRMFieldSchemaName”).setValue(‘My New Value’);


// Hiding An Attribute
Xrm.Page.ui.controls.get("ownerid").setVisible(false);


Hide/Show a tab/section
Xrm.Page.ui.tabs.get(5).setVisible(false);
Xrm.Page.ui.tabs.get(5).setVisible(true);
 Xrm.Page.ui.tabs.get(tabNumber).sections.get(sectionNumber).setVisible(false);
 Xrm.Page.ui.tabs.get(tabNumber).sections.get(sectionNumber).setVisible(true);

Call the onchange event of a field
Xrm.Page.getAttribute(“CRMFieldSchemaName”).fireOnChange();

Get the selected value of picklist
Xrm.Page.getAttribute(“CRMFieldSchemaName”).getSelectedOption().text;

Set the requirement level
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“none”);
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“required”);
Xrm.Page.getAttribute(“CRMFieldSchemaName”).setRequiredLevel(“recommended”);

Set the focus to a field
Xrm.Page.getControl(“CRMFieldSchemaName”).setFocus(true);



// Hide Left Navigation link
Xrm.Page.ui.navigation.items.get("navContact").setVisible(false);


// Hide Left Navigation Pane
document.getElementById("crmNavBar").parentElement.style.display = "none";


Stop an on save event
event.returnValue = false;

Return array of strings of users security role GUIDs:
Xrm.Page.context.getUserRoles()


// Retrieving Object Type Code of Entity, etc = Entity Type Code
var etc = Xrm.Page.context.getQueryStringParameters().etc;



// Set lookup value to a field
function SetLookupValue(fieldName, id, name, entityType) {
if(fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;

Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}

// usage
SetLookupValue("new_field", "GUID", "Name", "new_entityname");

//Getting parent window context in child window
var parentcontext = window.top.opener.parent.Xrm.Page.context;


//Getting Parent window Object type code
var parobjcode = window.top.opener.parent.Xrm.Page.context.getQueryStringParameters().etc;

// get parent  Entity fields data
var parentFieldData = window.top.opener.parent.Xrm.Page.getAttribute("crmfield").getValue();

// Get the Server url with org Name
var serverAndOrgUrl = Xrm.Page.context.getServerUrl();
// Get the Current Organization Unique Name
var OrgName ="/"+Xrm.Page.context.getOrgUniqueName();

calling crms service from java script in CRM2011

//calling crms service from java script in CRM2011

Here I am going to call CRM service using java script to retrieve data from a custom entity and assign the result values to the current form fields.

function SetBrand(brachid)
{

try
{


if(brachid!= null && brachid!= "" )
{
brachid= brachid.replace("%7b","").replace("%7d","");

var authenticationHeader = Xrm.Page.context.getAuthenticationHeader();

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\">" +
 authenticationHeader+
 "<soap:Body>" +
 // Specify the RetrieveMultiple message.
 "<RetrieveMultiple xmlns="+
 "\"http://schemas.microsoft.com/crm/2007/WebServices\">" +
 // Specify that this is a QueryByAttribute query.
 "<query xmlns:q1="+
 "\"http://schemas.microsoft.com/crm/2006/Query\" "+
 "xsi:type=\"q1:QueryByAttribute\">" +
 // Query the customeraddress entity.
 "<q1:EntityName>new_branch</q1:EntityName>" +
 // Set the columns you want to return.
 "<q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 "<q1:Attributes>" +
 "<q1:Attribute>new_brand</q1:Attribute>" +
 "</q1:Attributes>" +
 "</q1:ColumnSet>" +
 // Specify the attribute that you are querying on.
 "<q1:Attributes>" +
 "<q1:Attribute>new_branchid</q1:Attribute>" +
 "</q1:Attributes>" +
 // Set the value of the attribute using the customerid
 // value of the case record.
 "<q1:Values>" +
 "<q1:Value xsi:type=\"xsd:string\">"+
 brachid+
 "</q1:Value>" +
 "</q1:Values>" +
 "</query>" +
 "</RetrieveMultiple>" +
 "</soap:Body>" +
 "</soap:Envelope>";
// Create an instance of an XMLHTTP object.
 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
// Configure the XMLHttp object for the
// Microsoft CRM Web services.
 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 );
// Send the XMLHttp request.
 xmlHttpRequest.send(xml);
// Capture the XMLHttp response in XML format.
 var resultXml = xmlHttpRequest.responseXML;

// Create an XML document that you can parse.
 var oXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
 oXmlDoc.async = false;
// Load the document that has the results.
 oXmlDoc.loadXML(resultXml.xml);
 // Get only the BusinessEntity results.
 var businessEntities = oXmlDoc.getElementsByTagName('BusinessEntity');

// Loop through the BusinessEntity elements.
 for (i=0;i < businessEntities.length;i++)
 {
     if (businessEntities[i].selectSingleNode('./q1:new_brand') != null)
       {
    
        var NameElement = businessEntities[i].selectSingleNode('./q1:new_brand');
        // We already know it is not null.
        var NameValue = NameElement.text;
    // Set the value of the lookup field to the value of the array.

            Xrm.Page.getAttribute("new_brand").setValue(NameValue);
       }
  }
}
}
catch (e)
{}

}

Re-arange the tabindex sequence in left to right order in MSCRM

The following code will re-arange the tabindex sequence in a left to right order.

function OnCrmPageLoad()

{
     ReArangeTabIndex();
}



function ReArangeTabIndex()

{

    for( var i = 0 ; i < crmForm.all.length ; i++ )

    {

          if( crmForm.all[ i ].tabIndex )

              crmForm.all[ i ].tabIndex = 1000 + (i*10);

    }
}

calling ondemand workflow using java script

Here is the logic to call on-demand workflow from java script.

function TriggerWorkflow() {

//  pass the workflow guid
var WorkflowId ="61A3C919-9636-44DC-87E4-C5FF2A63F2B4";

  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>" + crmForm.ObjectId + "</EntityId>" +
    "<WorkflowId>" + WorkflowId + "</WorkflowId>" + //WorkflowId = guid of the workflow
    "</Request>" +
    "</Execute>" +
    "</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/Execute");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
  xmlHttpRequest.send(xml);

  var resultXml = xmlHttpRequest.responseXML;
  return (resultXml.xml);
}

Thursday, December 9, 2010

CRM 2011sample java script

Few sample scripts for crm 2011

// Getting the Form Type
Xrm.Page.ui.getFormType()

// Set Focus to a field
Xrm.Page.getControl("fieldname").setFocus(true);


// Setting required Field dynamically
Xrm.Page.getAttribute("fieldname").setRequiredLevel("none");
Xrm.Page.getAttribute("fieldname").setRequiredLevel("required");

Tuesday, November 2, 2010

Dependent Picklist Issue in CRM 2011

To implement Cascading picklist in crm 2011, Add the following piece of code to the first drop down change event


function firstPickListOnChange()
{
  var firstPickListValue = Xrm.Page.getAttribute("new_ddl1").getValue();
    var secondPickListControl = Xrm.Page.ui.controls.get("new_ddl2");
    var secondPickListOptions = secondPickListControl.getAttribute().getOptions();
    secondPickListControl.clearOptions();

switch(firstPickListValue)
  {
     case 100000001:
     secondPickListControl.addOption(secondPickListOptions [0], 0);
     secondPickListControl.addOption(secondPickListOptions [1], 1);
     secondPickListControl.addOption(secondPickListOptions [2], 2);
     break;

     case 100000002:
     secondPickListControl.addOption(secondPickListOptions [3], 0);
     secondPickListControl.addOption(secondPickListOptions [4], 1);
     secondPickListControl.addOption(secondPickListOptions [5], 2);  
     break;
    }
}

updating field/Attribute using crmservice in java script

Here is the process to update field using crmservice

var xml1 = "<?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>"+
"<Update xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+
"<entity xsi:type='new_entity'>" +
"<new_field1>"+ xmlencode(data) +"</new_field1>" +
"<new_primarykeyfield>" + crmForm.ObjectId + "</new_primarykeyfield>" +
"</entity>"+
"</Update>"+
"</soap:Body>"+
"</soap:Envelope>";
var xHReq1 = new ActiveXObject("Msxml2.XMLHTTP");
xHReq1.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xHReq1.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Update");
xHReq1.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xHReq1.setRequestHeader("Content-Length", xml1.length);
xHReq1.send(xml1);
// Capture the result
var resultXml1 = xHReq1.responseXML;
var errorCount1 = resultXml1.selectNodes('//error').length;


//  Encoding method to replace special characters of the field data

function xmlencode(string) {
    return string.replace(/\&/g,'&'+'amp;').replace(/</g,'&'+'lt;').replace(/>/g,'&'+'gt;').replace(/\'/g,'&'+'apos;').replace(/\"/g,'&'+'quot;');
}