Convert Separate Date Fields to Single Date Value

Hi Folks,

Just starting to get to grips with yii so please bear with me if this is a simple question!

I have a model with a birthday attribute (datetime type in mysql) which looks like this:


...

array('birthday', 'required'),

array('birthday', 'numerical', 'integerOnly'=>true),

...

On my register form I output 3 select lists representing the month, day, year fields eg:


...

echo CHtml::activeDropDownList($form, 'month', Date::getMonths(),$html);

echo CHtml::activeDropDownList($form, 'day', Date::getDays(),$html);

echo CHtml::activeDropDownList($form, 'year', Date::getYears(),$html);?>

...

When I submit the form what is the correct approach to take these 3 values and convert them into a single value to be used in the birthday attribute?

Incidentally I’ve seen the jquery date control is available but I don’t like the user experience for selecting a birthday via a calendar widget. I’d prefer to stay with the 3 lists ala Digg.

Thanks,

Paul.

You can “build” the birthday attribute in the model’s beforeValidate() method which is invoked before validation starts.

http://www.yiiframework.com/doc/api/CModel#beforeValidate-detail

Thanks Andy,

Would something like this seem to be the right way to go:


$user->setAttribute("birthday",/* calculated date value */);

Paul.

Why not just $user->birthday = $value ?

Also, you can add month, day, year fields to your model and some rules for them (to be integer only, for example). But don’t forget to set them “safe”.

Ah ok. I’d done setAttribute because I was following some example code where it does this in the controller for a “register” scenario:


 $form->attributes=$_POST['User'];  

I appreciate that does a mass update but I assumed it was still necessary to use setAttribute to set individual model attributes as well. Also when debugging the model doesn’t appear to have an explicit birthday attribute so I thought going your route would cause an error - obviously it doesn’t!.

Thanks again for your help.

Hi there,

What about if your database has day, month and year values in three separated columns.

And you want to query for all records that are older than today?

Today is 2011-05-22.-

Ex.




 column_id | column_year | column_month | column_day

 --------------------------------------------------

 1 | 2010 | 05 | 25

 2 | 2011 | 03 | 14

 3 | 2011 | 04 | 28

  

My first approach is wrong… is something like this:




 		$criteria->condition='

 			column_year <= :year

 			AND

 			column_month <= :month

 			AND

 			column_day <= :day

 			';

 		$criteria->params = array(

 			':year'		=> '2011',

 			':month'	=> '05',

 			':day'		=> '22'

 			);

 

Record 1 and 3 will not be shown.-

Any ideas? Thx!