Set Custom View as Default View for Lookup Control


Let’s say we have to set Custom View as Default View of a particular Lookup. Below are the steps to set Custom View as default View.

1. Create a Custom View as per your requirement and Save it.(In my case, Created a custom view of Account which will be shown on contact entity for Primary Customer Field)
CustomView

2. Get View Id from Browser. 3. Download Fetch XML for your custom view as shown below. In my case, below is the FetchXML query..

<fetch version=”1.0″ output-format=”xml-platform” mapping=”logical” distinct=”false”>   <entity name=”account”>     <attribute name=”name” />     <attribute name=”primarycontactid” />     <attribute name=”telephone1″ />     <attribute name=”accountid” />     <attribute name=”accountratingcode” />     <order attribute=”name” descending=”false” />     <filter type=”and”>       <condition attribute=”telephone1″ operator=”eq” value=”555-0135″ />     </filter>   </entity> </fetch>

4. Format the FetchXML  as string variable as below.

    var fetchXml = “<fetch version=’1.0′ “ +
 “output-format=’xml-platform’ “ +
 ” mapping=’logical’ “ +
 ” distinct=’false’>” +
  “<entity name=’account’>” +
    “<attribute name=’name’ />” +
    “<attribute name=’primarycontactid’ />” +
    “<attribute name=’telephone1′ />” +
    “<attribute name=’accountid’ />” +
    “<attribute name=’accountratingcode’ />” +
    “<order attribute=’name’ descending=’false’ />” +
    “<filter type=’and’>” +
     ” <condition attribute=’telephone1′ operator=’eq’ value=’555-0135′ />” +
    “</filter>” +
  “</entity>” +
“</fetch>”;
5. Create layoutXml to set Grid properties to display the view as below.
var layoutXml = “<grid name=’resultset’ “ +
“object=’1′ “ +
“jump=’name’ “ +
“select=’1′ “ +
“icon=’1′ “ +
“preview=’1′>” +
“<row name=’result’ “ +
“id=’accountid’>” +
“<cell name=’name’ “ +
“width=’300′ />” +
“<cell name=’primarycontactid’ “ +
“width=’150′ />” +
“<cell name=’telephone1′ “ +
“width=’100′ />” +
“<cell name=’accountratingcode’ “ +
“width=’100′ />” +
“disableSorting=’1′ />” +
“</row>” +
“</grid>”;

6. Call the addCustomView() method of Lookup to set custom view as Default View.

Sets the viewId, viewDisplayName, fetchXml, and layoutXml variables to pass as arguments so that a custom view is added as the default view to the control for the Parent Customer lookup field.

7. Add above steps in a custom function and call it on OnLoad or OnChange as per requirement
function setDefaultCustomView() {
    var viewId = “{00000000-0000-0000-00AA-000010001001}”;
    var viewDisplayName = “Custom Account View”;
    var fetchXml = “<fetch version=’1.0′ ” +
“output-format=’xml-platform’ ” +
” mapping=’logical’ ” +
” distinct=’false’>” +
“<entity name=’account’>” +
“<attribute name=’name’ />” +
“<attribute name=’primarycontactid’ />” +
“<attribute name=’telephone1′ />” +
“<attribute name=’accountid’ />” +
“<attribute name=’accountratingcode’ />” +
“<order attribute=’name’ descending=’false’ />” +
“<filter type=’and’>” +
” <condition attribute=’telephone1′ operator=’eq’ value=’555-0135′ />” +
“</filter>” +
“</entity>” +
“</fetch>”;

    var layoutXml = “<grid name=’resultset’ ” +
“object=’1′ ” +
“jump=’name’ ” +
“select=’1′ ” +
“icon=’1′ ” +
“preview=’1′>” +
“<row name=’result’ ” +
“id=’accountid’>” +
“<cell name=’name’ ” +
“width=’300′ />” +
“<cell name=’primarycontactid’ ” +
“width=’150′ />” +
“<cell name=’telephone1′ ” +
“width=’100′ />” +
“<cell name=’accountratingcode’ ” +
“width=’100′ />” +
“disableSorting=’1′ />” +
“</row>” +
“</grid>”;

Xrm.Page.getControl(“parentcustomerid”).addCustomView(viewId, “account”, viewDisplayName, fetchXml, layoutXml, true); 

}

Note: Pls change the double quote(“) manually before testing the code.

Create contact and share the record which contains Lookup,Picklist and string datatype


This sample will show how to create Contact record in CRM 4.o through Web Application which contains Lookup, Picklist and String datatype.

I have created a custom entity(new_hobby) and created a 1-N relationship from Hobby to Contact. I have also created Team called CRM Team and added members to that team. Whenever a contact will be created, contact will be shared to the CRM Team which have only Read Access to that contact.

First create Web Reference to CrmService and MetaDataService  to create proxy class and include this into project with the help of using statement.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CrmPractice.CrmSdk;
using System.Web.Services.Protocols;
using CrmPractice.MetaDataSdk;
namespace CrmPractice
{
public partial class _Default : System.Web.UI.Page
{
public static Dictionary<string, string> dics = new Dictionary<string, string>();
public static Dictionary<string, string> AddDics = new Dictionary<string, string>();
List<ListItem> HobbyList = new List<ListItem>();
List<ListItem> Addlist = new List<ListItem>();
string teamId = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CrmService service = GetCrmService();
CrmPractice.MetaDataSdk.MetadataService metadataService = GetMetaDataService();

//Populate Lookup Value
PopulateLookupValue(service);

//Populate Picklist Value using metadataservice
GetPickListValue(metadataService);
}
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
CrmService service = GetCrmService();

//Create contact record
contact conts = new contact();
conts.firstname = txtFirstName.Text;
conts.lastname = txtLastName.Text;
conts.mobilephone = txtMobileNo.Text;

// Set Hobby Lookup value

Lookup hobbyLookup = new Lookup();
hobbyLookup.name = ddlHobby.SelectedItem.Value.ToString();
hobbyLookup.type = EntityName.new_hobby.ToString();
hobbyLookup.Value = new Guid(dics[ddlHobby.SelectedItem.Value.ToString()]);
conts.new_hobbyid = hobbyLookup;

// Set AddressType Picklist value

Picklist addPickList=new Picklist();
addPickList.name=ddlAddressType.SelectedItem.Value.ToString();
addPickList.Value=Convert.ToInt16(AddDics[ddlAddressType.SelectedItem.Value.ToString()]);

conts.address1_addresstypecode = addPickList;
conts.emailaddress1  = txtEmailId.Text;

//Create Contact
Guid contactId = service.Create(conts);

// Get Team id to share the record
teamId = GetTeamId(service);

// Share record with Team
ShareWithTeam(service, contactId.ToString(), teamId);

//Clear the field
ClearField();
}
catch(SoapException ex)
{
ex.Detail.InnerText.ToString();
}
}

/// <summary>

/// /Populate Hobbylist from CRM and bind it with DropDownlist

/// </summary>

/// <param name=”service”>CRM Service</param>

private void PopulateLookupValue(CrmService service)
{
try
{
ColumnSet cols = new ColumnSet();
cols.Attributes = new string[] { “new_name”, “new_hobbyid”, };

OrderExpression order = new OrderExpression();
order.AttributeName = “new_name”;
order.OrderType = OrderType.Ascending;

QueryExpression query = new QueryExpression();
query.ColumnSet = cols;
query.EntityName = EntityName.new_hobby.ToString();
query.Orders = new OrderExpression[] { order };

BusinessEntityCollection hobbies = service.RetrieveMultiple(query);

DropDownList hb = new DropDownList();
for (int i = 0; i < hobbies.BusinessEntities.Length; i++)
{
new_hobby hobby = (new_hobby)hobbies.BusinessEntities[i];
dics.Add(hobby.new_name.ToString(), hobby.new_hobbyid.Value.ToString());
HobbyList.Add(new ListItem(hobby.new_name.ToString(), hobby.new_hobbyid.Value.ToString()));
hb.Attributes.Add(hobby.new_name.ToString(), hobby.new_hobbyid.Value.ToString());
}

ddlHobby.DataSource = HobbyList;
ddlHobby.DataBind();
}
catch (SoapException ex)
{
ex.Detail.InnerText.ToString();
}
}

/// <summary>

/// Get Picklist value using metadata service and bind

/// it with dropdown

/// </summary>

/// <param name=”metaDataService”>MetaDataService</param>

private void GetPickListValue(MetadataService metaDataService)
{
try
{
DropDownList address = new DropDownList();

AttributeMetadata metadata = new AttributeMetadata();
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();
attributeRequest.EntityLogicalName = EntityName.contact.ToString();
attributeRequest.LogicalName = “address1_addresstypecode”;

RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)metaDataService.Execute(attributeRequest);

PicklistAttributeMetadata addressType = (PicklistAttributeMetadata)attributeResponse.AttributeMetadata;
for (int i = 0; i < addressType.Options.Length; i++)
{
AddDics.Add(addressType.Options[i].Label.UserLocLabel.Label, addressType.Options[i].Value.Value.ToString());
Addlist.Add(new ListItem(addressType.Options[i].Label.UserLocLabel.Label, addressType.Options[i].Value.Value.ToString()));
}
ddlAddressType.DataSource = Addlist ;
ddlAddressType.DataBind();

}

catch (SoapException ex)

{

ex.Detail.InnerText.ToString();

}

}

/// <summary>

/// Get CrmService

/// </summary>

/// <returns>CrmService</returns>

private CrmService GetCrmService()
{
CrmPractice.CrmSdk.CrmAuthenticationToken token = new CrmPractice.CrmSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = “CMDev”;

CrmService service = new CrmService();
service.Url = http://<CrmServer>/mscrmservices/2007/crmservice.asmx;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.CrmAuthenticationTokenValue = token;
return service;
}

/// <summary>

/// Get Metadata service

/// </summary>

/// <returns>MetaDataService</returns>

private MetaDataSdk.MetadataService  GetMetaDataService()
{
CrmPractice.MetaDataSdk.CrmAuthenticationToken token = new CrmPractice.MetaDataSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = “CMDev”;
MetaDataSdk.MetadataService  service = new MetaDataSdk.MetadataService();
service.Url = http://<CrmServer>/mscrmservices/2007/metadataservice.asmx;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.CrmAuthenticationTokenValue = token;
return service;
}

/// <summary>

/// Get TeamId to share the record

/// </summary>

/// <returns>Team Id</returns>

private string GetTeamId(CrmService service)
{
// Query express to find out team id to share the rescord
QueryByAttribute query = new QueryByAttribute ();
query.EntityName =EntityName.team.ToString();

ColumnSet cols = new ColumnSet ();
cols.Attributes=new string[]{“teamid”};

query.ColumnSet = cols;query.Attributes =new string[] { “name”};
query.Values =new string[] { “CRM Team” };

BusinessEntityCollection retrieved = (BusinessEntityCollection)service.RetrieveMultiple(query);
if(retrieved.BusinessEntities.Length> 0 )
{
team newTeam = (team )retrieved.BusinessEntities[0];
CrmPractice.CrmSdk.Key teamGuid = (CrmPractice.CrmSdk.Key )newTeam.teamid;
teamId = teamGuid.Value.ToString();
}
return teamId;
}

private void ShareWithTeam(CrmService service,string recordId,string teamId)
{
// Create the SecurityPrincipal Object
SecurityPrincipal principal = new SecurityPrincipal();
principal.Type = SecurityPrincipalType.Team;

// PrincipalId is the Guid of the user to whom access is being granted
principal.PrincipalId = new Guid(teamId);

// Create the PrincipalAccess Object
PrincipalAccess principalAccess = new PrincipalAccess();

// Set the PrincipalAccess Object’s Properties
principalAccess.Principal = principal;

// Gives the principal access to read
principalAccess.AccessMask = AccessRights.ReadAccess;

// Create the Target Object for the Request
TargetOwnedContact  target = new TargetOwnedContact();

// EntityId is the Guid of the contact access is being granted to
target.EntityId = new Guid(recordId);

// Create the Request Object
GrantAccessRequest grant = new GrantAccessRequest();

// Set the Request Object’s properties
grant.PrincipalAccess = principalAccess;
grant.Target = target;

// Execute the Request
GrantAccessResponse granted = (GrantAccessResponse)service.Execute(grant);
}
private voidClearField()
{
txtFirstName.Text=””;
txtLastName.Text=””;
txtMobileNo.Text=””;
txtEmailId.Text=””;
}
}
} 

Hope its help you 🙂

Populate Lookup value on selection of another Lookup


 Step 1.


Step 2.

Step 3.

Let me explain the scenario…

Suppose we have City Lookup on Lead entity and we want to populate Region (Lookup), State (Lookup) and Zone (Lookup) on selection of particular City from City Lookup. You need to write below code on OnChange event of City Lookup field.

if(crmForm.all.new_cityid.DataValue !=null)

{

    var citylookupValues = crmForm.all.new_cityid.DataValue;

    if(citylookupValues[0] !=null)

    {

        var cityID = citylookupValues[0].id;

        var regionID = GetAttributeValueFromID(“new_city”, cityID , “new_regionid”);

        var stateID = GetAttributeValueFromID(“new_city”, cityID , “new_stateid”);

        var zoneID = GetAttributeValueFromID(“new_region”, regionID , “new_zoneid”);   

        if(regionID != null)

        {

            //Create an array to set as the DataValue for the lookup control.

            var regionlookupData = new Array();

            //Create an Object add to the array.

            var regionlookupItem= new Object();

            //Set the id, typename, and name properties to the object.

            regionlookupItem.id = regionID;

            regionlookupItem.typename = ‘new_region’;

            regionlookupItem.name = regionName;

            // Add the object to the array.

            regionlookupData[0] = regionlookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_regionid.DataValue = regionlookupData;

            crmForm.all.new_regionid.ForceSubmit = true;

 

        }

        if(stateID != null)

        {

            //Create an array to set as the DataValue for the lookup control.

            var statelookupData = new Array();

            //Create an Object add to the array.

            var statelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

            statelookupItem.id = stateID;

            statelookupItem.typename = ‘new_state’;

            statelookupItem.name = stateName;

            // Add the object to the array.

            statelookupData[0] = statelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_stateid.DataValue = statelookupData;

            crmForm.all.new_stateid.ForceSubmit = true;

        }

        if(zoneID != null)

        {

            var zoneName = GetAttributeValueFromID(“new_zone”, zoneID, “new_name”);

            //Create an array to set as the DataValue for the lookup control.

            var zonelookupData = new Array();

            //Create an Object add to the array.

            var zonelookupItem = new Object();

            //Set the id, typename, and name properties to the object.

            zonelookupItem.id = zoneID;

            zonelookupItem.typename = ‘new_zone’;

            zonelookupItem.name = zoneName;

            // Add the object to the array.

            zonelookupData[0] = zonelookupItem;

            // Set the value of the lookup field to the value of the array.

            crmForm.all.new_zoneid.DataValue = zonelookupData;

            crmForm.all.new_zoneid.ForceSubmit = true;

        }

     }

}

else

{

     crmForm.all.new_regionid.DataValue = null;

    crmForm.all.new_stateid.DataValue = null;

    crmForm.all.new_zoneid.DataValue = null;

}

 

function  GetAttributeValueFromID(sEntityName, sGUID, sAttributeName)

{

    /*

    * sEntityName: the name of the CRM entity (account, etc.)

    * whose attribute value wish to look up

    * sGUID: string representation of the unique identifier of the specific object whose attrbuite value we wish to look up

    * sAttributeName – the schema name of the attribute whose value we wish returned

    */

 

    var sXml = “”;

    //var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);

    var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP.6.0”);

 

    //var serverurl = “http://10.10.40.50:5555&#8221;;

    var serverurl = “”;

 

    //set up the SOAP message

    sXml += “<?xml version=\”1.0\” encoding=\”utf-8\” ?>”;

    sXml += “<soap:Envelope xmlns:soap=\”http://schemas.xmlsoap.org/soap/envelope/\””

    sXml += ” xmlns:xsi=\”http://www.w3.org/2001/XMLSchema-instance\””

    sXml += ” xmlns:xsd=\”http://www.w3.org/2001/XMLSchema\”>”;

    sXml += “<soap:Body>”;

    sXml += “<entityName xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” +

    sEntityName + “</entityName>”;

    sXml += “<id xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” +

    sGUID + “</id>”;

    sXml += “<columnSet xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\””

    sXml += ” xmlns:q=\”http://schemas.microsoft.com/crm/2006/Query\””

    sXml += ” xsi:type=\”q:ColumnSet\”><q:Attributes><q:Attribute>” +

    sAttributeName + “</q:Attribute></q:Attributes></columnSet>”;

    sXml += “</soap:Body>”;

    sXml += “</soap:Envelope>”;

 

    // send the message to the CRM Web service

    oXmlHttp.Open(“POST”, serverurl +

    “/MsCrmServices/2006/CrmService.asmx”,false);

    oXmlHttp.setRequestHeader(“SOAPAction”,

    “http://schemas.microsoft.com/crm/2006/WebServices/Retrieve&#8221;);

    oXmlHttp.setRequestHeader(“Content-Type”, “text/xml; charset=utf-8”);

    oXmlHttp.setRequestHeader(“Content-Length”, sXml.length);

    oXmlHttp.send(sXml);

 

    // retrieve response and find attribute value

    //var result = oXmlHttp.responseXML.selectSingleNode(“//” + sAttributeName);

    var result = oXmlHttp.responseXML.selectSingleNode(“//*[local-name()=\””+  sAttributeName +”\”]”);

    if (result == null)

    {

    return “”;

    }

    else

    return result.text;

}

Populate lookup value on selection of another lookup


I had client requirement that on the selection of City (lookup), Region and Sub Region should be populated automatically which is read only field. To achieve this we mapped the city with region (lookup) and sub region (lookup) on the city entity. After writing below code I was getting following error.

There was an error with this field’s customized event.

Field:new_cityid

Event:onchange

Error:’ new_subregionid.value ‘ is null or not an object

I solved the issue with help of this link and answer posted by Adi Katz .

“The keyValues are only available when you use the lookup dialog. The form assistant does not contain the columns that are retrieved by the lookup and this is why the items array is empty.”

For details please visit below link.

http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/ad9b5b22-da6b-4f20-9fd4-b7e46d9a7556

After this solution I added Sub Region field to lookup dialog (lookup view) and this solve my issue.

Put below code on OnChange of City Lookup field.

/*****Auto Populate SubRegion on Selection of City field******************/

if (crmForm.all.new_cityid.DataValue==null)

{
crmForm.all.new_subregionid.DataValue = null;
}

else

{

var lookup_guid;

var lookup_name;

var lookup_type;

var lookup_typename;

var lookupItem = new Array;

lookupItem = crmForm.all.new_cityid.DataValue;

lookup_guid=lookupItem[0].id;

lookup_name=lookupItem[0].name;

lookup_type=lookupItem[0].type;

lookup_typename=lookupItem[0].typename;

var subRegionName;

if(crmForm.all.new_cityid.items != null)

{
var lookupValues = crmForm.all.new_cityid.items[0].keyValues;
subRegionName = lookupValues.new_subregionid.value? lookupValues.new_subregionid.value : null;

}
else
{
subRegionName = null;

}

var subregionidvalue = GetAttributeValueFromID(lookup_typename, lookup_guid, ‘new_subregionid’);

if(subregionidvalue != null)

{
var subregionlookupData = new Array();

//Create an Object add to the array.

var subregionlookupItem = new Object();

//Set the id, typename, and name properties to the object.

subregionlookupItem.id = subregionidvalue;

regionlookupItem.typename = ‘new_subregion’;

regionlookupItem.name = subRegionName ;

// Add the object to the array.

subregionlookupData[0] = subregionlookupItem;

// Set the value of the lookup field to the value of the array.

crmForm.all.new_subregionid.DataValue = subregionlookupData;

crmForm.all.new_subregionid.ForceSubmit = true;

}

function GetAttributeValueFromID(sEntityName, sGUID, sAttributeName)

{

var sXml = “”;

var oXmlHttp = new ActiveXObject(“Msxml2.XMLHTTP.6.0”);

var serverurl = “”;

//set up the SOAP message

sXml += “<?xml version=\”1.0\” encoding=\”utf-8\” ?>”;

sXml += “<soap:Envelope xmlns:soap=\”http://schemas.xmlsoap.org/soap/envelope/\””;

sXml += ” xmlns:xsi=\”http://www.w3.org/2001/XMLSchema-instance\””;

sXml += ” xmlns:xsd=\”http://www.w3.org/2001/XMLSchema\”>”;

sXml += “<soap:Body>”;

sXml += “<entityName xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” + sEntityName +

“</entityName>”;

sXml += “<id xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\”>” + sGUID + “</id>”;

sXml += “<columnSet xmlns=\”http://schemas.microsoft.com/crm/2006/WebServices\””;

sXml += ” xmlns:q=\”http://schemas.microsoft.com/crm/2006/Query\””;

sXml += ” xsi:type=\”q:ColumnSet\”><q:Attributes><q:Attribute>” + sAttributeName +

“</q:Attribute></q:Attributes></columnSet>”;

sXml += “</soap:Body>”;

sXml += “</soap:Envelope>”;

// send the message to the CRM Web service

oXmlHttp.open(“POST”, serverurl + “/MsCrmServices/2006/CrmService.asmx”,false);

oXmlHttp.setRequestHeader(“SOAPAction”,”http://schemas.microsoft.com/crm/2006/WebServices/Retrieve&#8221;);

oXmlHttp.setRequestHeader(“Content-Type”, “text/xml;charset=utf-8”);

oXmlHttp.setRequestHeader(“Content-Length”, sXml.length);

oXmlHttp.send(sXml);

// retrieve response and find attribute value

// retrieve the given attribute name in any XML namespace

var result = oXmlHttp.responseXML.selectSingleNode(“//*[local-name()=\”” +  sAttributeName +”\”]”);

if (result == null)

{

return “”;

}

else

{

return result.text;

}

}

}

%d bloggers like this: