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

Monday 23 September 2013

Extracting the SSRS Report in PDF programmatically using Plugin or Wokflow in mscrm 2011

Extracting the Report in PDF programmatically.
Code snippet:
ReportGenerator rg = new ReportGenerator("http://crm/Reportserver/ReportExecution2005.asmx",
                new NetworkCredential("administrator", "Password", "contoso"));

            ParameterValue[] parameters = new ParameterValue[1];
            parameters[0] = new ParameterValue();
            parameters[0].Name = "P1";
            parameters[0].Value = string.Format("Select * From FilteredQuote Where QuoteId = '{0}'",
                context.PrimaryEntityId);

            byte[] reportresult = rg.Render("/contoso_mscrm/quote", FormatType.PDF, parameters);

            Entity attachment = new Entity("activitymimeattachment");
            attachment["objectid"] = Email.Get<EntityReference>(executionContext);
            attachment["objecttypecode"] = "email";
            attachment["filename"] =
            attachment["subject"] = "Quote.pdf";
            attachment["body"] = System.Convert.ToBase64String(reportresult);

Ref Links:




Tuesday 10 September 2013

Get DateTime formate from Retrieved stringDateAttribute Using Odata Java Script – MS CRM 2011


Get DateTime formate from Retrieved stringDateAttribute  Using Odata Java Script:
Some times you may get date time value as milli seconds in the below format as “/Date(1371723451000)/”
var RetrievedDate = ”/Date(1371723451000)/”;
to convert this into normal date you need to pass “RetrievedDate” string to the below highlited area.
var DateValue = new Date(parseInt(RetrievedDate.replace(“/Date(“, “”).replace(“)/”, “”), 10));
Now you will get DateValue in UTC date time format.
Cheers,

BY Vivek

Monday 19 August 2013

How to hide the “New” or “Properties” button from the CRM 2011 Lookup Dialog

How to hide the “New” or “Properties” button from the CRM 2011 Lookup Dialog.

Here’s the new way to hide the “New” button:

var lookupControl = Sys.Application.findComponent("some_lookupid");
 
  if (lookupControl != null)
  {
       lookupControl._element._behaviors[0].AddParam("ShowNewButton", 0);

   }

Display Custom Advance Find view in Iframe in CRM 2011 by Guru Prasad

Display Custom Advance Find view in Iframe in CRM 2011  by Guru Prasad

Hi All, To bind FetchXml to Iframe Adi Katz,MVP has provided nice article to do in CRM4.0. Thanks Adi Katz for the great article. I just started converting it to work with CRM 2011. Here is the working copy of mine, to bind FetchXml to Iframe.


function loadIFrame() {

    window.fetchActivtities = new FetchViewer("IFRAME_TEST");
    fetchActivtities.FetchXml = getFetchXml();
    fetchActivtities.LayoutXml = getLayoutXml();
    fetchActivtities.Entity = "activitypointer";
    fetchActivtities.QueryId = "{00000000-0000-0000-00aa-000010001899}"; // view GUID
    fetchActivtities.RegisterOnTab(2); //IFRAME TAB INDEX


}



function getFetchXml() {

//  FetchXML Query
    return ' <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="true">' +
                '<entity name="activitypointer">' +
                 ' <attribute name="subject" />' +
                 ' <attribute name="scheduledstart" />' +
                 ' <attribute name="regardingobjectid" />' +
                 ' <attribute name="prioritycode" />' +
                 ' <attribute name="scheduledend" />' +
                 ' <attribute name="activitytypecode" />' +
                 ' <attribute name="instancetypecode" />' +
                 ' <order attribute="scheduledend" descending="false" />' +
                '<filter type="and">'+
                  '<condition attribute="regardingobjectid" operator="in">'+
                    '<value  uitype="account">{7CC58DF6-3114-E111-8E22-1CC1DEEAE7D7}</value>'+                  
                 ' </condition>'+
                '</filter>'+
                '  <attribute name="activityid" />' +
               ' </entity>' +
             ' </fetch>';

}

function getLayoutXml() {

// grid layout, you can get easily from Customization.xml file
    return '<grid name="resultset" object="4200" jump="subject" select="1" icon="1" preview="1">' +
               ' <row name="result" id="activityid" multiobjectidfield="activitytypecode">' +
               '   <cell name="instancetypecode" width="100" ishidden="1" />' +
               ' </row>' +
             ' </grid>';

}

function FetchViewer(iframeId) {
    var Instance = this;
    var vDynamicForm;
    var m_iframeTab;
    var m_iframeDoc;

    Instance.Entity = "";
    Instance.Iframe = null;
    Instance.FetchXml = "";
    Instance.QueryId = "";
    Instance.LayoutXml = "";

    Instance.RegisterOnTab = function (tabIndex) {
        Instance.Iframe = document.getElementById(iframeId);

        if (!Instance.Iframe)
            return alert("Iframe " + iframeId + " is undefined");

        m_iframeDoc = getIframeDocument();
        var loadingGifHTML = "<table height='100%' width='100%' style='cursor:wait'>";
        loadingGifHTML += "<tr>";
        loadingGifHTML += "<td valign='middle' align='center'>";
        loadingGifHTML += "<img alt='' src='/_imgs/AdvFind/progress.gif'/>";
        loadingGifHTML += "<div/><b>Loading View...</b>";
        loadingGifHTML += "</td></tr></table>";
        m_iframeDoc.body.innerHTML = loadingGifHTML;

        Instance.Refresh();

    }

    function RefreshOnReadyStateChange() {

        if (Instance.Iframe.readyState != 'complete')
            return;

        Instance.Refresh();
    }

    Instance.Refresh = function () {
   
        if (!Instance.Iframe)
            return alert("Iframe " + iframeId + " is undefined");

        m_iframeDoc = getIframeDocument();

        Instance.Iframe.detachEvent("onreadystatechange", RefreshOnReadyStateChange);

        var create = m_iframeDoc.createElement;
        var append1 = m_iframeDoc.appendChild;
        vDynamicForm = create("<FORM name='vDynamicForm' method='post'>");

        var append2 = vDynamicForm.appendChild;
        append2(create("<INPUT type='hidden' name='FetchXml'>"));
        append2(create("<INPUT type='hidden' name='LayoutXml'>"));
        append2(create("<INPUT type='hidden' name='EntityName'>"));
        append2(create("<INPUT type='hidden' name='DefaultAdvFindViewId'>"));
        append2(create("<INPUT type='hidden' name='ViewType'>"));
        append1(vDynamicForm);

        vDynamicForm.action = prependOrgName("/AdvancedFind/fetchData.aspx");
        vDynamicForm.FetchXml.value = Instance.FetchXml;
        vDynamicForm.LayoutXml.value = Instance.LayoutXml;
        vDynamicForm.EntityName.value = Instance.Entity;
        vDynamicForm.DefaultAdvFindViewId.value = Instance.QueryId;
        vDynamicForm.ViewType.value = 1039;
        vDynamicForm.submit();


        Instance.Iframe.attachEvent("onreadystatechange", OnViewReady);
    }

    function OnViewReady() {
        if (Instance.Iframe.readyState != 'complete') return;

        Instance.Iframe.style.border = 0;
        Instance.Iframe.detachEvent("onreadystatechange", OnViewReady);
        m_iframeDoc = getIframeDocument();
        m_iframeDoc.body.scroll = "no";
        m_iframeDoc.body.style.padding = "0px";
    }

    function getIframeDocument() {
        return Instance.Iframe.contentWindow.document;
    }

}

Monday 12 August 2013

Sub Grid Custom Filter in MSCRM 2011

function FilterContactsBasedLookUpFiled() {

    var grid = document.getElementById('gridname');

    if (grid == null) {
        setTimeout('FilterContactsBasedOnShipTo()', 2000);
    }
    else {

        var lookupfield = new Array;
        var lookupid = null;

        lookupfield = Xrm.Page.getAttribute("Lookup").getValue();

        if (lookupfield != null) {

            lookupid = lookupfield[0].id;
        }

        //Else the function will return and no code will be executed.

        else {

            return;
        }

        //This method is to ensure that grid is loaded before processing.


        //This is the fetch xml code which will retrieve all the order products related to the order selected for the case.
        var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
        fetchXml += "<entity name='qcg_contact_shipping_address'>";
        fetchXml += " <attribute name='qcg_shippingaddress' />";
        fetchXml += "<attribute name='qcg_role' />";
        fetchXml += "<attribute name='qcg_contact' />";
        fetchXml += "<order attribute='qcg_shippingaddress' descending='false' />";
        fetchXml += "<link-entity name='contact' from='contactid' to='qcg_contact' alias='am'>";
        fetchXml += " <filter type='and'>";
        fetchXml += "  <condition attribute='parentcustomerid' operator='eq'  value='" + lookupid + "' />";
        fetchXml += "</filter>";
        fetchXml += "</link-entity>";
        fetchXml += "</entity>";
        fetchXml += "</fetch>";

        //Setting the fetch xml to the sub grid.

        grid.control.SetParameter("fetchXml", fetchXml);

        //This statement will refresh the sub grid after making all modifications.

        grid.control.refresh();
    }

}

Thursday 8 August 2013

Formula filed functionality in MSCRM 2011 like Sales Force.

This needs Jquery  Library support


// This function is called in onchange of some  look up field.
function RetrieveAccountInfo() {

// Get the lookup filed id value
    customerAttribute = XP.data.entity.attributes.get("xxxid");

    if (customerAttribute != null) {

        customerValue = customerAttribute.getValue();
        if (customerValue != null && customerValue[0] != null) {
            customerType = customerValue[0].typename;
            customerId = customerValue[0].id;
            return retrieveRecord(customerId, "AccountSet", retrieveCompleted, null);
        }
    }
}

// Firing the Rest call to get the all the attributes of this look up record
function retrieveRecord(id, odataSetName, successCallback, errorCallback) {
    //var context = GetGlobalContext();

    var odataEndPoint = "/XRMServices/2011/OrganizationData.svc";
    if (!id) {
        alert("record id is required.");
        return;
    }
    if (!odataSetName) {
        alert("odataSetName is required.");
        return;
    }

    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + odataEndPoint + "/" + odataSetName + "(guid'" + id + "')",
        beforeSend: function (XMLHttpRequest) {

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

// Call Back method to parse values from response
function retrieveCompleted(data, textStatus, XmlHttpRequest) {
    /*Display the required fields and hide if the fields are null */
    entity = data;
    if (!IsNull(entity.xxxxfield. value)) {

        if (entity.xxxxfield.LogicalName == "pricelevel") {

            var lookupValue = new Array();
            lookupValue[0] = new Object();
            lookupValue[0].id = entity.xxxxfield.Id;
            lookupValue[0].name = entity.xxxxfield.Name;
            lookupValue[0].entityType = entity.xxxxfield.LogicalName;
            XP.getAttribute("pricelevelid").setValue(lookupValue);


        }
        else {
            XP.getAttribute("xxxxfiledvalue").setValue(null);
        }
    }
    else {
        XP.getAttribute("xxxxfiledvalue").setValue(null);
    }
}

Get Object type code for MSCRM entities


  •  Using SQL Query :-
Get Object Type codes by Sql Query
Query>
SELECT ObjectTypeCode,*
FROM
ENTITYVIEW
Using JScript  :-
  • The “ObjectTypeCode” can be extracted from Query String using JScript
  • “ObjectTypeCode” resides in “etc” query string  parameter
  • Below is the JScript statement to get “ObjectTypeCode”
var currEntityObjTypeCode= Xrm.Page.context.getQueryStringParameters().etc
Key Points
  • Type codes below 10,000 are reserved for OOB entities.
  • Custom entities have a value greater than or equal to 10,000.
Note:- Custom entity object type codes may change during import and are not guaranteed to be the same between systems.
Getting Object Type Code by ‘Entity Name’ using Jscript
Below script uses CRM inbuilt logic and return the entity type code (or) object type code for the given entity name.
function getObjectTypeCodeByName(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 (e) {
alert(“Error while getting ETC by Name – ” + e.description);
}
}



BY  

Friday 2 August 2013

Code to Get the Sub grid row values in Mscrm 2011


    function GettheSubGridRowValues() {
   

       // Get the Grid conrttol using its name
      var  grid = document.getElementById("Events");
      // Chek the grid is loaded or not
       if (grid.readyState != "complete") {
        // delay one second and try again. to wait  for grid loading 
        setTimeout(SubGridRefresh, 1000);
        return;
    }
    if (grid) {
         var gridControl = document.getElementById("Events").control;
        //Get the Row ids 
         var  ids = gridControl.get_allRecordIds();
         var  IslogicExecutionRequired= false;
        //Iterate by row wise
        for (i = 0; i < ids.length; i++) {
              // Get the call value by its column name
            var cellValue = gridControl.getCellValue('sci_name', ids[i]);
             if (cellValue == "xxxxx") {
                  IslogicExecutionRequired= true;
            }          
        }
   
    }
}

Attaching Sub Grid Refresh Event In MSCRM 2011



var grid = null;
var gridControl = null;
var ids = null;
var IsScottsdaleShowdown = false;



// call this finction on form laod
function Form_onload() {

// time out set as the grod will load littile late asynchronously after form laod , so we are waiting 2.5 seconds
    setTimeout("SubGridRefresh();", 2500);
}


// Attach  Sub grid refresh event
function SubGridRefresh() {

     grid = document.getElementById("Events");

     // Chek gris controll loaded or not 
    if (grid.readyState != "complete") {
        // delay one second and try after one second whether grid is loaded or not  
        setTimeout(SubGridRefresh, 1000);
        return;
    }

    if (grid) {
    // Attach  grid refresh event
        grid.attachEvent("onrefresh", CustomLogic);

      //cALLING THE CUSTOM LOGIC WHICH NEED TO BE EXECUTED R SUB GRID REFRESH
        grid.control.add_onRefresh(CustomLogic);

    }

    function CustomLogic() {

// Write the custom Logic which need to be executed in Grid Refresh.
    }



Thursday 18 July 2013

Dependent Picklist in MScrm 2011

Dependent Picklist in CRM 2011

             MS CRM 2011 doesn't have Out-Of-the-Box functionality to filter the option set values based on the value selected in another option set. We can implement this functionality using Javascript. Lets consider one example here. We have two option set fields called Country and City. City field has to be filtered based on the value selected in Country field. Below JScript code will do this functionality.

Prerequisite:

1. Create two optionset fields named new_country(with values say, India, USA and Srilanka) and new_city(with values say, Bangalore, Delhi, New York, Colombo, California and Hyderabad).
2. Create a JScript Webresource with the below code.
3. Attach this webrecource to call optionSetChanged() method on change of Country field and OnLoad of the form.
4. Configure getCollection() method to match the Cities with respect to Country.


/************************
Functionality: To populate the picklist values based on the value selected in another picklist.
Field Name: new_country
Field Event: OnChange, OnLoad
***************************/

function optionSetChanged() {

    ///<summary>
    /// Change the dependent picklist values based on the value selected in the control picklist.
    ///</summary>

    var _collection = getCollection();
    var _selectedCity = null;
    var _cityOptionset = Xrm.Page.ui.controls.get("new_city");
    if (_cityOptionset != null)
        _selectedCity = _cityOptionset.getAttribute().getValue();

    var _cityOptions = _cityOptionset.getAttribute().getOptions();
    var _selectedCountry = Xrm.Page.getAttribute("new_country").getText();
        
    // If Country is empty, then clear the City field.
    if (_selectedCountry == "") {
        _cityOptionset.clearOptions();
    }
    else {
        for (var i = 0; i < _collection.length; i++) {
            if (_selectedCountry.toLowerCase() == _collection[i].Country.toLowerCase()) {
                _cityOptionset.clearOptions();
                for (var j = 0; j < _collection[i].Cities.length; j++) {
                    for (var k = 0; k < _cityOptions.length; k++) {
                        if (_collection[i].Cities[j].toLowerCase() == _cityOptions[k].text.toLowerCase()) {
                            _cityOptionset.addOption(_cityOptions[k]);
                            break;
                        }
                    }
                }
                break;
            }
        }
        if (_cityOptionset != null && _selectedCity != null)
            _cityOptionset.getAttribute().setValue(_selectedCity);
    }
}


function getCollection() {

    ///<summary>
    /// Creates and returns a collection of Cities with respect to their Countries.
    ///</summary>

    var _collection = new Array();
    var India_Cities = new Array("Bangalore", "Delhi", "Hyderabad");
    var India_obj = { Country: "India", Cities: India_Cities };
    _collection.push(India_obj);

    var Srilanka_Cities = new Array("Colombo");
    var SriLanka_obj = { Country: "SriLanka", Cities: Srilanka_Cities };
    _collection.push(SriLanka_obj);

    var USA_Cities = new Array("California", "New York");
    var USA_obj = { Country: "USA", Cities: USA_Cities };
    _collection.push(USA_obj);

    return _collection;
}



    This functionality can be tested by changing the Country field and check the values populated in City field. Result of this dependent pick list is can be seen here.

Country: India and Cities: Bangalore,Delhi & Hyderabad.

Country: USA and Cities: California & NewYork.

Monday 11 March 2013


Update Record In mscrm 2011 form form javascript:


Soap:



function updateAccount() {
    var FORM_TYPE_UPDATE = 2;
    var formType = Xrm.Page.ui.getFormType();
    if (formType == FORM_TYPE_UPDATE) {
        // Prepare variables for updating a contact.
        var accountId = Xrm.Page.data.entity.getId();
        var parentAccount = Xrm.Page.getAttribute('parentaccountid');
        var parentAccountId;

        if (parentAccount != null) {

            var lookUpObjectValue = parentAccount.getValue();

            if ((lookUpObjectValue != null)) {

                parentAccountId = lookUpObjectValue[0].id;

            }
            var authenticationHeader = GenerateAuthenticationHeader();

            // Prepare the SOAP message.
            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>" +
"<Update xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
"<entity xsi:type='account'>" +
"<parentaccountid>" + parentAccountId + "</parentaccountid>" +
"<accountid>" + accountId + "</accountid>" +
"</entity>" +
"</Update>" +
"</soap:Body>" +
"</soap:Envelope>";
            // Prepare the xmlHttpObject and send the request.
            var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
            xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
            xHReq.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Update");
            xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
            xHReq.setRequestHeader("Content-Length", xml.length);
            xHReq.send(xml);
        }
    }
}




Rest:

function updateContactRest() {

    var FORM_TYPE_UPDATE = 2;
    var formType = Xrm.Page.ui.getFormType();
    if (formType == FORM_TYPE_UPDATE) {
        // Prepare variables for updating a contact.
        var accountId = Xrm.Page.data.entity.getId();
        var parentAccount = Xrm.Page.getAttribute('parentaccountid');
        var parentAccountId;

        if (parentAccount != null) {

            var lookUpObjectValue = parentAccount.getValue();

            if ((lookUpObjectValue != null)) {

                parentAccountId = lookUpObjectValue[0].id;


            }
            // Gets the record Guid
            var id = Xrm.Page.data.entity.getId();
            var changes = {
                // Text field

                // Lookup field
                ParentAccountId: {
                    Id: parentAccountId, // 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);
}


















How to have a custom filtering on lockup using form java script in mscrm 2011: by Srinivas kalwakuntla





function Accountview() {

    var account = Xrm.Page.getAttribute('tls_parentaccount');
    var accountid;

    if (account != null) {

        var lookUpObjectValue = account.getValue();

        if ((lookUpObjectValue != null)) {

            var lookuptextvalue = lookUpObjectValue[0].name;

            var accountid = lookUpObjectValue[0].id;

        }


        if (!IsNull(accountid)) {
            var viewId = "{1DFB2B35-B07C-44D1-868D-258DEEAB88E2}";
            var entityName = "account";
            var viewDisplayName = "Default View For Account";


            var fetchXml = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">' +
                     '<entity name="account">' +
                        '<attribute name="name" />' +
                         '<attribute name="sic" />' +
                        '<attribute name="accountid" />' +
                         '<attribute name="address1_city" />' +
                         '<attribute name="telephone1" />' +
                         '<attribute name="primarycontactid" />' +
                         '<filter type="and">' +
                          '<condition attribute="accountid" operator="ne" value="' + accountid + '"/>' +
                        '</filter>' +
                     '</entity>' +
                  '</fetch>';

            // build Grid Layout
            var layoutXml = "<grid name='resultset' " +
                "object='1' " +
                "jump='account' " +
                "select='0' " +
                "icon='0' " +
                "preview='1'>" +
                "<row name='result' " +
                "id='accountid'>" +
                "<cell name='name' " +
                "width='200' />" +
                "<cell name='primarycontactid' " +
                "width='150' />" +
                "<cell name='sic' " +
                "width='150' />" +
                "<cell name='address1_city' " +
                "width='150' />" +
                "<cell name='telephone1' " +
                "width='150' />" +
                "</row>" +
                "</grid>";

            Xrm.Page.getControl("new_newemployer").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
            Xrm.Page.getControl("new_previousemployer").addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);

        }

    }
}





Javascript code for phone number format in mscrm 2011:by srinivas kalwakuntla


//Phone Number Format
function FormatPhoneNumber(context) {
    var oField = context.getEventSource().getValue();
    var sTmp = oField;

    if (typeof (oField) != "undefined" && oField != null) {
        sTmp = oField.replace(/[^0-9]/g, "");
        switch (sTmp.length) {
            case 10:
                sTmp = sTmp.substr(0, 3) + "-" + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
                break;


            default:
                alert("Phone Number must contain 10 numbers.");
                break;
        }
    }
    context.getEventSource().setValue(sTmp);
}


Tuesday 27 November 2012

Multiple entities selection in single look up:


If you create custom lookup in CRM, this lookup is oriented only for one entity.
I want to add possibility to select from some entities in one lookup.

I have custom lookup "originatingleadid". This lookup is oriented on Lead entity. I want to select from views of three different entities: Lead, Contact, User.

For this I've done some customization in opportunity entity, I've created three hidden text fields:
new_type - to save lookup type
new_guid - to save lookup guid
new_name - to save lookup name.
That is all customization.

I've developed three javascript function:

1. function to handle OnChange event on lookup.


function onchange()
{
var originatingLeadValue = Xrm.Page.getAttribute("originatingleadid").getValue();
if (IsNull(originatingLeadValue) || originatingLeadValue[0].type == "4")
{
// Lookup is null or there is a Lead, need to clear hidden fields. To clear one of them will be enough, we will be check this field during onload.
Xrm.Page.getAttribute("new_guid").setValue(null);
}
else
{
// Lookup contains Contact or User, so need to store lookup properties to our hidden fields.
Xrm.Page.getAttribute("new_type").setValue(originatingLeadValue[0].type);
Xrm.Page.getAttribute("new_guid").setValue(originatingLeadValue[0].id);
Xrm.Page.getAttribute("new_name").setValue(originatingLeadValue[0].name);
}
}

2. function to handle OnSave event on Opportuniry Form.

function onsave()
{
var originatingLeadValue = Xrm.Page.getAttribute("originatingleadid").getValue();
if (!IsNull(originatingLeadValue) && originatingLeadValue[0].type != '4')
{
Xrm.Page.getAttribute("originatingleadid").setValue(null);
}
}
 3. function to handle OnLoad event on Opportunity Form.

function onload()
{
lookuptypeIcons = '/_imgs/ico_16_2.gif:/_imgs/ico_16_4.gif:/_imgs/ico_16_8.gif';
lookuptypenames = 'contact:2:Contact,lead:4:Lead,systemuser:8:User';
lookuptypes = '2,4,8';
var savedId = Xrm.Page.getAttribute("new_guid").getValue();
var savedType = Xrm.Page.getAttribute("new_type").getValue();
var savedName = Xrm.Page.getAttribute("new_name").getValue();
var savedEntityName = savedType == "8" ? "systemuser" : "contact";
document.getElementById("originatingleadid").setAttribute("lookuptypes", lookuptypes);
document.getElementById("originatingleadid").setAttribute("lookuptypenames", lookuptypenames);
document.getElementById("originatingleadid").setAttribute("lookuptypeIcons", lookuptypeIcons);
document.getElementById("originatingleadid").setAttribute("defaulttype", "4"); // default type - Lead entity
var originatingLeadValue = Xrm.Page.getAttribute("originatingleadid").getValue();
if (IsNull(originatingLeadValue) && !IsNull(savedId))
{
var value = new Array();
value[0] = new Object();
value[0].displayClass = "ms-crm-Lookup-Item";
value[0].keyValues = new Object();
value[0].values = new Object();
value[0].onclick = "openlui()";
value[0].id = savedId;
value[0].entityType = savedEntityName;
value[0].typename = savedEntityName;
value[0].name = savedName;
value[0].type = savedType;
Xrm.Page.getAttribute("originatingleadid").setValue(value);
}
}
So, now you can select from  three different entity in one lookup :-)
Custom Lookup view