Yii2的日期插件(Daterangepicker)实用版

Yii2的日期插件封装

(一)定义安装目录

1
"directory" : "../yiisoft/vendor/bower"

(二)安装相关插件与注册yii2assets

  1. 打开终端开始安装daterangepicker插件
  2. 运行bower install bootstrap-daterangepicker
  3. 成功后在项目的assets目录新建DaterangepickerAsset的文件.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
namespace app\assets;
use yii\web\AssetBundle;
class DaterangepickerAsset extends AssetBundle
{
public $sourcePath = '@bower';
public $js = [
'moment/moment.js',
'bootstrap-daterangepicker/daterangepicker.js',
];
public $css = [
'bootstrap-daterangepicker/daterangepicker.css'
];
public $depends = [
'yii\bootstrap\BootstrapAsset',
];
}

(三)新建一个日期组件扩展InputWidget类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
namespace backend\componment;
use backend\assets\DaterangepickerAsset;
use yii\widgets\InputWidget;
use yii\helpers\Html;
use yii\helpers\Json;
class Daterangepickper extends InputWidget
{
/**
* @var array
*
*/
public $inputOptions = ['class' => 'form-control'];
public $initConfig = [
'locale'=>[ 'format' => 'YYYY-MM-DD'],
'singleDatePicker'=> true,
'showDropdowns'=> true
];
public $options = [];
public $language;
public $config = [];
public $is_show_applyLabel = true;
public $is_show_cancelLabel = true;
public function init()
{
parent::init(); // TODO: Change the autogenerated stub
if(!isset($this->options['id'])){
$this->options['id'] = $this->getId();
}
}
/**
* Executes the widget.
* @return string the result of widget execution to be outputted.
*/
public function run()
{
parent::run(); // TODO: Change the autogenerated stub
$start = Html::activeTextInput($this->model, $this->attribute.'[start]', ['id'=>$this->options['id'].'start' ,'class' => 'form-control' ]);
$end = Html::activeTextInput($this->model, $this->attribute.'[end]', ['id'=>$this->options['id'].'end' ,'class' => 'form-control' ]);
$html =<<<HTML
<div class="input-group input-daterange">
<div class="">
{$start}
</div>
<span class="input-group-addon">到</span>
<div class="">
{$end}
</div>
</div>
HTML;
echo $html;
$this->registerClientScript();
}
public function registerClientScript(){
$id = $this->options['id'];
$config= Json::encode(array_merge($this->config, $this->initConfig));
$js = "
$('#{$id}start').daterangepicker({$config});
$('#{$id}end').daterangepicker({$config});
";
$view = $this->getView();
DaterangepickerAsset::register($view);
$view->registerJs($js);
}
}

(四)是调用写好的组件

1
2
3
4
5
<div class="row">
<div class="col-md-5">
<?= $form->field($model, 'attribute')->widget(Daterangepicker::className(),$config)?>
</div>
</div>