How to sort an array of structs in ColdFusion - sorting

I have an array of structs in ColdFusion. I'd like to sort this array based on one of the attributes in the structs. How can I achieve this? I've found the StructSort function, but it takes a structure and I have an array.
If this is not possible purely in ColdFusion, is it possible in Java somehow (maybe using Arrays.sort(Object[], Comparator))?

Here is something that closely resembles the original StructSort(). It also supports the pathToSubElement argument.
<cffunction name="ArrayOfStructSort" returntype="array" access="public" output="no">
<cfargument name="base" type="array" required="yes" />
<cfargument name="sortType" type="string" required="no" default="text" />
<cfargument name="sortOrder" type="string" required="no" default="ASC" />
<cfargument name="pathToSubElement" type="string" required="no" default="" />
<cfset var tmpStruct = StructNew()>
<cfset var returnVal = ArrayNew(1)>
<cfset var i = 0>
<cfset var keys = "">
<cfloop from="1" to="#ArrayLen(base)#" index="i">
<cfset tmpStruct[i] = base[i]>
</cfloop>
<cfset keys = StructSort(tmpStruct, sortType, sortOrder, pathToSubElement)>
<cfloop from="1" to="#ArrayLen(keys)#" index="i">
<cfset returnVal[i] = tmpStruct[keys[i]]>
</cfloop>
<cfreturn returnVal>
</cffunction>
Usage / test:
<cfscript>
arr = ArrayNew(1);
for (i = 1; i lte 5; i = i + 1) {
s = StructNew();
s.a.b = 6 - i;
ArrayAppend(arr, s);
}
</cfscript>
<cfset sorted = ArrayOfStructSort(arr, "numeric", "asc", "a.b")>
<table><tr>
<td><cfdump var="#arr#"></td>
<td><cfdump var="#sorted#"></td>
</tr></table>
Result:

As usual, CFLib.org has exactly what you want.
http://cflib.org/udf/ArrayOfStructsSort
/**
* Sorts an array of structures based on a key in the structures.
*
* #param aofS Array of structures.
* #param key Key to sort by.
* #param sortOrder Order to sort by, asc or desc.
* #param sortType Text, textnocase, or numeric.
* #param delim Delimiter used for temporary data storage. Must not exist in data. Defaults to a period.
* #return Returns a sorted array.
* #author Nathan Dintenfass (nathan#changemedia.com)
* #version 1, December 10, 2001
*/
function arrayOfStructsSort(aOfS,key){
//by default we'll use an ascending sort
var sortOrder = "asc";
//by default, we'll use a textnocase sort
var sortType = "textnocase";
//by default, use ascii character 30 as the delim
var delim = ".";
//make an array to hold the sort stuff
var sortArray = arraynew(1);
//make an array to return
var returnArray = arraynew(1);
//grab the number of elements in the array (used in the loops)
var count = arrayLen(aOfS);
//make a variable to use in the loop
var ii = 1;
//if there is a 3rd argument, set the sortOrder
if(arraylen(arguments) GT 2)
sortOrder = arguments[3];
//if there is a 4th argument, set the sortType
if(arraylen(arguments) GT 3)
sortType = arguments[4];
//if there is a 5th argument, set the delim
if(arraylen(arguments) GT 4)
delim = arguments[5];
//loop over the array of structs, building the sortArray
for(ii = 1; ii lte count; ii = ii + 1)
sortArray[ii] = aOfS[ii][key] & delim & ii;
//now sort the array
arraySort(sortArray,sortType,sortOrder);
//now build the return array
for(ii = 1; ii lte count; ii = ii + 1)
returnArray[ii] = aOfS[listLast(sortArray[ii],delim)];
//return the array
return returnArray;
}

I don't have the reputation points to comment on #mikest34 post above but #russ was correct that this callback no longer works the way it was explained.
It was Adam Cameron who discovered that when using arraySort with a callback, it no longer requires a True/False response but rather:
-1, if first parameter is "smaller" than second parameter
0, if first parameter is equal to second parameter
1, first parameter is "bigger" than second parameter
So the correct callback is:
ArraySort(yourArrayOfStructs, function(a,b) {
return compare(a.struct_date, b.struct_date);
});
Testing and working in CF2016

The accepted solution (from CFLib.org) is NOT safe. I experimented with this for something I needed to do at work and found that it returns incorrect results when sorting numeric with floats.
For example if I have these structs: (pseudocode)
a = ArrayNew(1);
s = StructNew();
s.name = 'orange';
s.weight = 200;
ArrayAppend(a, s);
s = StructNew();
s.name = 'strawberry';
s.weight = 28;
ArrayAppend(a, s);
s = StructNew();
s.name = 'banana';
s.weight = 90.55;
ArrayAppend(a, s);
sorted_array = arrayOfStructsSort(a, 'weight', 'asc', 'numeric');
Iterate over the sorted array and print the name & weight.
It won't be in the right order, and this is a limitation of mixing
an arbitrary key with the value being sorted.

You can use the Underscore.cfc library to accomplish what you want:
arrayOfStructs = [
{myAttribute: 10},
{myAttribute: 30},
{myAttribute: 20}
];
_ = new Underscore();
sortedArray = _.sortBy(arrayOfStructs, function (struct) {
return struct.myAttribute;
});
Underscore.cfc allows you to define a custom comparator and delegates to arraySort(). You can use it for sorting arrays, structs, queries, or string lists, but it always returns an array.
(Disclaimer: I wrote Underscore.cfc)

I wanted to throw my two cents in here. I ran into a case where I needed to sort an array of structures using more than one key. I wound up using a constructed query to do my sorting. The function takes the array of structs as the first argument, and then an array of structs indicating the sort order, like this:
<cfset result = sortArrayOfStructsUsingQuery(myArrayOfStructs,[
{name = "price", type = "decimal", sortOrder = "asc"},
{name = "id", type = "integer", sortOrder = "asc"}
])>
Within the sortArrayOfStructsUsingQuery function, I construct a query based only on the keys I pass in, then sort that query. Then, I loop over the query, find the structure element from the array which matches the data at the current query row, and add that structure to the array I hand back.
It's entirely possible there's a gaping hole in this code that my testing hasn't uncovered (there haven't been a lot of use-cases for me yet), but in case it's useful to anybody, here it is. Hope it's useful, and if there are any glaring holes, I'm happy to hear about them.
(just a note: I use the "local" scope for all variables that will stay in the function, and the "r" scope for anything I intend to hand back, for whatever that's worth)
<cffunction name="sortArrayOfStructsUsingQuery" output="yes" returnType="array">
<cfargument name="array" type="array" required="true">
<cfargument name="sortKeys" type="array" required="true">
<cfset var local = {
order = {
keyList = "",
typeList = "",
clause = ""
},
array = duplicate(arguments.array),
newArray = []
}>
<cfset var r = {
array = []
}>
<cftry>
<!--- build necessary lists out of given sortKeys array --->
<cfloop array=#arguments.sortKeys# index="local.key">
<cfset local.order.keyList = listAppend(local.order.keyList, local.key.name)>
<cfset local.order.typeList = listAppend(local.order.typeList, local.key.type)>
<cfset local.order.clause = listAppend(local.order.clause, "#local.key.name# #local.key.sortOrder#")>
</cfloop>
<!--- build query of the relevant sortKeys --->
<cfset local.query = queryNew(local.order.keyList, local.order.typeList)>
<cfloop array=#arguments.array# index="local.obj">
<cfset queryAddRow(local.query)>
<cfloop list=#local.order.keyList# index="local.key">
<cfset querySetCell(local.query, local.key, structFind(local.obj, local.key))>
</cfloop>
</cfloop>
<!--- sort the query according to keys --->
<cfquery name="local.sortedQuery" dbtype="query">
SELECT *
FROM [local].query
ORDER BY #local.order.clause#
</cfquery>
<!--- rebuild the array based on the sorted query, then hand the sorted array back --->
<cfloop query="local.sortedQuery">
<cfloop from=1 to=#arraylen(local.array)# index=local.i>
<cfset local.matchP = true>
<cfloop list=#local.order.keylist# index="local.key">
<cfif structKeyExists(local.array[local.i], local.key)
AND structFind(local.array[local.i], local.key) EQ evaluate("local.sortedQuery.#local.key#")>
<cfset local.matchP = true>
<cfelse>
<cfset local.matchP = false>
<cfbreak>
</cfif>
</cfloop>
<cfif local.matchP>
<cfset arrayAppend(r.array, local.array[local.i])>
<cfelse>
<cfif NOT arrayContains(local.newArray, local.array[local.i])>
<cfset arrayAppend(local.newArray, local.array[local.i])>
</cfif>
</cfif>
</cfloop>
<cfset local.array = local.newArray>
</cfloop>
<!--- Outbound array should contain the same number of elements as inbound array --->
<cfif arrayLen(r.array) NEQ arrayLen(arguments.array)>
<!--- log an error here --->
<cfset r.array = arguments.array>
</cfif>
<cfcatch type="any">
<!--- log an error here --->
<cfset r.array = arguments.array>
</cfcatch>
</cftry>
<cfreturn r.array>
</cffunction>

It's actually even easier with the new CF Closure support.
Here's an example I worked on today where I wanted to sort an array of structs by a date stored in the struct. I was sorting in descending order.
ArraySort(yourArrayOfStructs, function(a,b) {
if ( DateCompare(a.struct_date, b.struct_date) == -1 ) {
return true;
} else {
return false;
}
});
I can't take total credit as I adapted this from Ray Camden's on Closures from 2012.

Here's a UDF based on Tomalak's answer that also supports custom objects (e.g., used by some Railo-based CMSs). This function is compatible with ColdFusion 9.
<cffunction name="sortStructArray" returntype="array" access="public">
<cfargument name="base" type="array" required="yes">
<cfargument name="sortType" type="string" required="no" default="text">
<cfargument name="sortOrder" type="string" required="no" default="ASC">
<cfargument name="pathToSubElement" type="string" required="no" default="">
<cfset var _sct = StructNew()>
<cfset var _aryKeys = ArrayNew(1)>
<cfset var arySorted = ArrayNew(1)>
<cfif IsStruct(base[1])>
<!--- Standard structure --->
<cfloop from="1" to="#ArrayLen(base)#" index="i">
<cfset _sct[i] = base[i]>
</cfloop>
<cfset _aryKeys = StructSort(_sct, sortType, sortOrder, pathToSubElement)>
<cfloop from="1" to="#ArrayLen(_aryKeys)#" index="i">
<cfset arySorted[i] = _sct[_aryKeys[i]]>
</cfloop>
<cfelse>
<!--- Custom object (e.g., Catalog) --->
<cfloop from="1" to="#ArrayLen(base)#" index="i">
<cfset _sct[i] = StructNew()>
<cfset _sct[i][pathToSubElement] = base[i][pathToSubElement]>
</cfloop>
<cfset _aryKeys = StructSort(_sct, sortType, sortOrder, pathToSubElement)>
<cfloop from="1" to="#ArrayLen(_aryKeys)#" index="i">
<cfset arySorted[i] = base[_aryKeys[i]]>
</cfloop>
</cfif>
<cfreturn arySorted>
</cffunction>

In case you don't want to use custom methods, Coldfusion has structSort method http://www.cfquickdocs.com/cf8/#StructSort . Yes it sorts structure with nested structures, BUT returns array so could be used to achieve same result.

Easy solution to sort an array of structures using more than one key using arraySort callback:
It takes array of structs to be sorted as first parameter and array of structs in format of sortkey/sortorder pair as second parameter e.g. [{sortkey: 'FirstName', sortorder: 'asc'}, {sortkey: 'LastName', sortorder: 'desc'}].
<cffunction name="arrayOfStructsSort" access="public" returntype="array" output="false" hint="This sorts an array of structures.">
<cfargument name="aOfS" type="array" required="yes" />
<cfargument name="key_sortOrder" type="array" required="yes" />
<cfscript>
arraySort(
aOfS,
function (a, b) {
for (var i = 1; i lte arrayLen(key_sortOrder); i = i + 1) {
var prop = key_sortOrder[i];
var key = prop.key;
var sortOrder = prop.sortOrder;
if (a[key] lt b[key]) {
if (sortOrder eq 'desc') {
return 1;
} else {
return -1;
}
}
if (a[key] gt b[key]) {
if (sortOrder eq 'desc') {
return -1;
} else {
return 1;
}
}
}
return 0;
}
);
return aOfS;
</cfscript>
</cffunction>
Simply call it with:
<cfset ArraySorted = arrayOfStructsSort(arrayToBeSorted,arrayOfSorkeys)>

Related

Sequence number generation in odoo

I am using this code for sequence generation
class cardInfo(models.Model):
_name = "library.card"
card_number = fields.Char(String = "Card Number" , size = 7, Translate = True, readonly = True)
user_name = fields.Many2one('student.student',String = "Name")
card_type = fields.Selection([('s', 'Student'), ('l', 'Staff')] , String = "Card Type")
number_of_book_limit = fields.Integer(String = "No Of Book Limit" , default = 0)
#api.model
def create(self, vals):
seq = self.env['ir.sequence'].next_by_code('library.card.number') or '/'
vals['card_number'] = seq
return super(cardInfo, self).create(vals)
but i am getting only the '/' as sequence number.. why?
You need to create "ir.sequance" in xml file like,
<record id="seq_library_card" model="ir.sequence">
<field name="name">Library Card</field>
<field name="code">library.card</field>
<field name="prefix">LIB</field>
<field name="padding">5</field>
<field name="company_id" eval="False" />
</record>
In Py file you have to write like,
#api.model
def create(self, vals):
x = self.env['ir.sequence'].next_by_code('library.card') or '/'
vals['card_number'] = x
return super(LibraryCard, self).create(vals)

Filtered subgrid - createCallbackFunctionObject throwing indescript error

I am attempting to create a filtered N:N subgrid with the code from here:
This is a Dynamics 365 Online instance if that helps. The problem I am facing though is strange in that the lookup window comes up, filters perfectly, and allows me to choose items. But when I click "add" I get a general error message.
As far as I can tell everything in the code is fine but I am unclear as to how I should proceed to debug this. My initial thought is that I could start debugging in the crmWindow.Mscrm.Utilities.createCallbackFunctionObject function but I am unclear as to how to debug that function in the global.ashx file in an online environment. My thought is that within there I may be able to get an error I can use.
Any idea?
//filters an add existing lookup view (N:N)
function addExistingFromSubGridCustom(gridTypeCode, gridControl, crmWindow, fetch, layout, viewName) {
var viewId = {DB2C6D94-48F2-E711-A2B6-00155D045E00}; // a dummy view ID
var relName = gridControl.GetParameter(relName);
var roleOrd = gridControl.GetParameter(roleOrd);
//creates the custom view object
var customView = {
fetchXml: fetch,
id: viewId,
layoutXml: layout,
name: viewName,
recordType: gridTypeCode,
Type: 0
};
var parentObj = crmWindow.GetParentObject(null, 0);
var parameters = [gridTypeCode, , relName, roleOrd, parentObj];
var callbackRef = crmWindow.Mscrm.Utilities.createCallbackFunctionObject(locAssocObjAction, crmWindow, parameters, false);
crmWindow.LookupObjectsWithCallback(callbackRef, null, multi, gridTypeCode, 0, null, , null, null, null, null, null, null, viewId, [customView]);
}
function filterAddExistingContact(gridTypeCode, gridControl, primaryEntity) {
debugger;
var crmWindow = Xrm.Internal.isTurboForm() ? parent.window : window;
var lookup = new Array();
lookup = Xrm.Page.getAttribute(new_channel).getValue();
if (lookup != null) {
var name = lookup[0].name;
var id = lookup[0].id;
var entityType = lookup[0].entityType;
}
else
{
crmWindow.Mscrm.GridRibbonActions.addExistingFromSubGridAssociated(gridTypeCode, gridControl); //default button click function
return;
}
if (primaryEntity != nxt_callreport) {
crmWindow.Mscrm.GridRibbonActions.addExistingFromSubGridAssociated(gridTypeCode, gridControl); //default button click function
return;
//Mscrm.GridRibbonActions.addExistingFromSubGridAssociated(gridTypeCode, gridControl); //default button click function
//return;
}
//fetch to retrieve filtered data
var fetch = <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> +
<entity name="new_market"> +
<attribute name="new_marketid" /> +
<attribute name="new_name" /> +
<attribute name="createdon" /> +
<order attribute="new_name" descending="false" /> +
<filter type="and"> +
<condition attribute="new_channel" operator="eq" uiname=" + name + " uitype=" + entityType + " value=" + id + " /> +
</filter> +
</entity> +
</fetch>;
//columns to display in the custom view (make sure to include these in the fetch query)
var layout = <grid name="resultset" object="1" jump="new_name" select="1" icon="1" preview="1"> +
<row name="result" id="new_name"> +
<cell name="new_name" width="300" /> +
</row> +
</grid>;
addExistingFromSubGridCustom(gridTypeCode, gridControl, crmWindow, fetch, layout, Filtered Markets);
}
Update this line:
var crmWindow = Xrm.Internal.isTurboForm() ? parent.window : window;
To
var crmWindow = Xrm.Internal.isTurboForm() ? top.parent.window : top.window;
and update:
crmWindow.Mscrm.Utilities.createCallbackFunctionObject(

cf9 query grid values SQL

I have a grid bound to a cfc, populating an id column and a checkbox (boolean) column. onLoad, i want to get a list of ID values, but only those having checkbox = 1
Here is the working code, with great help from Jan S
<script language="JavaScript">
function init(){
var grid = ColdFusion.Grid.getGridObject('testgrid');
var gs = grid.getStore();
var records = gs.getRange();
var filteredRecords = [];
for (i = 0; i < records.length; i++) {
// note: for CF, you MUST capitalize grid header names
if (records[i].get('SELECT') === 1) {
var thisID = records[i].get('ID');
filteredRecords.push(thisID);
}
}
document.getElementById('idList').value=filteredRecords;
}
ColdFusion.Event.registerOnLoad(init,null,false,true);
</script>
<cfset items=QueryNew("id,Description,Select")>
<cfset Temp=QueryAddRow(items,1)>
<cfset Temp=QuerySetCell(items,"id","11")>
<cfset Temp=QuerySetCell(items,"Description","Some item")>
<cfset Temp=QuerySetCell(items,"Select",1)>
<cfset Temp=QueryAddRow(items)>
<cfset Temp=QuerySetCell(items,"id","22")>
<cfset Temp=QuerySetCell(items,"Description","Some other item")>
<cfset Temp=QuerySetCell(items,"Select",1)>
<cfset Temp=QueryAddRow(items)>
<cfset Temp=QuerySetCell(items,"id","33")>
<cfset Temp=QuerySetCell(items,"Description","A third item")>
<cfset Temp=QuerySetCell(items,"Select",0)>
<cfform>
<cfgrid name="testgrid" format="html" query="items">
<cfgridcolumn name="id" header="ID" select="no">
<cfgridcolumn name="Description" header="Description" select="no">
<cfgridcolumn name = "Select" header="Select" select="yes" type="boolean">
</cfgrid>
<br>
<!--- populate this with list of ID's having the checkbox checked, here: 11,22 --->
<input type="text" name="idList" id="idList"> <input type="button" name="getList" value="Get List" onClick="init()">
</cfform>
Basically I need to translate into AJAX this SQL statement:
select stringColumn where booleanColumn = 1 from myGrid
I'm using Cold Fusion 9 which is based on js ext 3.1 i believe
to get an array with all a field from all records where another field is 1:
isData.on('load', function(store, records){
// create a new array with all records where the 'booleanColumn' is = 1
var filteredRecords = [];
for (i = 0; i < records.length; i++) {
if (records[i].get('booleanColumn') === 1) {
filteredRecords.push(records[i]);
}
}
console.log(filteredRecords);
// create a new array of 'stringColumn' values
var filteredValues = [];
for (i = 0; i < filteredRecords.length; i++) {
filteredValues[i] = filteredRecords[i].get('stringColumn');
}
console.log(filteredValues);
// proceed with filtered values...
});

How to get the values of this xml using linq?

I have the following in my xml:
<mur>
<bak>
</bak>
<itemfb ident="c_fb">
<flow_m>
<mat>
<text texttype="text/plain">correct answer comments</text>
</mat>
</flow_m>
</itemfb>
<itemfb ident="gc_fb">
<flow_m>
<mat>
<text texttype="text/plain">wrong, you made a blunder</text>
</mat>
</flow_m>
</itemfb>
</mur>
Now, the 'itemfb' tag, may or may not exist within a 'mur' tag and if exists, I need to parse and get the values "correct answer comments" (or) "wrong, you made a blunder" depending on "itemfb" ident. Here is what I have tried. Assume rowObj has the loaded xml from "mur" and 'ns' is the namespace
if (rowObj.Elements(ns + "itemfb").Any())
{
var correctfb = (from cfb in rowObj
.Descendants(ns + "itemfb")
where (string)cfb.Attribute(ns + "ident").Value == "cfb"
select new
{
ilcfb = (string)cfb.Element(ns + "mat")
}).Single();
some_variable_1 = correctfb.ilcfb;
var incorrectfb = (from icfb in rowObj
.Descendants(ns + "itemfb")
where (string)icfb.Attribute(ns + "ident").Value == "gcfb"
select new
{
ilicfb = (string)icfb.Element(ns + "mat")
}).Single();
some_variable_2 = incorrectfb.ilicfb;
}
This should be a way to get the information you want. I omitted ns for simplicity.
var correctfb = rowObj.Descendants("mur")
.Descendants("itemfb")
.Where(e => e.Attribute("ident").Value == "c_fb")
.Descendants("text").FirstOrDefault();
if (correctfb != null)
some_variable_1 = correctfb.Value;
var incorrectfb = rowObj.Descendants("mur")
.Descendants("itemfb")
.Where(e => e.Attribute("ident").Value == "gc_fb")
.Descendants("text").FirstOrDefault();
if (incorrectfb != null)
some_variable_2 = incorrectfb.Value;

Can I 'flatten' an XDocument with Linq?

I have a heavily nested XML document that I need to load into my db for additional processing. For various reasons beyond the scope of this discussion I need to 'flatten' that structure down, then load it into a DataTables and then I can SQLBulkCopy it into the db where it will get processed. So assume my original XML looks something like this (mine is even more heavily nested, but this is the basic idea):
<data>
<report id="1234" name="XYZ">
<department id="234" name="Accounting">
<item id="ABCD" name="some item">
<detail id="detail1" value="1"/>
<detail id="detail2" value="2"/>
<detail id="detail3" value="3"/>
</item>
</department>
</report>
</data>
and I want to flatten that down into a single (albeit redundant) table structure where each attribute becomes a column (i.e. ReportId, ReportName, DepartmentId, DepartmentName, ItemId, ItemName, Detail1, Detail2, Detail3).
So my question is simply 'is it possible to accomplish this with a simple Linq query'? In the past I would just write some XSLT and be done with it but I'm curious if the Linq library can accomplish the same thing?
thanks!
Is this what you're looking for?
var doc = XDocument.Load(fileName);
var details =
from report in doc.Root.Elements("report")
from department in report.Elements("department")
from item in department.Elements("item")
from detail in item.Elements("detail")
select new
{
ReportId = (int)report.Attribute("id"),
ReportName = (string)report.Attribute("name"),
DepartmentId = (int)department.Attribute("id"),
DepartmentName = (string)department.Attribute("name"),
ItemId = (string)item.Attribute("id"),
ItemName = (string)item.Attribute("name"),
DetailId = (string)detail.Attribute("id"),
DetailValue = (int)detail.Attribute("value"),
};
If you want it as a DataTable, you can use the following extension method:
public static DataTable ToDataTable<T>(this IEnumerable<T> source)
{
PropertyInfo[] properties = typeof(T).GetProperties()
.Where(p => p.CanRead && !p.GetIndexParameters().Any())
.ToArray();
DataTable table = new DataTable();
foreach (var p in properties)
{
Type type = p.PropertyType;
bool allowNull = !type.IsValueType;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
allowNull = true;
type = Nullable.GetUnderlyingType(type);
}
DataColumn column = table.Columns.Add(p.Name, type);
column.AllowDBNull = allowNull;
column.ReadOnly = !p.CanWrite;
}
foreach (var item in source)
{
DataRow row = table.NewRow();
foreach (var p in properties)
{
object value = p.GetValue(item, null) ?? DBNull.Value;
row[p.Name] = value;
}
table.Rows.Add(row);
}
return table;
}
Use it like this:
var table = details.CopyToDataTable();

Resources