查看: 630|回复: 0

[PHP学习] Yii2实现增删改查后留在当前页的方法详解

发表于 2017-11-25 09:40:15

前言

实现增删改查操作成功后仍留在当前页,能给用户一个良好的体验。但是 Yii2 框架本身是没有在增删改查操作成功后仍留在当前页的效果的,要实现这样的一个效果得自己写。我的原则是不动核心代码,始终坚持自己的原则,现实现了我把它分享出来。殊途同归,如有更好的实现方法,欢迎交流。

需求分析

一、实现增删改查后操作成功后仍然留在当前页面。

1、链接的效果图


封装代码

共有两个文件ActionColumn.php和Helper.php1、ActionColumn.php文件

  1. <?php
  2. use Closure;
  3. use kartik\icons\Icon;
  4. use Yii;
  5. use yii\grid\Column;
  6. use yii\helpers\ArrayHelper;
  7. use yii\helpers\Html;
  8. use yii\helpers\Url;
  9. use common\components\Helper;
  10. /*
  11. *重写ActionColumn
  12. */
  13. class ActionColumn extends Column
  14. {
  15. public $buttons;
  16. private $defaultButtons = [];
  17. private $callbackButtons;
  18. public $controller;
  19. public $urlCreator;
  20. public $url_append = '';
  21. public $appendReturnUrl = true; //默认为true,返回当前链接
  22. public function init()
  23. {
  24. parent::init();
  25. $this->defaultButtons = [
  26. [
  27. 'url' => 'view',
  28. 'icon' => 'eye',
  29. 'class' => 'btn btn-success btn-xs',
  30. 'label' => Yii::t('yii', 'View'),
  31. 'appendReturnUrl' => false,
  32. 'url_append' => '',
  33. 'keyParam' => 'id',//是否传id,不传设置null
  34. ],
  35. [
  36. 'url' => 'update',
  37. 'icon' => 'pencil',
  38. 'class' => 'btn btn-primary btn-xs',
  39. 'label' => Yii::t('yii', 'Update'),
  40. ],
  41. [
  42. 'url' => 'delete',
  43. 'icon' => 'trash-o',
  44. 'class' => 'btn btn-danger btn-xs',
  45. 'label' => Yii::t('yii', 'Delete'),
  46. 'options' => [
  47. 'data-action' => 'delete',
  48. ],
  49. ]
  50. ];
  51. if (null === $this->buttons) {
  52. $this->buttons = $this->defaultButtons;
  53. } elseif ($this->buttons instanceof Closure) {
  54. $this->callbackButtons = $this->buttons;
  55. }
  56. }
  57. public function createUrl(
  58. $action,
  59. $model,
  60. $key,
  61. $index,
  62. $appendReturnUrl = null,
  63. $url_append = null,
  64. $keyParam = 'id',
  65. $attrs = []
  66. ) {
  67. if ($this->urlCreator instanceof Closure) {
  68. return call_user_func($this->urlCreator, $action, $model, $key, $index);
  69. } else {
  70. $params = [];
  71. if (is_array($key)) {
  72. $params = $key;
  73. } else {
  74. if (is_null($keyParam) === false) {
  75. $params = [$keyParam => (string)$key];
  76. }
  77. }
  78. $params[0] = $this->controller ? $this->controller . '/' . $action : $action;
  79. foreach ($attrs as $attrName) {
  80. if ($attrName === 'model') {
  81. $params['model'] = $model;
  82. } elseif ($attrName === 'mainCategory.category_group_id' && $model->getMainCategory()) {
  83. $params['category_group_id'] = $model->getMainCategory()->category_group_id;
  84. } else {
  85. $params[$attrName] = $model->getAttribute($attrName);
  86. }
  87. }
  88. if (is_null($appendReturnUrl) === true) {
  89. $appendReturnUrl = $this->appendReturnUrl;
  90. }
  91. if (is_null($url_append) === true) {
  92. $url_append = $this->url_append;
  93. }
  94. if ($appendReturnUrl) {
  95. $params['returnUrl'] = Helper::getReturnUrl();
  96. }
  97. return Url::toRoute($params) . $url_append;
  98. }
  99. }
  100. protected function renderDataCellContent($model, $key, $index)
  101. {
  102. if ($this->callbackButtons instanceof Closure) {
  103. $btns = call_user_func($this->callbackButtons, $model, $key, $index, $this);
  104. if (null === $btns) {
  105. $this->buttons = $this->defaultButtons;
  106. } else {
  107. $this->buttons = $btns;
  108. }
  109. }
  110. $min_width = count($this->buttons) * 34; //34 is button-width
  111. $data = Html::beginTag('div', ['class' => 'btn-group', 'style' => 'min-width: ' . $min_width . 'px']);
  112. foreach ($this->buttons as $button) {
  113. $appendReturnUrl = ArrayHelper::getValue($button, 'appendReturnUrl', $this->appendReturnUrl);
  114. $url_append = ArrayHelper::getValue($button, 'url_append', $this->url_append);
  115. $keyParam = ArrayHelper::getValue($button, 'keyParam', 'id');
  116. $attrs = ArrayHelper::getValue($button, 'attrs', []);
  117. Html::addCssClass($button, 'btn');
  118. Html::addCssClass($button, 'btn-sm');
  119. $buttonText = isset($button['text']) ? ' ' . $button['text'] : '';
  120. $data .= Html::a(
  121. $button['label'] . $buttonText,
  122. $url = $this->createUrl(
  123. $button['url'],
  124. $model,
  125. $key,
  126. $index,
  127. $appendReturnUrl,
  128. $url_append,
  129. $keyParam,
  130. $attrs
  131. ),
  132. ArrayHelper::merge(
  133. isset($button['options']) ? $button['options'] : [],
  134. [
  135. //'data-pjax' => 0,
  136. // 'data-action' => $button['url'],
  137. 'class' => $button['class'],
  138. 'title' => $button['label'],
  139. ]
  140. )
  141. ) . ' ';
  142. }
  143. $data .= '</div>';
  144. return $data;
  145. }
  146. }
复制代码

2、Helper.php文件

  1. <?php
  2. use Yii;
  3. class Helper
  4. {
  5. private static $returnUrl;
  6. public static $returnUrlWithoutHistory = false;
  7. /**
  8. * @param int $depth
  9. * @return string
  10. */
  11. public static function getReturnUrl()
  12. {
  13. if (is_null(self::$returnUrl)) {
  14. $url = parse_url(Yii::$app->request->url);
  15. $returnUrlParams = [];
  16. if (isset($url['query'])) {
  17. $parts = explode('&', $url['query']);
  18. foreach ($parts as $part) {
  19. $pieces = explode('=', $part);
  20. if (static::$returnUrlWithoutHistory && count($pieces) == 2 && $pieces[0] === 'returnUrl') {
  21. continue;
  22. }
  23. if (count($pieces) == 2 && strlen($pieces[1]) > 0) {
  24. $returnUrlParams[] = $part;
  25. }
  26. }
  27. }
  28. if (count($returnUrlParams) > 0) {
  29. self::$returnUrl = $url['path'] . '?' . implode('&', $returnUrlParams);
  30. } else {
  31. self::$returnUrl = $url['path'];
  32. }
  33. }
  34. return self::$returnUrl;
  35. }
  36. }
复制代码

视图调用

1、直接调用,把Yii2自带的['class' => 'yiigridActionColumn']换成我们新写的['class' => 'common\components\ActionColumn'] 。

2、如直接调用不能满足你的要求可以自定义链接,自定义链接的写法如下:

  1. [
  2. 'class' => 'common\components\ActionColumn',
  3. 'urlCreator' => function($action, $model, $key, $index) use ($id) {
  4. //自定义链接传的参数
  5. $params = [
  6. $action,
  7. 'option_id' => $model->option_id,
  8. 'id' => $id,
  9. ];
  10. $params['returnUrl'] = common\components\Helper::getReturnUrl();
  11. return yii\helpers\Url::toRoute($params);
  12. },
  13. 'buttons' => [
  14. [
  15. 'url' =>'view',
  16. 'class' => 'btn btn-success btn-xs',
  17. 'label' => Yii::t('yii', 'View'),
  18. 'appendReturnUrl' => false,//是否保留当前URL,默认为true
  19. 'url_append' => '',
  20. 'keyParam' => 'id', //是否传id,不传设置null
  21. ],
  22. [
  23. 'url' => 'update',
  24. 'class' => 'btn btn-primary btn-xs btn-sm',
  25. 'label' => Yii::t('yii', 'Update'),
  26. 'appendReturnUrl' => true,//是否保留当前URL,默认为true
  27. 'url_append' => '',
  28. 'keyParam' => 'id', //是否传id,不传设置null
  29. ],
  30. [
  31. 'url' => 'delete',
  32. 'class' => 'btn btn-danger btn-xs btn-sm',
  33. 'label' => Yii::t('yii', 'Delete'),
  34. 'options' => [
  35. 'data-action' => 'delete',
  36. ],
  37. 'appendReturnUrl' => true,//是否保留当前URL,默认为true
  38. 'url_append' => '',
  39. 'keyParam' => 'id', //是否传id,不传设置null
  40. ],
  41. ],
  42. ],
复制代码

3、新增的话,这么引用 Helper::getReturnUrl()], ['class' => 'btn btn-success']) ?> 。

控制器逻辑

1、用get获取returnUrl,代码:$returnUrl = Yii:app->request->get('returnUrl'); 。

2、跳转到的URL:return $this->redirect($returnUrl); 。

分析总结

1、此方法的好处是不动核心代码,调用方式保留了Yii2自带的方式。

2、不足之处是在自定义链接的时候需要把每一个操作update、view、delete都写出来,不能用这种'template' => '{view}{update}{delete}'简单且看着舒服能根据需求去写了。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条