occurs because the widget yii\bootstrap5\Modal does not have a public property named aria-labelledby. Your code is somehow passing aria-labelledby directly as a configuration property to Modal::begin(), which causes this exception.
Why does this happen?
The Modal::begin() method accepts options array, but it does not expect arbitrary HTML attributes to be passed directly as top-level config keys. For example:
php
Modal::begin([
'id' => 'modal-id',
'aria-labelledby' => 'label', // causes error because no such property
]);
This is incorrect because aria-labelledby is not a property of the modal widget; instead, it's an HTML attribute that should be assigned inside certain HTML options.
How to fix?
1. Pass HTML attributes properly under options
Attributes like aria-labelledby belong inside the 'options' array which represents the attributes of the outer container (modal div).
But $modalOptions may contain keys like directly, which causes this problem.
User
code
public function run(): void
{
// Determine modal ID, or generate a unique ID if not provided
$id = $this->options['id'] ?? $this->getId();
// Determine modal title and size, allowing user to override via $options
$modalTitle = $this->options['title'] ?? $this->title;
$modalSize = $this->options['size'] ?? $this->size;
// Extract 'options' (HTML attributes for modal container) or empty array
$htmlOptions = $this->options['options'] ?? [];
// Prepare default classes to ensure Bootstrap modal styles and smooth
// fade + your custom class 'square'
$defaultClasses = ['modal', 'fade', 'square'];
// Merge with any classes user provided in $htmlOptions['class']
$existingClasses = [];
if (isset($htmlOptions['class']))
{
if (is_array($htmlOptions['class']))
{
$existingClasses = $htmlOptions['class'];
}
elseif (is_string($htmlOptions['class']))
{
$existingClasses = preg_split('/\s+/', trim($htmlOptions['class']));
}
}
$combinedClasses = array_unique(array_merge($defaultClasses, $existingClasses));
$htmlOptions['class'] = implode(' ', $combinedClasses);
// Prepare modal config: include all options from $this->options
// except 'id', 'title', 'size', and 'options' which we handled separately
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Merge with our base configuration
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
// Begin the modal widget
BootstrapModal::begin($config);
/**
* Render the Bootstrap Modal with the Inquiry Form.
*
* The model is accessible via $this->formModel, which eliminates the
* need to pass it repeatedly through different methods.
*/
$params = array_merge(['model' => $this->formModel, 'id' => $id], $this->viewParams);
echo $this->render($this->view, $params);
// End the modal definition.
BootstrapModal::end();
// Register JavaScript for form submission handling.
$this->registerJs($id);
}
is what i have so far
Assistant
Your updated run() method looks almost good. The main issue causing the error remains that some HTML attributes like aria-labelledby might still be passed as top-level keys in $modalOptions, which is incorrect.
They need to be inside the 'options' array passed to BootstrapModal::begin().
How to fix your current run() method:
You should extract any HTML attributes from $modalOptions and add them to $htmlOptions before merging.
Here is a modified snippet of your method incorporating this fix:
indicates that you are trying to set a backdrop property directly on yii\bootstrap5\Modal, but the widget does not have a public property backdrop.
Why does this happen?
The yii\bootstrap5\Modal widget does not have a backdrop property you can set directly.
Instead, options like backdrop, keyboard, focus, and others are part of the client options, i.e. the JavaScript options passed to initialize the Bootstrap modal JavaScript plugin.
In Yii Bootstrap 5 extension, they are passed inside the 'clientOptions' array.
How to fix this?
Instead of passing 'backdrop' => ... at the top level of modal config, pass it inside 'clientOptions' => [ ... ].
Example:
php
Modal::begin([
'id' => 'modal-id',
'clientOptions' => [
'backdrop' => false,
'keyboard' => true,
],
// other options (like 'size', 'title', 'options' for html attributes) here
]);
What to change in your widget code?
Currently, it looks like you might be passing 'backdrop' => false (or other client options) directly at the top level config ($modalOptions).
Modify your widget code so these client options go inside 'clientOptions'.
How to do this?
In your code, after pulling out non-widget properties (like id, title, size, options), check for client options like backdrop, and move them into a 'clientOptions' array inside the modal configuration.
This is the same type of problem as with backdrop:
yii\bootstrap5\Modal does not have public properties named keyboard, backdrop, or similar.
Bootstrap modal options like keyboard, backdrop, focus, show, etc. are not widget properties but client-side (JavaScript) options, and must be passed inside the 'clientOptions' array.
Why the error happens
If you pass:
php
Modal::begin([
'keyboard' => true, // <-- this raises UnknownPropertyException
]);
this fails because keyboard is not a public property of the widget.
You want to collect all known client options from $modalOptions and move them into clientOptions subarray, then pass this structured configuration to Modal::begin().
Here's a code snippet that does this safely:
php
// Collect modal options, except some keys handled separately
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Prepare clientOptions array
$clientOptions = $modalOptions['clientOptions'] ?? [];
// List of known client options of Bootstrap modal widget
$clientOptionKeys = [
'backdrop', 'keyboard', 'focus', 'show', 'remote',
'scrollable', 'centered'
];
// Move client options from $modalOptions to $clientOptions
foreach ($clientOptionKeys as $key) {
if (array_key_exists($key, $modalOptions)) {
$clientOptions[$key] = $modalOptions[$key];
unset($modalOptions[$key]);
}
}
// Assign clientOptions back if not empty
if (!empty($clientOptions)) {
$modalOptions['clientOptions'] = $clientOptions;
}
// Build final config array for Modal::begin()
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
// Now safe to call
BootstrapModal::begin($config);
Summary
Always pass JS options such as keyboard, backdrop, etc. inside 'clientOptions'.
Do not pass these options at the top-level configuration array.
Your widget's logic should automatically separate the client options from widget properties.
If you want, I can prepare the full run() method with this logic integrated. Let me know!
Great! The reason your 'data-backdrop' => 'static' works when placed inside 'options' is because 'options' correspond to HTML attributes for the modal container (the rendered <div>), and HTML attributes data-*, including data-backdrop, are allowed there.
Important distinction:
'data-backdrop' => 'static' (with the data- prefix) is an HTML attribute and should go inside 'options'. This works because it adds the data-backdrop="static" attribute on the modal container div.
'backdrop' => false (without data-) is a Bootstrap JavaScript option, which must go inside the clientOptions array — otherwise, you'll get the "Unknown property" error.
So, these are the differences:
Feature
Where it goes
Purpose
'data-backdrop' => 'static'
Inside 'options'
Html attribute data-backdrop
'backdrop' => false
Inside 'clientOptions'
JS option configuring modal show behavior (false disables backdrop)
The Yii 2 Bootstrap 5 extension wraps the Bootstrap 5 modal and provides a widget interface.
Widget properties, such as:
id
title
size
options (this is for HTML container attributes, like class, aria-*, or data-* attributes)
Client-side JS plugin options are passed inside the widget's clientOptions property.
Specifically:
options → HTML attributes for the modal container (<div class="modal" ...>)
clientOptions → options passed to new bootstrap.Modal(...) JS constructor (backdrop, keyboard, focus, etc.)
3. What does this mean for backdrop and keyboard?
Pass and inside .
User
class ModalJQry extends Widget
{
/**
* @var array Options for modal configuration and container HTML attributes.
* Supported keys include:
*
* - 'id' => string
* The HTML ID attribute for the modal container element.
* If not provided, a unique ID will be generated automatically.
*
* - 'title' => string
* The modal header title text. Overrides the widget's titleprsize property if set.
* Use , or empty string for default size.
*
* - 'backdrop' => bool|string
* Controls the modal backdrop behavior.
* - (default): modal will have a dark backdrop which closes the modal on click.
* - : no backdrop is rendered.
* - : backdrop is present but clicking it will close the modal.
*
* - 'keyboard' => bool
* Determines if the modal can be closed via keyboard:
* - (default): pressing the Escape (Esc) key closes the modal.
* - : pressing Escape key will not close the modal.
*
* - 'centered' => bool
* If , the modal dialog is vertically centered within the page.
* If (default), modal appears aligned to top of viewport.
*
* - 'scrollable' => bool
* If , the modal body becomes scrollable and fixed height will be applied if content exceeds viewport.
*
* - 'fade' => bool
* Enables or disables the fade-in and fade-out CSS animation for the modal.
* Default is to enable smooth transition.
*
* - 'options' => array
* HTML attributes for the modal container tag. For example:
* - => string|array, additional CSS classes to add to modal container.
* - Any other valid HTML attributes like , .
*
* These options follow the Bootstrap 5 modal plugin configuration and control
* both the visual appearance and behavior of the modal dialog.
*/
public array $options = [];
Assistant
Exactly, your understanding is correct.
To integrate properly with Yii2's yii\bootstrap5\Modal widget, Bootstrap modal JavaScript options like backdrop and keyboard should not be passed in the 'options' array (which is for HTML attributes). Instead, they belong in the 'clientOptions' array.
So in your widget, here’s what you should do:
From your $this->options, separate HTML attributes (put in 'options' for Modal widget)
Separate Bootstrap JS plugin options (backdrop, keyboard, focus, show, scrollable, centered, fade, etc.) and set them inside 'clientOptions'.
Modify your current run() method like this (just the relevant part):
php
// ... after you unset 'id', 'title', 'size', 'options' from $modalOptions
// Known client options for Bootstrap modal JS plugin
$clientOptionKeys = [
'backdrop', 'keyboard', 'focus', 'show',
'scrollable', 'centered', 'fade'
];
// Separate client options
$clientOptions = [];
foreach ($clientOptionKeys as $key) {
if (array_key_exists($key, $modalOptions)) {
$clientOptions[$key] = $modalOptions[$key];
unset($modalOptions[$key]);
}
}
// Also extract HTML attribute keys (aria-*, data-*, keys with dash)
foreach ($modalOptions as $key => $value) {
if (str_starts_with($key, 'aria') || str_starts_with($key, 'data') || strpos($key, '-') !== false) {
$htmlOptions[$key] = $value;
unset($modalOptions[$key]);
}
}
// If you have extracted clientOptions, assign it back to modalOptions
if (!empty($clientOptions)) {
$modalOptions['clientOptions'] = $clientOptions;
}
// Now merge config
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
// Then begin
BootstrapModal::begin($config);
User
are they the only two options that need this change?
Assistant
Good question!
No, not just backdrop and keyboard, but any Bootstrap Modal JavaScript plugin options need to go into clientOptions in Yii2's yii\bootstrap5\Modal. These options configure the Bootstrap JS behavior rather than HTML attributes.
Typical Bootstrap 5 Modal JS Plugin Options to Put in clientOptions:
Option
Description
Type
Default
backdrop
Controls modal backdrop behavior
true, false, 'static'
true
keyboard
Whether ESC key closes modal
boolean
true
focus
Autofocus modal on show
boolean
true
show
Whether modal shows immediately on init
boolean
true
scrollable
Enable scrollable modal body (affects internal dialog classes)
boolean
false
centered
Vertically center modal dialog
boolean
false (depends on Bootstrap CSS classes)
Also, bootstrap 5 modal config in yii is extended slightly, but as of yii-bootstrap 5 module, the following are commonly supported JS options (usually documented either in yii-bootstrap or bootstrap docs):
backdrop
keyboard
focus
show
scrollable
centered
fade (fade animation enabled)
What should not go in clientOptions but in 'options'?
HTML container attributes such as:
id
class
aria-labelledby
User
lets change the code than for these changes
Assistant
Certainly! Here's your updated run() method with proper separation of Bootstrap JS modal options into clientOptions and HTML attributes into options:
php
User
need the full code.. setting of vars all of it
Assistant
Certainly! Below is a complete example of your ModalJQry widget class, updated to properly separate Bootstrap Modal JS options into clientOptions and HTML attributes into options. It includes all your properties, init(), run(), comments, and proper handling of classes and options.
php
User
im leaving:
code
public array $options = [];
/**
* @var string Default modal title (overridden by $options['title'] if set)
*/
public string $title = 'Modal Title';
/**
* @var string Default modal size (overridden by $options['size'] if set)
* Use Modal::SIZE_DEFAULT, Modal::SIZE_LARGE, Modal::SIZE_SMALL
*/
public string $size = BootstrapModal::SIZE_LARGE;
so than they dont have to be in the options
Assistant
Yes, that’s a perfectly valid approach and even cleaner!
By keeping these as separate, public properties on your widget:
php
public array $options = [];
public string $title = 'Modal Title';
public string $size = BootstrapModal::SIZE_LARGE;
You allow users of your widget to set $title and $size directly as widget properties instead of nesting them inside the $options array.
Then your run() method should prefer these properties over $this->options['title'] and $this->options['size']:
php
// Prefer explicit widget properties for title and size first,
// then fallback to $options if you want (or just ignore $options keys for these)
$modalTitle = $this->title;
$modalSize = $this->size;
Or just ignore any 'title' and 'size' keys inside $options so they aren’t confusing.
Why is this beneficial?
It clearly separates widget configuration ($title, $size) from HTML attributes/configuration in $options.
You avoid confusion or redundancies (title doesn’t live in $options['title'] and $this->title both).
namespace app\models\forms;
use yii\base\Model;
use app\models\Product;
class CartAddForm extends Model
{
public int $productId;
public int $quantity = 1;
public function rules()
{
return [
[['productId', 'quantity'], 'required'],
['productId', 'integer'],
['quantity', 'integer', 'min' => 1],
['productId', 'exist', 'targetClass' => Product::class, 'targetAttribute' => [
'productId' => 'id'
]],
];
}
public function attributeLabels()
{
return [
'productId' => 'Product',
'quantity' => 'Quantity',
];
}
}
lets make qunaity optional
Assistant
To make quantity optional, you need to:
Remove it from the 'required' validation rule, so it won't be required.
Provide a default value (you already have = 1).
Keep other validations like integer and min value so if provided it is valid.
Updated rules() method:
php
public function rules()
{
return [
[['productId'], 'required'], // only productId is required now
['productId', 'integer'],
['quantity', 'integer', 'min' => 1], // quantity is optional but if provided must be integer >=1
['productId', 'exist', 'targetClass' => Product::class, 'targetAttribute' => ['productId' => 'id']],
];
}
Explanation:
Since quantity has default value 1, if you don’t send it, $quantity will be set to 1.
Having 'quantity' only validated as integer and minimal value means it's optional but validated if present.
productId still required.
Complete updated class for clarity:
php
namespace app\models\forms;
use yii\base\Model;
use app\models\Product;
class CartAddForm extends Model
{
public int $productId;
public int $quantity = 1;
public function rules()
{
return [
[['productId'], 'required'],
['productId', 'integer'],
['quantity', 'integer', 'min' => 1],
['productId', 'exist', 'targetClass' => Product::class, 'targetAttribute' => [
'productId' => 'id'
]],
];
}
public function attributeLabels()
{
return [
'productId' => 'Product',
'quantity' => 'Quantity',
];
}
}
That’s all! Now quantity is optional with default value 1.
Therefore, you should extract all HTML attribute keys (like aria-*) into the 'options' array instead of passing them at the top level.
3. A better approach — separate modal widget properties from HTML attributes
Modify your code to:
Remove these known widget properties from $modalOptions: 'id', 'title', 'size', 'options' (you already do that).
Then, move all remaining keys in $modalOptionsthat are not actual widget properties into $htmlOptions.
Example fix snippet:
Change this part in your code:
php
// modalOptions currently includes aria-labelledby as a top-level key
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Combine known htmlOptions with any html attributes in modalOptions (for example aria-labelledby)
foreach ($modalOptions as $key => $value) {
// Attributes with dashes or starting with 'aria-' or 'data-' should be moved into HTML attributes
if (str_contains($key, '-') || str_starts_with($key, 'aria') || str_starts_with($key, 'data')) {
$htmlOptions[$key] = $value;
unset($modalOptions[$key]);
}
}
// Now modalOptions should only have valid widget properties
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
This separates widget properties and HTML attributes correctly.
Alternative quick fix in your case:
If you know which HTML attributes you want to add (like aria-labelledby), ensure that they are passed inside options when using the widget, e.g.:
php
echo ModalJQry::widget([
'options' => [
'id' => 'myModal',
'title' => 'My Title',
'options' => [ // this is HTML attributes for modal container
'aria-labelledby' => 'myModalLabel',
],
],
]);
aria-labelledby is not a property of yii\bootstrap5\Modal.
Place HTML attributes such as aria-labelledby inside the 'options' array.
Your widget code should separate modal widget config and html attributes correctly.
Do not pass unknown keys as widget properties.
If you need me to, I can provide a fixed version of your widget code reflecting these changes. Just ask!
public function run(): void
{
// Determine modal ID, or generate a unique ID if not provided
$id = $this->options['id'] ?? $this->getId();
// Determine modal title and size, allowing user to override via $options
$modalTitle = $this->options['title'] ?? $this->title;
$modalSize = $this->options['size'] ?? $this->size;
// Extract 'options' (HTML attributes for modal container) or empty array
$htmlOptions = $this->options['options'] ?? [];
// Prepare default classes to ensure Bootstrap modal styles and smooth
// fade + your custom class 'square'
$defaultClasses = ['modal', 'fade', 'square'];
// Merge with any classes user provided in $htmlOptions['class']
$existingClasses = [];
if (isset($htmlOptions['class'])) {
if (is_array($htmlOptions['class'])) {
$existingClasses = $htmlOptions['class'];
} elseif (is_string($htmlOptions['class'])) {
$existingClasses = preg_split('/\s+/', trim($htmlOptions['class']));
}
}
$combinedClasses = array_unique(array_merge($defaultClasses, $existingClasses));
$htmlOptions['class'] = implode(' ', $combinedClasses);
// Prepare modal config: include all options from $this->options
// except 'id', 'title', 'size', and 'options' which we handled separately
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Extract all keys from $modalOptions that look like HTML attributes (e.g., aria-*, data-*, or contain dashes),
// and move them into $htmlOptions instead of keeping them at top-level config
foreach ($modalOptions as $key => $value) {
if (str_starts_with($key, 'aria') || str_starts_with($key, 'data') || strpos($key, '-') !== false) {
$htmlOptions[$key] = $value;
unset($modalOptions[$key]);
}
}
// Merge with our base configuration; only valid widget properties stay in $modalOptions
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
// Begin the modal widget
BootstrapModal::begin($config);
/**
* Render the Bootstrap Modal with the Inquiry Form.
*
* The model is accessible via $this->formModel, which eliminates the
* need to pass it repeatedly through different methods.
*/
$params = array_merge(['model' => $this->formModel, 'id' => $id], $this->viewParams);
echo $this->render($this->view, $params);
// End the modal definition.
BootstrapModal::end();
// Register JavaScript for form submission handling.
$this->registerJs($id);
}
Explanation
The newly added loop scans $modalOptions for keys that should be HTML attributes rather than modal widget properties (keys starting with aria or data, or containing dashes).
Those keys get moved into $htmlOptions.
The rest of $modalOptions contains only valid modal widget properties to be passed along.
This prevents the error Setting unknown property: yii\bootstrap5\Modal::aria-labelledby.
Additional remarks
Make sure you keep using the correct namespace/class for the modal widget. You called it BootstrapModal::begin(). Just ensure your use statement matches.
Your $options array passed into this widget should correctly place HTML modal container attributes inside the 'options' key.
Example usage in your controller/view:
php
echo ModalJQry::widget([
'options' => [
'id' => 'myModal',
'title' => 'My Modal Title',
'options' => [ // HTML attributes for modal container <div>
'aria-labelledby' => 'modalLabel',
'data-backdrop' => 'static',
],
'size' => \yii\bootstrap5\Modal::SIZE_LARGE,
],
// other widget properties if any
]);
Let me know if you want me to help with other parts.
// Extract modal options except 'id', 'title', 'size', 'options'
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Initialize clientOptions array if not set
$clientOptions = $modalOptions['clientOptions'] ?? [];
// Move known client options from modalOptions to clientOptions
$clientOptionKeys = ['backdrop', 'keyboard', 'focus', 'show', 'remote', 'scrollable', 'centered'];
foreach ($clientOptionKeys as $key) {
if (array_key_exists($key, $modalOptions)) {
$clientOptions[$key] = $modalOptions[$key];
unset($modalOptions[$key]);
}
}
// Assign updated clientOptions back to modalOptions if not empty
if (!empty($clientOptions)) {
$modalOptions['clientOptions'] = $clientOptions;
}
// Now build the full config:
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
Summary
'backdrop' and other Bootstrap modal JS options go into 'clientOptions'.
Don't pass backdrop directly at top-level config for the widget.
Adjust your widget to move these automatically into 'clientOptions' to avoid this error.
If you want, I can help you refactor your widget code fully to handle the separation of widget config, html options, and client options cleanly. Just ask!
u
i
r
y′
)
,′
s
i
z
e′
=>
Modal::
SIZESMALL,′options′=>
[′id′=
>′
inquiry−
modal′,//uniquemodalID′class′=
>′
custom−
modal−
class′,//addstodefaultclasses′aria−
labelledby′=
>′
my−
modal−
label′,′data−
backdrop′=
>′
static′,′keyboard′=>
false,],′formModel′=>
Summary about what you observed
Adding 'data-backdrop' => 'static' inside 'options' works because it's an HTML attribute that Bootstrap's JavaScript reads automatically.
Passing 'backdrop' => false (or any JS options) directly inside 'options' or top-level config does NOT work and causes errors. They belong in 'clientOptions'.
What I recommend for your widget
Keep 'aria-labelledby', 'data-backdrop', 'class', and other HTML attributes inside 'options'.
In your widget’s run() method, automatically move props accordingly (per previous suggestions).
If you want, I can help you update your widget code accordingly for best practice and to prevent errors!
Class yii\bootstrap\Modal
All Classes | Properties | Methods | Constants
Inheritance yii\bootstrap\Modal » yii\bootstrap\Widget » yii\base\Widget
Uses Traits yii\bootstrap\BootstrapWidgetTrait
Available since extension's version 2.0
Source Code https://github.com/yiisoft/yii2-bootstrap/blob/master/src/Modal.php
Modal renders a modal window that can be toggled by clicking on a button.
The following example will show the content enclosed between the begin() and end() calls within the modal window:
Modal::begin([
'header' => '<h2>Hello world</h2>',
'toggleButton' => ['label' => 'click me'],
]);
echo 'Say hello...';
Modal::end();
See also http://getbootstrap.com/javascript/#modals.
Public Properties
Hide inherited properties
Property Type Description Defined By
$bodyOptions array Body options yii\bootstrap\Modal
$clientEvents array The event handlers for the underlying Bootstrap JS plugin. yii\bootstrap\BootstrapWidgetTrait
$clientOptions array The options for the underlying Bootstrap JS plugin. yii\bootstrap\BootstrapWidgetTrait
$closeButton array|false The options for rendering the close button tag. yii\bootstrap\Modal
$footer string The footer content in the modal window. yii\bootstrap\Modal
$footerOptions string Additional footer options yii\bootstrap\Modal
$header string The header content in the modal window. yii\bootstrap\Modal
$headerOptions string Additional header options yii\bootstrap\Modal
$options array The HTML attributes for the widget container tag. yii\bootstrap\Widget
$size string The modal size. yii\bootstrap\Modal
$toggleButton array The options for rendering the toggle button tag. yii\bootstrap\Modal
Public Methods
Hide inherited methods
Method Description Defined By
getView() yii\bootstrap\BootstrapWidgetTrait
init() Initializes the widget. yii\bootstrap\Modal
run() Renders the widget. yii\bootstrap\Modal
Protected Methods
Hide inherited methods
Method Description Defined By
initOptions() Initializes the widget options. yii\bootstrap\Modal
registerClientEvents() Registers JS event handlers that are listed in $clientEvents. yii\bootstrap\BootstrapWidgetTrait
registerPlugin() Registers a specific Bootstrap plugin and the related events yii\bootstrap\BootstrapWidgetTrait
renderBodyBegin() Renders the opening tag of the modal body. yii\bootstrap\Modal
renderBodyEnd() Renders the closing tag of the modal body. yii\bootstrap\Modal
renderCloseButton() Renders the close button. yii\bootstrap\Modal
renderFooter() Renders the HTML markup for the footer of the modal yii\bootstrap\Modal
renderHeader() Renders the header HTML markup of the modal yii\bootstrap\Modal
renderToggleButton() Renders the toggle button. yii\bootstrap\Modal
Constants
Hide inherited constants
Constant Value Description Defined By
SIZE_DEFAULT "" yii\bootstrap\Modal
SIZE_LARGE "modal-lg" yii\bootstrap\Modal
SIZE_SMALL "modal-sm" yii\bootstrap\Modal
Property Details
Hide inherited properties
$bodyOptions public property (available since version 2.0.7)
Body options
See also \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
public array $bodyOptions = [
'class' => 'modal-body',
]
$closeButton public property
The options for rendering the close button tag. The close button is displayed in the header of the modal window. Clicking on the button will hide the modal window. If this is false, no close button will be rendered.
The following special options are supported:
tag: string, the tag name of the button. Defaults to 'button'.
label: string, the label of the button. Defaults to '×'.
The rest of the options will be rendered as the HTML attributes of the button tag. Please refer to the Modal plugin help for the supported HTML attributes.
public array|false $closeButton = []
$footer public property
The footer content in the modal window.
public string $footer = null
$footerOptions public property (available since version 2.0.1)
Additional footer options
See also \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
public string $footerOptions = null
$header public property
The header content in the modal window.
public string $header = null
$headerOptions public property (available since version 2.0.1)
Additional header options
See also \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
public string $headerOptions = null
$size public property
The modal size. Can be SIZE_LARGE or SIZE_SMALL, or empty for default.
public string $size = null
$toggleButton public property
The options for rendering the toggle button tag. The toggle button is used to toggle the visibility of the modal window. If this property is false, no toggle button will be rendered.
The following special options are supported:
tag: string, the tag name of the button. Defaults to 'button'.
label: string, the label of the button. Defaults to 'Show'.
The rest of the options will be rendered as the HTML attributes of the button tag. Please refer to the Modal plugin help for the supported HTML attributes.
public array $toggleButton = false
Method Details
Hide inherited methods
getView() public abstract method
Defined in: yii\bootstrap\BootstrapWidgetTrait::getView()
See also \yii\base\Widget::getView().
public abstract \yii\web\View getView ( )
return \yii\web\View
The view object that can be used to render views or view files.
init() public method
Initializes the widget.
public void init ( )
initOptions() protected method
Initializes the widget options.
This method sets the default values for various options.
protected void initOptions ( )
registerClientEvents() protected method (available since version 2.0.2)
Defined in: yii\bootstrap\BootstrapWidgetTrait::registerClientEvents()
Registers JS event handlers that are listed in $clientEvents.
protected void registerClientEvents ( )
registerPlugin() protected method
Defined in: yii\bootstrap\BootstrapWidgetTrait::registerPlugin()
Registers a specific Bootstrap plugin and the related events
protected void registerPlugin ( $name )
$name string
The name of the Bootstrap plugin
renderBodyBegin() protected method
Renders the opening tag of the modal body.
protected string renderBodyBegin ( )
return string
The rendering result
renderBodyEnd() protected method
Renders the closing tag of the modal body.
protected string renderBodyEnd ( )
return string
The rendering result
renderCloseButton() protected method
Renders the close button.
protected string renderCloseButton ( )
return string
The rendering result
renderFooter() protected method
Renders the HTML markup for the footer of the modal
protected string renderFooter ( )
return string
The rendering result
renderHeader() protected method
Renders the header HTML markup of the modal
protected string renderHeader ( )
return string
The rendering result
renderToggleButton() protected method
Renders the toggle button.
protected string renderToggleButton ( )
return string
The rendering result
run() public method
Renders the widget.
public void run ( )
is yii2 doc on modal
and this is the bootstrap 5.3 doc
code
Modal
Use Bootstrap’s JavaScript modal plugin to add dialogs to your site for lightboxes, user notifications, or completely custom content.
On this page
How it works
Examples
Modal components
Live demo
Static backdrop
Scrolling long content
Vertically centered
Tooltips and popovers
Using the grid
Varying modal content
Toggle between modals
Change animation
Remove animation
Dynamic heights
Accessibility
Embedding YouTube videos
Optional sizes
Fullscreen Modal
CSS
Variables
Sass variables
Sass loops
Usage
Via data attributes
Toggle
Dismiss
Via JavaScript
Options
Methods
Passing options
Events
How it works
Before getting started with Bootstrap’s modal component, be sure to read the following as our menu options have recently changed.
Modals are built with HTML, CSS, and JavaScript. They’re positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead.
Clicking on the modal “backdrop” will automatically close the modal.
Bootstrap only supports one modal window at a time. Nested modals aren’t supported as we believe them to be poor user experiences.
Modals use position: fixed, which can sometimes be a bit particular about its rendering. Whenever possible, place your modal HTML in a top-level position to avoid potential interference from other elements. You’ll likely run into issues when nesting a .modal within another fixed element.
Once again, due to position: fixed, there are some caveats with using modals on mobile devices. See our browser support docs for details.
Due to how HTML5 defines its semantics, the autofocus HTML attribute has no effect in Bootstrap modals. To achieve the same effect, use some custom JavaScript:
const myModal = document.getElementById('myModal')
const myInput = document.getElementById('myInput')
myModal.addEventListener('shown.bs.modal', () => {
myInput.focus()
})
The animation effect of this component is dependent on the prefers-reduced-motion media query. See the reduced motion section of our accessibility documentation.
Keep reading for demos and usage guidelines.
Examples
Modal components
Below is a static modal example (meaning its position and display have been overridden). Included are the modal header, modal body (required for padding), and modal footer (optional). We ask that you include modal headers with dismiss actions whenever possible, or provide another explicit dismiss action.
Modal title
Modal body text goes here.
<div class="modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
In the above static example, we use <h5>, to avoid issues with the heading hierarchy in the documentation page. Structurally, however, a modal dialog represents its own separate document/context, so the .modal-title should ideally be an <h1>. If necessary, you can use the font size utilities to control the heading’s appearance. All the following live examples use this approach.
Live demo
Toggle a working modal demo by clicking the button below. It will slide down and fade in from the top of the page.
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Static backdrop
When backdrop is set to static, the modal will not close when clicking outside of it. Click the button below to try it.
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">
Launch static backdrop modal
</button>
<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
Scrolling long content
When modals become too long for the user’s viewport or device, they scroll independent of the page itself. Try the demo below to see what we mean.
You can also create a scrollable modal that allows scrolling the modal body by adding .modal-dialog-scrollable to .modal-dialog.
<!-- Scrollable modal -->
<div class="modal-dialog modal-dialog-scrollable">
...
</div>
Vertically centered
Add .modal-dialog-centered to .modal-dialog to vertically center the modal.
<!-- Vertically centered modal -->
<div class="modal-dialog modal-dialog-centered">
...
</div>
<!-- Vertically centered scrollable modal -->
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
...
</div>
Tooltips and popovers
Tooltips and popovers can be placed within modals as needed. When modals are closed, any tooltips and popovers within are also automatically dismissed.
<div class="modal-body">
<h2 class="fs-5">Popover in a modal</h2>
<p>This <button class="btn btn-secondary" data-bs-toggle="popover" title="Popover title" data-bs-content="Popover body content is set in this attribute.">button</button> triggers a popover on click.</p>
<hr>
<h2 class="fs-5">Tooltips in a modal</h2>
<p><a href="#" data-bs-toggle="tooltip" title="Tooltip">This link</a> and <a href="#" data-bs-toggle="tooltip" title="Tooltip">that link</a> have tooltips on hover.</p>
</div>
Using the grid
Utilize the Bootstrap grid system within a modal by nesting .container-fluid within the .modal-body. Then, use the normal grid system classes as you would anywhere else.
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">.col-md-4</div>
<div class="col-md-4 ms-auto">.col-md-4 .ms-auto</div>
</div>
<div class="row">
<div class="col-md-3 ms-auto">.col-md-3 .ms-auto</div>
<div class="col-md-2 ms-auto">.col-md-2 .ms-auto</div>
</div>
<div class="row">
<div class="col-md-6 ms-auto">.col-md-6 .ms-auto</div>
</div>
<div class="row">
<div class="col-sm-9">
Level 1: .col-sm-9
<div class="row">
<div class="col-8 col-sm-6">
Level 2: .col-8 .col-sm-6
</div>
<div class="col-4 col-sm-6">
Level 2: .col-4 .col-sm-6
</div>
</div>
</div>
</div>
</div>
</div>
Varying modal content
Have a bunch of buttons that all trigger the same modal with slightly different contents? Use event.relatedTarget and HTML data-bs-* attributes to vary the contents of the modal depending on which button was clicked.
Below is a live demo followed by example HTML and JavaScript. For more information, read the modal events docs for details on relatedTarget.
html
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@mdo">Open modal for @mdo</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@fat">Open modal for @fat</button>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal" data-bs-whatever="@getbootstrap">Open modal for @getbootstrap</button>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">New message</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form>
<div class="mb-3">
<label for="recipient-name" class="col-form-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="mb-3">
<label for="message-text" class="col-form-label">Message:</label>
<textarea class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Send message</button>
</div>
</div>
</div>
</div>
site/src/assets/partials/snippets.js
const exampleModal = document.getElementById('exampleModal')
if (exampleModal) {
exampleModal.addEventListener('show.bs.modal', event => {
// Button that triggered the modal
const button = event.relatedTarget
// Extract info from data-bs-* attributes
const recipient = button.getAttribute('data-bs-whatever')
// If necessary, you could initiate an Ajax request here
// and then do the updating in a callback.
// Update the modal's content.
const modalTitle = exampleModal.querySelector('.modal-title')
const modalBodyInput = exampleModal.querySelector('.modal-body input')
modalTitle.textContent = `New message to ${recipient}`
modalBodyInput.value = recipient
})
}
Toggle between modals
Toggle between multiple modals with some clever placement of the data-bs-target and data-bs-toggle attributes. For example, you could toggle a password reset modal from within an already open sign in modal. Please note multiple modals cannot be open at the same time—this method simply toggles between two separate modals.
html
<div class="modal fade" id="exampleModalToggle" aria-hidden="true" aria-labelledby="exampleModalToggleLabel" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalToggleLabel">Modal 1</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Show a second modal and hide this one with the button below.
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-bs-target="#exampleModalToggle2" data-bs-toggle="modal">Open second modal</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel2" tabindex="-1">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalToggleLabel2">Modal 2</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Hide this modal and show the first with the button below.
</div>
<div class="modal-footer">
<button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Back to first</button>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" data-bs-target="#exampleModalToggle" data-bs-toggle="modal">Open first modal</button>
Change animation
The $modal-fade-transform variable determines the transform state of .modal-dialog before the modal fade-in animation, the $modal-show-transform variable determines the transform of .modal-dialog at the end of the modal fade-in animation.
If you want for example a zoom-in animation, you can set $modal-fade-transform: scale(.8).
Remove animation
For modals that simply appear rather than fade in to view, remove the .fade class from your modal markup.
<div class="modal" tabindex="-1" aria-labelledby="..." aria-hidden="true">
...
</div>
Dynamic heights
If the height of a modal changes while it is open, you should call myModal.handleUpdate() to readjust the modal’s position in case a scrollbar appears.
Accessibility
Be sure to add aria-labelledby="...", referencing the modal title, to .modal. Additionally, you may give a description of your modal dialog with aria-describedby on .modal. Note that you don’t need to add role="dialog" since we already add it via JavaScript.
Embedding YouTube videos
Embedding YouTube videos in modals requires additional JavaScript not in Bootstrap to automatically stop playback and more. See this helpful Stack Overflow post for more information.
Optional sizes
Modals have three optional sizes, available via modifier classes to be placed on a .modal-dialog. These sizes kick in at certain breakpoints to avoid horizontal scrollbars on narrower viewports.
Size Class Modal max-width
Small .modal-sm 300px
Default None 500px
Large .modal-lg 800px
Extra large .modal-xl 1140px
Our default modal without modifier class constitutes the “medium” size modal.
<div class="modal-dialog modal-xl">...</div>
<div class="modal-dialog modal-lg">...</div>
<div class="modal-dialog modal-sm">...</div>
Fullscreen Modal
Another override is the option to pop up a modal that covers the user viewport, available via modifier classes that are placed on a .modal-dialog.
Class Availability
.modal-fullscreen Always
.modal-fullscreen-sm-down 576px
.modal-fullscreen-md-down 768px
.modal-fullscreen-lg-down 992px
.modal-fullscreen-xl-down 1200px
.modal-fullscreen-xxl-down 1400px
<!-- Full screen modal -->
<div class="modal-dialog modal-fullscreen-sm-down">
...
</div>
CSS
Variables
Added in v5.2.0
As part of Bootstrap’s evolving CSS variables approach, modals now use local CSS variables on .modal and .modal-backdrop for enhanced real-time customization. Values for the CSS variables are set via Sass, so Sass customization is still supported, too.
scss/_modal.scss
--#{$prefix}modal-zindex: #{$zindex-modal};
--#{$prefix}modal-width: #{$modal-md};
--#{$prefix}modal-padding: #{$modal-inner-padding};
--#{$prefix}modal-margin: #{$modal-dialog-margin};
--#{$prefix}modal-color: #{$modal-content-color};
--#{$prefix}modal-bg: #{$modal-content-bg};
--#{$prefix}modal-border-color: #{$modal-content-border-color};
--#{$prefix}modal-border-width: #{$modal-content-border-width};
--#{$prefix}modal-border-radius: #{$modal-content-border-radius};
--#{$prefix}modal-box-shadow: #{$modal-content-box-shadow-xs};
--#{$prefix}modal-inner-border-radius: #{$modal-content-inner-border-radius};
--#{$prefix}modal-header-padding-x: #{$modal-header-padding-x};
--#{$prefix}modal-header-padding-y: #{$modal-header-padding-y};
--#{$prefix}modal-header-padding: #{$modal-header-padding}; // Todo in v6: Split this padding into x and y
--#{$prefix}modal-header-border-color: #{$modal-header-border-color};
--#{$prefix}modal-header-border-width: #{$modal-header-border-width};
--#{$prefix}modal-title-line-height: #{$modal-title-line-height};
--#{$prefix}modal-footer-gap: #{$modal-footer-margin-between};
--#{$prefix}modal-footer-bg: #{$modal-footer-bg};
--#{$prefix}modal-footer-border-color: #{$modal-footer-border-color};
--#{$prefix}modal-footer-border-width: #{$modal-footer-border-width};
scss/_modal.scss
--#{$prefix}backdrop-zindex: #{$zindex-modal-backdrop};
--#{$prefix}backdrop-bg: #{$modal-backdrop-bg};
--#{$prefix}backdrop-opacity: #{$modal-backdrop-opacity};
Sass variables
scss/_variables.scss
$modal-inner-padding: $spacer;
$modal-footer-margin-between: .5rem;
$modal-dialog-margin: .5rem;
$modal-dialog-margin-y-sm-up: 1.75rem;
$modal-title-line-height: $line-height-base;
$modal-content-color: var(--#{$prefix}body-color);
$modal-content-bg: var(--#{$prefix}body-bg);
$modal-content-border-color: var(--#{$prefix}border-color-translucent);
$modal-content-border-width: var(--#{$prefix}border-width);
$modal-content-border-radius: var(--#{$prefix}border-radius-lg);
$modal-content-inner-border-radius: subtract($modal-content-border-radius, $modal-content-border-width);
$modal-content-box-shadow-xs: var(--#{$prefix}box-shadow-sm);
$modal-content-box-shadow-sm-up: var(--#{$prefix}box-shadow);
$modal-backdrop-bg: $black;
$modal-backdrop-opacity: .5;
$modal-header-border-color: var(--#{$prefix}border-color);
$modal-header-border-width: $modal-content-border-width;
$modal-header-padding-y: $modal-inner-padding;
$modal-header-padding-x: $modal-inner-padding;
$modal-header-padding: $modal-header-padding-y $modal-header-padding-x; // Keep this for backwards compatibility
$modal-footer-bg: null;
$modal-footer-border-color: $modal-header-border-color;
$modal-footer-border-width: $modal-header-border-width;
$modal-sm: 300px;
$modal-md: 500px;
$modal-lg: 800px;
$modal-xl: 1140px;
$modal-fade-transform: translate(0, -50px);
$modal-show-transform: none;
$modal-transition: transform .3s ease-out;
$modal-scale-transform: scale(1.02);
Sass loops
Responsive fullscreen modals are generated via the $breakpoints map and a loop in scss/_modal.scss.
scss/_modal.scss
@each $breakpoint in map-keys($grid-breakpoints) {
$infix: breakpoint-infix($breakpoint, $grid-breakpoints);
$postfix: if($infix != "", $infix + "-down", "");
@include media-breakpoint-down($breakpoint) {
.modal-fullscreen#{$postfix} {
width: 100vw;
max-width: none;
height: 100%;
margin: 0;
.modal-content {
height: 100%;
border: 0;
@include border-radius(0);
}
.modal-header,
.modal-footer {
@include border-radius(0);
}
.modal-body {
overflow-y: auto;
}
}
}
}
Usage
The modal plugin toggles your hidden content on demand, via data attributes or JavaScript. It also overrides default scrolling behavior and generates a .modal-backdrop to provide a click area for dismissing shown modals when clicking outside the modal.
Via data attributes
Toggle
Activate a modal without writing JavaScript. Set data-bs-toggle="modal" on a controller element, like a button, along with a data-bs-target="#foo" or href="#foo" to target a specific modal to toggle.
<button type="button" data-bs-toggle="modal" data-bs-target="#myModal">Launch modal</button>
Dismiss
Dismissal can be achieved with the data-bs-dismiss attribute on a button within the modal as demonstrated below:
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
or on a button outside the modal using the additional data-bs-target as demonstrated below:
<button type="button" class="btn-close" data-bs-dismiss="modal" data-bs-target="#my-modal" aria-label="Close"></button>
While both ways to dismiss a modal are supported, keep in mind that dismissing from outside a modal does not match the ARIA Authoring Practices Guide dialog (modal) pattern. Do this at your own risk.
Via JavaScript
Create a modal with a single line of JavaScript:
const myModal = new bootstrap.Modal(document.getElementById('myModal'), options)
// or
const myModalAlternative = new bootstrap.Modal('#myModal', options)
Options
As options can be passed via data attributes or JavaScript, you can append an option name to data-bs-, as in data-bs-animation="{value}". Make sure to change the case type of the option name from “camelCase” to “kebab-case” when passing the options via data attributes. For example, use data-bs-custom-class="beautifier" instead of data-bs-customClass="beautifier".
As of Bootstrap 5.2.0, all components support an experimental reserved data attribute data-bs-config that can house simple component configuration as a JSON string. When an element has data-bs-config='{"delay":0, "title":123}' and data-bs-title="456" attributes, the final title value will be 456 and the separate data attributes will override values given on data-bs-config. In addition, existing data attributes are able to house JSON values like data-bs-delay='{"show":0,"hide":150}'.
The final configuration object is the merged result of data-bs-config, data-bs-, and js object where the latest given key-value overrides the others.
Name Type Default Description
backdrop boolean, ’static' true Includes a modal-backdrop element. Alternatively, specify static for a backdrop which doesn’t close the modal when clicked.
focus boolean true Puts the focus on the modal when initialized.
keyboard boolean true Closes the modal when escape key is pressed.
Methods
All API methods are asynchronous and start a transition. They return to the caller as soon as the transition is started, but before it ends. In addition, a method call on a transitioning component will be ignored. Learn more in our JavaScript docs.
Passing options
Activates your content as a modal. Accepts an optional options object.
const myModal = new bootstrap.Modal('#myModal', {
keyboard: false
})
Method Description
dispose Destroys an element’s modal. (Removes stored data on the DOM element)
getInstance Static method which allows you to get the modal instance associated with a DOM element.
getOrCreateInstance Static method which allows you to get the modal instance associated with a DOM element, or create a new one in case it wasn’t initialized.
handleUpdate Manually readjust the modal’s position if the height of a modal changes while it is open (i.e. in case a scrollbar appears).
hide Manually hides a modal. Returns to the caller before the modal has actually been hidden (i.e. before the hidden.bs.modal event occurs).
show Manually opens a modal. Returns to the caller before the modal has actually been shown (i.e. before the shown.bs.modal event occurs). Also, you can pass a DOM element as an argument that can be received in the modal events (as the relatedTarget property). (i.e. const modalToggle = document.getElementById('toggleMyModal'); myModal.show(modalToggle).
toggle Manually toggles a modal. Returns to the caller before the modal has actually been shown or hidden (i.e. before the shown.bs.modal or hidden.bs.modal event occurs).
Events
Bootstrap’s modal class exposes a few events for hooking into modal functionality. All modal events are fired at the modal itself (i.e. at the <div class="modal">).
Event Description
hide.bs.modal This event is fired immediately when the hide instance method has been called. Can be prevented by calling event.preventDefault(). See JavaScript events documentation for more details on event prevention.
hidden.bs.modal This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).
hidePrevented.bs.modal This event is fired when the modal is shown, its backdrop is static and a click outside of the modal is performed. The event is also fired when the escape key is pressed and the keyboard option is set to false.
show.bs.modal This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.
shown.bs.modal This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete). If caused by a click, the clicked element is available as the relatedTarget property of the event.
const myModalEl = document.getElementById('myModal')
myModalEl.addEventListener('hidden.bs.modal', event => {
// do something...
})
Passing them inside options (HTML attributes) as backdrop or keyboardwill not work and causes errors because those are not HTML attributes, but JS options.
Passing them as top-level keys in the config array to the Yii widget also causes errors because the widget does not have those properties.
4. However, Bootstrap 5 supports controlling the modal by HTML data attributes with a specific prefix:
If you add data-bs-backdrop="static" and data-bs-keyboard="false" inside options, Bootstrap will read these when it initializes the modal from the HTML automatically. This is basically a Bootstrap 5 feature, independent of Yii.
Example:
php
Modal::begin([
'options' => [
'id' => 'myModal',
'data-bs-backdrop' => 'static',
'data-bs-keyboard' => 'false',
],
// no clientOptions needed in this case
]);
In this case, you can omit clientOptions if you prefer configuring the modal via these data attributes, because Bootstrap 5 supports reading options from them.
5. So which style is better?
Passing client options via the widget’s clientOptions array is the most explicit and integrates well with Yii’s widget system.
Passing Bootstrap options as data-bs-* HTML attributes (within 'options') also works and is sometimes simpler.
But you must use the proper data-bs- prefix, because Bootstrap 5 expects that form.
6. Why does your 'keyboard' => false inside 'options' cause an error?
Because without the data-bs- prefix, 'keyboard' is treated as a raw attribute on the modal <div>and if you attempt to pass 'keyboard' at top-level config to the widget, Yii tries to assign it to the widget property and throws "Unknown property" exception.
7. What should your widget run() method do?
It should accept:
'options' array for HTML attributes (add your classes, ARIA attributes, data-bs-* stuff here)
'clientOptions' array to configure JS options such as backdrop, keyboard, etc.
Your widget should NOT pass keys like 'backdrop', 'keyboard' directly at top-level to Modal::begin() because these are invalid.
Your widget may optionally support automatically moving known client options from $this->options into 'clientOptions' internally for convenience.
If you want me to help refactor your widget's run() method to support this cleanly, just ask!
o
p
er
t
y
i
f
se
t
.
∗
∗−′
size′=>
string∗
ThemodalsizeCSSclass.Overridesthewidget′s
Modal::SIZE_LARGE
Modal::SIZE_SMALL
true
false
'static'
not
true
false
true
false
true
true
'class'
'aria-labelledby'
'data-*'
code
/**
* @var string Default modal title (overridden by $options['title'] if set)
*/
public string $title = 'Modal Title';
/**
* @var string Default modal size (overridden by $options['size'] if set)
* Use Modal::SIZE_DEFAULT, Modal::SIZE_LARGE, Modal::SIZE_SMALL
*/
public string $size = BootstrapModal::SIZE_LARGE;
// This property will hold the instance of the form model passed
public object $formModel;
// Optional property to enforce a specific form model class
public ?string $expectedFormModelClass = null;
// Default modal view
public string $view = '_defaultModal';
// View params
public array $viewParams = [];
// Note: Every protected variable below CacheWidgetTrait is used by the trait
use CacheWidgetTrait;
protected bool $_debugMode = false;
protected bool $_compressJsCss = false;
protected bool $_cacheEnable = false;
protected int $_cacheJsCssTime = 3600;// +1 hour
protected string $_cacheKeyPrefix = 'widget_modalJQry_Data_';
const DEFAULT_DURATION_SECONDS = 3600;// +1 hour
/**
* Initializes the widget.
*
* Note:
* The check for required properties like $formModel must be done here in `init()`
* instead of the constructor because Yii applies the widget configuration (i.e.,
* assigning public properties passed in via the config array) *after* the constructor
* is called but *before* `init()` is invoked.
*/
public function init()
{
/**
* Always call the parent init method first to ensure any
* initialization logic defined in the base class is executed first.
*/
parent::init();
// ... initialization after configuration is applied...
if (!isset($this->formModel))
{
throw new YiiBaseInvalidArgumentException('The "model" property must be set.');
}
if ($this->expectedFormModelClass !== null &&
!($this->formModel instanceof $this->expectedFormModelClass))
{
throw new InvalidArgumentException(
'The "model" property must be an instance of ' . $this->expectedFormModelClass
);
}
// Get cacheDuration from Param and set with TimeHelper
$cacheDuration = ParamHelper::get('widgets.cacheDuration');
$this->_cacheJsCssTime = TimeHelper::convertDurationToSeconds($cacheDuration);
// Cache & Compression
$this->_cacheEnable = ParamHelper::get('widgets.cacheEnable');
$this->_compressJsCss = ParamHelper::get('widgets.compressJsCss');
}
/**
* Runs the widget and renders the modal with the form.
* @return void
*/
public function run(): void
{
// Determine modal ID, or generate a unique ID if not provided
$id = $this->options['id'] ?? $this->getId();
// Determine modal title and size, allowing user to override via $options
$modalTitle = $this->options['title'] ?? $this->title;
$modalSize = $this->options['size'] ?? $this->size;
// Extract 'options' (HTML attributes for modal container) or empty array
$htmlOptions = $this->options['options'] ?? [];
// Prepare default classes to ensure Bootstrap modal styles and smooth
// fade + your custom class 'square'
$defaultClasses = ['modal', 'fade', 'square'];
// Merge with any classes user provided in $htmlOptions['class']
$existingClasses = [];
if (isset($htmlOptions['class']))
{
if (is_array($htmlOptions['class']))
{
$existingClasses = $htmlOptions['class'];
}
elseif (is_string($htmlOptions['class']))
{
$existingClasses = preg_split('/\s+/', trim($htmlOptions['class']));
}
}
$combinedClasses = array_unique(array_merge($defaultClasses, $existingClasses));
$htmlOptions['class'] = implode(' ', $combinedClasses);
// Prepare modal config: include all options from $this->options
// except 'id', 'title', 'size', and 'options' which we handled separately
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Extract all keys from $modalOptions that look like HTML attributes (e.g., aria-*, data-*, or contain dashes),
// and move them into $htmlOptions instead of keeping them at top-level config
foreach ($modalOptions as $key => $value)
{
if (str_starts_with($key, 'aria') || str_starts_with($key, 'data') || strpos($key, '-') !== false)
{
$htmlOptions[$key] = $value;
unset($modalOptions[$key]);
}
}
// Merge with our base configuration
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
// Begin the modal widget
BootstrapModal::begin($config);
/**
* Render the Bootstrap Modal with the Inquiry Form.
*
* The model is accessible via $this->formModel, which eliminates the
* need to pass it repeatedly through different methods.
*/
$params = array_merge(['model' => $this->formModel, 'id' => $id], $this->viewParams);
echo $this->render($this->view, $params);
// End the modal definition.
BootstrapModal::end();
// Register JavaScript for form submission handling.
$this->registerJs($id);
}
}
for my code tho, backdrop and keyboard need to be outside hte options and in their own.. and than should be set in
clientOptions to fit yii2 standards for modal
Why?
'options' key in BootstrapModal is the HTML container attributes (class, aria-*, data-*).
'clientOptions' key is the config object passed to the Bootstrap JS plugin. So putting backdrop and keyboard here is required.
Any unknown keys at top-level in the widget's config cause the Unknown Property error (yii\base\UnknownPropertyException).
With this setup, you can use your widget like this:
php
echo ModalJQry::widget([
'options' => [
'id' => 'myModal',
'title' => 'My Modal Title',
'backdrop' => 'static', // JS modal option, automatically moved to clientOptions
'keyboard' => false, // JS modal option, moved to clientOptions too
'class' => 'custom-class', // HTML attribute included in options
'aria-labelledby' => 'modalLabel', // HTML attribute included
'data-something' => 'value', // HTML data attribute
],
'formModel' => $model,
// other widget options...
]);
Your widget will correctly move backdrop and keyboard into the proper 'clientOptions' key for BootstrapModal.
Summary
Keep backdrop, keyboard and similar Bootstrap plugin options outside the 'options' array.
Your widget should extract those from $this->options and place inside 'clientOptions' before passing to BootstrapModal.
HTML attributes stay in 'options'.
This avoids unknown property exceptions and makes modal options work properly in Yii2 with Bootstrap 5.
If you want, I can prepare a full fixed version of your class' run() method incorporating these improvements. Just ask!
aria-hidden
data-bs-* attributes (these are HTML attributes)
Why is this separation necessary?
The options array corresponds to HTML attribute rendering on the modal container (<div class="modal" ...>).
The clientOptions go into the JavaScript plugin initialization call (new bootstrap.Modal(...)).
Passing JS plugin-specific properties at the wrong level will cause the widget to raise "Unknown property" exceptions.
Summary:
Option name
Where to put it
id
options (because it's an HTML attribute)
class
options
aria-labelledby
options
data-bs-* attributes
options
backdrop
clientOptions
keyboard
clientOptions
focus
clientOptions
show
clientOptions
scrollable
clientOptions
centered
clientOptions
fade
clientOptions
Final note:
You can always check the source code of yii\bootstrap5\Modal::initOptions() to confirm supported options, but generally, all Bootstrap JS modal options go in clientOptions, and everything that's an HTML attribute (including ARIA, CSS classes, and data-bs- attributes) goes in options.
If your widget extracts those keys accordingly, you won't get any unknown property errors and your modal behaves correctly.
If you want, I can help you write the exact array of keys to move to clientOptions in your widget. Just say!
public function run(): void
{
// Determine modal ID, or generate a unique ID if not provided
$id = $this->options['id'] ?? $this->getId();
// Determine modal title and size, allowing user to override via $options
$modalTitle = $this->options['title'] ?? $this->title;
$modalSize = $this->options['size'] ?? $this->size;
// Extract HTML attributes for the modal container (options['options'])
$htmlOptions = $this->options['options'] ?? [];
// Prepare default classes to ensure Bootstrap modal styles and smooth
// fade + your custom class 'square'
$defaultClasses = ['modal', 'fade', 'square'];
// Merge with any classes user provided in $htmlOptions['class']
$existingClasses = [];
if (isset($htmlOptions['class'])) {
if (is_array($htmlOptions['class'])) {
$existingClasses = $htmlOptions['class'];
} elseif (is_string($htmlOptions['class'])) {
$existingClasses = preg_split('/\s+/', trim($htmlOptions['class']));
}
}
$combinedClasses = array_unique(array_merge($defaultClasses, $existingClasses));
$htmlOptions['class'] = implode(' ', $combinedClasses);
// Prepare modal options excluding keys already handled
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Known Bootstrap Modal JS plugin options to be moved to clientOptions
$clientOptionKeys = [
'backdrop', 'keyboard', 'focus', 'show',
'scrollable', 'centered', 'fade',
];
$clientOptions = [];
// Extract clientOptions from modalOptions
foreach ($clientOptionKeys as $key) {
if (array_key_exists($key, $modalOptions)) {
$clientOptions[$key] = $modalOptions[$key];
unset($modalOptions[$key]);
}
}
// Extract any remaining keys in modalOptions which look like HTML attributes (aria-*, data-*, contain dash)
foreach ($modalOptions as $key => $value) {
if (str_starts_with($key, 'aria') || str_starts_with($key, 'data') || strpos($key, '-') !== false) {
// Move them into htmlOptions, as they are HTML attributes
$htmlOptions[$key] = $value;
unset($modalOptions[$key]);
}
}
// Add clientOptions back to modalOptions if any
if (!empty($clientOptions)) {
$modalOptions['clientOptions'] = $clientOptions;
}
// Merge all prepared configs
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
// Begin the modal widget
BootstrapModal::begin($config);
// Render modal content, passing form model and other view params
$params = array_merge(['model' => $this->formModel, 'id' => $id], $this->viewParams);
echo $this->render($this->view, $params);
// End the modal widget
BootstrapModal::end();
// Register any JS needed for your form (your method)
$this->registerJs($id);
}
Summary of changes:
Bootstrap JS options like backdrop, keyboard, etc. are moved to $clientOptions array, which is passed as 'clientOptions' to BootstrapModal::begin().
HTML attributes (e.g., aria-labelledby, data-*, class names) remain in 'options'.
Ensures no unknown property errors and proper Bootstrap modal behavior.
If you'd like, I can help with the full widget file or further improvements!
<?php
namespace app\widgets;
use yii\base\Widget;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\base\InvalidCallException;
use yii\base\InvalidValueException;
use yii\base\Exception as YiiBaseException;
use yii\base\InvalidArgumentException as YiiBaseInvalidArgumentException;
use yii\bootstrap5\Modal as BootstrapModal; // Ensure you import the correct Bootstrap 5 Modal
use Yii;
class ModalJQry extends Widget
{
/**
* @var array Options for modal configuration and container HTML attributes.
* Supported keys include:
*
* - 'id' => string
* The HTML ID attribute for the modal container element.
* If not provided, a unique ID will be generated automatically.
*
* - 'title' => string
* The modal header title text. Overrides the widget's $title property if set.
*
* - 'size' => string
* The modal size CSS class. Overrides the widget's $size property if set.
* Use `Modal::SIZE_LARGE`, `Modal::SIZE_SMALL` or empty string for default size.
*
* - 'backdrop' => bool|string
* Controls the modal backdrop behavior.
* - `true` (default): modal will have a dark backdrop which closes the modal on click.
* - `false`: no backdrop is rendered.
* - `'static'`: backdrop is present but clicking it will *not* close the modal.
*
* - 'keyboard' => bool
* Determines if the modal can be closed via keyboard:
* - `true` (default): pressing the Escape (Esc) key closes the modal.
* - `false`: pressing Escape key will not close the modal.
*
* - 'centered' => bool
* If `true`, the modal dialog is vertically centered within the page.
* If `false` (default), modal appears aligned to top of viewport.
*
* - 'scrollable' => bool
* If `true`, the modal body becomes scrollable and fixed height will be applied if content exceeds viewport.
*
* - 'fade' => bool
* Enables or disables the fade-in and fade-out CSS animation for the modal.
* Default is `true` to enable smooth transition.
*
* - 'options' => array
* HTML attributes for the modal container tag. For example:
* - `'class'` => string|array, additional CSS classes to add to modal container.
* - Any other valid HTML attributes like `'aria-labelledby'`, `'data-*'`.
*
* These options follow the Bootstrap 5 modal plugin configuration and control
* both the visual appearance and behavior of the modal dialog.
*/
public array $options = [];
/**
* @var string Default modal title (overridden by $options['title'] if set)
*/
public string $title = 'Modal Title';
/**
* @var string Default modal size (overridden by $options['size'] if set)
* Use Modal::SIZE_LARGE, Modal::SIZE_SMALL, or empty string for default size
*/
public string $size = BootstrapModal::SIZE_LARGE;
/**
* @var object Holds the model instance to be used in the modal content
*/
public object $formModel;
/**
* @var string|null Optional fully qualified class name to enforce $formModel type
*/
public ?string $expectedFormModelClass = null;
/**
* @var string View file path (relative to widget view path) or alias to render inside modal
*/
public string $view = '_defaultModal';
/**
* @var array Additional parameters for the view
*/
public array $viewParams = [];
// Traits or other protected/private properties as needed
// For example: cache/compression flags, debug modes, etc.
use CacheWidgetTrait;
protected bool $_debugMode = false;
protected bool $_compressJsCss = false;
protected bool $_cacheEnable = false;
protected int $_cacheJsCssTime = 3600; // 1 hour default
protected string $_cacheKeyPrefix = 'widget_modalJQry_Data_';
const DEFAULT_DURATION_SECONDS = 3600;
/**
* Initialize the widget.
*
* @throws YiiBaseInvalidArgumentException
* @throws InvalidArgumentException
*/
public function init()
{
parent::init();
if (!isset($this->formModel)) {
throw new YiiBaseInvalidArgumentException('The "formModel" property must be set.');
}
if ($this->expectedFormModelClass !== null &&
!($this->formModel instanceof $this->expectedFormModelClass)) {
throw new InvalidArgumentException(
'The "formModel" property must be an instance of ' . $this->expectedFormModelClass
);
}
// Example: Load caching/compression config from app params or custom helpers
$cacheDuration = ParamHelper::get('widgets.cacheDuration') ?? self::DEFAULT_DURATION_SECONDS;
$this->_cacheJsCssTime = TimeHelper::convertDurationToSeconds($cacheDuration);
$this->_cacheEnable = ParamHelper::get('widgets.cacheEnable') ?? false;
$this->_compressJsCss = ParamHelper::get('widgets.compressJsCss') ?? false;
}
/**
* Runs the widget to render the modal.
*/
public function run(): void
{
// Determine modal ID, or generate unique one
$id = $this->options['id'] ?? $this->getId();
// Get title and size (override defaults if provided)
$modalTitle = $this->options['title'] ?? $this->title;
$modalSize = $this->options['size'] ?? $this->size;
// Extract HTML attributes for modal container or empty array
$htmlOptions = $this->options['options'] ?? [];
// Prepare default classes for Bootstrap modal and any custom classes
$defaultClasses = ['modal', 'fade', 'square'];
// Merge with user-provided classes inside options['options']['class']
$existingClasses = [];
if (isset($htmlOptions['class'])) {
if (is_array($htmlOptions['class'])) {
$existingClasses = $htmlOptions['class'];
} elseif (is_string($htmlOptions['class'])) {
$existingClasses = preg_split('/\s+/', trim($htmlOptions['class']));
}
}
$combinedClasses = array_unique(array_merge($defaultClasses, $existingClasses));
$htmlOptions['class'] = implode(' ', $combinedClasses);
// Copy $this->options and remove keys that we've handled separately
$modalOptions = $this->options;
unset($modalOptions['id'], $modalOptions['title'], $modalOptions['size'], $modalOptions['options']);
// Known Bootstrap 5 JS modal plugin options
$clientOptionKeys = [
'backdrop', 'keyboard', 'focus', 'show',
'scrollable', 'centered', 'fade',
];
$clientOptions = [];
// Extract client options from modalOptions, remove them after extraction
foreach ($clientOptionKeys as $key) {
if (array_key_exists($key, $modalOptions)) {
$clientOptions[$key] = $modalOptions[$key];
unset($modalOptions[$key]);
}
}
// Move remaining keys that are HTML attributes (aria-*, data-*, contain dash) to $htmlOptions
foreach ($modalOptions as $key => $value) {
if (str_starts_with($key, 'aria') || str_starts_with($key, 'data') || strpos($key, '-') !== false) {
$htmlOptions[$key] = $value;
unset($modalOptions[$key]);
}
}
// Assign clientOptions to modal options if any present
if (!empty($clientOptions)) {
$modalOptions['clientOptions'] = $clientOptions;
}
// Merge the prepared options into the final config
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
// Begin modal widget
BootstrapModal::begin($config);
// Render your modal's internal content (form etc.)
$params = array_merge(['model' => $this->formModel, 'id' => $id], $this->viewParams);
echo $this->render($this->view, $params);
// End modal widget
BootstrapModal::end();
// Register additional JavaScript (your method)
$this->registerJs($id);
}
/**
* Your method for registering JS if needed.
* Implement this as per your requirements.
*/
protected function registerJs(string $id): void
{
// Example JS registration code here
}
}
Explanation
Properties at the top have comprehensive docblocks, including usage notes.
init() validates the required formModel and optionally verifies the model class.
run() does the key work:
Extracts all known JS plugin options (backdrop, keyboard, etc.) into 'clientOptions'.
Collects HTML attributes for the modal container into 'options'.
Ensures default CSS classes like 'modal', 'fade', and your custom 'square' are always included.
Merges all into Yii's BootstrapModal::begin() config and renders the modal.
registerJs() placeholder function you can customize for registering JavaScript.
Let me know if you want me to help integrate caching/compression or provide the corresponding default view _defaultModal.php.
public function run(): void
{
$id = $this->options['id'] ?? $this->getId();
$modalTitle = $this->title;
$modalSize = $this->size;
$htmlOptions = $this->options['options'] ?? [];
// Your existing class merging code for $htmlOptions['class']...
$modalOptions = $this->options;
// Remove handled keys to avoid duplicates/conflicts if you want
unset($modalOptions['id'], $modalOptions['options'], 'title', 'size');
// Extract JS plugin clientOptions and htmlOptions as before...
// Build config
$config = array_merge([
'id' => $id,
'title' => $modalTitle,
'size' => $modalSize,
'options' => $htmlOptions,
], $modalOptions);
BootstrapModal::begin($config);
// render modal content...
BootstrapModal::end();
}
Summary:
Keeping $title and $size as first-class widget properties makes your code usage and API simpler and more explicit. I recommend this — just make sure you don’t also accept them inside $options to avoid ambiguity.
If you'd like, I can help you finalize the full widget code with these conventions!