我目前正在使用这个函数
public $year;
public $month;
public $day;
protected function afterFind() {
parent::afterFind();
$dob = explode('/', $this->dob);
$this->year = $dob[0];
$this->month = $dob[1];
$this->day = $dob[2];
return $this;
}
protected function beforeSave() {
$this->dob = $this->year .'/'. $this->month .'/'. $this->day;
}
<div class="col-md-2 dayForm noPadding">
<?php
echo $form->textFieldGroup(
$user,
'day',
array(
'widgetOptions' => array(
'htmlOptions' => array(
'placeholder' => 'DD'
)
)
)
);
?>
</div>
<div class="col-md-3 monthForm ">
<?php
echo $form->dropDownListGroup(
$user,
'month',
array(
'widgetOptions' => array(
'data' => array('01' => 'January' , '02' => 'February' , '03' => 'March' , '04' => 'April' , '05' => 'May' , '06' => 'June' , '07' =>'July' , '08' =>'August' , '09' =>'September' , '10' =>'October' , '11' =>'November' , '12' =>'December'),
// 'data' => 'Jan','Feb';
'htmlOptions' => array(
'class' => 'col-md-3 ',
'prompt' => 'Choose month',
),
)
)
);
?>
</div>
<div class="col-md-2 yearForm noPadding">
<?php
echo $form->textFieldGroup(
$user,
'year',
array(
'widgetOptions' => array(
'htmlOptions' => array(
'placeholder' => 'YYYY',
'class' => 'col-md-3',
)
)
)
);
?>
</div>
将出生日期字段拆分为 3 个单独的字段。简单正确的是,用户输入日,月和年,并以正确的格式。我遇到的问题是,当用户去更新整个 dob 字段时,所有 dob 字段都显示在年份文本字段组中,不太好。
如何在出路时将其分解,以便所有相应的字段都出现在其文本字段组/下拉列表组中?
我总是尽量避免使用afterFind
,因为它往往会使事情复杂化,从而难以解决像您这样的问题。您通常可以通过添加 getter(以及可选的设置器)来实现类似的结果;
protected function getDobParts()
{
return explode('/', $this->dob);
}
protected function changeDobPart($part, $newValue)
{
$parts = $this->getDobParts();
$parts[$part] = $newValue;
$this->dob = implode('/', $parts);
}
public function getYear()
{
return $this->getDobParts()[0];
}
public function setYear($value)
{
$this->changeDobPart(0, $value);
}
public function getMonth()
{
return $this->getDobParts()[1];
}
public function setMonth($value)
{
$this->changeDobPart(1, $value);
}
public function getDay()
{
return $this->getDobParts()[2];
}
public function setMonth($value)
{
$this->changeDobPart(2, $value);
}
Yii 将负责使这些 getter/setter 自动作为属性提供(例如 $class-> 年)。
您的视图代码应保持不变。
通常最佳做法是在重写父方法时返回父方法的结果。例如,beforeSave()
的最后一行通常应该return parent::beforeSave();
。如果您不这样做,您的类甚至可能无法正确保存。