Sunday, April 11, 2010

ColdMVC: Create your own Helpers.

I wanted to try extending ColdMVC's helpers and create my own helper that formatted stuff for me and it turned out to be quite simple.

First, I created my own directory in my project called "helpers".

Second, I added a cfc named "format".

Third, I extended the ViewHelper from ColdMVC. Not sure, If this is the correct Helper Util class I am suppose to be using...but it worked.


<cfcomponent extends="coldmvc.utils.ViewHelper">

<!------>

<cffunction name="money" access="public" output="false" returntype="any">
<cfargument name="amount" required="false" default="0"/>

<cfreturn dollarFormat(arguments.amount)/>


</cffunction>

<!------>

</cfcomponent>


Lastly, I used my new helper function:

#$.format.money(product.getPrice())#


If you noticed in money() I set a default value of zero. For some odd reason when I put "product.getPrice()" in for the amount argument it has a value of [empty string] and it throws an error. The error says "The AMOUNT parameter to the money function is required but was not passed in.". But clearly there is a value of [empty string]. If any one knows what up give me hollar.

3 comments:

  1. If your helper isn't using anything from the base class, you definitely don't need to extend anything. In your case, you don't need to extend ViewHelper since your function is all self-contained.

    As for your issue with the AMOUNT parameter, welcome to the world of Hibernate. If you're dealing with a new product, your properties will all have NULL values. This is different than your properties having empty values. To get around this, you could use product.price(), which routes the request through onMissingMethod and returns an empty string if the property's value is null.

    On another note, you could create either a tag or a view plugin method to display the value, rather than accessing the helper directly, which reads rather poorly with #$.

    ReplyDelete
  2. I second that the "#$" being gross :)

    ReplyDelete