Friday 6 February 2009

Do you know how to retieve the form value from bean in MVC Framework in Coldfusion ?

While working with MVC framework, if you want to retrieve the value from UI form elements to bean file of model.
Sometimes, we have this kinda problem, we are not able to retrieve value from bean. To resolve the value which are provided to UI, at that time, the Name of function on Bean file should be exactly same as the elements NAME value in UI.

Lets take a small example here,
you make a userBean.cfc at with the following content;

< cfcomponent output="false" name="userBean" displayName="Users Bean" >
< cfset variables.instance.username = "" / >
< cfset variables.instance.password = "" / >

< cffunction name="setUsername" returnType="void" access="public" output="false" >
< cfargument name="username" type="string" required="true" >
< cfset variables.instance.username = arguments.username >
< /cffunction >

< cffunction name="getUsername" returnType="string" access="public" output="false" >
< cfreturn variables.instance.username >
< /cffunction >

< cffunction name="setPassword" returnType="void" access="public" output="false" >
< cfargument name="password" type="string" required="true" >
< cfset variables.instance.password = arguments.password >
< /cffunction >

< cffunction name="getPassword" returnType="string" access="public" output="false" >
< cfreturn variables.instance.password >
< /cffunction >
< /cfcomponent >

you have a UI file as login.cfm at with the following content;
 
< cfform action="#viewstate.getValue('myself')#adminLoggedIn" method="post" >
< span >Sign In< /span >
< label for="username" >Email:< /label >
< cfinput type="text" name="username" value=""/ >< br / >
< label for="password" >Password:< /label >
< cfinput type="password" name="password" value=""/ >< br / >
< input type="submit" value="Submit" / >
< /cfform >

Now, if you go through above Bean file (userBean.cfc) & UI file (login.cfm),
the name= "username" and name="password" of login.cfm file have same name as the function name of userBean.cfc file as
setUsername();
getUsername();
setPassword();
getPassword();

Which do really work out.

if name value of login form and function name after have get/set prefix should be exactly same, otherwise it will not work out.