search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the method of staying on the current page after adding, deleting, modifying and checking in Yii2

Detailed explanation of the method of staying on the current page after adding, deleting, modifying and checking in Yii2

Nov 28, 2017 am 09:20 AM
yii2Add, delete, modify and checkDetailed explanation of method

ImplementationAdd, Delete, Modify and CheckIt will remain on the current page after the operation is successful, which can give the user a good experience. However, the Yii2 framework itself does not have the effect of remaining on the current page after the add, delete, modify, operation is successful. To achieve such an effect, you have to write it yourself. My principle is not to leave the core code alone and always stick to my own principles. Now that I have achieved it, I will share it. Different paths lead to the same goal. If there is a better way to implement Add, Delete, Modify and Check, please feel free to communicate.

Encapsulation code

There are two files ActionColumn.php and Helper.php

1 , ActionColumn.php file

<?php

use 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 = &#39;&#39;;

 public $appendReturnUrl = true; //默认为true,返回当前链接

 public function init()
 {
 parent::init();
 
 $this->defaultButtons = [
  [
  &#39;url&#39; => &#39;view&#39;,
  &#39;icon&#39; => &#39;eye&#39;,
  &#39;class&#39; => &#39;btn btn-success btn-xs&#39;,
  &#39;label&#39; => Yii::t(&#39;yii&#39;, &#39;View&#39;),
  &#39;appendReturnUrl&#39; => false,
  &#39;url_append&#39; => &#39;&#39;,
  &#39;keyParam&#39; => &#39;id&#39;,//是否传id,不传设置null
  ],
  [
  &#39;url&#39; => &#39;update&#39;,
  &#39;icon&#39; => &#39;pencil&#39;,
  &#39;class&#39; => &#39;btn btn-primary btn-xs&#39;,
  &#39;label&#39; => Yii::t(&#39;yii&#39;, &#39;Update&#39;),
  ],
  [
  &#39;url&#39; => &#39;delete&#39;,
  &#39;icon&#39; => &#39;trash-o&#39;,
  &#39;class&#39; => &#39;btn btn-danger btn-xs&#39;,
  &#39;label&#39; => Yii::t(&#39;yii&#39;, &#39;Delete&#39;),
  &#39;options&#39; => [
   &#39;data-action&#39; => &#39;delete&#39;,
  ],
  ]
 ];


 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 = &#39;id&#39;,
 $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 . &#39;/&#39; . $action : $action;
  foreach ($attrs as $attrName) {
  if ($attrName === &#39;model&#39;) {
   $params[&#39;model&#39;] = $model;
  } elseif ($attrName === &#39;mainCategory.category_group_id&#39; && $model->getMainCategory()) {
   $params[&#39;category_group_id&#39;] = $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[&#39;returnUrl&#39;] = 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(&#39;div&#39;, [&#39;class&#39; => &#39;btn-group&#39;, &#39;style&#39; => &#39;min-width: &#39; . $min_width . &#39;px&#39;]);
 foreach ($this->buttons as $button) {
  $appendReturnUrl = ArrayHelper::getValue($button, &#39;appendReturnUrl&#39;, $this->appendReturnUrl);
  $url_append = ArrayHelper::getValue($button, &#39;url_append&#39;, $this->url_append);
  $keyParam = ArrayHelper::getValue($button, &#39;keyParam&#39;, &#39;id&#39;);
  $attrs = ArrayHelper::getValue($button, &#39;attrs&#39;, []);
  Html::addCssClass($button, &#39;btn&#39;);
  Html::addCssClass($button, &#39;btn-sm&#39;);
  $buttonText = isset($button[&#39;text&#39;]) ? &#39; &#39; . $button[&#39;text&#39;] : &#39;&#39;; 
  $data .= Html::a(
   $button[&#39;label&#39;] . $buttonText,
   $url = $this->createUrl(
   $button[&#39;url&#39;],
   $model,
   $key,
   $index,
   $appendReturnUrl,
   $url_append,
   $keyParam,
   $attrs
   ),
   ArrayHelper::merge(
   isset($button[&#39;options&#39;]) ? $button[&#39;options&#39;] : [],
   [
    //&#39;data-pjax&#39; => 0,
    // &#39;data-action&#39; => $button[&#39;url&#39;],
    &#39;class&#39; => $button[&#39;class&#39;],
    &#39;title&#39; => $button[&#39;label&#39;],
   ]
   )
  ) . &#39; &#39;;
 }
 $data .= &#39;</div>&#39;; 
 return $data;
 }

}

2, Helper.php file

<?php

use 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[&#39;query&#39;])) {
  $parts = explode(&#39;&&#39;, $url[&#39;query&#39;]);
  foreach ($parts as $part) {
   $pieces = explode(&#39;=&#39;, $part);
   if (static::$returnUrlWithoutHistory && count($pieces) == 2 && $pieces[0] === &#39;returnUrl&#39;) {
   continue;
   }
   if (count($pieces) == 2 && strlen($pieces[1]) > 0) {
   $returnUrlParams[] = $part;
   }
  }
  }
  if (count($returnUrlParams) > 0) {
  self::$returnUrl = $url[&#39;path&#39;] . &#39;?&#39; . implode(&#39;&&#39;, $returnUrlParams);
  } else {
  self::$returnUrl = $url[&#39;path&#39;];
  }
 }
 return self::$returnUrl;
 }
}

View call

1. Call it directly and replace the ['class' => 'yiigridActionColumn'] that comes with Yii2 with the new one we wrote ['class' => 'common\components\ActionColumn'].

2. If the direct call cannot meet your requirements, you can customize the link. The custom link is written as follows:

[
 &#39;class&#39; => &#39;common\components\ActionColumn&#39;,
 &#39;urlCreator&#39; => function($action, $model, $key, $index) use ($id) {
 //自定义链接传的参数
 $params = [
  $action,
  &#39;option_id&#39; => $model->option_id, 
  &#39;id&#39; => $id,
 ];
 $params[&#39;returnUrl&#39;] = common\components\Helper::getReturnUrl();
 return yii\helpers\Url::toRoute($params);
 },
 &#39;buttons&#39; => [
   [
   &#39;url&#39; =>&#39;view&#39;,
   &#39;class&#39; => &#39;btn btn-success btn-xs&#39;,
   &#39;label&#39; => Yii::t(&#39;yii&#39;, &#39;View&#39;),
   &#39;appendReturnUrl&#39; => false,//是否保留当前URL,默认为true
   &#39;url_append&#39; => &#39;&#39;,
   &#39;keyParam&#39; => &#39;id&#39;, //是否传id,不传设置null
   ],
   [
   &#39;url&#39; => &#39;update&#39;,
   &#39;class&#39; => &#39;btn btn-primary btn-xs btn-sm&#39;,
   &#39;label&#39; => Yii::t(&#39;yii&#39;, &#39;Update&#39;),
   &#39;appendReturnUrl&#39; => true,//是否保留当前URL,默认为true
   &#39;url_append&#39; => &#39;&#39;,
   &#39;keyParam&#39; => &#39;id&#39;, //是否传id,不传设置null
   ],
   [
   &#39;url&#39; => &#39;delete&#39;,
   &#39;class&#39; => &#39;btn btn-danger btn-xs btn-sm&#39;,
   &#39;label&#39; => Yii::t(&#39;yii&#39;, &#39;Delete&#39;),
   &#39;options&#39; => [
   &#39;data-action&#39; => &#39;delete&#39;,
   ],
   &#39;appendReturnUrl&#39; => true,//是否保留当前URL,默认为true
   &#39;url_append&#39; => &#39;&#39;,
   &#39;keyParam&#39; => &#39;id&#39;, //是否传id,不传设置null
   ],
 ],

],

3. If you add a new one, quote it like this:

<?= Html::a(Yii::t(&#39;yii&#39;, &#39;Create&#39;), [&#39;create&#39;,&#39;returnUrl&#39; => Helper::getReturnUrl()], [&#39;class&#39; => &#39;btn btn-success&#39;]) ?> 。

ControllerLogic

1. Use get to get returnUrl, code: $returnUrl = Yii::$ app->request->get('returnUrl'); .

2. The URL to jump to: return $this->redirect($returnUrl);.

Analysis Summary

1. The advantage of this method is that it does not leave the core code, and the calling method retains the Yii2 built-in method.

2. The disadvantage is that when customizing the link, you need to write out each operation update, view, and delete. You cannot use this kind of 'template' => '{view}{ update}{delete}' is simple and comfortable to look at. You can write it according to your needs.

Okay, that’s the entire content of this article. I hope the content of this article can be of some help to everyone’s study or work. If you have any questions, you can leave a message to communicate.

The above is a detailed explanation of the method of leaving the current page after adding, deleting, modifying and checking in Yii2. Welcome to discuss and exchange issues in PHP Chinese Community!

Related recommendations:

Detailed explanation of the registration and creation methods of components in Yii2

How Yii2 uses camel case naming to access controller instances

Implementation code for the QR code generation function of Yii2.0 framework

How to implement the automatic login and login and exit functions of Yii2 framework

The above is the detailed content of Detailed explanation of the method of staying on the current page after adding, deleting, modifying and checking in Yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.