{SCIRPTING TIP} Filter Lookup field based on Date Range in Dynamics CRM

Requirement: to filter a Lookup field options dependent on the date field in the current entity.

clip_image001

Description: The lookup field has fields for dates and field should be filtered based on them. For example,

Date on the current entity is 07/10/2015. Lookup field start date should only allow start date in lookup entity to be earlier or equal to 07/10/2015 and end date on the lookup field should be same or after the current entity date 07/10/2015. Only those dates should be allowed to selection.

Code:

This was achieved by adding Pre-filter to the lookup field as below:

function preFilterLookup()

{

      Xrm.Page.getControl(“lookupfieldname”).addPreSearch(function ()

      {

            var dateObject = Xrm.Page.getAttribute(“datefieldname”).getValue();

            var editedDate = yyyymmdd(dateObject);

           

            if (dateObject != null)

            {

                  // Filter the fetchxml by date range

                  fetchXml = “<filter type=’and’><condition attribute=’startdatefieldname’ operator=’on-or-before’ value='” + editedDate +

                        “‘ /><condition attribute=’enddatefieldname’ operator=’on-or-after’ value='” + editedDate +

                        “‘ /></filter>”;

                  // Apply the filter to the field

                  Xrm.Page.getControl(“lookupfieldname”).addCustomFilter(fetchXml);

            }

      });

}

Hope it helps and Happy CRMing!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s