Page 1 of 1

Return All if Filter Field is Empty

Posted: 11 Sep 2017
by TonyDuke
Hi I have a Cascading Lookup that works 100% however I want to return all results if no choice is made in the Filter by field as this is not a required field.
So we have a Company Name field and a Contact Name field, the contact name field is a Lookup filtered by the Company Name field, but if no choice is made in the Company Name field I want all Contacts to be retrieved rather than none.
My Current Code is -

function (term, page) {
var CompanyNameId = fd.field('Company_x0020_Name').value();
if (!CompanyNameId) {
CompanyNameId = 0;
}

// Filtering by the selected company
if (!term || term.length == 0) {
return "{WebUrl}/_api/web/lists('{ListId}')/items?$select=Id,{LookupField},Company/Id,&$orderby=Title asc&$expand=Company/Id&$filter=Company/Id eq " + CompanyNameId + "&$top=10";
}
return "{WebUrl}/_api/web/lists('{ListId}')/items?$select=Id,{LookupField},Company/Id,&$orderby={LookupField}&$expand=Company/Id&$filter=startswith({LookupField}, '" + term + "') and Company/Id eq " + CompanyNameId + "&$top=10";
}

As I say this works other than if no Company is selected in the Company Name field it returns "No Matches Found" where I want it to return all results.

Help greatly appreciated.

Re: Return All if Filter Field is Empty

Posted: 11 Sep 2017
by Nikita Kurguzov
Try something like this. I might've broken the code somewhere, so make sure that everything is correct, but I think you'll get the general idea. Only return the filtered value when CompanyNameId has value selected, otherwise return unfiltered list.

Code: Select all

function (term, page) {
 var CompanyNameId = fd.field('Company_x0020_Name').value();
 if (!CompanyNameId) {
     if (!term || term.length == 0) {
     return "{WebUrl}/_api/web/lists('{ListId}')/items?$select=Id,{LookupField}&$orderby=Title asc&$top=10";
    }
   return "{WebUrl}/_api/web/lists('{ListId}')/items?$select=Id,{LookupField}&$orderby={LookupField}&$filter=startswith({LookupField}, '" + term + "')&$top=10";
 }
 
    // Filtering by the selected company
    if (!term || term.length == 0) {
     return "{WebUrl}/_api/web/lists('{ListId}')/items?$select=Id,{LookupField},Company/Id,&$orderby=Title asc&$expand=Company/Id&$filter=Company/Id eq " + CompanyNameId + "&$top=10";
    }
   return "{WebUrl}/_api/web/lists('{ListId}')/items?$select=Id,{LookupField},Company/Id,&$orderby={LookupField}&$expand=Company/Id&$filter=startswith({LookupField}, '" + term + "') and Company/Id eq " + CompanyNameId + "&$top=10";
}

Re: Return All if Filter Field is Empty

Posted: 11 Sep 2017
by TonyDuke
That works really well,

Thank You.