Search code examples
google-app-maker

Best way for displaying total Pages for a datasource in Appmaker


I have a Google drive table data source which stores list of open positions. Now in the data source I've set "Query per size" field to 10 so that I can get 10 records per page. I've added a Pager as well to show pagination.

My query is I want to display like "Page 1 of X" to my end users and this X will vary based on certain search filters. What will the best way to achieve this in Appmaker?

I've tried counting total records in a data source as per below code but every time updating that with the search criteria and recounting it is not a proper solution.

//Server side
    var newQuery = app.models.Company.newQuery();
    var records = newQuery.run();
    var totalCount =0;
    for(var i=0;i<records.length;i++)
    {
       totalCount=totalCount+1;
    }
    return totalCount;

Solution

  • I've achieved this using Calculated Model as suggested by Pavel.

    Steps :

    1. Create a calculated data source with one field count.
    2. In that data source add one parameter searchQuery. This will contain users filter going forward. Currently I have only one search query in which user can search many things. So I've added one parameter only.
    3. In this data source add following server script.

    Code:

    // Server script
    function getTotalRecords(query) {
      var receivedQuery = query.parameters.searchQuery;
      // console.log('Received query:' + query.parameters.searchQuery);
    
      var records = app.models.Company.newQuery();
      records.parameters.SearchText = query.parameters.searchQuery;
    
      if(receivedQuery !== null) {
        records.where = '(Name contains? :SearchText or InternalId contains? ' +
          ':SearchText or LocationList contains? :SearchText )';
      }
    
      var recordsCount = records.run().length;
      var calculatedModelRecords = []; 
      var draftRecord = app.models.RecordCount.newRecord();
      draftRecord.count = ''+recordsCount;
      calculatedModelRecords.push(draftRecord);
    
      return calculatedModelRecords;
    }
    

    .

    1. On the Appmaker page bind a label with this data source.
    2. On search query/your filter applied event add following code which Reload this data source and assign value to Parameter.
    // Client script
    function updateRecordCount(newValue) {
      var ds = app.datasources.RecordCount;
      ds.query.parameters.searchQuery = newValue;
      ds.unload();
      ds.load();
    }