dongyu9850
2019-01-18 11:10
浏览 297
已采纳

Yii2在ActiveForm中包含datetimepicker

I'm using Activeform and I need a custom field to insert datetime values.

I've found a possible solution myself with kartik DateTimePicker although it is much more complex than I wanted, anyway I don't know how to put the value in the model's attribute.

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
    ]
]);
?>

I accept also solutions offering a simpler way to show the field.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqp99585 2019-01-18 11:50
    已采纳

    If i understand correctly you are asking about using the widget with the model rather than calling it statically as you are currently copying the value to another ActiveForm field and then submitting it. If that is correct you can use the widget as a part of ActiveForm field so that you don't have to insert the date into a separate model input to submit and save, see below.

    <?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
            ]
        ]
        );
    ?>
    

    or you can pass the $model and attribute to your current code when calling the widget like below

    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
            ]
        ]
    );
    

    You can either pass the name/model & attribute option see details

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题