Yii2的日期插件(Daterangepicker)实用版 发表于 2015-12-08 Yii2的日期插件封装(一)定义安装目录1"directory" : "../yiisoft/vendor/bower" (二)安装相关插件与注册yii2assets 打开终端开始安装daterangepicker插件 运行bower install bootstrap-daterangepicker 成功后在项目的assets目录新建DaterangepickerAsset的文件. 123456789101112131415161718namespace 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类1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677namespace 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); }} (四)是调用写好的组件12345<div class="row"> <div class="col-md-5"> <?= $form->field($model, 'attribute')->widget(Daterangepicker::className(),$config)?> </div></div>