1

ユーザーの誕生日をフォーム(表示)で、日、月、年の3つのフィールドに分けます。私はそれを正しくやっているかどうか、そしてこれを行うためのより簡単な方法があるかどうか疑問に思います。

パフォーマンスのより良い方法はありますか?必須ではありませんが、すべての検索で日付が区切られています。


Model.php:

public $birthday_day;
public $birthday_month;
public $birthday_year;

...

public function afterFind() {
    $this->birthday_day = date('j', strtotime($this->birthday));
    $this->birthday_month = date('n', strtotime($this->birthday));
    $this->birthday_year = date('Y', strtotime($this->birthday));
}


public function beforeValidate() {
    if ($this->birthday_day  AND  $this->birthday_month  AND  $this->birthday_year)
        $this->birthday = new DateTime($birthday_year.'-'$birthday_month'-'.$birthday_day);

}
4

1 に答える 1

1

入力目的で日付を3つの部分に分割するだけの場合、代替オプションの1つは、CJuiDatePickerを使用して、ユーザーが完全な日付を選択できるようにすることです。

$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name'=>'birthday',
    'model'=>$model,
    'attribute'=>'birthday',
    'options'=>array(
        'showAnim'=>'fold',
    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));

次に、結果をデータベースに挿入するための目的の形式にフォーマットできます。

...
public function actionCreate()
{
    $model=new Model;
    if(isset($_POST['Model']))
    {
        $model->attributes=$_POST['Model'];
        $model->save();
        ...
    }
    ...
}
...

または更新します。

...
public function actionUpdate($id)
{
    $model=$this->loadModel($id);
    if(isset($_POST['Model']))
    {
        $model->attributes=$_POST['Model'];
        $model->save();
        ...
    }
    ...
}
...

日付を正しい形式で保存するために(つまり、ユーザーフレンドリーな形式からCJuiDatePicker dd / mm / yyyyをSQLテーブル形式に変換します。おそらくYYYY-mm-ddのようなものです)、モデルを保存する前にこれを変換できます。 、 そのようです;

public function beforeSave() {

    $this->birthday=date('Y-m-d',strtotime($this->birthday); // Or however you want to insert it

    return parent::beforeSave();
}

その後、アプリの他の場所に表示するために特定の日/月/年が必要な場合は、例のようにプロパティ(public $birthday_day;など)として設定できますが、まったく問題はありません。または、モデルのインスタンスを呼び出すたびに日付を変換したくない場合は、次のようにプロパティを設定できます。

public function getBirthday($part) {
    switch($part)
    {
        case 'day':
            return date('j', strtotime($this->birthday));
            break;
        case 'month':
            return date('n', strtotime($this->birthday));
            break;
        case 'year':
            return date('Y', strtotime($this->birthday));
            break;
        default:
            return date('d/m/Y', strtotime($this->birthday));
            break;
    }
}

そして、あなたがその日を望むなら、ただ電話$model->getBirthday('day');してください...またはあなたがそれをしたいのであれば、その最後のビットはより個人的な好みです!

于 2012-12-19T14:12:02.897 に答える