Since I have made the switch to using ColdBox, I never get tired of discovering features that are already built into the framework. I find myself so caught up in the framework “just working” that I sometimes forget to look into all of the plugins for features that I could really take advantage of. Luis calls ColdBox “A next generation Framework and Development Toolkit” and I really keep forgetting about the development toolkit part. There are so many built-in tools to help you out with your application that its almost dizzying.
One such plugin that I have found myself using quite often lately is the BeanFactory plugin. This plugin makes working with Transfer extremely easy by automatically populating new beans with data for you among other things. Im not going to go into full detail but I wanted to show an example of populating an empty Transfer object with data and saving that Transfer object back to the database.I have a form that accepts user data to allow users to register with the site. Whats in this form is not really relevant at this point, we just need to know that when we submit the form, its data is put into the request collection or RC scope for us by ColdBox and that the form is submitted to an event named User.doAddUser. Lets take a look at the code for the doAddUser method in the User event handler that will be saving our form data.
Now lets break this code down further and see just whats going on here. Im not going to cover the standard ColdBox code, that stuff has been covered in other posts on my blog. Instead we will focus on the bits that get the work done.
The first line here grabs the event collection and sticks it into the rc scope for easy reference. This isnt entirely necessary as there are other ways of doing it but this is the easier and has almost become a convention among ColdBox users.
The next couple of lines create a local variable and assign it to a new empty Transfer object of the users type from our trasfer config.
Now the magic happens! We make a simple call to the beanFactory plugin and call the populateBean method and pass in our empty Transfer object. The beanFactory will take the form data out of the RC scope and use it to populate the Transfer object automagically.
Then we simply call the save method of our Transfer object and pass our newly populated bean as an argument.
Lastly, we use another one of ColdBox’s nifty tools and call the MessageBox plugin to return a nice success message to our next event and then relocate the request to the dspUsers method to display our list.
Thats all there is to it. Thats one of the things that sets ColdBox apart form some of the other ColdFusion frameworks in my opinion. Its not only geared toward helping you build more elegant applications but also to make that process easier with its toolset.