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

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;

Related

Yii2: Rest POST Request Parameters not arriving

Good morning,
I dont get any further in this Topic so i am writing a Question here.
First of all i created a DB Table with Data from the Tutorial: https://www.yiiframework.com/doc/guide/2.0/en/start-databases
Then i created a Rest Controller from that Tutorial with the Data above: https://www.yiiframework.com/doc/guide/2.0/en/rest-quick-start
The first example GET Request from the Tutorial works fine and gives me all of the data from the DB.
My Request URL: http://XX.X.X.12:XX90/country/
Now we come to my Error when trying to create a new Country in the DB via a POST Request.
When using the CURL Command from underneath the Tutorial with my Test-Data i get following error:
SQLSTATE[HY000]: General error: 1364 Field 'code' doesn't have a default value**strong text**
(
[0] => HY000
[1] => 1364
[2] => Field 'code' doesn't have a default value
)
My standard logging from rest api says that the POST Var is empty, but why?
I also tested sending POST Request via a Tool (Postman) but i get the same error.
$_GET = []
$_POST = []
$_FILES = []
$_COOKIE = []
$_SERVER = [....]
My Model:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
}
My Controller:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class CountryController extends ActiveController
{
public $modelClass = 'app\models\Country';
}
My CURL Request:
curl -i -H "Accept:application/json" -H "Content-Type:application/json" \
-XPOST "http://XX.X.X.12:XX90/countries/" \
-d '{"code": "TEST", "name": "TestCountry", "population": 01}'
My web.php Config:
<?php
$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'#bower' => '#vendor/bower-asset',
'#npm' => '#vendor/npm-asset',
],
'name' => 'Yii2-ExtJS Rest API',
'modules' => [
'user' => [
'class' => Da\User\Module::class,
// ...other configs from here: [Configuration Options](installation/configuration-options.md), e.g.
'administrators' => ['admin'], // this is required for accessing administrative actions
// 'generatePasswords' => true,
// 'switchIdentitySessionKey' => 'myown_usuario_admin_user_key',
],
'debug' => [
'class' => 'yii\debug\Module',
'allowedIPs' => ['XX.X.X.XXX', 'XX.XXX.XXX.XXX', '127.0.0.1', '::1']
],
],
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'XXXXXXXXXXXXXXXX',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => \yii\symfonymailer\Mailer::class,
'viewPath' => '#app/mail',
// send all mails to a file by default.
'useFileTransport' => true,
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
// 'levels' => ['error', 'warning', 'trace', 'info'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => 'country'],
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
'allowedIPs' => ['XX.X.X.XX', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
Suggestions?
You need to declare validation rules for working with the Rest API
Thanks to #Bizley
My Country Model now:
<?php
namespace app\models;
use yii\db\ActiveRecord;
class Country extends ActiveRecord
{
public function rules()
{
return [
[['code', 'name', 'population'], 'required']
];
}
}

Yii Console Script, Login to User [duplicate]

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;

can't view backend user admin pages using Yii2-usuario

I'm using Yii2-usuario for my user module.
I ran the migrations found in "first step" under the section "Creating the first Administrator during a migration", and only changed from new \Da\User\Model\User() to new \app\models\user\Model\User() like this
$user = new \app\models\user\Model\User([
'scenario' => 'create',
'email' => "admin#admin.com",
'firstname' => 'first',
'lastname' => 'last',
'password' => "verysecret" // >6 characters!
]);
it populated my tables correctly. But when i login to backend and try to view https://localhost/bla/backend/web/user/admin/index, i get a 403 forbidden error
in my backend main.php i have this
'components' => [
....
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
'defaultRoles' => ['guest'],
],
],
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'enableEmailConfirmation' => true,
'enableRegistration' => false,
'maxPasswordAge' => 90,
'enableGdprCompliance' => false,
'classMap' => [
'User' => 'app\models\user\Model\User',
],
'viewPath' => '#app/views/user',
'controllerMap' => [
//disable for backend
'profile' => [
'class' => Da\User\Controller\ProfileController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'recovery' => [
'class' => Da\User\Controller\RecoveryController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Registration' => [
'class' => Da\User\Controller\RegistrationController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'Settings' => [
'class' => Da\User\Controller\SettingsController::class,
'as access' => [
'class' => yii\filters\AccessControl::class,
'rules' => [['allow' => false]],
],
],
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
],
],
my User model in backend\models\user\Model looks like this
use Da\User\Model\User as BaseUser;
class User extends BaseUser
{
public static function tableName()
{
return '{{%admin}}';
}
...
...
..
}
the list of RBAC and admin action don't work. i get a 403.
any idea what I'm missing here or did wrong? Thanks.
In the link which was provided for the first step with migration code, next is written
After installing the extension and having configured everything, you
need setup your application with the all the user related stuff, e.g.
You need to run this migration only after you did all installation steps mentioned here. But still it won't work because default user table will be populated, which was created from initial migration. This package creates its own user table and moreover in installation steps there is a Note
Note: If you are using Yii2's Advanced Application Template, before
starting to work with database, please ensure you have deleted
m130524_201442_init.php migration file which comes from the default
installation. It's located at
%PROJECT_DIR%/console/migrations/m130524_201442_init.php path.
Step 1
In your case i would do yii migrate/down 2, which will revert last 2 migrations(init migration contain user table description). Only in case if you didn't add more migrations :)
Total 2 migrations to be reverted:
m190124_110200_add_verification_token_column_to_user_table
m130524_201442_init
In case migration fail, you can run few SQL queries
drop table user;
delete from migration where version='m130524_201442_init';
and then delete m130524_201442_init.php and m190124_110200_add_verification_token_column_to_user_table.php(second one is optional but its your call) files
Step 2
After that according to docs, you need to run rbac + Yii 2 Usuario migrations all together as stated in this note
Note: You will still have to apply Yii 2 RBAC migrations by executing
./yii migrate --migrationPath=#yii/rbac/migrations. Remember that you
have to configure the AuthManager component first. Also, namespaced
migrations were introduced in Yii 2.0.10, so before using them
consider updating your framework installation version. If you are
using a Yii 2 version prior to 2.0.10, you'll have to copy the
migrations located on vendor/2amigos/yii2-usuario/src/User/Migration,
remove its namespaces and add it to your #app/migrations folder.
But before that, you need to move code below from backend/config/main.php to %PROJECT_DIR%/console/config/main.php
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationNamespaces' => [
'Da\User\Migration',
],
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations',
],
],
]
and add authManager into console config for rbac also
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
in final your console/config/main.php should be similar to this
return [
// ....
'controllerMap' => [
// ...
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations', // Just in case you forgot to run it on console (see next note)
],
'migrationNamespaces' => [
'Da\User\Migration',
],
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ...
],
// ...
];
Step 3
Run the migration from note
./yii migrate --migrationPath=#yii/rbac/migrations
Total 13 new migrations to be applied:
Da\User\Migration\m000000_000001_create_user_table
Da\User\Migration\m000000_000002_create_profile_table
Da\User\Migration\m000000_000003_create_social_account_table
Da\User\Migration\m000000_000004_create_token_table
Da\User\Migration\m000000_000005_add_last_login_at
Da\User\Migration\m000000_000006_add_two_factor_fields
Da\User\Migration\m000000_000007_enable_password_expiration
Da\User\Migration\m000000_000008_add_last_login_ip
Da\User\Migration\m000000_000009_add_gdpr_consent_fields
m140506_102106_rbac_init
m170907_052038_rbac_add_index_on_auth_assignment_user_id
m180523_151638_rbac_updates_indexes_without_prefix
m200409_110543_rbac_update_mssql_trigger
Step 4
Create and run migration from first steps without changing model in example.
Step 5
Remove user config from both backend/config/main.php and frontend/config/main.php
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
],
Apply authManager and user module with proper administrators option to respective config files. This array should contain same role name as in migration which you did in step 4.
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
In the final your frontend and backend config files should be similar to this
return [
// ...
'modules' => [
'user' => [
'class' => Da\User\Module::class,
'administrators' => ['admin']
],
],
'components' => [
'authManager' => [
'class' => 'Da\User\Component\AuthDbManagerComponent',
],
// ....
]
// ...
];
Step 6
My favorite step :)
http://yourapp/index.php?r=user/admin visit and enter your creds from migration. Enjoy!

yii2 adding extra language

I tried many times to add extra language for yii2 basic template and I have been failing in all them, let me show you all my codes and could you please help me to fix my error, actually the site does not say any error, everything is working smoothly but the language is not being switched to another
-----config/web.php----
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
return [
// set target language to be Russian
'language' => 'ru-RU',
// set source language to be English
'sourceLanguage' => 'en-US',
];
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
//'basePath' => '#app/messages',
//'sourceLanguage' => 'en-US',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'qwdqdq',
],
messages/ru-RU/app.php
<?php
return [
'welcome' => 'Добро пожаловать',
'log in' => 'Войти',
'This is a string to translate!' => 'Это строка для перевода'
//...
];
----------siteController.php-------
Class SiteController extends Controller
{
public function actionChangeLang($local)
{
$available_locales = [
'ru-RU',
'en-US'
];
if (!in_array($local, $available_locales)) {
throw new \yii\web\BadRequestHttpException();
}
\Yii::$app->language = $local;
retur
n $this->goBack();
}
view file----- site/index.php
In your config/web.php add 'on beforeAction' like fallowing
return [
'id' => 'basic',
// set target language to be Russian
'language' => 'ru-RU',
// set source language to be English
'sourceLanguage' => 'en-US',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
...
],
'params' => [
...
],
'on beforeAction' => function(){
// get language from cookie, session or db
// and set it to app language
Yii::$app->language = isset($_COOKIE['language'])?$_COOKIE['language']:Yii::$app->language;
}
];
In your SiteControler function actionChangeLang replace line
\Yii::$app->language = $local;
with
setcookie("language", $local);
Now you will be able to change your locale and keep it between requests.
In my example I used cookies but you also may use any type of storage to store your locale.

Yii2 Console Controller Errors

I created a console controller named beanstalk, this is my first time using the console controllers, am trying to run it from the terminal and i got these errors
Error: Getting unknown property: yii\console\Application::user
Error: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/apc.so'...
The Controller
class BeanstalkController extends \yii\console\Controller {
public function actionIndex() {
echo 'test console controller';
} }
and i am calling it using
php yii beanstalk
i also tried other actions names with no luck
here is my console 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,
];
can anyone help?

Categories