Widget.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\bootstrap;
  8. use Yii;
  9. use yii\helpers\Json;
  10. /**
  11. * \yii\bootstrap\Widget is the base class for all bootstrap widgets.
  12. *
  13. * @author Antonio Ramirez <amigo.cobos@gmail.com>
  14. * @author Qiang Xue <qiang.xue@gmail.com>
  15. * @since 2.0
  16. */
  17. class Widget extends \yii\base\Widget
  18. {
  19. /**
  20. * @var array the HTML attributes for the widget container tag.
  21. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  22. */
  23. public $options = [];
  24. /**
  25. * @var array the options for the underlying Bootstrap JS plugin.
  26. * Please refer to the corresponding Bootstrap plugin Web page for possible options.
  27. * For example, [this page](http://getbootstrap.com/javascript/#modals) shows
  28. * how to use the "Modal" plugin and the supported options (e.g. "remote").
  29. */
  30. public $clientOptions = [];
  31. /**
  32. * @var array the event handlers for the underlying Bootstrap JS plugin.
  33. * Please refer to the corresponding Bootstrap plugin Web page for possible events.
  34. * For example, [this page](http://getbootstrap.com/javascript/#modals) shows
  35. * how to use the "Modal" plugin and the supported events (e.g. "shown").
  36. */
  37. public $clientEvents = [];
  38. /**
  39. * Initializes the widget.
  40. * This method will register the bootstrap asset bundle. If you override this method,
  41. * make sure you call the parent implementation first.
  42. */
  43. public function init()
  44. {
  45. parent::init();
  46. if (!isset($this->options['id'])) {
  47. $this->options['id'] = $this->getId();
  48. }
  49. }
  50. /**
  51. * Registers a specific Bootstrap plugin and the related events
  52. * @param string $name the name of the Bootstrap plugin
  53. */
  54. protected function registerPlugin($name)
  55. {
  56. $view = $this->getView();
  57. BootstrapPluginAsset::register($view);
  58. $id = $this->options['id'];
  59. if ($this->clientOptions !== false) {
  60. $options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions);
  61. $js = "jQuery('#$id').$name($options);";
  62. $view->registerJs($js);
  63. }
  64. if (!empty($this->clientEvents)) {
  65. $js = [];
  66. foreach ($this->clientEvents as $event => $handler) {
  67. $js[] = "jQuery('#$id').on('$event', $handler);";
  68. }
  69. $view->registerJs(implode("\n", $js));
  70. }
  71. }
  72. }