KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: An orderByFormula Formula to Sort an Entity Selection's Field Against a Collection
PRODUCT: 4D | VERSION: 20 | PLATFORM: Mac & Win
Published On: September 12, 2023

Below is a Method that can be used as a Formula in the .orderByFormula() entity selection function to sort the entity selection in the order of a passed collection applied to the specified field's values.

// Method: OrderByCollectionFormula
#DECLARE($argsObj : Object)->$result : Integer

$result:=$argsObj.collection.indexOf(This[$argsObj.fieldName])

If (($result=-1) & (Not($argsObj.descending=True)))
   $result:=$argsObj.collection.length
End if

The .orderByFormula() function takes in a Formula as the first parameter. There is an optional second Integer to specify the sort ordering which defaults to ascending, but can be descending by applying the constant dk descending. The last parameter is an object that can contain the parameters for the formula. The format of the object is that it must contain an attribute "args". The attribute "args" must contain an object as it's value. This object is passed as the first parameter into the function.

The OrderByCollectionFormula method's parameters are
.collection - a collection of values in a specified order to sort the entity selection
.fieldName - the name of the field that will be used to sort the entity selection
.descending - an optional boolean parameter. This is used if the entity selection's field contains values not specified in the collection. The default (False) will place these entities at the end of an ascending sort. Applying True will place these entities at the end of a descending sort.

Below is an example of using the method:
$values:=New collection(3333; 1111; 2222)

$entSel:=ds.Table_2.all()
$formula:=Formula(OrderByCollectionFormula($1))

$paramObj:=New object()
$paramObj.args:=New object("collection"; $values; "fieldName"; "Field_2")
$entSelOrderedAsc:=$entSel.orderByFormula($formula; $paramObj)

$paramObj.args.descending:=True
$entSelOrderedDesc:=$entSel.orderByFormula($formula; dk descending; $paramObj)

Below is the results in the debugger:

As shown, the entity selection gets sorted based on the collection's ordering of 3333 then 1111 then 2222. The original entity selection has a random ordering based on their ordering in the table. The ascending entity selection sorts by the collection with the unfound values placed at the end. The descending order entity selection has a reverse sort with the unfound values still placed at the end.