In the backend application of Yii2, the current user can switch roles, hoping to have a role=distributor or role=management in all links. Links in the view implement echo url::toroute(/user/profile); . How to achieve?
1. Now the portal link to switch the role to Distributor is the background homepage:https://console.apply.local/?role=distributor
2. I hope that in this portal URL, all links are automatically added to the request parameter: role=distributor, which is not available now. as shown in Figure 1
3. Create a custom URLManager component Rewrite the CreateUrl method, and automatically attach the current role parameter when the role parameter on the URL is Distributor or Service.
<?php
namespace management\components;
use Yii;
class UrlManager extends \yii\web\UrlManager
{
public function createUrl($params): string
{
$role = Yii::$app->request->get('role', 'management');
if (in_array($role, ['distributor', 'service'])) {
$params['role'] = $role;
}
return parent::createUrl($params);
}
}
4. The configuration application replaces the default UrlManager in the Backend configuration file using a custom URLManager.
'urlManager' => [
'class' => 'management\components\UrlManager',
],
5. In this portal URL, all links automatically add the request parameter: role=distributor. in line with expectations. as shown in Figure 2

6. However, there are several links that should not add the request parameter: role=distributor. It just needs to be cancelled. as shown in Figure 3

7. When generating the link, manually add a flag bit
‘_skip_role’ => true
, and then judge in createUrl()
<?php
namespace management\components;
use Yii;
class UrlManager extends \yii\web\UrlManager
{
public function createUrl($params): string
{
if (!isset($params['_skip_role'])) {
// 仅当 role 为 distributor|service 时,才支持参数 role
$role = Yii::$app->request->get('role', 'management');
if (in_array($role, ['distributor', 'service']) && !isset($params['role'])) {
$params['role'] = $role;
}
} else {
unset($params['_skip_role']); // 清除这个临时参数,避免出现在 URL 中
}
return parent::createUrl($params);
}
}
8. Use in the view as follows, the generated links are as expected. as shown in Figure 4
<div class="col-6 mb-3 text-right">
<a class="btn btn-warning btn-rounded" href="<?php echo Url::toRoute(['/', '_skip_role' => true]); ?>">管理 <?php echo $eventCount['management'];?></a> <!-- / -->
<a class="btn btn-danger btn-rounded" href="<?php echo Url::toRoute(['/', 'role' => 'distributor']); ?>">联络 <?php echo $eventCount['distributor'];?></a> <!-- /?role=distributor -->
<a class="btn btn-purple btn-rounded" href="<?php echo Url::toRoute(['/', 'role' => 'service']); ?>">接待 <?php echo $eventCount['service'];?></a> <!-- /?role=service -->
</div>

