212 lines
7.7KB

  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\widgets;
  8. use Yii;
  9. use yii\base\Widget;
  10. use yii\helpers\ArrayHelper;
  11. use yii\helpers\Html;
  12. use yii\helpers\Json;
  13. use yii\web\Response;
  14. /**
  15. * Pjax is a widget integrating the [pjax](https://github.com/yiisoft/jquery-pjax) jQuery plugin.
  16. *
  17. * Pjax only deals with the content enclosed between its [[begin()]] and [[end()]] calls, called the *body content* of the widget.
  18. * By default, any link click or form submission (for those forms with `data-pjax` attribute) within the body content
  19. * will trigger an AJAX request. In responding to the AJAX request, Pjax will send the updated body content (based
  20. * on the AJAX request) to the client which will replace the old content with the new one. The browser's URL will then
  21. * be updated using pushState. The whole process requires no reloading of the layout or resources (js, css).
  22. *
  23. * You may configure [[linkSelector]] to specify which links should trigger pjax, and configure [[formSelector]]
  24. * to specify which form submission may trigger pjax.
  25. *
  26. * You may disable pjax for a specific link inside the container by adding `data-pjax="0"` attribute to this link.
  27. *
  28. * The following example shows how to use Pjax with the [[\yii\grid\GridView]] widget so that the grid pagination,
  29. * sorting and filtering can be done via pjax:
  30. *
  31. * ```php
  32. * use yii\widgets\Pjax;
  33. *
  34. * Pjax::begin();
  35. * echo GridView::widget([...]);
  36. * Pjax::end();
  37. * ```
  38. *
  39. * @author Qiang Xue <qiang.xue@gmail.com>
  40. * @since 2.0
  41. */
  42. class Pjax extends Widget
  43. {
  44. /**
  45. * @var array the HTML attributes for the widget container tag. The following special options are recognized:
  46. *
  47. * - `tag`: string, the tag name for the container. Defaults to `div`
  48. * This option is available since version 2.0.7.
  49. * See also [[\yii\helpers\Html::tag()]].
  50. *
  51. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  52. */
  53. public $options = [];
  54. /**
  55. * @var string|false the jQuery selector of the links that should trigger pjax requests.
  56. * If not set, all links within the enclosed content of Pjax will trigger pjax requests.
  57. * If set to false, no code will be registered to handle links.
  58. * Note that if the response to the pjax request is a full page, a normal request will be sent again.
  59. */
  60. public $linkSelector;
  61. /**
  62. * @var string|false the jQuery selector of the forms whose submissions should trigger pjax requests.
  63. * If not set, all forms with `data-pjax` attribute within the enclosed content of Pjax will trigger pjax requests.
  64. * If set to false, no code will be registered to handle forms.
  65. * Note that if the response to the pjax request is a full page, a normal request will be sent again.
  66. */
  67. public $formSelector;
  68. /**
  69. * @var string The jQuery event that will trigger form handler. Defaults to "submit".
  70. * @since 2.0.9
  71. */
  72. public $submitEvent = 'submit';
  73. /**
  74. * @var boolean whether to enable push state.
  75. */
  76. public $enablePushState = true;
  77. /**
  78. * @var boolean whether to enable replace state.
  79. */
  80. public $enableReplaceState = false;
  81. /**
  82. * @var integer pjax timeout setting (in milliseconds). This timeout is used when making AJAX requests.
  83. * Use a bigger number if your server is slow. If the server does not respond within the timeout,
  84. * a full page load will be triggered.
  85. */
  86. public $timeout = 1000;
  87. /**
  88. * @var boolean|integer how to scroll the page when pjax response is received. If false, no page scroll will be made.
  89. * Use a number if you want to scroll to a particular place.
  90. */
  91. public $scrollTo = false;
  92. /**
  93. * @var array additional options to be passed to the pjax JS plugin. Please refer to the
  94. * [pjax project page](https://github.com/yiisoft/jquery-pjax) for available options.
  95. */
  96. public $clientOptions;
  97. /**
  98. * @inheritdoc
  99. */
  100. public function init()
  101. {
  102. if (!isset($this->options['id'])) {
  103. $this->options['id'] = $this->getId();
  104. }
  105. if ($this->requiresPjax()) {
  106. ob_start();
  107. ob_implicit_flush(false);
  108. $view = $this->getView();
  109. $view->clear();
  110. $view->beginPage();
  111. $view->head();
  112. $view->beginBody();
  113. if ($view->title !== null) {
  114. echo Html::tag('title', Html::encode($view->title));
  115. }
  116. } else {
  117. $options = $this->options;
  118. $tag = ArrayHelper::remove($options, 'tag', 'div');
  119. echo Html::beginTag($tag, array_merge([
  120. 'data-pjax-container' => '',
  121. 'data-pjax-push-state' => $this->enablePushState,
  122. 'data-pjax-replace-state' => $this->enableReplaceState,
  123. 'data-pjax-timeout' => $this->timeout,
  124. 'data-pjax-scrollto' => $this->scrollTo,
  125. ], $options));
  126. }
  127. }
  128. /**
  129. * @inheritdoc
  130. */
  131. public function run()
  132. {
  133. if (!$this->requiresPjax()) {
  134. echo Html::endTag(ArrayHelper::remove($this->options, 'tag', 'div'));
  135. $this->registerClientScript();
  136. return;
  137. }
  138. $view = $this->getView();
  139. $view->endBody();
  140. // Do not re-send css files as it may override the css files that were loaded after them.
  141. // This is a temporary fix for https://github.com/yiisoft/yii2/issues/2310
  142. // It should be removed once pjax supports loading only missing css files
  143. $view->cssFiles = null;
  144. $view->endPage(true);
  145. $content = ob_get_clean();
  146. // only need the content enclosed within this widget
  147. $response = Yii::$app->getResponse();
  148. $response->clearOutputBuffers();
  149. $response->setStatusCode(200);
  150. $response->format = Response::FORMAT_HTML;
  151. $response->content = $content;
  152. $response->send();
  153. Yii::$app->end();
  154. }
  155. /**
  156. * @return boolean whether the current request requires pjax response from this widget
  157. */
  158. protected function requiresPjax()
  159. {
  160. $headers = Yii::$app->getRequest()->getHeaders();
  161. return $headers->get('X-Pjax') && explode(' ', $headers->get('X-Pjax-Container'))[0] === '#' . $this->options['id'];
  162. }
  163. /**
  164. * Registers the needed JavaScript.
  165. */
  166. public function registerClientScript()
  167. {
  168. $id = $this->options['id'];
  169. $this->clientOptions['push'] = $this->enablePushState;
  170. $this->clientOptions['replace'] = $this->enableReplaceState;
  171. $this->clientOptions['timeout'] = $this->timeout;
  172. $this->clientOptions['scrollTo'] = $this->scrollTo;
  173. if (!isset($this->clientOptions['container'])) {
  174. $this->clientOptions['container'] = "#$id";
  175. }
  176. $options = Json::htmlEncode($this->clientOptions);
  177. $js = '';
  178. if ($this->linkSelector !== false) {
  179. $linkSelector = Json::htmlEncode($this->linkSelector !== null ? $this->linkSelector : '#' . $id . ' a');
  180. $js .= "jQuery(document).pjax($linkSelector, $options);";
  181. }
  182. if ($this->formSelector !== false) {
  183. $formSelector = Json::htmlEncode($this->formSelector !== null ? $this->formSelector : '#' . $id . ' form[data-pjax]');
  184. $submitEvent = Json::htmlEncode($this->submitEvent);
  185. $js .= "\njQuery(document).on($submitEvent, $formSelector, function (event) {jQuery.pjax.submit(event, $options);});";
  186. }
  187. $view = $this->getView();
  188. PjaxAsset::register($view);
  189. if ($js !== '') {
  190. $view->registerJs($js);
  191. }
  192. }
  193. }