ERROR:Can't cast Object type [DateTime] to a value of type [Array]
<cfset Seniority=ArrayNew(1)>
<CFLOOP QUERY="all_employees">
<cfif isNull(all_employee.TimeInPositionDate) >
<cfset ArrayAppend(Seniority,all_employee.hiredate)>
<cfelse>
<cfset ArrayAppend(Seniority,all_employee.TimeInPositionDate)>
</cfif>
</CFLOOP>
I still think looping is much easier in CFScript (not to mention the fact that it just looks cleaner to me. Anyway, I can knock this down to essentially one line of code (beyond the array creation and looping code).
First, I set up my fake query object:
I have created 3 rows. 1 full row, 1 with just a
TimeInPositionDate, 1 with just ahiredateand 1 with neither. ColdFusion has always been a little odd with how it treatsnull, and it doesn't always mesh up well with a SQL query. In our fake query, we just don't define the rows we want to benull.Next I create my array:
We don't have to use
ArrayNew()to make an array. We can just use implicit notation to be much shorter.Next we use a
for/inloop around our query to append row data to our new array.Here, we're using the
append()member function to add to ourSeniorityarray. We also use a ternary operation to pick which value we want to add. It basically says that if there is a length toTimeInPositionDatefor that row, then we use the first condition (TimeInPositionDate), otherwise we usehiredate.I though about using an Elvis Operator...
..., but since the query is likely returning
q.TimeInPositionDate=""instead of an actualnullvalue, then the first value is technically defined and gets chosen. That would work on a truenull, but an empty string isn't anull.You could probably also use
each()or some other loopish function to iterate through your query object, but I've foundfor/inloops to usually be faster in cases like this. You'll have to test.You can play with the full thing at:
https://cffiddle.org/app/file?filepath=de107907-234c-4df8-9386-02a288e53313/fdf21791-6cc4-4c55-b923-ad7726efa8ee/b3b6b906-8e3a-4f6b-9ec8-65845efc40f1.cfm
EDIT:
NULLs can be so much fun. If we drop back into some Java, we can get an actualnullvalue from the query rather than thecfquery-converted empty string, and show that Elvis is still in the building.Since Java's
getDate()on a query will get the actual value and can handle anull, that correctly chooses the 2nd option for rows whereTimeInPositionDateisnull. That said, while I do appreciate the integration of Java and ColdFusion, I do not recommend it in this case. It's doing a lot of mixing of Java into the CF and isn't necessary beyond the demonstration.