Repository: 2amigos/yii2-date-picker-widget
Branch: master
Commit: 48e73f154f8e
Files: 35
Total size: 43.8 KB
Directory structure:
gitextract_2641p111/
├── .gitattributes
├── .gitignore
├── .scrutinizer.yml
├── .travis.yml
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── composer.json
├── phpunit.xml.dist
├── src/
│ ├── DatePicker.php
│ ├── DatePickerAsset.php
│ ├── DatePickerLanguageAsset.php
│ ├── DatePickerTrait.php
│ ├── DateRangePicker.php
│ ├── DateRangePickerAsset.php
│ └── assets/
│ └── css/
│ └── bootstrap-daterangepicker.css
└── tests/
└── functional/
├── AssetManager.php
├── DatePickerAssetTest.php
├── DatePickerLanguageAssetTest.php
├── DatePickerTest.php
├── DateRangePickerAssetTest.php
├── DateRangePickerTest.php
├── TestCase.php
├── assets/
│ └── .gitignore
├── bootstrap.php
├── models/
│ └── Post.php
├── overrides/
│ ├── TestDatePicker.php
│ ├── TestDatePickerLanguageAsset.php
│ ├── TestDateRangePicker.php
│ └── TestDateRangePickerAsset.php
└── views/
├── datepicker-widget.php
├── daterangepicker-widget.php
└── layouts/
├── main.php
└── rawlayout.php
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Path-based git attributes
# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# Ignore all test and documentation with "export-ignore".
/.gitattributes export-ignore
/.gitignore export-ignore
/.travis.yml export-ignore
/phpunit.xml.dist export-ignore
/.scrutinizer.yml export-ignore
/tests export-ignore
/composer.lock export-ignore
================================================
FILE: .gitignore
================================================
build
#composer.lock
docs
vendor
# cache directories
Thumbs.db
*.DS_Store
*.empty
#phpstorm project files
.idea
#netbeans project files
nbproject
#eclipse, zend studio, aptana or other eclipse like project files
.buildpath
.project
.settings
# mac deployment helpers
switch
index
================================================
FILE: .scrutinizer.yml
================================================
filter:
excluded_paths: [tests/*]
checks:
php:
code_rating: true
remove_extra_empty_lines: true
remove_php_closing_tag: true
remove_trailing_whitespace: true
fix_use_statements:
remove_unused: true
preserve_multiple: false
preserve_blanklines: true
order_alphabetically: true
fix_php_opening_tag: true
fix_linefeed: true
fix_line_ending: true
fix_identation_4spaces: true
fix_doc_comments: true
tools:
external_code_coverage:
timeout: 600
runs: 3
php_analyzer: true
php_code_coverage: false
php_code_sniffer:
config:
standard: PSR2
filter:
paths: ['src']
php_loc:
enabled: true
excluded_dirs: [vendor, tests]
php_cpd:
enabled: true
excluded_dirs: [vendor, tests]
================================================
FILE: .travis.yml
================================================
language: php
php:
- 5.5
- 5.6
install:
- composer self-update
- composer global require "fxp/composer-asset-plugin:^1.2.0"
- composer install
before_script:
- travis_retry composer self-update
- travis_retry composer install --no-interaction --prefer-source --dev
script:
- phpunit --coverage-text --coverage-clover=coverage.clover
after_script:
- wget https://scrutinizer-ci.com/ocular.phar
- php ocular.phar code-coverage:upload --format=php-clover coverage.clover
================================================
FILE: CHANGELOG.md
================================================
# Changelog
## 1.0.5 - 2015-04-02
## Changed
- Added CHANGELOG.md file
## Fixed
- Fixed asset registration bug when using form
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
Contributions are **welcome** and will be fully **credited**.
We accept contributions via Pull Requests on [Github](https://github.com/2amigos/yii2-datepicker-widget).
## Pull Requests
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
- **Create feature branches** - Don't ask us to pull from your master branch.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please squash them before submitting.
## Running Tests
``` bash
$ phpunit
```
**Happy coding**!
================================================
FILE: LICENSE.md
================================================
# The BSD License (BSD)
Copyright (c) 2013-2015, 2amigOS! Consulting Group LLC.
> Redistribution and use in source and binary forms, with or without modification,
> are permitted provided that the following conditions are met:
>
> Redistributions of source code must retain the above copyright notice, this
> list of conditions and the following disclaimer.
>
> Redistributions in binary form must reproduce the above copyright notice, this
> list of conditions and the following disclaimer in the documentation and/or
> other materials provided with the distribution.
>
> Neither the name of 2amigOS! Consulting Group, LLC. nor the names of its
> contributors may be used to endorse or promote products derived from
> this software without specific prior written permission.
>
>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
>ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
>WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
>DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
>ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
>(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
>LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
>ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
>(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
>SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README.md
================================================
Bootstrap DatePicker Widget for Yii2
====================================
[](https://github.com/2amigos/yii2-date-picker-widget/tags)
[](LICENSE.md)
[](https://travis-ci.org/2amigos/yii2-date-picker-widget)
[](https://scrutinizer-ci.com/g/2amigos/yii2-date-picker-widget/code-structure)
[](https://scrutinizer-ci.com/g/2amigos/yii2-date-picker-widget)
[](https://packagist.org/packages/2amigos/yii2-date-picker-widget)
Renders a [Bootstrap DatePicker plugin](http://bootstrapformhelpers.com/datepicker/).
Installation
------------
The preferred way to install this extension is through [composer](http://getcomposer.org/download/).
Either run
```bash
$ composer require 2amigos/yii2-date-picker-widget:~1.0
```
or add
```json
"2amigos/yii2-date-picker-widget" : "~1.0"
```
to the require section of your application's `composer.json` file.
Usage
-----
The widget comes in two flavors:
- DatePicker
- DateRangePicker
**DatePicker**
This widget renders a Bootstrap DatePicker input control. Best suitable for model with date string attribute.
***Example of use with a form***
There are two ways of using it, with an `ActiveForm` instance or as a widget setting up its `model` and `attribute`.
```php
= DatePicker::widget([
'model' => $model,
'attribute' => 'date',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-M-yyyy'
]
]);?>
= $form->field($model, 'date')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => true,
// modify template for custom rendering
'template' => '
{input}
',
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-M-yyyy'
]
]);?>
```
***Example of use without a model***
```php
= DatePicker::widget([
'name' => 'Test',
'value' => '02-16-2012',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-M-yyyy'
]
]);?>
```
**DateRangePicker**
This widget renders a Bootstrap DateRangePicker Input control.
***Example of use with a form***
The following example works with a model that has two attributes named `date_from` and `date_to`.
```php
= $form->field($tour, 'date_from')->widget(DateRangePicker::className(), [
'attributeTo' => 'date_to',
'form' => $form, // best for correct client validation
'language' => 'es',
'size' => 'lg',
'clientOptions' => [
'autoclose' => true,
'format' => 'dd-M-yyyy'
]
]);?>
```
***Example of use without a model***
```php
= DateRangePicker::widget([
'name' => 'date_from',
'value' => '02-16-2012',
'nameTo' => 'name_to',
'valueTo' => '02-20-2012'
]);?>
```
Testing
-------
To test the extension, is better to clone this repository on your computer. After, go to the extensions folder and do
the following (assuming you have `composer` installed on your computer):
```bash
$ composer install --no-interaction --prefer-source --dev
```
Once all required libraries are installed then do:
```bash
$ vendor/bin/phpunit
```
I would recommend to have `phpunit` globally installed together with `xdebug` so you can have code coverage analysis too.
Further Information
-------------------
Please, check the [Bootstrap DatePicker site](http://bootstrap-datepicker.readthedocs.io/en/latest/) documentation for further information about its configuration options.
Contributing
------------
Please see [CONTRIBUTING](CONTRIBUTING.md) for details.
Credits
-------
- [Antonio Ramirez](https://github.com/tonydspaniard)
- [All Contributors](../../contributors)
License
-------
The BSD License (BSD). Please see [License File](LICENSE.md) for more information.
> [](http://www.2amigos.us)
Web development has never been so fun!
[www.2amigos.us](http://www.2amigos.us)
================================================
FILE: composer.json
================================================
{
"name": "2amigos/yii2-date-picker-widget",
"description": "Bootstrap DatePicker widget for Yii2.",
"type": "yii2-extension",
"keywords": [
"2amigos",
"yii",
"yii2",
"yii 2",
"extension",
"widget",
"datepicker"
],
"homepage": "http://yiiwheels.com/extension/bootstrap-datepicker",
"license": "BSD-3-Clause",
"authors": [
{
"name": "2amigOS! Consulting Group",
"email": "hola@2amigos.us",
"homepage": "http://2amigos.us",
"role": "Developer"
}
],
"support": {
"issues": "https://github.com/2amigos/yii2-date-picker-widget/issues",
"source": "https://github.com/2amigos/yii2-date-picker-widget"
},
"require": {
"yiisoft/yii2": ">=2.0.9",
"yiisoft/yii2-bootstrap": "*",
"bower-asset/bootstrap-datepicker": "1.7.0"
},
"require-dev": {
"phpunit/phpunit": "4.*"
},
"autoload": {
"psr-4": {
"dosamigos\\datepicker\\": "src"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
},
"asset-installer-paths": {
"bower-asset-library": "vendor/bower"
}
}
}
================================================
FILE: phpunit.xml.dist
================================================
./tests/functional./src/
================================================
FILE: src/DatePicker.php
================================================
* @link http://www.ramirezcobos.com/
* @link http://www.2amigos.us/
* @package dosamigos\datepicker
*/
class DatePicker extends InputWidget
{
use DatePickerTrait;
/**
* @var string the addon markup if you wish to display the input as a component. If you don't wish to render as a
* component then set it to null or false.
*/
public $addon = '';
/**
* @var string the template to render the input.
*/
public $template = '{input}{addon}';
/**
* @var bool whether to render the input as an inline calendar
*/
public $inline = false;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->inline) {
$this->options['readonly'] = 'readonly';
Html::addCssClass($this->options, 'text-center');
}
if ($this->size) {
Html::addCssClass($this->options, 'input-' . $this->size);
Html::addCssClass($this->containerOptions, 'input-group-' . $this->size);
}
Html::addCssClass($this->options, 'form-control');
Html::addCssClass($this->containerOptions, 'input-group date');
}
/**
* @inheritdoc
*/
public function run()
{
$input = $this->hasModel()
? Html::activeTextInput($this->model, $this->attribute, $this->options)
: Html::textInput($this->name, $this->value, $this->options);
if ($this->inline) {
$input .= '';
}
if ($this->addon && !$this->inline) {
$addon = Html::tag('span', $this->addon, ['class' => 'input-group-addon']);
$input = strtr($this->template, ['{input}' => $input, '{addon}' => $addon]);
$input = Html::tag('div', $input, $this->containerOptions);
}
if ($this->inline) {
$input = strtr($this->template, ['{input}' => $input, '{addon}' => '']);
}
echo $input;
$this->registerClientScript();
}
/**
* Registers required script for the plugin to work as DatePicker
*/
public function registerClientScript()
{
$js = [];
$view = $this->getView();
// @codeCoverageIgnoreStart
if ($this->language !== null && $this->language !== 'en') {
$this->clientOptions['language'] = $this->language;
DatePickerLanguageAsset::register($view)->js[] = 'bootstrap-datepicker.' . $this->language . '.min.js';
} else {
DatePickerAsset::register($view);
}
// @codeCoverageIgnoreEnd
$id = $this->options['id'];
$selector = ";jQuery('#$id')";
if ($this->addon || $this->inline) {
$selector .= ".parent()";
}
$options = !empty($this->clientOptions) ? Json::encode($this->clientOptions) : '';
if ($this->inline) {
$this->clientEvents['changeDate'] = "function (e){ jQuery('#$id').val(e.format());}";
}
$js[] = "$selector.datepicker($options);";
if (!empty($this->clientEvents)) {
foreach ($this->clientEvents as $event => $handler) {
$js[] = "$selector.on('$event', $handler);";
}
}
$view->registerJs(implode("\n", $js));
}
}
================================================
FILE: src/DatePickerAsset.php
================================================
* @link http://www.ramirezcobos.com/
* @link http://www.2amigos.us/
* @package dosamigos\datepicker
*/
class DatePickerAsset extends AssetBundle
{
public $sourcePath = '@bower/bootstrap-datepicker/dist';
public $css = [
'css/bootstrap-datepicker3.css',
];
public $js = [
'js/bootstrap-datepicker.js'
];
public $depends = [
'yii\bootstrap\BootstrapPluginAsset'
];
}
================================================
FILE: src/DatePickerLanguageAsset.php
================================================
* @link http://www.ramirezcobos.com/
* @link http://www.2amigos.us/
* @package dosamigos\datepicker
*/
class DatePickerLanguageAsset extends AssetBundle
{
public $sourcePath = '@bower/bootstrap-datepicker/dist/locales';
public $depends = [
'dosamigos\datepicker\DateRangePickerAsset'
];
}
================================================
FILE: src/DatePickerTrait.php
================================================
* @link http://www.ramirezcobos.com/
* @link http://www.2amigos.us/
* @package dosamigos\datepicker
*/
trait DatePickerTrait
{
/**
* @var string the language to use
*/
public $language;
/**
* @var array the options for the Bootstrap DatePicker plugin.
* Please refer to the Bootstrap DatePicker plugin Web page for possible options.
* @see http://bootstrap-datepicker.readthedocs.org/en/release/options.html
*/
public $clientOptions = [];
/**
* @var array the event handlers for the underlying Bootstrap DatePicker plugin.
* Please refer to the [DatePicker](http://bootstrap-datepicker.readthedocs.org/en/release/events.html) plugin
* Web page for possible events.
*/
public $clientEvents = [];
/**
* @var string the size of the input ('lg', 'md', 'sm', 'xs')
*/
public $size;
/**
* @var array HTML attributes to render on the container
*/
public $containerOptions = [];
}
================================================
FILE: src/DateRangePicker.php
================================================
* @link http://www.ramirezcobos.com/
* @link http://www.2amigos.us/
* @package dosamigos\datepicker
*/
class DateRangePicker extends InputWidget
{
use DatePickerTrait;
/**
* @var string the attribute name for date range (to Date)
*/
public $attributeTo;
/**
* @var string the name for date range (to Date)
*/
public $nameTo;
/**
* @var string the value for date range (to Date value)
*/
public $valueTo;
/**
* @var array HTML attributes for the date to input
*/
public $optionsTo;
/**
* @var string the label to. Defaults to 'to'.
*/
public $labelTo = 'to';
/**
* @var \yii\widgets\ActiveForm useful for client validation of attributeTo
*/
public $form;
/**
* @var string the template to render. Used internally.
*/
protected $_template = '{inputFrom}{labelTo}{inputTo}';
/**
* @inheritdoc
* @throws \yii\base\InvalidConfigException
*/
public function init()
{
parent::init();
if ((!$this->hasModel() && $this->nameTo === null) || ($this->hasModel() && $this->attributeTo === null)) {
// @codeCoverageIgnoreStart
throw new InvalidConfigException("Either 'nameTo', or 'model' and 'attributeTo' properties must be specified.");
// @codeCoverageIgnoreEnd
}
if ($this->size) {
Html::addCssClass($this->options, 'input-' . $this->size);
Html::addCssClass($this->optionsTo, 'input-' . $this->size);
Html::addCssClass($this->containerOptions, 'input-group-' . $this->size);
}
Html::addCssClass($this->containerOptions, 'input-group input-daterange');
Html::addCssClass($this->options, 'form-control');
Html::addCssClass($this->optionsTo, 'form-control');
}
/**
* @inheritdoc
*/
public function run()
{
if ($this->form) {
Html::addCssClass($this->options, 'datepicker-from');
Html::addCssClass($this->optionsTo, 'datepicker-to');
$inputFrom = $this->form->field(
$this->model,
$this->attribute,
[
'template' => '{input}{error}',
'options' => ['class' => 'input-group datepicker-range'],
]
)->textInput($this->options);
$inputTo = $this->form->field(
$this->model,
$this->attributeTo,
[
'template' => '{input}{error}',
'options' => ['class' => 'input-group datepicker-range'],
]
)->textInput($this->optionsTo);
} else {
$inputFrom = $this->hasModel()
? Html::activeTextInput($this->model, $this->attribute, $this->options)
: Html::textInput($this->name, $this->value, $this->options);
$inputTo = $this->hasModel()
? Html::activeTextInput($this->model, $this->attributeTo, $this->optionsTo)
: Html::textInput($this->nameTo, $this->valueTo, $this->optionsTo);
}
echo Html::tag(
'div',
strtr(
$this->_template,
['{inputFrom}' => $inputFrom, '{labelTo}' => $this->labelTo, '{inputTo}' => $inputTo]
), $this->containerOptions);
$this->registerClientScript();
}
/**
* Registers required script for the plugin to work as DateRangePicker
*/
public function registerClientScript()
{
$js = [];
$view = $this->getView();
// @codeCoverageIgnoreStart
if($this->language !== null) {
$this->clientOptions['language'] = $this->language;
DatePickerLanguageAsset::register($view)->js[] = 'bootstrap-datepicker.' . $this->language . '.min.js';
} else {
DateRangePickerAsset::register($view);
}
// @codeCoverageIgnoreEnd
$id = $this->options['id'];
$selector = ";jQuery('#$id').parent()";
if($this->form && $this->hasModel()) {
// @codeCoverageIgnoreStart
$selector .= '.parent()';
$class = "field-" . Html::getInputId($this->model, $this->attribute);
$js[] = "$selector.closest('.$class').removeClass('$class');";
// @codeCoverageIgnoreEnd
}
$options = !empty($this->clientOptions) ? Json::encode($this->clientOptions) : '';
$js[] = "$selector.datepicker($options);";
// @codeCoverageIgnoreStart
if (!empty($this->clientEvents)) {
foreach ($this->clientEvents as $event => $handler) {
$js[] = "$selector.on('$event', $handler);";
}
}
// @codeCoverageIgnoreEnd
$view->registerJs(implode("\n", $js));
}
}
================================================
FILE: src/DateRangePickerAsset.php
================================================
* @link http://www.ramirezcobos.com/
* @link http://www.2amigos.us/
* @package dosamigos\datepicker
*/
class DateRangePickerAsset extends AssetBundle
{
public $sourcePath = '@vendor/2amigos/yii2-date-picker-widget/src/assets';
public $css = [
'css/bootstrap-daterangepicker.css'
];
public $depends = [
'dosamigos\datepicker\DatePickerAsset'
];
}
================================================
FILE: src/assets/css/bootstrap-daterangepicker.css
================================================
/*!
* Custom styling. Removing padding when using DateRangePicker.
*/
.datepicker {
z-index: 1151 !important;
}
.datepicker-range {
padding: 0 !important;
border: 0 !important;
text-align: left !important;
}
.datepicker-from {
border-radius: 4px !important;
border-top-right-radius: 0 !important;
border-bottom-right-radius: 0 !important;
text-align: left !important;
}
.datepicker-to {
border-radius: 4px !important;
border-top-left-radius: 0 !important;
border-bottom-left-radius: 0 !important;
text-align: left !important;
}
div.datepicker-range {
width: 100%;
}
================================================
FILE: tests/functional/AssetManager.php
================================================
_hashes[$path])) {
$this->_hashes[$path] = $this->_counter++;
}
return $this->_hashes[$path];
}
}
================================================
FILE: tests/functional/DatePickerAssetTest.php
================================================
getView();
$this->assertEmpty($view->assetBundles);
DatePickerAsset::register($view);
$this->assertEquals(4, count($view->assetBundles));
$this->assertArrayHasKey('yii\\web\\JqueryAsset', $view->assetBundles);
$this->assertTrue($view->assetBundles['dosamigos\\datepicker\\DatePickerAsset'] instanceof AssetBundle);
$content = $view->render('//layouts/rawlayout.php');
$this->assertContains('jquery.js', $content);
$this->assertContains('bootstrap.js', $content);
$this->assertContains('bootstrap-datepicker.js', $content);
$this->assertContains('bootstrap-datepicker3.css', $content);
}
}
================================================
FILE: tests/functional/DatePickerLanguageAssetTest.php
================================================
getView();
$this->assertEmpty($view->assetBundles);
TestDatePickerLanguageAsset::register($view)->js[] = 'bootstrap-datepicker.es.min.js';
$this->assertEquals(6, count($view->assetBundles));
$this->assertTrue($view->assetBundles['tests\overrides\TestDatePickerLanguageAsset'] instanceof AssetBundle);
$content = $view->render('//layouts/rawlayout.php');
$this->assertContains('jquery.js', $content);
$this->assertContains('bootstrap-datepicker.es.min.js', $content);
}
}
================================================
FILE: tests/functional/DatePickerTest.php
================================================
create_time = 1425807308;
$out = DatePicker::widget([
'model' => $model,
'attribute' => 'create_time'
]);
$expected = '