access to subfolders controller and view in YII2 - yii

hi i built a controller in a folder inside controllers folder
i tryed to access my controller and its view but i couldnt always error 404
please tell me what is the problem
here is the details
this is SiteUserController in Controllers/userzone/ folder
namespace app\controllers\userzone;
use yii\web\Controller;
use app\models\UserZone;
/**
* Default controller for the `dashboard` module
*/
class SiteUserController extends Controller
{
/**
* Renders the index view for the module
* #return string
*/
public function actionIndex()
{
$id = \Yii::$app->user->id;
$model = UserZone::find()->where(['id_zone'=>$id])->with('user')->one();
// $model->joinWith('companiesCompany');
return $this->render('siteuser/index',[
'model'=>$model
]);
}
}
the view file is in Views/siteuser/index.php directory .
i changed url manager to
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'userzone/<controller:\w+>/<action:\w+>'=>'userzone/<controller>/<action>',
],
],

In Controller:
return $this->render('index',[
'model'=>$model
]);
Its Working

You need to change you controllerNamespace in config/main file i.e. below code for config/main.php
<?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-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'app\controllers\userzone', //here is your controller path
'components' => [
'view' => [
'theme' => [
'pathMap' => [
'#frontend/views' => '#themes/frontend/views',
],
],
],
'request' => [
'csrfParam' => '_csrf-frontend',
],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];

Related

Not Found Page Working On Backend But Not Working at Frontend Yii2

I have yii installed on my live server we have two interfaces one backend and one frontend. In backend we add products and in front end the view is rendered for the products. The problem is that for example this is our website https://mmstore.be/products/714/IPhone-12-Mini-Scherm-Reparatie product page if you put anything at the last of the url like this https://mmstore.be/products/714/IPhone-12-Mini-Scherm-Reparatie/03003300303094949949494 the page will remain the same means it should be showing not found page but the same page comes again.
Below is my config file code frontend.
<?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-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'request' => [
'csrfParam' => '_csrf-frontend',
],
'cache' => [
'class' => 'yii\caching\FileCache',],
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
// this is the name of the session cookie used for login on the frontend
'name' => 'advanced-frontend',
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'baseUrl' => '',
'enablePrettyUrl' => false,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules'=>array(
'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'class' => 'yii\web\UrlNormalizer',
'collapseSlashes' => true,
'normalizeTrailingSlash' => true,
),
],
],
'params' => $params,
];
i have error.php in my site directory and below is its code
<?php
/* #var $this yii\web\View */
/* #var $name string */
/* #var $message string */
/* #var $exception Exception */
use yii\helpers\Html;
$this->title = $name;
?>
<h1><?= Html::encode($this->title) ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
</div>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
It is strange that you disabled "enablePrettyUrl", and using pretty url. If "/products/" is a controller name and assuming "IPhone-12-Mini-Scherm-Reparatie" is a parameter named "url" then you can change urlManager like this:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'/'=>'site/index',
'/products/<id>/<url>'=>'products/view',
'/products/<id>'=>'products/view',
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
],
],
in controller it should be something like this
public function actionView($id, $url) {
$product = Product::find()->where(['id'=>$id])->one();
// ...
}

Yii2: How to link from backend to frontend when both are in the same domain?

I want to try to make an URL from backend to frontend, I tried to add the following code in backend/config/main.php but it didn't worked.
'urlManagerFrontEnd' => [
'class' => 'yii\web\urlManager',
'baseUrl' => '/',
'enablePrettyUrl' => true,
'showScriptName' => false,
],
Then when I tried this code, it showed "localhost/admin" instead just "localhost" (where the frontend is).
echo Html::a(Yii::t('app', 'test'), [Yii::$app->urlManagerFrontEnd->createUrl(['/'])]);
Just for reference, both frontend/web and backend/web are inside a folder called "public". frontend/web is in the root of public folder while backend/web is inside an admin folder which is inside the public one.
An example of implementation on a project with three subdomains.
Config in common
'urlManagerBackend' => \yii\helpers\ArrayHelper::merge(
[
'hostInfo' => env('BACKEND_HOST_INFO'),
'baseUrl' => env('BACKEND_BASE_URL'),
],
require(Yii::getAlias('#backend/config/_urlManager.php'))
),
'urlManagerFrontend' => \yii\helpers\ArrayHelper::merge(
[
'hostInfo' => env('FRONTEND_HOST_INFO'),
'baseUrl' => env('FRONTEND_BASE_URL'),
],
require(Yii::getAlias('#frontend/config/_urlManager.php'))
),
Env - it is configuration file
FRONTEND_HOST_INFO = http://site.lan
BACKEND_HOST_INFO = http://admin.site.lan
another project, realization - backend - web.php
$config = [
'components' => [
'urlManagerF' => [
'class' => 'yii\web\urlManager',
'baseUrl'=>env('FRONTEND_HOST_INFO'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [],
],
'urlManagerS' => [
'class' => 'yii\web\urlManager',
'baseUrl'=>env('STORAGE_HOST_INFO'),
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [],
],
],
],

in yii2 : why my default language is en

how to change default language from en to another language
$config = [
'on beforeAction' => function ($event)
{
Yii::$app->language = 'fa';
},
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'language' => '/fa',
'components' => [
'jdate' => [
'class' => 'jDate\DateTime'
],
'mycomponent' => [
'class' => 'app\components\MyComponent',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '******',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'urlManager' => [
'class' => 'codemix\localeurls\UrlManager',
// Disable index.php
'languages' => ['fa', 'en'], // List all supported languages here
'showScriptName' => true,
// Disable r= routes
'enablePrettyUrl' => true,
'rules' => array(
// '' => 'site/index/fa',
// '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
// '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
),
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
/*
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
*/
],
'params' => $params,
];
this is my $config in web.php
i want set default to 'fa' in root site !
my site automatic change lang to 'en' in first time in any browser!
i try to change lang with
'on beforeAction' => function ($event)
{
Yii::$app->language = 'fa';
},
but that is dosent correct work!
Remove this ridiculous 'on beforeAction' thing and just set
'language' => 'fa', // NOT '/fa'!
سلام
ویدئو های آقای صیف زاده رو مشاهده کردین؟
لینک زیر آموزش های ویدئویی ایشون هست . در شماره های 17 و 18 و 19
این موضوع رو آموزش دادن.
https://drive.google.com/drive/folders/0B4ZlNlar4Ij6XzJrbVZOejRCcGM

Yii2 - How to implement RBAC Authorization in RESTful API?

HI I just discovered Yii framework and I need some guidelines to implement this...
Yii2 RBAC - Official Guide
...in my RESTful app. I know I have to override the method [checkAccess][3]() in my controllers but I can't found any example. My API has token based Beare autentication and sessions are disabled (stateless).
In your controller:
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
];
// add CORS filter
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
],
];
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options', 'login', 'signup'];
$behaviors['access'] = [
'class' => AccessControl::className(),
'only' => [
'update',
'delete',
'view',
'index',
],
'rules' => [
[
'actions' => [
'update',
'delete',
'view',
'index',
],
'allow' => true,
'roles' => ['#'],
],
],
];
$behaviors['verbFilter'] = [
'class' => VerbFilter::className(),
'actions' => [
'signup' => ['POST'],
'login' => ['POST'],
'update' => ['PUT'],
'delete' => ['DELETE'],
'view' => ['GET'],
'index' => ['GET'],
],
];
return $behaviors;
}

Yii GroupGridView buttons

I use this extension(GroupGridView) in my yii project.
Now, I need help. How to add crud buttons for the grouped elements, to get something like this:
I don't really know is it right sollution.
I've created component GroupButtonColumn:
class GroupButtonColumn extends CButtonColumn {
public $name = 'buttons';
public $value; }
And my view
$this->widget('ext.groupGridView.GroupGridView', array(
'dataProvider' => $model->search(),
'summaryText' => false,
'filter' => $model,
'mergeColumns' => ['t_id', 'buttons'],
'columns' => [
[
'name' => 't_id',
'header' => '№',
'value' => 'CHtml::link($data->t_id, ["/task/view", "id"=>$data->t_id])',
'filter' => false,
'type' => 'raw'
],
/* ... */
[
'class' => 'GroupButtonColumn',
'template' => '{update}, {delete}',
'buttons' => [
'update' => [
'url' => '$this->grid->controller->createUrl("/task/update", array("id"=>$data->t_id))'
],
'delete' => [
'url' => '$this->grid->controller->createUrl("/task/delete", array("id"=>$data->t_id))'
]
]
],
],
));
Try this way:
'mergeColumns' => array('project_id', 'project_id')
/* ... */
'columns' => [
'project_id',
'id',
/* ... */
[
'name' => 'project_id',
'header' => 'Action',
'type'=>'raw',
'value' => function($data){
return 'Start';
}
],