Right now your code has three problems:
- addPreSearch() is being used incorrectly
- he filter XML is incorrect (parentproductid condition)
- addPreSearch() expects a function, not a filter string
Because of this, the lookup always returns all records.
Main Problem in Your Code
You currently do this:
- formContext.getControl('parentproductid').addPreSearch(filter,formContext);
But addPreSearch() expects:
- addPreSearch(functionName)
Then inside that function you call addCustomFilter().
Try do the code like below :
function onFamilyIdChange(executionContext) {
var formContext = executionContext.getFormContext();
// 1. Register the handler (only needs to be done once, usually OnLoad or OnChange)
formContext.getControl("parentproductid").addPreSearch(applyProductFilter);
}
function applyProductFilter(executionContext) {
var formContext = executionContext.getFormContext();
var familyId = formContext.getAttribute("cr1da_familyid").getValue();
if (familyId) {
// Calculate your length logic
var targetLength = familyId.length - 2;
// Since we can't wait for WebAPI here without breaking the UI flow,
// it is best to use a FetchXML filter that expresses your logic directly.
// If the logic is too complex for FetchXML, you must pre-fetch the data
// into a variable/hidden field before the user clicks the lookup.
var filter = "<filter type='and'>" +
"<condition attribute='cr1da_familyid_length' operator='eq' value='" + targetLength + "' />" +
"</filter>";
formContext.getControl("parentproductid").addCustomFilter(filter, "product");
}
}