web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested Answer

Not filter Products when change Account or contact

(1) ShareShare
ReportReport
Posted on by 2
I've a field at Lead table named Product (crf2e_service) , And at product table there are 3 bool fields named Individual, Private, Governorate,

Contact is individual, and Account contain a classification field (Private, or Governorate)

At Creating lead i want when user choose Existing contact filter product according to individual type only, and when user choose account filter according to classification

The JS code i write works only at the first time i choose contact or account, when i remove or choose another type not clearing filter or change it

I but onload method at Form OnLoad Event Handler And applyProductFilter at Existing Contact, And Existing Account OnChange Event Handler

var isProductFilterApplied = false;

function onLoad(executionContext) {
    var formContext = executionContext.getFormContext();
    var formType = formContext.ui.getFormType();

    if (formType !== 1) return; // Only apply for new records

    console.log("onLoad executed, form type: " + formType);

    // Add OnChange event handlers for parentcontactid and parentaccountid
    var parentContactField = formContext.getAttribute("parentcontactid");
    var parentAccountField = formContext.getAttribute("parentaccountid");

    if (parentContactField) {
        parentContactField.addOnChange(function (context) {
            applyProductFilter(context);
        });
    }

    if (parentAccountField) {
        parentAccountField.addOnChange(function (context) {
            applyProductFilter(context);
        });
    }

    // Apply filter on load
    applyProductFilter(executionContext);
}

function applyProductFilter(executionContext) {
    var formContext = executionContext.getFormContext();
    debugger;
    var parentContactField = formContext.getAttribute("parentcontactid");
    var parentAccountField = formContext.getAttribute("parentaccountid");

    var parentContact = parentContactField ? parentContactField.getValue() : null;
    var parentAccount = parentAccountField ? parentAccountField.getValue() : null;

    console.log("applyProductFilter executed");

    clearProductFilter(formContext);

    if (parentAccount) {
        var accountId = parentAccount[0].id.replace('{', '').replace('}', '');
        console.log("Parent Account ID: " + accountId);
        filterProductsByAccount(formContext, accountId);
    } else if (parentContact) {
        var contactId = parentContact[0].id.replace('{', '').replace('}', '');
        console.log("Parent Contact ID: " + contactId);
        filterProductsByContact(formContext, contactId);
    } else {
        console.log("No parent contact or account selected");
    }
}

function clearProductFilter(formContext) {
    var productField = formContext.getControl("crf2e_service");

    if (productField) {
        console.log("Clearing product filter");
        productField.removePreSearch(productFilterHandler);
        productField.addPreSearch(function () {
            productField.addCustomFilter("<filter type='and'></filter>");
        });
        isProductFilterApplied = false;
    }
}

function productFilterHandler() {
    // Dummy function to use as a reference for adding/removing the handler
}

function filterProductsByContact(formContext, contactId) {
    Xrm.WebApi.retrieveRecord("contact", contactId, "?$select=contactid").then(
        function success(result) {
            console.log("filterProductsByContact executed");
            var filter = "<filter type='and'><condition attribute='crf2e_isindividual' operator='eq' value='true' /></filter>";
            applyProductLookupFilter(formContext, filter);
        },
        function (error) {
            console.log("Error retrieving contact: " + error.message);
        }
    );
}

function filterProductsByAccount(formContext, accountId) {
    Xrm.WebApi.retrieveRecord("account", accountId, "?$select=ownershipcode").then(
        function success(result) {
            console.log("filterProductsByAccount executed");
            var classification = result.ownershipcode;
            var filter = "";

            if (classification === 2) { // Assuming 2 is the value for Private
                filter = "<filter type='and'><condition attribute='crf2e_isprivate' operator='eq' value='true' /></filter>";
            } else if (classification === 1) { // Assuming 1 is the value for Government
                filter = "<filter type='and'><condition attribute='crf2e_isgovernment' operator='eq' value='true' /></filter>";
            }

            applyProductLookupFilter(formContext, filter);
        },
        function (error) {
            console.log("Error retrieving account: " + error.message);
        }
    );
}

function applyProductLookupFilter(formContext, filter) {
    var productField = formContext.getControl("crf2e_service");

    if (productField) {
        console.log("Applying product lookup filter: " + filter);
        productField.addPreSearch(function () {
            productField.addCustomFilter(filter);
        });

        isProductFilterApplied = true;
    }
}
 
FilterProductsAtL...

Your file is currently under scan for potential threats. Please wait while we review it for any viruses or malicious content.

I have the same question (0)
  • Cui Hao Profile Picture
    on at
    Hi,

    I checked your code and analyzed it according to your problem.

    I learned a bit about the functions removePreSearch and addPreSearch, but addPreSearch can't directly override the previous filter, it needs to be removed by removePreSearch first.
    Because you're adding an anonymous function to addPreSearch, you can't remove it with the removePreSearch method.
    The removePreSearch method takes one argument, a reference to the event handler you want to remove.

    So you need to use a named function instead of an anonymous function. For example, you can define a function first and then use the name of that function in addPreSearch and removePreSearch.
    You can try to change it as I suggested above.


    If my answer was helpful, please click Like, and if it solved your problem, please mark it as verified to help other community members find more. If you have further questions, please feel free to contact me.


    Best regards,
    Cui Hao

     
  • Suggested answer
    Cui Hao Profile Picture
    on at
    Hi,

    I checked your code and analyzed it according to your problem.

    I learned a bit about the functions removePreSearch and addPreSearch, but addPreSearch can't directly override the previous filter, it needs to be removed by removePreSearch first.
    Because you're adding an anonymous function to addPreSearch, you can't remove it with the removePreSearch method.
    The removePreSearch method takes one argument, a reference to the event handler you want to remove.

    So you need to use a named function instead of an anonymous function. For example, you can define a function first and then use the name of that function in addPreSearch and removePreSearch.
    You can try to change it as I suggested above.


    If my answer was helpful, please click Like, and if it solved your problem, please mark it as verified to help other community members find more. If you have further questions, please feel free to contact me.

    Best regards,
    Cui Hao
  • Suggested answer
    Cui Hao Profile Picture
    on at
    Hi,
     
    Do you have any other questions? If you have any other questions feel free to ask me.
    If it solved your problem, please mark it as verified to help other community members find more. 
     
     
     
    Best regards,
    Cui Hao
  • mshaaban Profile Picture
    2 on at
    Thanks for your support, 
    Can you please,  modify my code to match your suggested solution  

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

News and Announcements

Season of Giving Solutions is Here!

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Pallavi Phade Profile Picture

Pallavi Phade 98

#2
Tom_Gioielli Profile Picture

Tom_Gioielli 79 Super User 2025 Season 2

#3
TAHER Mehdi Profile Picture

TAHER Mehdi 58

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans