Thursday, April 9, 2009

Accessing and Controlling the CrmForm from an iframe.

If you write custom web applications in iframes that depend on the data in the parent form, it is important to run on up to date information to avoid user confusion.

Important! This requires that the Restrict cross-frame scripting box for your iframe is NOT checked.

image

Accessing attribute values on the Parent Form can be done simply by adding a parent.document in front of your normal attribute names. This gets you the values currently on the form, but doesn't guarantee those values have been saved.

var myAttributeValue = parent.document.crmForm.all.new_attribute.DataValue;

Parent Form Save "if modified" This is a nice method to call because if there are no modified values on the form it won't do anything and your application can continue on it's merry way.

parent.document.crmForm.Save();

Force a Parent Save Sometimes you want to force a save so that a Plug-in is called to do some additional calculations even though no attributes have been modified on your current form. The recalculate on the Opportunity, Quote, Order, and Invoice forms is a good example.

Note: The SubmitCrmForm method is not a MS supported method, but it hasn't changed in the last couple CRM revisions.

SubmitCRMForm( Mode, Validate, ForceSubmit, closeWindow)

Modes:
1 = Save, 2 = SaveAndClose, 7 = Send,
58 = SaveAsCompleted, 59 = SaveAndNew

Example: In this example I am forcing a save so that a plug-in is called on the Pre Update for the quote to create a new total value from the quote details that were filled in when the Quote was created from an Opportunity. These new fields were  mapped between the detail products see Mapping Note below. The iframe contains a button to do something that requires all of the data on the quote be up to date.

function RecalculateQuote() 
{ 
   if ( parent.document.crmForm.all.new_totalamount.DataValue == null)
   {    
    parent.document.crmForm.SubmitCrmForm(1, true, true, false);   
    return false;      
    } 
    
    parent.document.crmForm.Save();
}

The above JavaScript is made to work with an OnClientClick so that a return false will not generate a postback.

Why do we need a return false option?  If the validation fails, a message is generated for the user, the save is not performed, and you do not want your action to run.

The data has already been filled in, then the crmFrom.Save() will check to make sure that any modified fields on the form have been saved.

<asp:Button ID="RunMyNeatFeature" CssClass="button" runat="server" Text="Go" OnClick="RunMyNeatFeature_Click"
OnClientClick="javascript:return RecalculateQuote();"/>

For the button the OnClick will PostBack and run the functionality I care about only if the RecalculateQuote() is not false.

This safeguards the user from running the functionality with different data than what is on the screen when they press the "Go" button.

Mapping Note: For mapping details open SQL Management Studio and look at the EntityMapBase table to find the EntityMapId that has the SourceEntityName and TargetEntityName that you are interested in. Add your guid to the end of the URL below and it will bring up a form to map attributes between the Source and Target Entities.

http://yourcrmservername:5555//tools/systemcustomization/relationships/mappings/mappinglist.aspx?mappingId=

Sunday, March 15, 2009

Techniques for Driving MS CRM Email Templates

The email templates in MS CRM can be leveraged as a powerful building block when generating emails programmatically.

Tips:

  • Generate your HTML in another editor and then paste it into the template editor to add data slugs.
  • Associate your template with the entity that you want the most information from.
  • Use Template Naming conventions that organize things and make programmatic template selection easier.

For an example lets say that we have product specific Quote Letters.

Using my helper method from a previous blog article, grab an email template matching a specific name based on the product.

// Get appropriate Template
BusinessEntityCollection templates = 
   h.GetAllEntitieswithFilter(EntityName.template.ToString(), new[] { "templateid" }, new[]{"title"}, new[]{emailTemplateTitle});

Then create a new InstantiateTemplateRequest using the template id and point it at an entity with the information that you want merged in. This must be the same type that you associated your template with when you created it.

var instTemplate = new InstantiateTemplateRequest
     {
         TemplateId = thisTemplate.templateid.Value,
         ObjectId = quoteId,
         ObjectType = EntityName.quote.ToString()
     };


// Execute the request to create an email message from the template.
var instTemplateResponse = (InstantiateTemplateResponse)h.service.Execute(instTemplate);

var newEmail = (email)instTemplateResponse.BusinessEntityCollection.BusinessEntities[0];

The result of the InstantiateTemplateResponse is an email entity collection. For this example we just have one email.

From here you can regard the email to a completely different entity if you want. It is only important that the ObjectId and ObjectType be set for the merge process. After that is complete this is just another email with a bunch of fields pre-filled. Now you can have your way with it like any other email that you created from scratch. This is critical to making the best use of email templates.

Additional Merging
If you are calculating other numbers or pulling information from another data source outside of CRM, there is no reason to limit merging to what can be represented as data slugs.

In this example I am using putting additional information into the email body with a simple string replace using an agreed upon naming convention to represent additional merge fields.

// If template had #EmbedLicense# in body replace it with the license information
newEmail.description = newEmail.description.Replace("#EmbedLicense#", embedFile);

From here you can add attachments as shown here.

Proofing before Email is Sent
Another useful thing to do if you are doing this in a web application or a client Winform application is save the email and then open it in a new window for final review before it is sent. To do that generate a URL like the following with your orgname and email id passed in. You can get the CRM server base URL from the registry as shown here which you need for your web service reference, and then use the following: CrmServerBaseUrl = CrmServiceUrl.Substring(0, CrmServiceUrl.ToLower().IndexOf("mscrmservices"));

 // Open newly created email activity at this Url.
var emailUrl = h.CrmServerBaseUrl + "/"+orgname+"/activities/email/edit.aspx?id={" + emailId + "}";

From a WinForm application you can pop a CRM screen up like this.

For a web application register some JavaScript in the code behind that sets the value of the new email's URL.

 // Sets Javascript variables to envoke Window Open to new Explorer Window with body onload event
const string SETQUERYSTRING_SCRIPT = "Email_String";

if (!Page.ClientScript.IsClientScriptBlockRegistered(SETQUERYSTRING_SCRIPT))
{
   Page.ClientScript.RegisterClientScriptBlock(GetType(), SETQUERYSTRING_SCRIPT, string.Format(@"<script language=""javascript"">emailRecordUrl = '{0}';</script>", emailUrl));
}

Then in the aspx file use the following JavaScript code to open the new window. Call the script from the onload of the body.

<script type="text/javascript"> var emailRecordUrl = ""; function UpdateCRMFormGenerateEmail() { if (emailRecordUrl != "") { window.open( emailRecordUrl,
"_blank", "toolbar=no,scrollbars=yes,resizable=yes"); emailRecordUrl = ""; } } </script> </head> <body onload="UpdateCRMFormGenerateEmail();">

Wednesday, February 25, 2009

MS CRM 4.0 Plug-in Stages, Pipelines and Execution Modes

I've found a lot of contradictory information and misinformation about what you can and can't do inside of a plugin depending on how you are calling it, and when you should call each one, so I hope this will help.

Stage of Execution:

Pre-Stage: (synchronous) called before the write to the database.

The main reasons to use a Pre-Stage of Execution are synchronous in nature:

  • Modify data before it is written to the database.
  • Abort the action being taken
  • Server Side Validity checking

Post-Stage: (synchronous or asynchronous)

Use the Post-Stage of Execution whenever you don't need to use Pre-Stage.

If you don't want the user to wait for the process to finish and there is no race condition use asynchronous.

Triggering Pipeline:

The triggering pipeline is a little less obvious in nature and has an impact on what functionality that you can use in your plugin.

Parent Pipeline: This is the pipeline that is the most common and there are no restrictions imposed in a parent pipeline.

Child Pipeline: This is the pipeline that causes the most confusion and there are limitations that vary with Stage and Execution Mode.

Sometimes a child pipeline is required to trap the event you need, and sometimes you need to trap both the parent and child pipeline for the same entity, message and stage.

Example: Change the quotenumber in the Pre-Stage for the Create of a Quote.

The quotenumber is a field that the CRM web service will not allow you to change after it is written to the database so you need to use the Pre-Stage and modify the context Entity before the end of the Execute method as shown below.

var entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target];

// . . . retrieve data to populate number . . .

// Set value before it is written to the database

if( entity.Properties.Contains(numberField))
{
    entity.Properties.Remove(numberField);
}

var prop = new StringProperty(numberField, newNumber);
entity.Properties.Add(prop);

So far so good. This will work in any Pre-Create pipeline!

You can create a Quote in a few ways.

  • Sales -> Quotes -> New
  • (open an Account) -> Quotes -> New Quote
  • Sales -> Opportunities (open an opportunity) -> Quotes -> New Quote

Do you think that Creating a Quote always happens in the same pipeline?

Since you are an efficient plugin developer and are using the ICrmService and dynamic entities to access CRM data because it is pre-authenticated and fast. You retrieve some information to help create the number.

ICrmService service = context.CreateCrmService(true);
retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);

You register your plugin using the handy plugin registration tool for the Quote entity with the following settings:

  • Create
  • Pre Stage
  • Synchronous
  • Parent Pipeline

 CreateQuoteParent

You create your Quote from Sales -> Quotes -> New and it works!

However, in many business processes the user will create a Quote from an opportunity so it will inherit opportunityproduct information.

Now you create your quote from Sales -> Opportunities (open an opportunity) -> Quotes -> New Quote and for some reason your plugin did not fire. That is because this quote was created in a child pipeline.

The entire QOI chain also occurs in a child pipeline. If you create an order from a quote or invoice from an order it is happening in a child pipeline. There are other places that this occurs as well like creation of an account or contact from a lead.

You are in a child pipeline, now what ?

The first thing that you might try is to take your existing plugin and register it against the child pipeline, but it won't work. The ICrmService is not available to you in a child pipeline.

If you downloaded the plug-in template for CRM, you have probably seen the following method, which is what you need to use in a child pipeline.

/// <summary>
/// Creates a CrmService proxy for plug-ins that execute in the child pipeline.
/// </summary>
/// <param name="context">The execution context that was passed to the plug-ins Execute method.</param>
/// <param name="flag">Set to True to use impersontation.</param>
/// <returns>A CrmServce instance.</returns>
private static CrmService CreateCrmService(IPluginExecutionContext context, Boolean flag)
{
    var authToken = new CrmAuthenticationToken { AuthenticationType = 0, OrganizationName = context.OrganizationName, CallerId = (flag ? context.UserId : context.InitiatingUserId) };

    var corToken = new CorrelationToken { CorrelationId = context.CorrelationId, CorrelationUpdatedTime = context.CorrelationUpdatedTime, Depth = context.Depth };

    var regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM", false);

    var service = new CrmService
    {
        CrmAuthenticationTokenValue = authToken,
        UseDefaultCredentials = true,
        Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/crmservice.asmx"),
        CorrelationTokenValue = corToken
    };

    return service;
}

You may find another method called GetCrmProxyUsingEndpointUrlInChildPipeline. It is essentially the same.

There is a comment in the plugin template that doesn't tell the whole story.

// For a plug-in running in the child pipeline, use this statement.
// CrmService crmService = CreateCrmService(context, true);

What it doesn't mention is that what you are allowed to do with that service depends on what your execution mode is.

Hard Coded Restrictions:

A CrmService running Synchronously in a child pipeline is limited to the following:

  • Create
  • Delete
  • Update
  • RetrieveExchangeRate

However a child plugin running in Asynchronous Execution Mode is not limited this way.

Those 4 allowed actions are hard coded by MS whenever the plugin is executed inside a transaction, and it appears that all synchronous child pipeline events occur inside a transaction.

However you can do a query in child pipeline if it is registered as asynchronous.

In review:

  • Use ICrmService for all parent pipelines when at all possible.
  • Use CrmService for child pipelines in asynchronous execution mode.
  • There is very limited functionality allowed with CrmService for any plugin registered in a synchronous child pipeline
  • Querying CRM data in a plug-in registered as a synchronous Pre Create in a child process is currently very unsupported. (ie. direct SQL access)

Sunday, February 8, 2009

Dynamic Entity and Entity query helper methods

If you do much MS CRM development you will find that you are constantly querying for things. These are a couple helper methods that I have found come in handy.

There are some subtle differences between them.

Querying for Collections

The following 2 methods retrieve any entity, filtering on any attribute(s), ordering on any attribute(s), and returning any number of specified attributes. The only real restraint is that they are hard coded to anding the filters together and only comparing filters with an Equal condition operator.

BusinessEntityCollection opportunityCollection = webservicehelper.GetAllEntitieswithFiltersOrdered(
EntityName.opportunity.ToString(),
new[]  "opportunityid", "name", "statecode" }, 
new[] { "customerid","statecode" },
new[] { thisAccount.accountid.Value.ToString(),"Open" },
new[] {"createdon"},
new[] {false});

BusinessEntityCollection opportunityCollection
= PluginHelper.GetDynamicEntitiesWithFiltersOrdered( EntityName.opportunity.ToString(),
new[] { "opportunityid", "name", "statecode" },
new[] { "customerid" },
new[] { accountId.ToString() },
new[] {"createdon"},
new[] {false}, 
service);

The following Helper methods do the exact same thing for strongly typed entities and then dynamic entities. They both return a BusinessEntityCollection but notice the differences in how they are implemented.

The first is for the strongly typed Entity.

public BusinessEntityCollection GetAllEntitieswithFiltersOrdered(string entity, string[] attributes, string[] fields, string[] values, string[] orderfields, bool[] orderAscending)
{

    var cols = new ColumnSet { Attributes = attributes };

    var conditions = new ConditionExpression[fields.Length];

    for (int i = 0; i < fields.Length; i++)
    {
        var condition = new ConditionExpression
        {
            AttributeName = fields[i],
            Operator = ConditionOperator.Equal,
            Values = new[] { values[i] }
        };

        conditions[i] = condition;
    }

    var filter = new FilterExpression
    {
        FilterOperator = LogicalOperator.And,
        Conditions = conditions
    };

    var orderArray = new OrderExpression[orderfields.Length];

    for (int i = 0; i < orderfields.Length; i++)
    {
        var thisOrder = new OrderExpression
        {
            AttributeName = orderfields[i],
            OrderType = (orderAscending[i] ? OrderType.Ascending : OrderType.Descending)
        };

        orderArray[i] = thisOrder;
    }


    var query = new QueryExpression
    {
        EntityName = entity,
        ColumnSet = cols,
        Criteria = filter,
        Orders = orderArray
    };

    try
    {
        return service.RetrieveMultiple(query);
    }

    catch (SoapException ex)
        var thisOrder = new OrderExpression
        {
            AttributeName = orderfields[i],
            OrderType = (orderAscending[i] ? OrderType.Ascending : OrderType.Descending)
        };

        orderArray[i] = thisOrder;
    }


    var query = new QueryExpression
    {
        EntityName = entity,
        ColumnSet = cols,
        Criteria = filter,
        Orders = orderArray
    };

    try
    {
        return service.RetrieveMultiple(query);
    }

    catch (SoapException ex)
    {
        emailNotifications.sendExceptionMessage(service.Url, " - GetAllEntitieswithFiltersOrdered FAILED:", errorEmails, ex,
            "<br/><br/>Entity: " + query.EntityName);
        throw;
    }
}
    {
        emailNotifications.sendExceptionMessage(service.Url, " - GetAllEntitieswithFiltersOrdered FAILED:", errorEmails, ex,
            "<br/><br/>Entity: " + query.EntityName);
        throw;
    }
}

The second is for a Dynamic Entity in a Plug-in.

public static BusinessEntityCollection GetDynamicEntitiesWithFiltersOrdered(string entityName, string[] attributes, string[] fields, string[] values, string[] orderfields, bool[] orderAscending, ICrmService serv)
{
    try
    {
        var filters = new FilterExpression { FilterOperator = LogicalOperator.And };

        for (int i = 0; i < fields.Length; i++)
        {
            var condition = new ConditionExpression
            {
                AttributeName = fields[i],
                Operator = ConditionOperator.Equal,
                Values = new[] { values[i] }
            };

            filters.Conditions.Add(condition);
        }
        
        var query = new QueryExpression
        {
            EntityName = entityName,
            ColumnSet = new ColumnSet(attributes),
            Criteria = filters
        };

        for (int i = 0; i < fields.Length; i++)
        {
            var oneExpression = new OrderExpression
                 {
                     AttributeName = orderfields[i],
                     OrderType = (orderAscending[i] ? OrderType.Ascending : OrderType.Descending)
                 };

            query.Orders.Add(oneExpression);
        }

        var retrieve = new RetrieveMultipleRequest { Query = query, ReturnDynamicEntities = true };

        var retrieved = (RetrieveMultipleResponse)serv.Execute(retrieve);

        return retrieved.BusinessEntityCollection;
    }

    catch (SoapException ex)
    {
        throw new InvalidPluginExecutionException(
             String.Format("An error occurred in GetDynamicEntitiesWithFilters plug-in. {0}", ex.Detail.InnerText), ex);
    }

    catch (Exception ex)
    {
        throw new InvalidPluginExecutionException(
           String.Format("An error occurred in GetDynamicEntitiesWithFilters plug-in. {0} - trace - {1} -  source - {2}", ex.Message, ex.StackTrace, ex.Source), ex);
    }
}

One of the largest differences between querying for these two types of collections is that you are assigning a complete arrays in one and adding to the other.

Monday, January 19, 2009

Case Responsible Contact To Email and other Activities

A typical customer request is for email created from a Case to default to send to the Responsible Contact instead of its default behavior which is to send it to the Customer.

Since the Responsible Contact isn't even on the Case form by default and a customer could be a contact, MS chose this default behavior. However most of my installations to date have an Account as the Customer and one of many Contacts related to that Account as a Responsible Contact.

This is actually something very easy to change.

Please Note: This is an unsupported modification, and any patch could overwrite this.

There is a JavaScript file, cases.js, in the following folder.

C:\Program Files\Microsoft Dynamics CRM Server\CRMWeb\_static\CS\cases

It contains a function called locAddActTo that fills the To: activity party variables that are sent in the QueryString to the activity like the URL below.

http://crmserver1:5555/MicrosoftCRM/activities/email/edit.aspx?
pId={E0F2E676-7FE2-DD11-9AE8-0003FF517B20}
&pType=112
&pName=CaseTitleGoesHere
&partyid={0EDF3D7E-E3E0-DD11-A5F9-0003FF517B20}
&partytype=1
&partyname=AccountNameGoesHere
&partyaddressused=&contactInfo=

What we care about are the partyid, partytype and partyname arguments.

function locAddActTo(iActivityType, sContentId)
{
var sParentId   = null;
var sParentType = null;
var sPartyId   = null;
var sPartyType = null;
var sPartyName = null;
var sPartyLocation = null;


sParentId   = crmFormSubmit.crmFormSubmitId.value;
sParentType = crmFormSubmit.crmFormSubmitObjectType.value;


if (iActivityType != Task)
{
var customerId = crmForm.all.customerid.DataValue;
if (!IsNull(customerId))
{
if (!IsNull(customerId[0]))
{
sPartyId   = customerId[0].id;
sPartyType = customerId[0].type;
}
}
sPartyName = crmForm.customerid.parentElement.previousSibling.innerText;

sPartyLocation = "";
}

As you can see this information is being pulled from the case form customer field crmForm.all.customerid.DataValue

So all we have to do is change this to crmForm.all.responsiblecontactid.DataValue

and change the sPartyName assignment.

sPartyName = crmForm.customerid.parentElement.previousSibling.innerText;
to
sPartyName = customerId[0].name;

You can just replace the above function with the one below if you would like.

function locAddActTo(iActivityType, sContentId)
{
var sParentId   = null;
var sParentType = null;
var sPartyId   = null;
var sPartyType = null;
var sPartyName = null;
var sPartyLocation = null;


sParentId   = crmFormSubmit.crmFormSubmitId.value;
sParentType = crmFormSubmit.crmFormSubmitObjectType.value;


if (iActivityType != Task)
{
var customerId = crmForm.all.responsiblecontactid.DataValue;
if (!IsNull(customerId))
{
if (!IsNull(customerId[0]))
{
sPartyId   = customerId[0].id;
sPartyType = customerId[0].type;
sPartyName = customerId[0].name;
}
}


sPartyLocation = "";
}

After you have saved the change, run  iisreset to flush the cache.

That's it.

Sunday, January 18, 2009

CRM 4.0 Custom Workflows

Custom Workflows in MS CRM 4.0 are very simple to deploy and are pretty simple to create especially if you are familiar with Plugin-in development. 

Before you can create a workflow you need to have the Workflow Extensions installed. This is more of a concern if you are running VS2005. If you are running VS 2008 SP1, you should have everything you need already.

If you have an assembly that you are already deploying for plug-ins you can even add a workflow to that assembly so that you have fewer deployment assemblies.

The following custom workflow was created for a customer who wanted to have a matching customer sales relationship created for an account whenever an opportunity role was assigned to a contact.

namespace OneCRMPro { // In the workflow editor // "OneCRMPro" is going to show up at the bottom of the Add Step pick list // "Create CustomerRelationship" will show up as item off of OneCRMPro. [PersistOnClose] [CrmWorkflowActivity("Create CustomerRelationship", "OneCRMPro")] public partial class CreateCustomerRelationship : SequenceActivity { // These DependencyProperty entries will show up in the Set Properties editor public static DependencyProperty RoleProperty = DependencyProperty.Register("Role", typeof(Lookup), typeof(CreateCustomerRelationship)); [CrmInput("Sales Role")] [CrmReferenceTarget("relationshiprole")] public Lookup Role { get { return (Lookup)GetValue(RoleProperty); } set { SetValue(RoleProperty, value); } } public static DependencyProperty CustomerProperty = DependencyProperty.Register("Customer", typeof(Lookup), typeof(CreateCustomerRelationship)); [CrmInput("Customer Contact")] [CrmReferenceTarget("contact")] public Lookup Customer { get { return (Lookup)GetValue(CustomerProperty); } set { SetValue(CustomerProperty, value); } } // End Set Properties /// <summary> /// Execute is called when the custom workflow is invoked /// </summary> /// <param name="executionContext"></param> /// <returns></returns> protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext) { //Get a workflow context var contextService = executionContext.GetService(typeof(IContextService)) as IContextService; var workflowContext = contextService.Context; CreateRole(workflowContext); return ActivityExecutionStatus.Closed; } /// <summary> /// Create a matching sales customer relationship role /// </summary> /// <param name="context"></param> private void CreateRole(IWorkflowContext context) { try { // Get Guids of Customer and RelationshipRole Guid contactId = Customer.Value; Guid salesRoleId = Role.Value; // get a local service ICrmService service = context.CreateCrmService(true); // Grab the contact involved var cols = new ColumnSet(new [] {"parentcustomerid"}); var thisContact = (contact)service.Retrieve(EntityName.contact.ToString(), contactId, cols); // Create a cooresponding customer relationship var role = new customerrelationship { customerid = thisContact.parentcustomerid, partnerid = CrmTypes.CreateCustomer(EntityName.contact.ToString(), contactId), partnerroleid = CrmTypes.CreateLookup(EntityName.relationshiprole.ToString(), salesRoleId) }; service.Create(role); } catch (SoapException) { // Handle error } catch (Exception) { // Handle error } } } }

Before you can use your workflow it needs to be strongly signed and registered.  Its assembly is registered in the same way as a plugin, but it doesn't require registering it at the entity or event level. If you don't have the plugin Registration Tool you can find it here. Plugin Deployment Tool

image

When you create a new Workflow you can now select this custom Workflow when you "Add Step" and pick the following at the bottom of the list.

OneCRMPro   >   Create CustomerRelationship

Now when you "Set Properties", you will see below how the DependencyProperty values will show up below.

The CrmInput keyword specifies the Property Name and the CrmReferenceTarget keyword specifies the expected attribute type to be mapped.

image

That's about it. Publish your workflow and try it out!

Saturday, December 20, 2008

MS CRM 4.0 Filtered Lookups

I just finished implementing a number of filtered lookups with Michael Höhne's Stunnware Filtered Lookup 4.0. Like most developers I have to think seriously about whether I want to build something vs. pay for someone else's work.

There has been a lot of work put into this product since its introduction with CRM 3.0. The 4.0 release seems pretty well sorted and really makes creating filtered lookups an easy task to accomplish. Supporting the Outlook client, multiple languages, multi-tenancy, and IFD makes this a much better solution then most(probably all) of us would take the time to build on our own.

Filtered Lookups have been reinvented far too many times and become maintenance issues for many upgrading from CRM 3.0 to CRM 4.0. I would rather not have to dig through another guy's failed attempt at this functionality in the future. I personally believe MS should pull this functionality into its product, but barring that, I think using a product like this is the best way to go.

I'm currently using it for a growing list of filtered Lookups for one my customers.  This includes some pretty standard lookups like the Account: Primary Contact Lookup, the Case: Responsible Contact, and the Email To:, CC:, and BCC: fields, as well as some for custom fields.

What is typically involved in making a filtered lookup with this tool is the following:

  1. Settings -> Filtered Lookup: Create a Retrieve Multiple Queries entity
    • This may involve using the Fetch Wizard to generate the query.
  2. Settings -> Filtered Lookup: Create a Single-View Lookup entity
  3. Settings -> Customizations: Add JavaScript to your entity's OnLoad event.

Here is a simple example:

I needed a filtered list for Reseller Accounts on an opportunity.

image

So I created a new Retrieve Multiple Query entity,image

copied the Query from the Active Accounts example and added a filter for an industrycode picklist value of 21,image

created a Single-View Lookup using the Query above,image

setup the columns for that Lookup,image 

set the Labels to English,image

added this JavaScript to my Opportunity's OnLoad Event. Published the opportunity and I was done.

SW_IS_LICENSED_USER = false; try
{ var httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); httpRequest.open("GET", prependOrgName("/isv/stunnware.com/cld4/cld4.aspx?orgname=" + ORG_UNIQUE_NAME), false); httpRequest.send(null); eval(httpRequest.responseText); } catch(e) { } if (SW_IS_LICENSED_USER) { var resellerAccountLookup = new SwSingleLookup("new_resellerid"); if (resellerAccountLookup.existsOnForm()) { resellerAccountLookup.setLookupClass("ResellerAccounts"); } }

All in all that took maybe 10 minutes including testing.

That was a very simple case. The examples in the help file show you how to create the Account: Primary Contact filtered lookup showing only Contacts associated with that Account. Implementing this only required cutting from the example and pasting into the OnLoad Event of the account form. Another example gave me the information I needed to to implement the Case Responsible Contacts Filter where the Filtered Lookup changes when the case's account is changed. This required a little JavaScript added to the OnChange for the customerid as well as the Onload for the form.

The email modifications I made were also very easy to implement as shown in the code that follows. Since the Account is almost always preloaded in the To: field, it was easy to overload the lookups for the target selections to default to the Contacts related to that Account.

SW_IS_LICENSED_USER = false;

try {
    var httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    httpRequest.open("GET", prependOrgName("/isv/stunnware.com/cld4/cld4.aspx?orgname=" + ORG_UNIQUE_NAME), false);
    httpRequest.send(null);
    eval(httpRequest.responseText);
}

catch(e) {
}

if (SW_IS_LICENSED_USER) 
{  
   if ( crmForm.all.to.DataValue != null )
   {
     var accountid =  crmForm.all.to.DataValue[0].id;
    
     var toContactLookup = new SwSingleLookup("to");
     toContactLookup.setParameter("parentcustomerid", accountid);
     toContactLookup.setLookupClass("AssociatedContacts");

     var ccContactLookup = new SwSingleLookup("cc");
     ccContactLookup.setParameter("parentcustomerid", accountid);
     ccContactLookup.setLookupClass("AssociatedContacts");

    var bccContactLookup = new SwSingleLookup("bcc");
    bccContactLookup.setParameter("parentcustomerid", accountid);
    bccContactLookup.setLookupClass("AssociatedContacts");
   }

}

For this instance I am still relying on the Form Assistant if the end user wants to select multiple Contacts for a single field or add a CRM user, which is a rare case for this customer. The Form Assistant is not modified by these lookups in any way.

Understanding 3 Important Lines of Code
There are three important lines of code to that you will use to create a filtered lookup.

1. Create a new lookup to override the existing lookup for specified field on the form. In this case the "to" field on the email form. 

      var toContactLookup = new SwSingleLookup("to");

2. Set a filter parameter that is defined in your Fetch and assign a value. 

      toContactLookup.setParameter("parentcustomerid", accountid);

Below is the Fetch that you can access under settings. Notice the parentcustomerid field in the filter section. You are not limited to a single parameter if you need additional criteria for your filter.

<fetch mapping="logical">
   <entity name="contact">
      <attribute name="emailaddress1" />
      <attribute name="telephone1" />
      <attribute name="fullname" />
      <order attribute="fullname" />
      <filter>
         <condition attribute="statecode" operator="eq" value="0" />
         <condition attribute="parentcustomerid" operator="eq" param="parentcustomerid" />
      </filter>
   </entity>
</fetch>


3. Set the class that you are using.  

     toContactLookup.setLookupClass("AssociatedContacts");

That's it, just save your customization and publish. You now have a working filtered Lookup.

Just the Beginning 
These are some very simple examples, but it is obvious how easily much more complex filters could be. If you are going to create complex Retrieve queries, it is worth downloading the Fetch Wizard as well, which is a really easy way to create the XML needed for the fetches that this tool relies on. The Fetch Wizard is part of the Stunnware Tools 4.0. that are available for download at no charge.

What you will see Under Settings-> Filtered Lookup are the following which will allow you to configure everything but the little bit of JavaScript that you will add to your forms, and there are even tools for tracing your filtered lookups if something isn't working quite right.image

This tool is made for a developer to use, but a person comfortable with customizing CRM and with some JavaScript experience should be able to get by. It requires an installation process that can require you to manually update the XML of your ISV.config and SiteMap, but if you read the instructions, it will all make sense.

If you are playing with the MS CRM 4.0 VPC Image, there is a license for that image that you can download at no cost to test this system out.

If you are considering reinventing this wheel, I seriously recommend trying this solution out first.