Yii 2 Bootstrap 5 Extension

Overview

Twitter Bootstrap 5 Extension for Yii 2


This is the Twitter Bootstrap extension for Yii framework 2.0. It encapsulates Bootstrap 5 components and plugins in terms of Yii widgets, and thus makes using Bootstrap components/plugins in Yii applications extremely easy.

For license information check the LICENSE-file.

Documentation is at docs/guide/README.md.

Latest Stable Version Total Downloads Build Status

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist yiisoft/yii2-bootstrap5

or add

"yiisoft/yii2-bootstrap5": "~1.0@dev"

to the require section of your composer.json file.

Usage

For example, the following single line of code in a view file would render a Bootstrap Progress plugin:

<?= yii\bootstrap5\Progress::widget(['percent' => 60, 'label' => 'test']) ?>
Comments
  • Refactore primitive widgets in helpers

    Refactore primitive widgets in helpers

    I don't find any reason to realize primitive BS components like as .btn, .progress and etc. as widgets, there are enough single methods in Html helper. Widgets works much slower and uses more memory, because triggering 3 unwatched events for every instance. Need convert classes as Button, Progress, Alert, ButtonGroup and ButtonToolbar to Html methods. To simply customization components we can implement class/attribute/options presets and pass preset name(s) to helper-methods in $options property:

    class Html extends BaseHtml
    {
        /**
         * @var string[] the option/attribute presets grouped by methods
         */
        protected static $optionPresets = [
              'buttonClose' => [
                    'default' => [],
                    'white' => ['class' => 'btn-close-white'],
                    'small' => ['class' => 'text-small'],
               ],
        ];
    
        public function presetOptions(string $methodName, string $presetName, array $options)
        {
                 // normalize $options and merge into static::$optionPresets 
        }
    
        protected static function normalizeOptions(string $method, array $defaults, array $options): array
        {
             $presets = ArrayHelper::remove($options, 'preset', 'default');
             // preset names separated by whitespace
             $presets = explode(' ', $presets);
             $options = [$defaults, $options];
             foreach ($presets as &$preset) {
                    $options[] = static::$optionPresets[$method][$preset] ?? [];
             }
            // optionally, converts ['data' => ['a' => 'b'], 'ariaLabel' => 'z'] to ['data-a' => 'b', 'aria-label' => 'Close dialog']
             // returns $options merged into flatten array
       }
    
        public static function buttonClose(array $options = []): string
        {
            $options = static::normalizeOptions(__FUNCTION__, ['class' => 'btn-close', 'aria-label' => null], $options);
            if ($options['aria-label'] === null) {
                $options['aria-label'] = Yii::t('yii/bootstrap5', 'Close');
            }
            $tag = ArrayHelper::remove($options, 'tag', 'button');
            if ($tag === 'a') {
                  $options += ['role' => 'button', 'href' => '#'];
            }
            return static::{$tag}('', $options);
        }
    }
    
    Html::buttonClose(['preset' => 'white small', 'tag' => 'a']);
    
    type:enhancement 
    opened by WinterSilence 24
  • I18n translation

    I18n translation

    What steps will reproduce the problem?

    Default labels not translated

    What is the expected result?

    $label = ArrayHelper::remove($toggleButton, 'label', Yii::t('yii/bootstrap5', 'Show'));
    

    What do you get instead?

    https://github.com/yiisoft/yii2-bootstrap5/blob/97a3b653b74f6dbff799d8cbf2acc716536b6d82/src/Modal.php#L239

    Additional info

    | Q | A | ---------------- | --- | Yii vesion | 2.0.* | PHP version | any | Operating system | any

    type:enhancement 
    opened by WinterSilence 16
  • Alert close button API is incompatible with previous versions

    Alert close button API is incompatible with previous versions

    Namely, the close button tag cannot be configured to have any content (label, previously), but the documentation does not explain how is this superior to the prior behavior.

    And, regardless of the tag value used, it always gets attribute type="button", which also is a deviation from the previous behavior. That probably is another issue, you're welcome to open one.

    What steps will reproduce the problem?

    1. Create a Composer project requiring PHPUnit and this extension:

      composer.json
      	{
      		"require": {
      			"phpunit/phpunit": "^9",
      			"yiisoft/yii2-bootstrap5": "~2.0.0"
      		},
      		"repositories": [
      			{
      				"type": "composer",
      				"url": "https://asset-packagist.org"
      			}
      		]
      	}
      
    2. Write a test:

      	<?php
      
      	declare(strict_types=1);
      
      	use PHPUnit\Framework\TestCase;
      	use yii\bootstrap5\Alert;
      	use yii\web\Application;
      	use yii\web\View;
      
      	final class AlertCloseButtonTest extends TestCase
      	{
      	    /** @before */
      	    public function setUp(): void
      	    {
      	        require_once __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
      
      	        $app = $this->createMock(Application::class);
      	        $app->method('getView')->willReturn($this->createMock(View::class));
      
      	        Yii::$app = $app;
      	    }
      
      	    public function testLabel(): void
      	    {
      	        $tag = 'foo';
      	        $label = 'bar';
      
      	        $pattern = "<div[^>]+>\\s+<({$tag})[^>]+>{$label}</\\1+>\\s+</div>";
      	        $string = Alert::widget(['closeButton' => compact('tag', 'label')]);
      
      	        $this->assertMatchesRegularExpression("(^{$pattern}$)", $string);
      	    }
      	}
      

      Of course the test should pass if the values of $tag and $label are replaced with any other string, as long the regex does not break.

      (Here's also a test for the button type issue, if you feel inclined to see it for yourself)
      	public function testType(): void
      {
          $tag = 'a';
      
          $pattern = <<<EOD
              <div[^>]+>\s*
              <($tag)[^>]+type="button"[^>]*>.*</\\1+>\s*
              </div>
              EOD;
          $string = Alert::widget(['closeButton' => compact('tag')]);
      
          $this->assertDoesNotMatchRegularExpression("(^{$pattern}$)", $string);
      }
      

      This test also should pass as long as the $tag is anything but button.

    3. Run the test:

      	vendor/bin/phpunit --bootstrap=vendor/autoload.php AlertCloseButtonTest.php
      

    What is the expected result?

    The test passes with all versions of Bootstrap extension.

    What do you get instead?

    The test only passes with Bootstrap 3 and Bootstrap 4 extensions, it fails with this one.

    Additional info

    As it turns out, these very same tests pass even with the brand spanking new next-generation Bootstrap 5 extension.

    (with some relatively minor changes)
    diff --git a/composer.json b/composer.json
    index 0407097..ca007eb 100644
    --- a/composer.json
    +++ b/composer.json
    @@ -1,7 +1,8 @@
     {
    +    "minimum-stability": "dev",
         "require": {
             "phpunit/phpunit": "^9",
    -        "yiisoft/yii2-bootstrap5": "~2.0.0"
    +        "yiisoft/yii-bootstrap5": "*"
         },
         "repositories": [
             {
    
    diff --git a/AlertCloseButtonTest.php b/AlertCloseButtonTest.php
    index 8500d33..a89c888 100644
    --- a/AlertCloseButtonTest.php
    +++ b/AlertCloseButtonTest.php
    @@ -3,21 +3,15 @@
     declare(strict_types=1);
     
     use PHPUnit\Framework\TestCase;
    -use yii\bootstrap5\Alert;
    -use yii\web\Application;
    -use yii\web\View;
    +use Yiisoft\Yii\Bootstrap5\Alert;
    +use Yiisoft\Widget\WidgetFactory;
     
     final class AlertCloseButtonTest extends TestCase
     {
         /** @before */
         public function setUp(): void
         {
    -        require_once __DIR__ . '/vendor/yiisoft/yii2/Yii.php';
    -
    -        $app = $this->createMock(Application::class);
    -        $app->method('getView')->willReturn($this->createMock(View::class));
    -
    -        Yii::$app = $app;
    +        WidgetFactory::initialize();
         }
     
         public function testLabel(): void
    @@ -26,7 +20,7 @@ final class AlertCloseButtonTest extends TestCase
             $label = 'bar';
     
             $pattern = "<div[^>]+>\\s+<({$tag})[^>]+>{$label}</\\1+>\\s+</div>";
    -        $string = Alert::widget(['closeButton' => compact('tag', 'label')]);
    +        $string = Alert::widget()->closeButton(compact('tag', 'label'))->render();
     
             $this->assertMatchesRegularExpression("(^{$pattern}$)", $string);
         }
    @@ -40,7 +34,7 @@ final class AlertCloseButtonTest extends TestCase
                 <($tag)[^>]+type="button"[^>]*>.*</\\1+>\s*
                 </div>
                 EOD;
    -        $string = Alert::widget(['closeButton' => compact('tag')]);
    +        $string = Alert::widget()->closeButton(compact('tag'))->render();
     
             $this->assertDoesNotMatchRegularExpression("(^{$pattern}$)", $string);
         }
    
    type:feature 
    opened by antichris 14
  • clientOptions false still renders JS

    clientOptions false still renders JS

    What steps will reproduce the problem?

    Render a widget with clientOptions set to false. registerPlugin on BootstrapWidgetTrait is still run.

    What is the expected result?

    No JS plugin is rendered. Calling the javascript can then be done manually.

    What do you get instead?

    It is rendered (and jQuery is not available on page load so it causes a console error).

    Additional info

    In yii2-bootstrap4 this was excluded: https://github.com/yiisoft/yii2-bootstrap4/blob/master/src/BootstrapWidgetTrait.php#L76

    However this conditional is not present in this library: https://github.com/yiisoft/yii2-bootstrap5/blob/master/src/BootstrapWidgetTrait.php#L79

    | Q | A | ---------------- | --- | Yii vesion | 2.0.44 | PHP version | 7.4 | Operating system | Ubuntu 20.04 LTS

    status:under discussion 
    opened by julianrutten 12
  • fix: clientOptions=false skips registerJs

    fix: clientOptions=false skips registerJs

    | Q | A | ------------- | --- | Is bugfix? | ✔️ | New feature? | ❌ | Breaks BC? | ❌ Not compared to previous versions. See issue. | Fixed issues | #36

    opened by julianrutten 11
  • build(*): Fix CI by allowing the yii2-composer plugin

    build(*): Fix CI by allowing the yii2-composer plugin

    This PR fixes the CI that broke due to the composer 2 allow-plugins setting. See failure in #46.

    PS: I was initially looking at adding PHP 8.1 in the CI, but I see that we need to fix a compatibility with PHPUnit first (see first failure).

    opened by machour 7
  • Update BaseHtml

    Update BaseHtml

    Replace PHPDoc of BaseHtml::$normalizeClassAttribute Add inline mode in BaseHtml::checkboxList() Add inline mode in BaseHtml::radioList()

    | Q | A | ------------- | --- | Is bugfix? | ❌ | New feature? | ✔️ | Breaks BC? | ❌ | Fixed issues |

    pr:request for unit tests 
    opened by WinterSilence 6
  • Fixed `homeUrl` in default `homeLink`

    Fixed `homeUrl` in default `homeLink`

    The Phpdoc descriptions says "If this property is not set, it will default to a link pointing to [[\yii\web\Application::homeUrl]] with the label 'Home'. If this property is false, the home link will not be rendered."

    | Q | A | ------------- | --- | Is bugfix? | ✔️ | New feature? | ❌ | Breaks BC? | ❌ | Fixed issues |

    opened by luke- 5
  • fix BootstrapWidgetTrait::registerPlugin

    fix BootstrapWidgetTrait::registerPlugin

    BootstrapWidgetTrait::registerPlugin not working if empty clientOptions provided for plugin.

    | Q | A | ------------- | --- | Is bugfix? | ✔️ | New feature? | ❌ | Breaks BC? | ❌ | Fix | #5

    type:bug pr:request for unit tests 
    opened by dicrtarasov 5
  • Missing css files while including `yii\bootstrap5\BootstrapPluginAsset`

    Missing css files while including `yii\bootstrap5\BootstrapPluginAsset`

    What steps will reproduce the problem?

    Set $depends in AppAsset to

        public $depends = [
            'yii\web\YiiAsset',
            'yii\bootstrap5\BootstrapPluginAsset'
        ]
    

    What is the expected result?

    Having bootstrap css files in assets folder

    What do you get instead?

    No css files

    Additional info

    | Q | A | ---------------- | --- | Yii vesion | 2.0.45 | PHP version | 8.1.12 | Operating system | Windows 10

    opened by insthync 4
  • Update BootstrapAsset

    Update BootstrapAsset

    • Load minified JS on production
    • Optimize list of publishes files
    • Normalize comments

    | Q | A | ------------- | --- | Is bugfix? | ✔️ | New feature? | ❌ | Breaks BC? | ❌ | Fixed issues |

    opened by WinterSilence 3
  • ActiveField | Additional fields: checkbox

    ActiveField | Additional fields: checkbox

    What steps will reproduce the problem?

    I tried to change the vanilla Yii2 checkbox from:

    $form->field($model, 'active')->checkBox()

    to:

    $form->field($model, 'active')->checkBox( ['switch' => True] )

    in order to show a fancy switch.

    What is the expected result?

    Reading the English Guide: https://github.com/yiisoft/yii2-bootstrap5/blob/master/docs/guide/usage-widgets.md, I was expecting to find a beauty switch like: https://getbootstrap.com/docs/5.1/forms/checks-radios/#switches

    What do you get instead?

    The same checkbox that comes out of the box with Yii2.

    Additional info

    | Q | A | ---------------- | --- | Yii vesion | 2.0.46 August 18, 2022 (Advanced template which comes with BS5) | PHP version | PHP 8.1.11 | Operating system | Ubuntu 20.04.5 LTS

    opened by numitec 4
  • Version 2.0.4 not working \kartik\datecontrol\DateControl

    Version 2.0.4 not working \kartik\datecontrol\DateControl

    Steps to reproduce the problem:

    If \kartik\datecontrol\DateControl is installed with version 2.0.4 - JavaScript error:

    Uncaught TypeError: Cannot read properties of undefined (reading 'parentNode')

    Additional info

    | Q | A | ---------------- | --- | Yii vesion |2.0.45 | PHP version |8.1 | Operating system |Linux

    opened by smartycoder 3
  • Update ActiveField class

    Update ActiveField class

    • Override error method
    • Update checkboxList and radioList methods: add 'inline' option, normalize wrapper class

    | Q | A | ------------- | --- | Is bugfix? | ✔️/❌ | New feature? | ✔️ | Breaks BC? | ❌ | Fixed issues |

    pr:request for unit tests type:enhancement 
    opened by WinterSilence 1
  • kartik Gridview widget problem with bootstrap5

    kartik Gridview widget problem with bootstrap5

    Hello, i noticed that using kartik\grid\GridView with bootstrap5 I can't no more use filters on gridviews. The page being created contains the following statement in a script:

    (new bootstrap.Dropdown('#w1-button', {}));

    but nothing exists with id="w1-button", so the script ends with a blocking exception and filtering no more works.

    This is the view:

    <?php
    use app\models\Quiz;
    use yii\helpers\Html;
    use yii\helpers\Url;
    use kartik\grid\ActionColumn;
    use kartik\grid\GridView;
    use Yii;
    
    /** @var yii\web\View $this */
    /** @var app\models\QuizSearch $searchModel */
    /** @var yii\data\ActiveDataProvider $dataProvider */
    
    $this->title = 'Quizzes';
    $this->params['breadcrumbs'][] = $this->title;
    ?>
    <div class="quiz-index">
        <h1><?= Html::encode($this->title) ?></h1>
        <p>
            <?= Html::a('Create Quiz', ['create'], ['class' => 'btn btn-success']) ?>
        </p>
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                ['class' => 'kartik\grid\SerialColumn'],
                'IdQuiz',
                'DtCreazione',
                'DtInizioTest',
                'DtFineTest',
                'Esito',
                [
                    'class' => ActionColumn::className(),
                    'urlCreator' => function ($action, Quiz $model, $key, $index, $column) {
                        return Url::toRoute([$action, 'IdQuiz' => $model->IdQuiz]);
                     }
                ],
            ],
        ]); ?>
    </div>
    

    I resolved substituting row 103 of BootstrapWidgetTrait.php with the following statement:

    $view->registerJs("if ($('#$id').length > 0) (new bootstrap.$name('#$id', $options));"); instead of

    $view->registerJs("(new bootstrap.$name('#$id', $options));");

    Additional info

    | System | Version | | ---------------- | ------------ | | Yii version | 2.0 | | PHP version | 8.1 | | Operating system | Ubuntu 18.04 |

    opened by pzavoli71 2
Releases(2.0.4)
  • 2.0.4(Nov 30, 2022)

    What's Changed

    • Breadcrumbs refactoring by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/40
    • Update BaseHtml by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/39
    • Update basic-usage.md by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/41
    • build(*): Fix CI by allowing the yii2-composer plugin by @machour in https://github.com/yiisoft/yii2-bootstrap5/pull/47
    • Fix dropdown & test data-bs usage by @machour in https://github.com/yiisoft/yii2-bootstrap5/pull/46
    • Update BootstrapWidgetTrait by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/48
    • Normalize TranslationBootstrap by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/53
    • Update BootstrapAsset by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/52
    • Update BootstrapPluginAsset by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/51
    • Translate default text of NavBar::$screenReaderToggleText by @WinterSilence in https://github.com/yiisoft/yii2-bootstrap5/pull/57

    Full Changelog: https://github.com/yiisoft/yii2-bootstrap5/compare/2.0.3...2.0.4

    Source code(tar.gz)
    Source code(zip)
Owner
Yii Software
Yii Framework and packages
Yii Software
Yii2-symfonymailer - Yii 2 Symfony mailer extension.

Yii Mailer Library - Symfony Mailer Extension This extension provides a Symfony Mailer mail solution for Yii framework 2.0. For license information ch

Yii Software 28 Dec 22, 2022
This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

This extension provides a view renderer for Pug templates for Yii framework 2.0 applications.

Revin Roman 9 Jun 17, 2022
Extension for creating and sending emails for the Yii PHP framework.

yii-emailer Extension for creating and sending emails for the Yii PHP framework. Usage Migrate the email_message database table by this command: yiic

Digia 12 Mar 30, 2022
This extension provides Flysystem integration for the Yii framework

This extension provides Flysystem integration for the Yii framework. Flysystem is a filesystem abstraction which allows you to easily swap out a local filesystem for a remote one.

Alexander Kochetov 276 Dec 9, 2022
Yii 2: The Fast, Secure and Professional PHP Framework

Yii 2 is a modern framework designed to be a solid foundation for your PHP application. It is fast, secure and efficient and works right out of the bo

Yii Software 14k Dec 31, 2022
Yii-specific middleware

Yii Middleware The package ... Requirements PHP 8.0 or higher. Installation The package could be installed with composer: composer require yiisoft/yii

Yii Software 9 Nov 4, 2022
Yii 2 widget for the Froala WYSIWYG HTML Editor.

Yii Framework Froala WYSIWYG HTML Editor Yii 2 widget for Froala Wysiwyg editor. Installation The preferred way to install this extension is through c

Froala 99 Sep 21, 2022
Geography module for Yii 2

Geography module for Yii 2

Sergey Fedorov 13 Oct 20, 2018
Code generation with logic-less templates for Yii

Caviar Code generation with logic-less templates for Yii. Caviar vs Gii You might be wondering why you should use Caviar instead of Gii, so let us tak

Christoffer Niska 10 Dec 19, 2015
Extends Yii Menu widget

Extends Yii Menu widget. This widget offers a scrollspy and affixed enhanced navigation (upto 2-levels) to highlight sections and secondary sections in each page.

Kartik Visweswaran 15 Mar 12, 2022
DepDrop widget is a Yii 2 wrapper for the dependent-dropdown jQuery plugin by Krajee.

yii2-widget-depdrop The DepDrop widget is a Yii 2 wrapper for the dependent-dropdown jQuery plugin by Krajee. This plugin allows multi level dependent

Kartik Visweswaran 82 Nov 27, 2022
An enhanced Yii 2 widget encapsulating the HTML 5 range input (sub repo split from yii2-widgets)

yii2-widget-rangeinput The RangeInput widget is a customized range slider control widget based on HTML5 range input. The widget enhances the default H

Kartik Visweswaran 19 Mar 12, 2022
Password strategies for Yii

Password strategies are specifications for how passwords should be encoded and verified and how complicated user supplied passwords should be.

Charles Pick 76 Apr 22, 2022
Easy integration of twitters bootstrap into symfony2

MopaBootstrapBundle MopaBootstrapBundle is a collection of code to integrate twitter's bootstrap (http://twitter.github.com/bootstrap/) as easy as pos

Philipp A. Mohrenweiser 717 Dec 15, 2022
yii2-app-advanced with Twitter Bootstrap 5

Yii 2 Advanced Project Template is a skeleton Yii 2 application best for developing complex Web applications with multiple tiers.

Nedarta 1 Nov 5, 2021
The package contains a bootstrap for running Yii3 web application.

Yii Web Runner The package contains a bootstrap for running Yii3 web application. Requirements PHP 8.0 or higher. Installation The package could be in

Yii Software 4 Oct 15, 2022
Date/Time Picker widget for Yii2 framework Based on Eonasdan's Bootstrap 3 Date/Time Picker

Yii2 Date/Time Picker Widget Date/Time Picker widget for Yii2 framework Based on Eonasdan's Bootstrap 3 Date/Time Picker Demo Since this is a part of

Yevhen Terentiev 8 Mar 14, 2022
A collapsible side navigation menu built to seamlessly work with Bootstrap framework

yii2-widget-sidenav This widget is a collapsible side navigation menu built to seamlessly work with Bootstrap framework. It is built over Bootstrap st

Kartik Visweswaran 36 Apr 9, 2022
An enhanced FileInput widget for Bootstrap 4.x/3.x with file preview, multiple selection, and more features (sub repo split from yii2-widgets)

yii2-widget-fileinput The FileInput widget is a customized file input widget based on Krajee's Bootstrap FileInput JQuery Plugin. The widget enhances

Kartik Visweswaran 227 Nov 6, 2022