Search code examples
google-apps-scriptgoogle-app-maker

How to get the sorting fields and order from a Query object in AppMaker?


In their examples there's something like this:

var query = app.models.Person.newQuery();
query.sorting.Name._ascending();

How can I extract the column and order from this?

I tried console.log(Object.keys(query.sorting)); but it doesn't work.


Solution

  • Based on my interpretation, which is that you would like to return the column name and the sorting order of the column that has sorting, I would propose the below solution.

    First, note that when using query.sorting.YourFieldName. in your query server script, the following options are presented in the code autocomplete - _ascending, _descending, _order, and _priority. When hovering on the _order choice you will note that this is a read-only property and it states that ascending order will return true and descending order will return false. What is not mentioned is that no order on a particular column will return undefined.

    So the following code worked for me and returned a console log with the column name and the order, albeit this code does not pick up if there are any relation fields that are sorted:

    var query = app.models.Person.newQuery();
    query.sorting.Name._ascending();
    var fields = app.metadata.models.Person.fields;
    for (var i in fields) {
      //if statement first checks column is not a foreign key and that column has sorting 
      if(i.indexOf('_fk') === -1 && query.sorting[i]._order !== undefined) {
        console.log(query.sorting[i]._order ? 'Column Name: ' + i + ', Order: Ascending' : 'Column Name: ' + i + ', Order: Descending');
      }
    }
    

    The console would return "Column Name: Name, Order: Ascending". Let us know if that is what you are in fact looking for.