Search Filters not applying in suitescript 2.0

I am Applying filters in my existing saved search, but it’s not getting applied.
i m creating a Suitelet form , from where i m passing filters as params,. I can view rthe filters and they are getting logged too but not getting applied in my search finction which  is getItems (). Can anyone help me what’s wrong i m doing, as I’m new in Suitescripts?

//Scheduled Script

/**
 * @NApiVersion 2.x
 * @NScriptType scheduledscript
 *
 */
define([‘N/ui/serverWidget’, ‘N/search’, ‘N/render’, ‘N/runtime’, ‘N/file’, ‘N/email’],
  function (ui, search, render, runtime, file, email) {
    function execute() {
      try {
        generateReport();
      }
      catch (e) {
        log.error(‘generateReport ERROR’, e);
      }
    }
    function generateReport() {
      var slfilters = runtime.getCurrentScript().getParameter({ name: ‘custscript_searchfilter_report’ });
      log.debug(‘slfilters’, slfilters);
      if (!!slfilters) {
        slfilters = JSON.parse(slfilters);
      }
      log.debug(‘slfilters2’, slfilters);
      var getUser = runtime.getCurrentUser();
      var gender = slfilters.isgender
      log.debug(‘gender’, gender)
      var item = slfilters.isItem
      log.debug(‘item’, item)
      var item_ = getItems(item, gender);
      log.debug(‘items table’, item)
      // return item;
      var xmlTemplateFile = file.load(3918);
      //var template = script.getParameter({ name: ‘custscript_template’ });
      var renderer = render.create();
      renderer.templateContent = xmlTemplateFile.getContents();
      var customSources = {
        alias: ‘searchdata’,
        format: render.DataSource.JSON,
        data: JSON.stringify({
          value: item_,
        })
      };
      renderer.addCustomDataSource(customSources);
      var xml = renderer.renderAsString();
      var pdf = render.xmlToPdf({
        “xmlString”: xml
      });
      email.send({
        author: 317,
        recipients: ‘aniswtf@gmail.com’,
        subject: ‘Item Report’,
        body: ‘Report Generated: ‘,
        attachments: [pdf]
      });
    }
    //
    // ─── GET RESULTS ───────────────────────────────────────────────────
    //
    const getResults = function (set) {
      var results = [];
      var i = 0;
      while (true) {
        var result = set.getRange({
          “start”: i,
          “end”: i + 1000
        });
        if (!result) break;
        results = results.concat(result);
        if (result.length < 1000) break;
        i += 1000;
      }
      return results;
    };
    //
    // ─── GET ITEMS ───────────────────────────────────────────────────
    //
    //function getItems(item, gender) {
    function getItems(item, gender) {
      try {
        log.error(‘Arrived in getItems Function’)
        var itemSearch = search.load({
          id: ‘customsearch_mx_itemsearch’
        });
        log.error(‘itemSearch’, itemSearch)
        var defaultFilters = itemSearch.filters;
        // log.error(‘defaultFilters’, defaultFilters)
        var arrFilters = [];
        arrFilters.push(search.createFilter({
          name: ‘custitem5’,//gender
          operator: ‘anyof’,
          values: [‘gender’]
        }));
        //arrFilters.push([‘AND’]);
        arrFilters.push(search.createFilter({
          name: ‘nameinternal’,
          operator: ‘anyof’,
          values: [‘item’]
        }));
        //defaultFilters = arrFilters;
        defaultFilters = defaultFilters.concat(arrFilters);
        log.error(‘Updated Filters’, defaultFilters)
        //return defaultFilters;
        var results = itemSearch.run().getRange({
          start: 0,
          end: 150
        });
        results.map(function (x) {
          // var results = getResults(itemSearch.run()).map(function (x) {
          return {
            ‘category’: x.getText({
              name: “custitem10”,
              join: “parent”
            }),
            ‘season’: x.getValue({
              name: “custitem11”,
              join: “parent”
            }),
            ‘riselabel’: x.getValue({
              name: “custitem_itemriselabel”,
              join: “parent”
            }),
            ‘fit’: x.getValue({
              name: “custitem9”,
              join: “parent”
            }),
            ‘name’: x.getValue({ //sku
              name: “itemid”,
              join: “parent”
            }),
            ‘style’: x.getValue({
              name: “custitem8”,
              join: “parent”
            }),
            ‘inseam’: x.getValue({
              name: “custitem7”,
              join: “parent”
            }),
            ‘wash’: x.getValue({
              name: “custitem_washname”,
              join: “parent”
            }),
          };
        });
        return results;
      } catch (e) {
        log.error(‘error in getItems’, e)
      }
    }
    return {
      execute: execute
    };
  });

//Suitelet

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 */
define([‘N/ui/serverWidget’, ‘N/search’, ‘N/render’, ‘N/runtime’, ‘N/file’, ‘N/task’],
  function (ui, search, render, runtime, file, task) {
    /**
     * main function for suitelet
     * @param {object} ctx
     */
    function onRequest(ctx) {
      var req = ctx.request;
      var res = ctx.response;
      var param = req.parameters;
      /**
       * create form is creating the UI for report generation
       */
      if (req.method === ‘GET’) {
        // createForm(req, res, param);
        createForm(req, res, param);
      } else {
        generateReport(req, res, param);
      }
    }
    // R E Q U E S T
    function createForm(req, res, param) {
      if (req.method === ‘GET’) {
        var form = ui.createForm({
          title: ‘Generate Item Report’
        });
        var item = form.addField({
          id: ‘custpage_selectitem’,
          type: ui.FieldType.SELECT,
          label: ‘Select Item’,
          source: ‘item’
        });
        item.isMandatory = true;
        var gender = form.addField({
          id: ‘custpage_selectgender’,
          type: ui.FieldType.SELECT,
          label: ‘Select Gender’,
          source: ‘customrecord6’
        });
        gender.isMandatory = true;
        var fromDate = form.addField({
          id: ‘custpage_selectdate’,
          // type: ui.FieldType.DATETIME,
          type: ui.FieldType.DATE,
          label: ‘Select Date/Time’,
        });
        form.addSubmitButton({
          label: ‘Generate Report’
        });
        res.writePage(form);
      }
    }
    // R E S P O N C E
    function generateReport(req, res, param) {
      var param = req.parameters;
      log.debug(‘parameters’, param);
      var script = runtime.getCurrentScript();
      var filters = {
        ‘isgender’: param.custpage_selectgender,
        ‘isItem’: param.custpage_selectitem,
        ‘fromDate’: param.custpage_selectdate
      };
      log.debug(‘filters’, filters);
      var scriptTask = task.create({ taskType: task.TaskType.SCHEDULED_SCRIPT });
      // scriptTask.scriptId = 3920;
      scriptTask.scriptId = ‘customscript_mx_itemreport_ss’;
      scriptTask.deploymentId = ‘customdeploy_mx_itemreport_ss’;
      scriptTask.params = {
        custscript_searchfilter_report: JSON.stringify(filters)
      };
      log.debug(‘workingtillhere’);
      var scriptTaskId = scriptTask.submit();
      res.write(“Your report is being generated. It will be emailed to you shortly.”)
    }
    return {
      onRequest: onRequest
    };
  });
Rookie Asked on October 22, 2019 in SuiteScript.
Add Comment
4 Answer(s)

Array.concat (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat returns a new array. Your code to add filters ends up creating a new array, which is not used by the search. Either set itemSearch.filters to your new array or add filters to the existing filters array.

itemSearch.filters.push(
 search.createFilter({
  name: "custitem5",
  operator: search.Operator.IS,
  values: gender
 }),
 search.createFilter({
  name: "nameinternal",
  operator: search.Operator.IS,
  values: item
 })
);

Keep in mind that my code example changed your filters. Its unlikely that the code you had added reasonable filters.

Intermediate Answered on October 22, 2019.

You can try sharing your changed code. And preferably what values you are using the values for your filters.

on October 23, 2019.
Add Comment

Try using filter expression instead

Beginner Answered on October 23, 2019.
Add Comment

Thanks battk. I tried removing .concat and did use .push but still script acts the same.

Rookie Answered on October 22, 2019.

Answers on this site are supposed to be used to answer the question. Comments are for clarifications

on October 23, 2019.
Add Comment

Hello,

i need to call  saved search and print in pdf i dont need to give filter

for example

var mySearch = search.load({
id: ‘customsearch_mx_itemsearch’
});

then that search  print in PDF

Rookie Answered on December 18, 2019.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.
  • This site made possible by our sponsors:   Tipalti   Celigo   Limebox   Become a Sponsor