I need to change a URL in Yii2 using the URL Manager from
http://www.domain.com/index.php?r=tamil-article/articles&categ=Innovation&id=44
to
http://www.domain.com/44/Innovation.html
How can this be done?
You can resolve this by configuring your UrlManager to use prettyUrls.
After that you can add a custom url rule to the rules array (in config/main.php):
'urlManager' => [
'class' => 'yii\web\UrlManager',
// Disable index.php
'showScriptName' => false,
// Add the .html suffix
'suffix' => '.html',
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => [
'<id:\d+>/<categ:\w+>' => 'tamil-article/articles',
],
],
Related
I have created a blank Yii 2 project that have created a REST UserController for already existing User model:
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'app\models\User';
}
I have modified the model to have all fields safe:
public function rules()
{
return [
['status', 'default', 'value' => self::STATUS_INACTIVE],
['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_INACTIVE, self::STATUS_DELETED]],
[['username', 'email'], 'required'],
[['username', 'email'], 'unique'],
['email', 'email'],
[['password_hash', 'password_reset_token', 'verification_token', 'auth_key', 'status,created_at', 'updated_at', 'password'], 'safe'],
];
}
I have configured URL rules to have both pluralized and non-pluralized paths:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'pluralize' => false,
'except' => ['index'],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'user',
'patterns' => [
'GET,HEAD,OPTIONS' => 'index',
],
],
],
I have enabled JSON input, if that matters:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
All the verbs are processed correctly except for OPTIONS /users:
When I execute OPTIONS /user/20 then I am getting:
200 OK
Empty content
List of allowed methods
But, when I execute OPTIONS users then I am getting 405 Method not Allowed.
What can be wrong or what am I missing?
You are getting 405 Method Not Allowed not because of routing but because of yii\filters\VerbFilter.
The yii\rest\Controller uses verbs() method to set up VerbFilter.
The yii\rest\ActiveController overrides verbs() method and sets VerbFilter to only allow GET and HEAD requests for index action.
It uses options action for OPTIONS method.
If you really want to use index action for OPTIONS method. You have to override verbs() method yourself and add OPTIONS as allowed method for that action. For example like this:
protected function verbs()
{
$verbs = parent::verbs();
$verbs['index'][] = 'OPTIONS';
return $verbs;
}
Or if you want to use options action you have to modify patterns settings as suggested by #Bizley in comments.
I just create a Basic App schema in Yii 2.
I try to test RESTFull api.
The site is working, by default, but when I change the urlManager
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'cliente'],
],
],
I only get 404 error.
I lost site/index!!!
Any idea?
It is this setting:
'enableStrictParsing' => true,
Look here:
https://github.com/yiisoft/yii2/blob/master/framework/web/UrlManager.php#L323
There are no explicit url rules for the siteController defined.
Read more here:
https://www.yiiframework.com/doc/guide/2.0/en/runtime-routing#url-rules
site/index action no longer works because of this setting: 'enableStrictParsing' => true. From $enableStrictParsing documentation:
If strict parsing is enabled, the incoming requested URL must match at least one of the $rules in order to be treated as a valid request. Otherwise, the path info part of the request will be treated as the requested route.
So if you enable this setting, you need to have matching URL rule to support given URL. In your case, you have only one rule for REST endpoint, so any other URL will not work. You should either disable this setting or add rule for your main page:
'rules' => [
'' => 'site/index',
['class' => 'yii\rest\UrlRule', 'controller' => 'cliente'],
],
how can I switch from frontend to backend using links in yii2 application? Actually, I only can set links between frontend or backend, not from frontend to backend.I suppose, I have to change my config-file(main-local.php/urlManager) So, here it is
.
.
.'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => true,
'enableStrictParsing' => true,
'rules' => [
'/' => 'site/login',
'home' => 'site/index',
'reset' => 'site/request-password-reset',
'about' => 'site/about',
'contact' => 'site/contact',
'logout' => 'site/logout',
'signup' => 'site/signup',
'gii' => '/gii',
'debugger' => '/debug',
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<id:\d+>' => '<controller>/save-as-new',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<action:(contact|captcha)>' => 'site/<action>',
],
.
.
.
Create another url manager in frontend and set the baseurl to direct it to backend and add your backend rules if any. And use the created component for creating backend urls
'urlManagerBackend' => [
'baseUrl' => str_replace('/frontend/web', '/backend/web', (new Request)->getBaseUrl()),
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
],
And vice-versa for backend to frontend
*and yes also include this in config
use \yii\web\Request;
I cloned our repositorie and created excatly the same URL-rules like at my own project. Now, i will get error like this after having logged in:
Firefox:
Fehler: Umleitungsfehler
The website called is rerouting request,which never will come to an end.
This problem sometimes occures, if cookies are deactivated
Chrome:
ERR_TOO_MANY_REDIRECTS
I definetly accepted using cookies at both browser!!
Debugging shows me,that I have dozen of 302-Requests,so Yii breaks down!
I use Windows, not LINUX, so I don't care about any permissions.
Here are the rules:
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => true,
'enableStrictParsing' => true,
'rules' => [
'/' => 'site/login',
'home' => 'site/index',
'logout' => 'site/logout',
'contact' => 'site/contact',
'signup' => 'site/signup',
'reset' => 'site/request-password-reset',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<action:(contact|captcha)>' => 'site/<action>'
],
Here is frontend configuration:
<?php
$config = [
// LZA 17-07-30
'sourceLanguage' => 'de-DE',
'language' => 'de-DE',
// LZA 17-07-30 siehe Funktionen in http://demos.krajee.com/grid#module
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '4lD2RxDNkC4ckpwxTmkDzOLIvk0JMs3F',
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// LZA 17-07-30 CRUD
'generators' => [// customized CRUD generator
'crud' => [
// 'class' => 'app\myCrud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'class' => '\common\wsl_dev\wsl_crud\crud\Generator', // LZA 17-07-20 die Klasse von CRUD generator
'templates' => [
'myCrud' => '/#common/wsl_dev/wsl_crud/crud/default', //LZA 17-07-20 Templatename und Templatepfad
]
]
],
// LZA 17-07-30 CRUD
];
}
return $config;
If I deacitvate URLManger,setting
'enablePrettyUrl' => false,
everything works fine.
If I put in manually Url like this:
http://localhost/yii2_perswitch/frontend/web/yiic.php/home
everything works fine,too
Any ideas,how to fix this?
I deleted all my cookies,without any effects!
Solution 1:
Enable debug mode from web/index.php (uncomment these two lines):
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
and you can see exactly what causes the problem.
Redirected too many times error was because the 777 permissions for
runtime and assets folder were not set.
Solution 2:
I think that the problem is related with the path or domain of the cookie. I believe that this info could be useful.
https://github.com/samdark/yii2-cookbook/blob/master/book/cookies.md
How is it possible to extend yii\rest\UrlRule in a way I can rewrite rules for actions of a controller? For example, I want to generate the following URIs:
/user/[username]
/user/keywords
/user/keyword/[key1]/[key2]/[...]
...
Every above actions are rendering their own view too.
You don't need to extend yii\rest\UrlRule. Just add your rules to routes of UrlManager by putting them on extraPatterns property of yii\rest\UrlRule.
For example suppose You defined a list action in your controller:
class BarController extends Controller
{
public $modelClass = 'app\models\Foo';
public function actionList()
{
return ['id' => 1];
}
}
Then in configuration file add extra route:
<?php
// some configs are here
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => [
'v1/bar',
],
'extraPatterns' => [
'GET list' => 'list',
],
],
],
],
// and some other configs are here
Now you can browse the api with /v1/bars/list. Read Yii2 Documentations for more examples.
you must change the extends of Controller in ActiveController
class ArticleController extends ActiveController