FW/1’s populate() method uses named arguments

Just a quick tip for anyone using FW/1’s populate() method to populate their objects.

I ran into a problem where my auto-generated setters were being called correctly by the populate() method, but my explicit setters were not. And because FW/1 ignores any error generated here, I couldn’t work out why this was…

Traditionally, I’ve always written my setters as follows:

<cffunction name="setFirstName">
	<cfargument name="value" type="string" required="true" />
	<cfset variables.firstname = arguments.value />
</cffunction>

…and it would work fine, since it was always being called as setFirstName("Seb"). It’s a bit of laziness really, when writing setters by hand – it means there’s two fewer changes to make when copying and pasting.

But a quick look at FW/1’s code shows us this:

<cfinvoke component="#arguments.cfc#" method="#key#" argumentCollection="#args#" />

So when it finds a value for rc.firstname, FW/1 is essentially calling:

setFirstName( firstname = rc.firstname )

- which will of course fail if my setter is expecting an argument of “value”.

The solution is this: when creating a setter, always name the argument to match the value being set. So my setter above should instead read:

<cffunction name="setFirstName">
	<cfargument name="firstname" type="string" required="true" />
	<cfset variables.firstname = arguments.firstname />
</cffunction>
 

Comments

Sean Corfield

You can define onPopulateError() in Application.cfc to see exceptions in populate() - and exceptions are only "ignored" if you specify trustKeys = true (which you need for the implicit setters in 1.x - they'll be supported better in 2.0).

15 August 2010, 19:58
Reply
Seb Duggan

Thanks Sean - it was using the onPopulateError() method that I found out what was wrong! And yes, I was using trustKeys=true.

Good also to hear about the improvement in 2.0...

15 August 2010, 23:29
Reply
Post a Comment
  1. Leave this field empty

Required Field