yii2 - urlmanager routing not working - php

Here i have used yii2 configuration with rules
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'rules' => require(__DIR__ . '/routes.php'),
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
And given below routes.php
<?php
use yii\web\UrlRule;
return array(
// REST routes for CRUD operations
'POST <controller:\w+>s' => '<controller>/create', // 'mode' => UrlRule::PARSING_ONLY will be implicit here
'api/<controller:\w+>s' => '<controller>/index',
'PUT api/<controller:\w+>/<id:\d+>' => '<controller>/update',// 'mode' => UrlRule::PARSING_ONLY will be implicit here
'DELETE api/<controller:\w+>/<id:\d+>' => '<controller>/delete', // 'mode' => UrlRule::PARSING_ONLY will be implicit here
'api/<controller:\w+>/<id:\d+>' => '<controller>/view',
// normal routes for CRUD operations
'<controller:\w+>s/create' => '<controller>/create',
'<controller:\w+>/<id:\d+>/<action:update|delete>' => '<controller>/<action>',
);
When i access local2host.com/advanced/backend/web/index.php/country/create - It's working fine
but when i access through local2host.com/advanced/backend/web/index.php/api/country/create
It's throwing 404 - not found error
Unable to resolve the request "api/country/create".
As per my requirement :
when i access this link local2host.com/advanced/backend/web/index.php/api/country/create
it should access "country" as controller and "create" as action

It seems you have modules. First you need to add your api module into your config file:
'modules' => [
'api'
],
Second, you need to add module into your rules like below:
'<module:\w+>/<controller:\w+>/<action:\w+>'=>'<module>/<controller>/<action>',
'<module:\w+><controller:\w+>/<action:update|delete>/<id:\d+>' => '<module>/<controller>/<action>',
This is remarkable that, you may need to take care of other rules with module and have your own customized rules.

Related

yii\rest\UrlRule with "pluralize" rule is not working in Yii2 REST

I am unable to access default endpoints with pluralize option, view action is also not working
Case 1: Access without configure Module
'controllerNamespace' => 'api\controllers',
...
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'country',
'tokens' => [
'{id}' => '<id:\\w+>'
],
/*'pluralize'=>false,*/
],
]
http://localhost/api/web/countries Not working
http://localhost/api/web/country is working fine
http://localhost/api/web/country/1 is Not working
Case 2: Access via module v1
'modules' => [
'v1' => [
'basePath' => '#app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
...
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => ['country' => 'v1/country'],
'tokens' => [
'{id}' => '<id:\\w+>'
],
],
]
'pluralize' is not working completely and when access
v1/country & v1/country/12 both giving same result as index action (country list)
Your rule is incorrect you are missing the module name v1 in your rules
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'tokens' => [
'{id}' => '<id:\\w+>'
],
'extraPatterns' => [
'GET index' => 'index',
],
],
Now you can access it with
http://localhost/api/web/v1/countries
Note : in order to enable the POST request along with GET add it to the extra patterns like 'GET,POST index' => 'index',

yii2 app on online server:Invalid Parameter – yii\base\InvalidParamException The view file does not exist

I uploaded YII2 advanced my web app to online server.
I have 2 tables(companies,employees) and generated CRUD for these 2 tables.In main menu navigation given to view of company.
the below code i given on backend/views/layouts/main.php for navigation.
$menuItems = [
['label' => 'HOME', 'url' => ['/site/index']],
['label' => 'COMPANIES', 'url' => ['/companies/index']]
['label' => 'EMPLOYEES', 'url' => ['/employee/index']],
];
It's worked properly on localhost. But in online getting this exception.
Invalid Parameter – yii\base\InvalidParamException The view file does
not exist:
/home/echosoft/public_html/echosoftware/backend/views/companies/index.php
The file is existing in that folder.Please help me to solve this issue. I am stuck with this for 3 days.
This is backend\config.php codes
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'request' => [
'csrfParam' => '_csrf-backend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the backend
'name' => 'advanced-backend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
This may help.Thanks in advance.
try using
['label' => 'COMPANIES', 'url' => ['/companies/index']]
and if the localhost is windows and online server is unix/linux like be sure you have the proper case in the pathname filename
Windows in case insensitive in pathname unix is case sensitive
If in your backend\views you have the folder name with uppercase (backend\views\Companies) you should change with lower case (backend\views\companies) ..

Yii2 i18n Validation messages not working

I have problem in i18n validations. Let me show what i have done. I have basic application.
In config/web.php
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'fileMap' => [
'yii'=>'yii.php',
'app'=>'app.php',
'app/validation'=>'validation.php',
]
],
],
],
config/i18n.php
return [
'color' => null,
'interactive' => true,
//'sourcePath' => '#yii',
'sourcePath'=> __DIR__. DIRECTORY_SEPARATOR .'..',
'messagePath' => __DIR__ . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR . 'messages',
//'messagePath' => '#yii/messages',
'languages' => ['en','gu','ta','te'],
'translator' => 'Yii::t',
'sort' => false,
'overwrite' => true,
'removeUnused' => false,
'markUnused' => true,
'except' => [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
'/BaseYii.php',
],
'only' => [
'*.php',
],
'format' => 'php',
'db' => 'db',
'sourceMessageTable' => '{{%source_message}}',
'messageTable' => '{{%message}}',
'catalog' => 'messages',
'ignoreCategories' => [],
];
I am not sure about what should be content of validation.php but i write like following.
return [
'Name'=>'பெயர் வெறுமையாக இருக்க முடியாது.',
];
In Biodata.php (model file) rule
['name','required','message'=>Yii::t('app/validation','{attribute} cannot be blank.')],
But still i am getting English validation. I need பெயர் வெறுமையாக இருக்க முடியாது.
I want whole validation in translated language. Thanks
Try this.
In your validation.php file
return [
'{attribute} cannot be blank.'=>'{attribute} வெறுமையாக இருக்க முடியாது.',
];

Yii2 - Getting unknown property: yii\console\Application::user

I am trying to run a console controller from the terminal, but i am getting this errors every time
Error: Getting unknown property: yii\console\Application::user
here is the controller
class TestController extends \yii\console\Controller {
public function actionIndex() {
echo 'this is console action';
} }
and this is the concole config
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'modules' => [],
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params];
I tried running it using these commands with no luck
php yii test/index
php yii test
php ./yii test
can anyone help please?
Console application does not have Yii->$app->user. So, you need to configure user component in config\console.php.
like as,
config\console.php
'components' => [
.........
......
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
],
'session' => [ // for use session in console application
'class' => 'yii\web\Session'
],
.......
]
More info about your problem see this : Link
OR
Visit following link :
Yii2 isGuest giving exception in console application
Note : There's no session in console application.
Set in \console\config\main.php
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'user' => [
'class' => 'yii\web\User',
'identityClass' => 'app\models\Credential',// class that implements IdentityInterface
//'enableAutoLogin' => true,
],
],
'params' => $params,
];
now in your \console\controller\AbcController.php add init method
public function init() {
parent::init();
Yii::$app->user->setIdentity(Credential::findOne(['id'=><cronloginid>]));
}
create a cron login and pass that login id in variable with this config your Blameable Behavior of yii2 will work
As #GAMITG said, you must config user component in config file, but unfortunately, you couldn't access session in console, that's because session is not available in console. Maybe you could solve the problem like this:
$user_id = isset(Yii::$app->user->id) ? Yii::$app->user->id : 0;

Not working Translations with Environments in Yii2

I have set 3 environments.
My app needs to load different sets of translations because each env is different.
I have the RO, HU, DE languages.
I am trying to set the translations, but it does not work.
in frontend/config main.php i have:
'sourceLanguage' => 'en',
'language' => 'en',
in the frontend/web/index.php i have:
defined('YII_ENV') or define('YII_ENV', 'dev_ro');
also, i am merging the config array:
(file_exists(__DIR__ . '/../../environments/' . YII_ENV . '/common/config/main-local.php') ? require(__DIR__ . '/../../environments/' . YII_ENV . '/common/config/main-local.php') : [])
now, in environments/dev_ro/common/config/, in components i have:
'i18n' => [
'translations' => [
'companie' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'sourceLanguage' => 'en',
'fileMap' => [
'companie' => 'companie.php',
],
],
],
],
in the Companie model i have:
'nume' => Yii::t('companie', 'Name'),
this is the movie, with my thing:
movie
The problem is in app*, because it's not app* category, this works:
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'fileMap' => [
'companie' => 'companie.php',
],
],
],
],
Or if you want write 'companie*' =>
If it is still not working, you did set incorrect path to translate files. By default it must be BasePath/messages/LanguageID/CategoryName.php.
If you want to use one file in backend and frontend you should create for example common alias in common config (advanced yii application) and set this alias in i18n config. This is full example:
Common config:
Yii::setAlias('#common', dirname(__DIR__));
return [
'language' => 'ru',
'sourceLanguage' => 'ru',
'components' => [
'i18n' => [
'translations' => [
'*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#common/messages',
'fileMap' => [
'companie' => 'companie.php',
],
....
In traslate file /common/messages/en-US/companie.php
<?php
return [
'string in russian' => 'string in english'
];
Check translate using this code:
\Yii::$app->language = 'en-US';
echo \Yii::t('companie', 'string in russian');
You can also try to replace dash with underscore in language code and folder name:
en-US >> en_US
Works for me.

Categories