Using addPreSearch with an asynchronous call to create the filter

Hello everyone;

Recently while answering questions on the Microsoft Forums a question was raised about how to filter the query of an addPreSearch lookup event based on values in a relationship.

The scenario we’re looking at is we have a table called “Collection”.  This table has a M:1 relationship with director and it has a 1:M relationship with a table called Movies. The Movies table has a M:1 relationship with the director table. 

The requirement is to have the Director lookup prefilter and only show a list of directors from movies related to the collection. In the picture below when we click on the Directors lookup we would expect to see 6 directors selectable based on the associated movies.

Collection Table Form

How we go about this is using three specific methods:

The addPreSearch allows you to specify what event will fire when a user clicks on the lookup. In this function you to pass in a function and it must then add a custom filter.
– formContext.getControl(arg).addPreSearch(myFunction)

The addCustomFilter function is an event that executes when you click on the lookup field and executes the filter or fetchxml filter passed into it.
– formContext.getControl(arg).addCustomFilter(filter, entityLogicaName)

The Xrm.WebApi.retrieveMultipleRecords is a method that allows us to retrieve multiple records but this is an asynchronous call which causes the issue of building the proper filter in this scenario.

What we need to do to achieve the goal of filtering the directors lookup based on the related movies to the collection are the following steps:

  1. Execute a Xrm.WebApi.retrieveMultipleRecords allowing us to build the filter statement with the proper directors.
  2. Once the filter statement has been completed we need to call the addCustomerFilter function.
  3. We need to have our function that calls the addPreSearch when the lookup event is changed using the filter statement.

Let’s dive into the code. I’ll post my full web resource file and we can discuss it in more detail below. This web resource file can also be found on github at https://github.com/jasoncosman/Collections/blob/master/jcmvp_collection.js.

 

    OnLoad: function (executionContext) {
        JCMVP.Collection.Form.getCollectionsMovies(executionContext);
    },


    filterMovieDirectors: function () {
        //https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addcustomfilter
        formContext.getControl("jcmvp_director").addCustomFilter(fetchDirectorFilter, "jcmvp_director");
    },


    getCollectionsMovies: function (executionContext) {
        formContext = executionContext.getFormContext();

        var collectionID = formContext.data.entity.getId().replace("{", "").replace("}", "");

        //https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-webapi/retrievemultiplerecords
        Xrm.WebApi.retrieveMultipleRecords("jcmvp_movie", "?$select=_jcmvp_director_value&$filter=(_jcmvp_collection_value eq " + collectionID + ")").then(
            function success(result) {
                debugger;

                if (result.entities.length > 0) {
                    fetchDirectorFilter = "<filter type='and'> <condition attribute = 'jcmvp_directorid' operator = 'in' uitype='jcmvp_director'>";
                }

                for (var i = 0; i < result.entities.length; i++) {
                    //_jcmvp_director_value
                    fetchDirectorFilter += "<value>" + result.entities[i]._jcmvp_director_value + "</value>";
                    console.log(result.entities[i]);
                }
                if (result.entities.length > 0) {
                    fetchDirectorFilter += "</condition ></filter >";
                    //https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addcustomfilter
                    formContext.getControl("jcmvp_director").addPreSearch(JCMVP.Collection.Form.filterMovieDirectors);    
                }

            },
            function (error) {
                console.log(error.message);
                // handle error conditions
            }

            
        );

    }

We start with calling the getCollectionsMovies function on the form load event. This function will execute our query to get the related movies and director column filtering on the collection table id your currently on.
– Xrm.WebApi.retrieveMultipleRecords(“jcmvp_movie”, “?$select=_jcmvp_director_value&$filter=(_jcmvp_collection_value eq ” + collectionID + “)”).then(

This is an asynchronous call that when it completes it will work towards building our filter and storing it on our global variable “fetchDirectorFilter”. An example of the built filter statement looks like this:
“<filter type=’and’> <condition attribute = ‘jcmvp_directorid’ operator = ‘in’ uitype=’jcmvp_director’><value>889c9059-865d-eb11-a812-000d3a84f1a3</value><value>03fa2f78-865d-eb11-a812-000d3a84f1a3</value><value>889c9059-865d-eb11-a812-000d3a84f1a3</value><value>40d8e290-865d-eb11-a812-000d3a84f1a3</value><value>78d8e290-865d-eb11-a812-000d3a84f1a3</value><value>93034497-865d-eb11-a812-000d3a84f1a3</value><value>15920af3-6d5f-eb11-a812-000d3a84f1a3</value></condition ></filter >”.

After our filter statement has been created we’re going then go ahead and use the addPreSearch function. formContext.getControl(“jcmvp_director”).addPreSearch(JCMVP.Collection.Form.filterMovieDirectors);). This will allow for when the user clicks on the director lookup on the collection form it fires the filterMovieDirectors function.

When the user clicks on the director field it will execute the function filterMovieDiretors. This function will use our built filter and set it for the lookup. formContext.getControl(“jcmvp_director”).addCustomFilter(fetchDirectorFilter, “jcmvp_director”);

This code scenario is covering when the form loads or refreshes. What it doesn’t cover is updating the director list when a movie is added to the collection. I’ll work through this and post an additional blog post when I have that completed.

Clarifying how Business Rules work with Editable Grids

Let’s clarify how business rules work with editable grids once in for all. I keep seeing this discussed passionately and many people believe they don’t work together.

As a note the functionality we’re going to review today works the same for the UCI (Unified Client interface) or the classic editable grid. There currently is a bug with the unified interface version that I need to note here. I feel that this bug may be a cause for a lot of the debate. In writing this blog post it became very clear in the UCI when you switch from the read only grid to the editable grid on the home screen that business rules aren’t being applied. Once I see this issue resolved i’ll post an update to this.

Let’s create a simple business rule that says if the created on date contains data then lock the email field. I’ve tested the scope with all forms or entity and got the same result. In this scenario in order for this business rule to execute it must be able to validate the if condition; this means that the editable view must have the created on field in order to evaluate it. This seems to be something that alludes people frequently.

Checking this business rule against this simple view in the editable grid we see that the email is still editable.  As the view doesn’t contain the created on date field.

Let’s create a simpler business rule that checks to see if the email contains data and if it does then lock the email field. I’ve tested the scope with all forms or entity and got the same result. This covers a common scenario that wouldn’t allow the user to change a fields value once entered in the system on the form or editable grid.

Checking this business rule against this simple view in the editable grid we see that the email locked because it contains data. If we clicked on an account record that didn’t have an email value it would be editable until a value was saved in it.

I hope this brings some clarity to how business rules interact with editable grids.

The more you know!

Firing Business Rules when making JavaScript changes!

With the investment being made in Dynamics 365 around business rules I typically try and leverage them when possible. I’ve found at times it creates some challenges along the way. One specific challenge  a college and I’ve ran into was when making JavaScript modifications to fields the related business rules were’t executing.

Making the business rules fire took a bit of research but it paid off as we’re able to continue to use Business Rules with JavaScript. A co-worker of mine Mike Wright found the answer and documentation. Microsoft has the documentation for the fireOnChange event you need to use on the Attribute here.

When the fireOnChange event is called it will call your related javascript event for that attribute as well execute any business rules associated to it. This is a great piece of knowledge to know when working with business rules and javascript.
Xrm.Page.getAttribute(arg).fireOnChange()

The more you know!

Understanding the Expand Query in the Dynamics 365 List Records connector

Hello;

Recently I’ve been diving deeply into the Dynamics 365 connector that is used in Power Apps, Logic Apps, and Flow. I’ve found the documentation lacking when trying to do more advanced features. Today were discussing the Expand Query component of this connector.

First lets start with a new flow and add the Dynamics 365 – List Records(preview) connector.
Dynamics 365 - List Records

Once we have the connector added we’re going to retrieve all Accounts. We select an organization and then select which entity we’re going to use. This will get us all accounts in the organization.
Dynamics 365 - List Records

The Expand Query option is where we’re going to focus on. MSDN documents this field here.  The documentation states:

Expand Query
string
Related entries to include with requested entries (default = none)
Key:
$expand

This doesn’t really give us a practical example to work from. When researching online the majority of searches come back with using the relationship name of a relationship. This is actually incorrect. Let’s take the Primary Contact relationship on the Account entity as an example.
Dynamics 365 - List Records

For the Expand Query field it actually takes the lookup value of this relationship. In this case it is looking for the “primarycontactid”.

Let’s go back to our query and add this in.
Dynamics 365 - List Records

As you can see we’re able to specify the lookup field and then select exactly which columns to be retrieved from the Contact entity. The output of this query returns the related record in a json object.

      "primarycontactid": {
        "@odata.type""#Microsoft.Azure.Connectors.Crm.SubItem",
        "fullname""Jason Cosman",
        "firstname""Jason",
        "lastname""Cosman"
      }

Getting the related record is only half the battle as it isn’t able to be used as dynamic content yet. You have to parse it out and then use it. Stay tuned for the next post where we update the account with contact information using the retrieved data.

Don’t forget to upgrade assemblies for custom code in Dynamics 365 v9+ upgrade!

Upgrading to the latest platform is never something to underestimate with any product. With Dynamics 365 we’ve experienced such rapid platform changes over the past 8 years we should be all getting used to some of the pieces of an upgrade.

With the Dynamics 365 V9+ update we have to remember to upgrade our custom code assemblies. This should be fairly straight forward if your using NuGet packages in your projects. Microsoft has invested into lots of different packages like https://www.nuget.org/packages/Microsoft.CrmSdk.CoreAssemblies/ .

I use Visual Studio for my custom code components like plugins and custom workflow activities.  After opening the project I’ve selected manage NuGet packages and I get a screen like this:

This update process also helps resolve any dependencies and highlights any errors if they occur. A great example of this is I mentioned before I’m using FakeXrmEasy as my unit test framework. This will need to be updated as well; in this example FakeXrmEasy has dependencies displayed on the bottom for the CrmSdk.CoreAssemblies less then version 9.0.0.

Since we’re upgrading into Dynamics 365 V9+ we need to make sure our unit test framework is using the right assemblies. In this case FakeXrmEasy provides a separate NuGet package for Dynamics 365 V9+; we’d simply remove the FakeXrmEasy.365 NuGet package and then install the new one.

Of course after doing this and deploying your assemblies into Dynamics 365 you have to test like crazy.

The more you know!

What is a system entity message?

Hello;

With the release of V9 we’ve seen new items in the solution structure and package. One such change is the Messages under each entity in the solution.

 

Messages give the ability to change the content displayed when the user sees these out of the box messages. It includes user interface text and error messages. It gives you the default display string and allows you to enter a custom display string and then a comment to explain the change. Editing is very straight forward and looks like this:

It’s worth noting that entity messages aren’t available for custom entities and that your only able to edit existing messages.

Creating an action using a custom workflow activity

Hello;

Today we’re going to be starting a series that will lead us into PowerApps. This is part one and it’s walks through creating a custom workflow activity, then inserting into a custom action in a v9 environment.

The business requirement for this post is to have an action that is able to activate/deactivate a process.

Custom Workflow Activity

Microsoft provides a very extensively list of out of the box actions which gets updated frequently. It’s worth checking out this documentation from time to time to catch the latest and greatest https://msdn.microsoft.com/en-us/library/mt607829.aspx. Unfortunately there isn’t an action to activate/deactivate a process; this has to be handled through a custom workflow activity. The following code below is what’s required.

    public class SetProcessState : CodeActivity

    {

        /// <summary>
        /// This is the workflow that needs to be activated/deactivated.
        /// </summary>
        [Input("Workflow")]
        [ReferenceTarget("workflow")]
        public InArgument<EntityReference> Workflow { get; set; }
        
        /// <summary>
        /// This is the state of the workflow entity.
        /// 0 is draft and 1 is Activated
        /// </summary>
        [Input("Workflow State")]
        public InArgument<int> WorkflowState { get; set; }

        /// <summary>
        /// This is the status of the workflow entity.
        /// </summary>
        [Input("Workflow Status")]
        public InArgument<int> WorkflowStatus { get; set; }

        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension<ITracingService>();

            //Create the context
            IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            EntityReference workflow = Workflow.Get<EntityReference>(executionContext);
            int workflowState = WorkflowState.Get<int>(executionContext);
            int workflowStatus = WorkflowStatus.Get<int>(executionContext);

            if(workflow == null)
            {
                tracingService.Trace("The workflow entity reference past in is not valid");
                throw new Exception("The workflow entity reference past in is not valid");
            }

            tracingService.Trace("Activate/Deactivate Workflow:");

            var activateRequest = new SetStateRequest
            {
                EntityMoniker = new EntityReference
                    (workflow.LogicalName, workflow.Id),
                State = new OptionSetValue(workflowState),
                Status = new OptionSetValue(workflowStatus)
            };
            service.Execute(activateRequest);
            Console.WriteLine("and sent request to service.");

        }
    }

This custom workflow activity takes three parameters:

  1. Workflow – This is a entity reference to the actual process that’s going to be activated/deactivated.
  2. Workflow State – This is the state of the workflow entity
  3. Workflow Status – This is the status of the workflow entity.

With these three parameters we’re ready to create the action which will allow us to activate/deactivate a process.

Creating the Action

Creating an action is pretty straight forward; an action is a type of a process. The best part about actions is they become a message that’s callable through the web api directly. This alone makes them extremely powerful. It’s a great way to compartmentalize business logic or technical components.

Let’s navigate to a new solution I’ve setup where we are going to create an action.

This particular action is going to be a global action which means it can be called standalone as apposed to against a specific entity. I do this because the process entity isn’t in the list of entities. The first thing we’ll do once the action is created is to add the three actions we defined in the custom workflow activity.

Now we have the arguments that we can pass directly into the custom workflow activity allowing us to activate/deactivate any process. Let’s go ahead and add the call to our custom workflow activity and set the parameters of the step.

I wanted to stop and highlight when trying to set the Workflow value. All non entity reference arguments of the action are contained within the Local Values -> Arguments section shown above. The entity reference argument is shown differently as per the highlight item; it’s displayed under a section called Argument Entity. This is the one we’ll select to give the workflow a value. We can save and close.

We are now left with a completed action with the functionality to activate/deactivate processes. I hope you enjoyed the walk through on combining these two items together. Next post we’ll look at putting this action to good use through the API.