I have two ActiveRecord models:
-
User
-
UserProfile
Also a FormModel:
- LoginForm
I have one action that persists the User and UserProfile models.
My form has a Birth Date separated just like Facebook: Three drop down lists, one for the day, one for the month, one for the year.
But, I persist the birth date as one single UserProfile.Birthdate attribute.
I have added this to the UserProfileModel:
public $BirthDay;
public $BirthMonth;
public $BirthYear;
public function beforeValidate()
{
$this->DateOfBirth = $this->BirthYear.'-'.$this->BirthMonth.'-'.$this->BirthDay;
//$this->DateOfBirth = $this->BirthDay.'/'.$this->BirthMonth.'/'.$this->BirthYear;
return parent::beforeValidate();
}
in rules:
array( 'BirthDay, BirthMonth, BirthYear', 'safe', 'on'=>'register' ),
array( 'DateOfBirth', 'type', 'type' => 'date', 'dateFormat' => 'yyyy-m-d', 'message' => '{attribute} no es una fecha válida', ),
array( 'DateOfBirth', 'validateDate' ),
/*
Validator function to be used from rules()
*/
public function validateDate( $attribute, $params )
{
if(
( $this->BirthDay > 28 &&
$this->BirthMonth == 2 &&
$this->BirthYear % 4 != 0 ) // 29/feb on a non-leap year
||
( $this->BirthDay > 30 &&
in_array( $this->BirthMonth, array( 4,6,9,11 ) ) ) // 31 on a month with 30 days
||
( $this->BirthDay > 29 && $this->BirthMonth == 2 ) // later than 29/feb
)
{
$this->addError( $attribute,'La fecha de nacimiento no es una fecha válida');
}
}
In the views, I have to do this:
<?php echo $form->labelEx($userProfileModel, 'DateOfBirth'); ?>
<?php
$days = array();
for( $i = 1; $i <= 31; ++$i )
$days[ $i ] = $i;
$months = array();
for( $i = 1; $i <= 12; ++$i )
$months[ $i ] = $i;
$top_year = date( 'Y' ) - 12;
$years = array();
for( $i = $top_year; $i >= 1900; $i-- )
$years[ $i ] = $i;
echo CHtml::activeDropDownList( $userProfileModel, 'BirthDay', $days,
array( 'empty' => 'día',
'options'=> array (
$_POST['UserProfile']['BirthDay'] =>
array( 'selected' => true ) ) ) );
echo CHtml::activeDropDownList( $userProfileModel, 'BirthMonth', $months,
array( 'empty' => 'mes',
'options'=> array (
$_POST['UserProfile']['BirthMonth'] =>
array( 'selected' => true ) ) ) );
echo CHtml::activeDropDownList( $userProfileModel, 'BirthYear', $years,
array( 'empty' => 'año',
'options'=> array (
$_POST['UserProfile']['BirthYear'] =>
array( 'selected' => true ) ) ) );
?>
How would you do this? Is this the "Yii" way of dealing with this kind of situation?
Regards!
Luis