Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Scripted Search Source

Alon Grod
Tera Expert

Hi,

I have a requirement to add another Search Source in esc portal named 'Categories'. When the user search from a term this search source will need to show all categories (from sc_category) that contains the search term and their corresponding catalog items (a row will have two columns: 1) name of category 2)name of catalog item that has this category.

What am I doing wrong?

Search page template:

<div ng-repeat="category in data">
    <!-- Display the category title -->
    <h3 class="text-primary">{{ category.title }}</h3>

    <!-- Display each catalog item under the category -->
    <ul>
        <li ng-repeat="item in category.items">
            <a href="?id=form&sys_id={{ item.sys_id }}&table=sc_cat_item" class="text-muted">
                {{ item.name }}
            </a>
        </li>
    </ul>
</div>

 


Data fetch script:

(function(query) {
    var results = [];
    query = query.toLowerCase();  // Convert query to lowercase for case-insensitive search

    // Query categories that contain the search term in their title
    var categoryGR = new GlideRecord('sc_category');
    categoryGR.addQuery('title', 'CONTAINS', query); // Searches for categories containing the search term
    categoryGR.addActiveQuery();  // Only fetch active categories
    categoryGR.query();

    while (categoryGR.next()) {
        var category = {
            title: categoryGR.getDisplayValue('title'),  // Category title
            sys_id: categoryGR.getUniqueValue(),         // Category sys_id (optional for linking)
            items: []
        };

        // Query for catalog items within this category
        var itemGR = new GlideRecord('sc_cat_item');
        itemGR.addQuery('category', categoryGR.getUniqueValue()); // Fetch items with the current category
        itemGR.addActiveQuery();  // Only fetch active items
        itemGR.query();

        // Loop through each catalog item and add it to the category's items array
        while (itemGR.next()) {
            category.items.push({
                name: itemGR.getDisplayValue('name'),  // Catalog item name
                sys_id: itemGR.getUniqueValue()        // Catalog item sys_id for linking
            });
        }

        // Add the category with its items to the results array
        results.push(category);
    }

    return results;
})(query);



Do I need to put something in the Facet as well?

0 REPLIES 0