Yii: specify a default value in a CActiveForm control

This evening I’ve been working again on my measurement system. This is a little application I wrote using the Yii framework to keep track of the energy needs of our household.

It keeps track of the gas, water and eletricity usage per day. As said the site is build using the Yii framework. It features some nice charting generated by the highcharts jquery plugin. I wrote this litte application in just a few days during my free time. Therefore there are alot of things to tweak.

One of the things I wanted to change today is to have the current date pre filled in in the add form (see screenshot ):

Since the Yii framework makes use of the CActiveForm class methods to generate a textfield I dont know for sure how to add a default value to the date textbox. So I fired up google and started to search for how other Yii developers would solve this problem. The first hit gave me a post on the official forums where a developer said that the original topic starter should set the default value in the model object.

I dont really like this advise. Because a model should never be aware of the behaviours of the view it is being used in so I decided to check the second hit and the advice someone gave at that particular post was much better. Simple use the html options property of the textfield method to set the ‘value’ property directly into the HTML like this:

$form->textfield(‘label’,’valuebinding’,array(‘value’=>date(‘d-m-y’));

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.