KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Using entitySelection.orderByFormula() with command Formula
PRODUCT: 4D | VERSION: 18 | PLATFORM: Mac & Win
Published On: March 16, 2020

Now with ORDA, the new entitySelection.orderByFormula() method makes it easy to sort items in an entity selection. This method can be combined with the Formula command (formerly New formula) to sort the entities almost any way we'd like.

For example, imagine the following scenario. We have a table of companies that stores the quarterly revenues for each company and also the country of origin. We want to get the selection of all companies from France, and also sort them in descending order according to total annual revenue. This can be accomplished in just three lines of code:

$frenchCompanies_es:=ds.Company.query("Country=:1";"France")
$formula_o:=Formula(This.Q1_Revenue+This.Q2_Revenue+This.Q3_Revenue+This.Q4_Revenue)
$sortedByTotalRevenue_es:=$frenchCompanies.orderByFormula($formula_o;dk descending)

After querying for all French entities, we can set a formula object to sum the quarterly revenues for each entity by using "This". Then we can just pass the formula into the orderByFormula method to sort the companies by highest annual revenue. Note that the method returns a new entity selection and does not modify the original entity selection.