Skip to main content

Notifications

Announcements

No record found.

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...
  • mshaaban Profile Picture
    mshaaban 2 on at
    Not filter Products when change Account or contact
    Thanks for your support, 
    Can you please,  modify my code to match your suggested solution  
  • Suggested answer
    Cui Hao Profile Picture
    Cui Hao on at
    Not filter Products when change Account or contact
    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
  • Suggested answer
    Cui Hao Profile Picture
    Cui Hao on at
    Not filter Products when change Account or contact
    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
  • Cui Hao Profile Picture
    Cui Hao on at
    Not filter Products when change Account or contact
    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

     

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

Quick Links

Congratulations 2024 Spotlight Honorees!

Kudos to all of our 2024 community stars! 🎉

Meet the Top 10 leaders for December!

Congratulations to our December super stars! 🥳

Get Started Blogging in the Community

Hosted or syndicated blogging is available! ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,661 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,379 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans