I have a page, where user can edit his own info. On this page there are also 3 dropdown lists for birth date (date, month, year). But I have only one column for birth date in my table, which accepts value in format "ddmmyyyy" How can I render these 3 fields in CActiveForm, so they together fill one complete value, like "ddmmyyyy"? Thank you. Update:
Model code:
public $day;
public $month;
public $year;
public function getDates()
{
return array(
20=>20,
21=>21,
);
}
public function getMonth()
{
return array(
01=>01,
02=>02,
);
}
public function getYears()
{
return array(
1990=>1990,
1991=>1991,
);
}
Controller code:
if(isset($_POST['User']))
{
$user->attributes=$_POST['User'];
$user->day = $_POST['User']['day'];
$user->month = $_POST['User']['month'];
$user->year = $_POST['User']['year'];
$date = $user->day . $user->month . $user->year;
$user->birthday = $date;
if($user->save())
$this->redirect('/user/index');
}
View code:
<div class="day">
<?php echo $form->dropDownList($user,'day', $user->getDates()); ?>
</div>
<div class="month">
<?php echo $form->dropDownList($user,'month', $user->getMonth()); ?>
</div>
<div class="year">
<?php echo $form->dropDownList($user,'year', $user->getYears()); ?>
</div>
In your model class create these 3 properties by hand. On your form you will reference just these three properties. You will make use of the events to wrap your database column values to these three fields like this:
In afterFind()
, make sure you have code that will split the database column property in all these three.
In beforeValidate()
make sure you have code that will take these three properties and join together in the database column property.
Add the necessary validation to the rules()
and labels to attributes()
.
Update
First of all some changes
$user->attributes=$_POST['User'];
$user->day = $_POST['User']['day'];
$user->month = $_POST['User']['month'];
$user->year = $_POST['User']['year'];
you don't need all the assignments if you add the day, month, year attribute to the 'safe' list. Read more at Understanding safe validation rules.
Move this code to the model class:
protected function beforeValidate()
{
$this->birthday = $this->day . $this->month . $this->year;
return parent::beforeValidate();
}
Make sure you call validation to validate the form:
if($user->validate() && $user->save())
$this->redirect('/user/index');
add code to afterFind() that is reverse to beforeValidate() as
protected function afterFind()
{
$this->day= ...get day part from $this->birthday...
$this->month=
$this->year=
return parent::afterFind();
}
You don't need all those getMonth() functions. You can use the range or the array_fill functions from PHP.
That means you get three variable value
you have to declare three variable.
$date=$_REQUEST['date'];
$month=$_REQUEST['month'];
$year=$_REQUEST['year'];
and you have other variable.
$birth_date=$date."/".$month."/".$year;
And then you will send this $birth_date variable data to your database table fild