Yii2實現增刪改查後留在當前頁的方法詳解

來源:互聯網
上載者:User
實現 增刪改查操作成功後仍留在當前頁,能給使用者一個良好的體驗。但是 Yii2 架構本身是沒有在 增刪改查操作成功後仍留在當前頁的效果的,要實現這樣的一個效果得自己寫。我的原則是不動核心代碼,始終堅持自己的原則,現實現了我把它分享出來。殊途同歸,如有更好的實現 增刪改查的方法,歡迎交流。

封裝代碼

共有兩個檔案ActionColumn.php和Helper.php

1、ActionColumn.php檔案

<?phpuse Closure;use kartik\icons\Icon;use Yii;use yii\grid\Column;use yii\helpers\ArrayHelper;use yii\helpers\Html;use yii\helpers\Url;use common\components\Helper;/**重寫ActionColumn */class ActionColumn extends Column{  public $buttons; private $defaultButtons = []; private $callbackButtons;  public $controller; public $urlCreator; public $url_append = ''; public $appendReturnUrl = true; //預設為true,返回當前連結 public function init() { parent::init();  $this->defaultButtons = [  [  'url' => 'view',  'icon' => 'eye',  'class' => 'btn btn-success btn-xs',  'label' => Yii::t('yii', 'View'),  'appendReturnUrl' => false,  'url_append' => '',  'keyParam' => 'id',//是否傳id,不傳設定null  ],  [  'url' => 'update',  'icon' => 'pencil',  'class' => 'btn btn-primary btn-xs',  'label' => Yii::t('yii', 'Update'),  ],  [  'url' => 'delete',  'icon' => 'trash-o',  'class' => 'btn btn-danger btn-xs',  'label' => Yii::t('yii', 'Delete'),  'options' => [   'data-action' => 'delete',  ],  ] ]; if (null === $this->buttons) {  $this->buttons = $this->defaultButtons; } elseif ($this->buttons instanceof Closure) {  $this->callbackButtons = $this->buttons; } }  public function createUrl( $action, $model, $key, $index, $appendReturnUrl = null, $url_append = null, $keyParam = 'id', $attrs = [] ) { if ($this->urlCreator instanceof Closure) {  return call_user_func($this->urlCreator, $action, $model, $key, $index); } else {  $params = [];  if (is_array($key)) {  $params = $key;  } else {  if (is_null($keyParam) === false) {   $params = [$keyParam => (string)$key];  }  }  $params[0] = $this->controller ? $this->controller . '/' . $action : $action;  foreach ($attrs as $attrName) {  if ($attrName === 'model') {   $params['model'] = $model;  } elseif ($attrName === 'mainCategory.category_group_id' && $model->getMainCategory()) {   $params['category_group_id'] = $model->getMainCategory()->category_group_id;  } else {   $params[$attrName] = $model->getAttribute($attrName);  }  }  if (is_null($appendReturnUrl) === true) {  $appendReturnUrl = $this->appendReturnUrl;  }  if (is_null($url_append) === true) {  $url_append = $this->url_append;  }  if ($appendReturnUrl) {  $params['returnUrl'] = Helper::getReturnUrl();  }  return Url::toRoute($params) . $url_append; } } protected function renderDataCellContent($model, $key, $index) {  if ($this->callbackButtons instanceof Closure) {  $btns = call_user_func($this->callbackButtons, $model, $key, $index, $this);   if (null === $btns) {  $this->buttons = $this->defaultButtons;  } else {  $this->buttons = $btns;  } } $min_width = count($this->buttons) * 34; //34 is button-width $data = Html::beginTag('div', ['class' => 'btn-group', 'style' => 'min-width: ' . $min_width . 'px']); foreach ($this->buttons as $button) {  $appendReturnUrl = ArrayHelper::getValue($button, 'appendReturnUrl', $this->appendReturnUrl);  $url_append = ArrayHelper::getValue($button, 'url_append', $this->url_append);  $keyParam = ArrayHelper::getValue($button, 'keyParam', 'id');  $attrs = ArrayHelper::getValue($button, 'attrs', []);  Html::addCssClass($button, 'btn');  Html::addCssClass($button, 'btn-sm');  $buttonText = isset($button['text']) ? ' ' . $button['text'] : '';   $data .= Html::a(   $button['label'] . $buttonText,   $url = $this->createUrl(   $button['url'],   $model,   $key,   $index,   $appendReturnUrl,   $url_append,   $keyParam,   $attrs   ),   ArrayHelper::merge(   isset($button['options']) ? $button['options'] : [],   [    //'data-pjax' => 0,    // 'data-action' => $button['url'],    'class' => $button['class'],    'title' => $button['label'],   ]   )  ) . ' '; } $data .= '</div>';  return $data; }}

2、Helper.php檔案

<?phpuse Yii;class Helper{  private static $returnUrl; public static $returnUrlWithoutHistory = false; /** * @param int $depth * @return string */ public static function getReturnUrl() { if (is_null(self::$returnUrl)) {  $url = parse_url(Yii::$app->request->url);  $returnUrlParams = [];  if (isset($url['query'])) {  $parts = explode('&', $url['query']);  foreach ($parts as $part) {   $pieces = explode('=', $part);   if (static::$returnUrlWithoutHistory && count($pieces) == 2 && $pieces[0] === 'returnUrl') {   continue;   }   if (count($pieces) == 2 && strlen($pieces[1]) > 0) {   $returnUrlParams[] = $part;   }  }  }  if (count($returnUrlParams) > 0) {  self::$returnUrl = $url['path'] . '?' . implode('&', $returnUrlParams);  } else {  self::$returnUrl = $url['path'];  } } return self::$returnUrl; }}

視圖調用

1、直接調用,把Yii2內建的['class' => 'yiigridActionColumn']換成我們新寫的['class' => 'common\components\ActionColumn'] 。

2、如直接調用不能滿足你的要求可以自訂連結,自訂連結的寫法如下:

[ 'class' => 'common\components\ActionColumn', 'urlCreator' => function($action, $model, $key, $index) use ($id) { //自訂連結傳的參數 $params = [  $action,  'option_id' => $model->option_id,   'id' => $id, ]; $params['returnUrl'] = common\components\Helper::getReturnUrl(); return yii\helpers\Url::toRoute($params); }, 'buttons' => [   [   'url' =>'view',   'class' => 'btn btn-success btn-xs',   'label' => Yii::t('yii', 'View'),   'appendReturnUrl' => false,//是否保留當前URL,預設為true   'url_append' => '',   'keyParam' => 'id', //是否傳id,不傳設定null   ],   [   'url' => 'update',   'class' => 'btn btn-primary btn-xs btn-sm',   'label' => Yii::t('yii', 'Update'),   'appendReturnUrl' => true,//是否保留當前URL,預設為true   'url_append' => '',   'keyParam' => 'id', //是否傳id,不傳設定null   ],   [   'url' => 'delete',   'class' => 'btn btn-danger btn-xs btn-sm',   'label' => Yii::t('yii', 'Delete'),   'options' => [   'data-action' => 'delete',   ],   'appendReturnUrl' => true,//是否保留當前URL,預設為true   'url_append' => '',   'keyParam' => 'id', //是否傳id,不傳設定null   ], ],],

3、新增的話,這麼引用:

<?= Html::a(Yii::t('yii', 'Create'), ['create','returnUrl' => 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}'簡單且看著舒服能根據需求去寫了。

好了,以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.