Sort child table

In a child table. How can I define sort order of the child table? I tried sort field but it does not work in child table. Any ideas?

@ccfield, do you need change the “idx” field, after that refresh the table field on parent

1 Like

@max_morais_dmm can I do it in the server side? I tried this

    def validate(self):
        idx = 1
        for range_ in frappe.db.sql("""select name from `tabTransmuted Grade Range` where parent=%s ORDER BY cast(transmuted_grade as INT) DESC """, self.name):
            value = frappe.get_doc("Transmuted Grade Range", range_[0])
            value.idx = idx
            value.save()
            idx += 1

but it does not work. It will just go back to the original idx. or I need to do it in the client side?

1 Like

@ccfiel let me understand first, what is the rule for sort order?

@max_morais_dmm is just one of the field (grade) of the child table (tabTransmuted Grade Range).

@ccfiel, I dont got you, can you giveme a sample? Screenshot?

@max_morais_dmm

the parent table is called “Transmuted Grade” and the child table is called “Transmuted Grade Range”
and the field I want to sort in the child table is “grade” The one I encircle that the field I want to sort

@ccfiel


def validate(self):
    for i, item in enumerate(sorted(self._range, key=lambda item: item.grade), start=1):
        item.idx = i


var idx = 1;
frm.doc._grade.sort(function(a,b){
  if (a.grade < b.grade){ return -1 }
  else if ( a.grade > b.grade){ return 1 }
  return 1;
});

frm.doc._grade.map(function(item){
  item.idx = idx++;
});

8 Likes

@max_morais_dmm wow! thats hardcore! :smile: It works. thanks! but for the sake of discussion I tried to comment out the server side script

def validate(self):
    for i, item in enumerate(sorted(self._range, key=lambda item: item.grade), start=1):
        item.idx = i

It still works. What is the use of this code? :smile:

1 Like

@ccfiel the comments below


enumerate # built-in function that return a list of (index, item) of a given list of objects), `start` is a parameter to define the first value of the index
sorted # built-in function that sort a list, if the list is a list of objects, do you need pass the `key` to get the value to be used in the sort comparization.

for i, item in enumerate(sorted(self._range, key=lambda item: item.grade), start=1):
    item.idx = i # define the new index to the object based on the sorted ordem

8 Likes

@max_morais_dmm thanks again! :slight_smile: