Git Product home page Git Product logo

yii2-bootstrap5's Introduction

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": "*"

to the require section of your composer.json file.

Translations

The i18n configuration will be automatically added to your application configuration via bootstrapping process.

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

yii2-bootstrap5's People

Contributors

antichris avatar arhell avatar deryabinsergey avatar dicrtarasov avatar evilkarter avatar hirenbhut93 avatar julianrutten avatar krakozaber avatar luke- avatar machour avatar mylistryx avatar samdark avatar simialbi avatar theblindfrog avatar wintersilence avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-bootstrap5's Issues

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

User Authentication plugin compatibility

I'm unable to find any Yii2 User Authentication plugin compatible with yii2-bootstrap5. All the common plugins require either yii2-bootstrap or yii2-bootstrap4.

Kindly help.

yii\bootstrap5\Breadcrumbs problem

    if ($this->homeLink === []) {
        $links[] = $this->renderItem([
            'label' => 'Home',
            'url' => '/',
        ], $this->itemTemplate);
    } else {
        $links[] = $this->renderItem($this->homeLink, $this->itemTemplate);
    }

$homeLink set false, has bug, need a little change

    if(!($this->homeLink === false)){
        if ($this->homeLink === []) {
            $links[] = $this->renderItem([
                'label' => 'Home',
                'url' => '/',
            ], $this->itemTemplate);
        } else {
            $links[] = $this->renderItem($this->homeLink, $this->itemTemplate);
        }
    }

OR

    if ($this->homeLink === []) {
        $links[] = $this->renderItem([
            'label' => 'Home',
            'url' => '/',
        ], $this->itemTemplate);
    } elseif ($this->homeLink !== false) {
        $links[] = $this->renderItem($this->homeLink, $this->itemTemplate);
    }

Accordion widget does not set "collapsed" class on toggle button

What steps will reproduce the problem?

Using an yii2\bootstrap5\Accordion widget with any kind of configuration.

What is the expected result?

HTML output that conforms to Bootstrap 5 (https://getbootstrap.com/docs/5.0/components/accordion/)

Specifically, on unexpanded items, the <button class="accordion-button"> should also have the class collapsed.

Something similar to this for an unexpanded item:

  <div class="accordion-item">
    <h2 class="accordion-header" id="headingTwo">
      <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
        Accordion Item #2
      </button>
    </h2>
    <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample">
      <div class="accordion-body">
        <strong>This is the second item's accordion body.</strong> It is hidden by default, until the collapse plugin adds the appropriate classes that we use to style each element. These classes control the overall appearance, as well as the showing and hiding via CSS transitions. You can modify any of this with custom CSS or overriding our default variables. It's also worth noting that just about any HTML can go within the <code>.accordion-body</code>, though the transition does limit overflow.
      </div>
    </div>
  </div>

What do you get instead?

The button class does not have the collapsed class, causing styling issues. The Bootstrap 5 Javascript correctly adds collapsed class after toggling the item back and forth.

Additional info

Presumably somewhere in yii2\bootstrap5\Accordion::renderItem() the class collapsed should be added to the $itemToggleOptions. Or alternatively, allow itemToggleOptions to be set per item via the config to allow us to set such classes ourselves on a per-item basis (itemToggleOptions is currently the same config for each item).

Q A
Yii version 2.0.45
PHP version 8.0
Operating system Ubuntu 20.04

Use both bs3 and bs5 in the same project

This is a similar to yiisoft/yii2-bootstrap4#11

I have a PHP application which is mainly written with bs3 using yii2-bootstrap.
Now, there is a new part on it that needs to be done in bs5 while keeping bs3 for the existing parts.

Trying to install yii2-bootstrap5 (while having already installed yii2-bootstrap) gives me an error:

  Problem 1
    - Root composer.json requires yiisoft/yii2-bootstrap5 * -> satisfiable by yiisoft/yii2-bootstrap5[2.0.1, 2.0.2, 2.0.3, 2.0.4].
    - yiisoft/yii2-bootstrap5[2.0.1, ..., 2.0.4] require bower-asset/bootstrap ^5.1.0 -> found bower-asset/bootstrap[v5.1.0, ..., v5.2.3] but the package is fixed to v3.4.1 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

yii2-bootstrap4 maintainers solved this by depending on "npm-asset/bootstrap" instead of "bower-asset", can you do the same for that repo ?

Modal::widget

In the migration instructions Modal::widget data-target and data-toggle change to data-bs-target and data-bs-toggle

Whole Bootstrap directory is published into web/assets

BootstrapAsset and BootstrapPluginAsset are publishing the whole Bootstrap directory into web/assets.

This line:
public $sourcePath = '@bower/bootstrap';

Could be changed to:
public $sourcePath = '@bower/bootstrap/dist';

So that only the "dist" directory is published.

Curious about card implementation

Hello, first want to say that I'm really appreciative of the work done on this extension.

And secondly, I'm curious if anyone has plans to implement the card component? (https://getbootstrap.com/docs/5.1/components/card/)

Card has quite a bit going on and seems like it might be tricky to implement, but I could take a stab at it. I'm in the process of moving some twig template code over to use this extension, but ran into a stopping point when I got to the cards.

So, just curious if this is on anyone's todo-list? Thanks!

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

invalid-feedback div breaks inline radio list

What steps will reproduce the problem?

I'm trying to implement an inline radio list like this:

<div class="col-md-6 allow-sms-col">
    <?= $form->field($model, 'my_field')->inline()->radioList(['1' => 'Yes', '0' => 'No'], ['unselect' => null]) ?>
</div>

What is the expected result?

It should render an inline radio list, like:

Captura desde 2023-08-01 12-47-42

What do you get instead?

But the .invalid-feedback div is included inside the last radio element (the last .form-check-inline div) causing this to happen:

Captura desde 2023-08-01 12-51-31

Also if has a small width or a long error message can cause the element to lose the inline position:

Captura desde 2023-08-01 12-55-52

Additional info

Q A
yii2-bootstrap5 version 2.0.2
Yii version 2.0.45
PHP version 8.0
Operating system linux

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

no error text when use inputTemplate

What steps will reproduce the problem?

First working code:

                  <?= $form->field($model, 'sigmapercent', [
                      'template' => "{label}\n{input}\n{hint}\n{error}"
                 ])->textInput() ?></div>

works like usual in Yii2.

And now I try to add suffix to the field

<?= $form->field($model, 'sigmapercent', [
                      'inputTemplate' => '<div class="input-group">{input}
                          <span class="input-group-text">%</span>
                      </div>',
                      'template' => "{label}\n{input}\n{hint}\n{error}"
                 ])->textInput()

What is the expected result?

I see a suffix all right

What do you get instead?

But when I put incorrect value in the field, I do not see error message under the field. Only field's border becomes red. (without reloading the page, only js validation)

Additional info

Q A
Yii vesion 2
PHP version 8
Operating system ubuntu

Toast JS registration

What steps will reproduce the problem?

Using the Toast Widget as explained in the documentation

<?= yii\bootstrap5\Toast::widget([
            'title' => 'Toast',
            'dateTime' => 'now',
            'body' => 'Body',
]) ?>  

What is the expected result?

The Toast component should be initialized/registered as per BS5 documentation.

What do you get instead?

It appears that BootstrapWidgetTrait's registerPlugin() generates BS4 JS methods/code:
jQuery('#w2').toast();

Please see:
https://getbootstrap.com/docs/5.2/components/toasts/#usage

Additional info

Q A
Yii vesion
PHP version
Operating system

ActiveForm | Incorrect radioList HTML/CSS

Incorrect HTML/CSS when rendering radioList field (ActiveForm) using LAYOUT_FLOATING

What steps will reproduce the problem?

use yii\bootstrap5\ActiveForm;

$form = ActiveForm::begin([
    'layout' => ActiveForm::LAYOUT_FLOATING,
]);
    // text fields are rendered as expected
    echo $form->field($model, 'from')->textInput(['autocomplete' => 'off', 'type' => 'date']);
    echo $form->field($model, 'to')->textInput(['autocomplete' => 'off', 'type' => 'date']);
    // radio list field shows incorrect HTML as a result of using LAYOUT_FLOATING
    echo $form->field($model, 'status')->radioList([0 => 'Inactive', 1 => 'Active']);
ActiveForm::end();

What is the expected result?

A normal stacked radio list with label on top
https://getbootstrap.com/docs/5.3/forms/checks-radios/#default-stacked

image

What do you get instead?

Stacked radio list but the label is rendered incorrectly inside the list:

image

Additional info

Q A
Yii vesion 2.0.47 (advanced template)
PHP version 8.1.2
Operating system Ubuntu 22.04.1 LTS
yiisoft/yii2-bootstrap5 2.0.4

Inline parameter is ignored in checkboxList and radioList

These lines should be changed:

$wrapperOptions = ArrayHelper::remove($options, 'wrapperOptions', ['class' => ['form-check']]);

$wrapperOptions = ArrayHelper::remove($options, 'wrapperOptions', ['class' => ['form-check']]);

From this:

                $wrapperOptions = ArrayHelper::remove($options, 'wrapperOptions', ['class' => ['form-check']]);

To this:

                $wrapperOptionsDefault =  ['class' => ['form-check']];
                if ($this->inline) {
                    Html::addCssClass($wrapperOptionsDefault, 'form-check-inline');
                }
                $wrapperOptions = ArrayHelper::remove($options, 'wrapperOptions', $wrapperOptionsDefault);

Sorry I don't have the time to create a pull request at this time myself.

Dropdown clientEvents do not fire

According to the docs, the events should be bound either on the toggling element or on the .dropdown-menu parent element, not on the .dropdown-menu itself like it is now: BS 5 Docs

All dropdown events are fired at the toggling element and then bubbled up. So you can also add event listeners on the .dropdown-menu’s parent element.

Additional info

Q A
Yii version 2.0.45
PHP version >= 7.4
Operating system Windows Server 2019 Standard

attributeHint appears on the same line with checkbox label

Invalid tag small used for attribute hint display, break visualisation of attribute hint text in forms - it appears on the same line with checkbox label. Actually tag small do nothing, because of fontsize is specified in text form-text class.

img

Changing hint tag to div become all Ok.

img

Pull request will provided.

Bootstrap5 Button is not registering clientEvents

What steps will reproduce the problem?

<?=
                        \yii\bootstrap5\Button::widget([
                            'id' => 'fullscreen-button',
                            'encodeLabel' => false,
                            'label' => '<i class="bi bi-fullscreen text-light fs-5"></i>',
                            'options' => ['class' => 'btn'],
                            'clientEvents' => [
                                'click' => new JsExpression('function () {
                                                              ---
                                            }')
                            ],
                        ]);
?>

What is the expected result?

The widget html is rendered, but clientEvents are not registered.

What do you get instead?

Just the visual button, but no handler was listening onClick.

Additional info

I have skimmed through the whole chain of code and nowhere are the Button plugin or client events registered.

Most widgets call plugin registration in the run() method, which in turn registers events, but not the Button code...

I have fixed the issue by adding $this->registerPlugin('button'); as the first line in the run() method - and now the button is rendered and event listers registered/rendered.

Q A
Yii version 2.0.48.1
PHP version 8.1.0
Operating system win11/wamp

yii\bootstrap5\BaseHtml::staticControl(): Argument #1 ($value) must be of type string, int given

TypeError: yii\bootstrap5\BaseHtml::staticControl(): Argument #1 ($value) must be of type string, int given, called in yiisoft/yii2-bootstrap5/src/BaseHtml.php on line 76 and defined in yiisoft/yii2-bootstrap5/src/BaseHtml.php:49

    public static function activeStaticControl(Model $model, string $attribute, $options = []): string
    {
        if (isset($options['value'])) {
            $value = $options['value'];
            unset($options['value']);
        } else {
            $value = static::getAttributeValue($model, $attribute);
        }

        return static::staticControl($value, $options);
    }

Model attribute and $options['value'] can also be float, int or even null,
So (string) typecast is needed.

Pull request will provided.

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

Change dropdown default cssclass

What steps will reproduce the problem?

Form Dropdown

What is the expected result?

<select class="form-select"></select>

What do you get instead?

<select class="form-control"></select>

Additional info

Q A
Yii vesion 2.0.43
PHP version 8.0
Operating system Windows 10 on dev and Debian on prod

Aria/data attributes

What steps will reproduce the problem?

Yii2 and this package support short syntax for data/aria attributes ('data' => ['suffix' => '...', 'suffix2' => '...']), but don't have methods to merge attributes using long syntax (['data-suffix' => '...']) with short syntax (['data' => ['suffix' => '...']]). This package uses both syntaxes, which only increases the chance of making error.

Two lines from single method:

'data' => ['bs-dismiss' => 'modal'],

if (!isset($this->toggleButton['data-bs-target']) && !isset($this->toggleButton['href'])) {

Fix

I see two solutions:

  1. add method to merge attributes
  2. select one syntax and replace another

Additional info

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

Navbar cannot accept collapseOptions = false

What steps will reproduce the problem?

Create a new Navbar, with collapseOptions set to false.

E.g.

Navbar::begin([
  'collapseOptions' => false,
]);

//... 

Navbar::end();

What is the expected result?

The outputted Navbar HTML to not contain a 'collapse' container

What do you get instead?

PHP Warning – yii\base\ErrorException
Trying to access array offset on value of type bool

Additional info

Q A
Yii vesion 2.0.47
PHP version 8.0
Operating system Docker

Translation re-factoring

Need

  1. Extract code from TranslationBootstrap::bootstrap() into BootstrapAsset::init() - no need add it bootstrap and load every time
  2. Move up messages directory - src must contain only class files

Dropdown template is incorrect

Why is your dropdown template not the same as the bootstrap 5 dropdown template?

Official docs

https://getbootstrap.com/docs/5.2/components/dropdowns/#single-button

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
    Dropdown button
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
    <li><a class="dropdown-item" href="#">Action</a></li>
    <li><a class="dropdown-item" href="#">Another action</a></li>
    <li><a class="dropdown-item" href="#">Something else here</a></li>
  </ul>
</div>

Your template is using div instead of ul
https://github.com/yiisoft/yii2-bootstrap5/blob/master/src/Dropdown.php#L166

Additional info

Q A
Yii vesion 2
PHP version *
Operating system *

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

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

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?

$label = ArrayHelper::remove($toggleButton, 'label', 'Show');

Additional info

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

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

Missing package twbs/boostrap-icons in composer.json

What steps will reproduce the problem?

composer create-project yiisoft/yii2-app-basic [foldername]
cd [foldername]
composer upgrade 

You now have Yii2 Basic installed with package yiisoft/bootstrap5 required as version ~2.0.2 in composer.json file (version 2.0.4). If you use any code that will access the yii2-bootstrap5\BootstrapIconAsset.php file, you will get an exception.

For example, if you install the package 2amigos/yii2-usuario, that uses the BootstraIconAsset.php file, you get the exception when you try to access the user/admin page.

To remove the error, you can require the package twbs/bootstrap-icons manually:

composer require twbs/bootstrap-icons

What is the expected result?

No error

What do you get instead?

Invalid Argument – yii\base\InvalidArgumentException
The file or directory to be published does not exist: /var/www/lonnsslipp/vendor/twbs/bootstrap-icons/font

Exception thrown from file /vendor/yiisoft/yii2/web/AssetManager.php line 26:

\yii\bootstrap5\BootstrapIconAsset::register($this);

The error occurrs because the file yii2-bootstrap5/BootstrapIconAsset.php has its $sourcePath property set to "@vendor/twbs/bootstrap-icons/font", while the composer.json does not require it.

Additional info

Q A
Yii vesion 2.0.49.3
PHP version 8.2.15
Operating system Linux Mint 20.3

BootstrapWidgetTrait::registerPlugin do nothing if no clientOptions is provided

protected function registerPlugin(string $name)
{
     ...
     
    if ($this->clientOptions !== []) {
        $options = empty($this->clientOptions) ? '' : Json::htmlEncode($this->clientOptions);
        $js = "jQuery('#$id').$name($options);";
        $view->registerJs($js);
    }
    ...
}

So, when no clientOptions provided for plugin, then plugin registration not working.
Pull request created.

Add brandImageOptions to NavBar.php to ensure accessibility.

What steps will reproduce the problem?

This code:

 <?php
    NavBar::begin([
        'brandLabel' => Yii::$app->name,
        'brandUrl'   => Yii::$app->homeUrl,
        'brandImage' => ['@web/img/logo.svg'],
        'options'    => ['class' => 'navbar-expand-md navbar-dark bg-dark fixed-top']
    ]);
    NavBar::end();
    ?>

will generate something like this:

<nav id="w0" class="navbar-expand-md navbar-dark bg-dark fixed-top navbar">
    <div class="container">
        <a class="navbar-brand" href="/"><img src="/img/logo.svg" alt=""></a>
          ....
    </div>
</nav>

The problem is that when I now try to make my website accessible, I get the following errors, for example, with the WAVE browser plugin:
1.1.1 Non-text Content (Level A)
2.4.4 Link Purpose (In Context) (Level A)

Decorative images don't need alt text, but as soon as they contain a link, logo, lettering or other text related content e.g. home page it must be present.

What is your proposed solution

Add a new attribute brandImageOptions to NavBar.php

This code:

 <?php
    NavBar::begin([
        'brandLabel' => Yii::$app->name,
        'brandUrl'   => Yii::$app->homeUrl,
        'brandImage' => ['@web/img/logo.svg'],
        'brandImageOptions' => ['alt' => 'Logo of company XYZ'],
        'options'    => ['class' => 'navbar-expand-md navbar-dark bg-dark fixed-top']
    ]);
    NavBar::end();
    ?>

will generate something like this:

<nav id="w0" class="navbar-expand-md navbar-dark bg-dark fixed-top navbar">
    <div class="container">
        <a class="navbar-brand" href="/"><img src="/img/logo.svg" alt="Logo of company XYZ"></a>
          ....
    </div>
</nav>

Additional info

Q A
Yii vesion 2.0.49.2
yii2-bootstrap5 version 2.0.4
PHP version 8.0
Operating system linux

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.