首页 > 解决方案 > Yii2 在 ActiveForm 中包含 datetimepicker

问题描述

我正在使用 Activeform,我需要一个自定义字段来插入日期时间值。

我自己用 kartik DateTimePicker 找到了一个可能的解决方案,虽然它比我想要的复杂得多,但无论如何我不知道如何将值放入模型的属性中。

use kartik\datetime\DateTimePicker;


<?php $form = ActiveForm::begin(); ?>

// my working field using kartik library
<?= $form->field($model, 'course')->widget(\kartik\select2\Select2::className(),[
    'data' => $data,
    'language' => 'it',
    'options' => ['placeholder' => 'Select a Course ...'],
    'pluginOptions' => [
        'allowClear' => true
    ],
]);?>

// the field I need to implement placing the result in $form->field($model, 'opening_date')
<?php //echo '<label style="position:absolute; top:5px; text-align:left;">Recording Time</label>';

echo '<label>Start Date/Time</label>';
echo DateTimePicker::widget([
        'name' => 'opening_date',
    'options' => ['placeholder' => 'Select operating time ...'],
    'convertFormat' => true,
    'pluginOptions' => [
            'format' => 'd-M-Y g:i A',
        'startDate' => '01-Mar-2014 12:00 AM',
        'todayHighlight' => true
    ]
]);
?>

我也接受提供更简单方式来展示该领域的解决方案。

标签: phpyii2

解决方案


如果我理解正确,您是在询问是否将小部件与模型一起使用,而不是在您当前将值复制到另一个 ActiveForm 字段然后提交时静态调用它。如果这是正确的,您可以将小部件用作字段的一部分,ActiveForm这样您就不必将日期插入单独的模型输入来提交和保存,见下文。

<?php echo $form->field($model, 'opening_date')->widget(
    DateTimePicker::class, 
    [
        'options' => ['placeholder' => 'Select operating time ...'],
        'convertFormat' => true,
        'pluginOptions' => [
            'format' => 'd-M-Y g:i A',
            'startDate' => '01-Mar-2014 12:00 AM',
            'todayHighlight' => true
        ]
    ]
    );
?>

或者您可以在调用小部件时将$modeland传递attribute给当前代码,如下所示

echo DateTimePicker::widget(
    [
        'model' => $model,
        'attribute' => 'opening_date',
        'options' => ['placeholder' => 'Select operating time ...'],
        'convertFormat' => true,
        'pluginOptions' => [
            'format' => 'd-M-Y g:i A',
            'startDate' => '01-Mar-2014 12:00 AM',
            'todayHighlight' => true
        ]
    ]
);

您可以通过name/ model&attribute选项查看详细信息


推荐阅读