Twig not working in Yii2 - php

I want to use Twig in Yii2 framework but it isn't working.
I am using yii2-app-advanced as the base project but I am new in the Yii world so I think I am not configuring Twig in the right way.
First I downloaded it using:
composer require yiisoft/yii2-twig
Then I follow this instructions but it's not easy to understand:
https://github.com/yiisoft/yii2-twig/blob/HEAD/docs/guide/installation.md#configuring-application
It says:
In order to start using Twig you need to configure view component like the following:
[
'components' => [
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => [
'html' => ['class' => '\yii\helpers\Html'],
],
'uses' => ['yii\bootstrap'],
],
// ...
],
],
],
]
In which file I have to paste this code?
In my index.php file I added the following code but it is not working:
{% if true %}
<p>It is true.</p>
{% else %}
<p>It is false.</p>
{% endif %}

I solved it doing this:
I modified the file backend/config/main-local-php:
<?php
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'CPeTotdTU98geIyM7q0PljmCpJbupPN4',
],
'view' => [
'class' => 'yii\web\View',
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'cachePath' => '#runtime/Twig/cache',
// Array of twig options:
'options' => [
'auto_reload' => true,
],
'globals' => [
'html' => ['class' => '\yii\helpers\Html'],
],
'uses' => ['yii\bootstrap'],
],
// ...
],
],
],
];
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',
];
}
return $config;
The SiteController.php file has the actionIndex() function. I added the extension .twig:
public function actionIndex()
{
return $this->render('index.twig');
}
And then I modified the name of the file backend/views/sire/index.php to index.twig.

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;

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;

Yii2 Moving folder mdm-admin of mdmsoft and xml view appeared

I'm using Yii2 to develop my web app. But when I using yii2-admin of mdmsoft with version 3 for prettyURL, I move folder of yii2-admin to modules folder, and change main.php like this:
'bootstrap' => [
'admin'
],
'authManager' => [
'class' => 'yii\rbac\DbManager', // or use 'yii\rbac\DbManager'
],
'modules' => [
'rbac' => [
'class' => 'app\modules\rbac\Module',
'layout' => '#backend/views/layouts/admin',
'controllerMap' => [
'assignment' => [
'class' => 'app\modules\rbac\controllers\AssignmentController',
]
],
]
],
],
'as access' => [
'class' => 'mdm\admin\classes\AccessControl',
'allowActions' => [
'*',
]
],
But when I access mydomain/rbac/assignment or mydomain.com/rbac/route ,... it's just a xml view, nothing more?
How I can fix it?

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