How to access defined URL in Yii2 - php

I have controller UserController and action actionAjax. I access by Chrome with below URL and it is working normally.
index.php?r=user/ajax
Now I define new action with named actionAjaxUser, still using Chrome to access URL index.php?user/ajaxUser
Then 404 returned.
What should I do to getting content of actionAjaxUser?

add for each additional uppercase Letter after "action" a "-" so in your case
index.php?r=user/ajax-user
So if you would have an action like actionTest1Test2Test3 the url would be controllername/test1-test2-test3.
Be aware that if you are using access rules you also have to use the "url" path.
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['test1-test2-test3'],
'allow' => true,
'roles' => ['#'],
],
],
],
];
The same Naming scheme is btw. also used for Controllers. E.g. if your Controller is named Test1Test2Controller the view folder name would be test1-test2.
Hope this clarifies this for you.

Related

translation view for Yii app not found

I set up an i18n page, where I translate messages using yii\i18n\PhpMessageSource with the following config part:
(config/web.php)
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['debug'],
'language' => 'de-DE',
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '#app/messages',
'fileMap' => [
'app' => 'app.php',
],
'forceTranslation' => true,
],
],
]]
...byt the way: this works fine.
For a kind of static content -like an imprint-, I like to use an complete translated view.
So I added some sub-directories in the views - folder, with the view insight:
#app/views/myController/de-DE/myview.php
#app/views/myController/en-US/myview.php
So my action does the following:
public function actionImpressum() {
\Yii::$app->language = 'en-US';
return $this->render('myview');
}
...which results in an invalid parameter
yii\base\InvalidParamException: The view file does not
exist: /path/to/my/app/views/myCtrl/myview.php
This error is valid, because there is no view at this path. But shouldn't the render() method use the path for the translation views, like:
/path/to/my/app/views/myCtrl/en-US/myview.php ??
Is there something I forgot?
Thank you.
Since there is no sourceLanguage set in your configuration I assume you have not changed it and the source language of your app is en-US (default one).
When the source language is the same as target language view is not translated.
See documentation about this:
Note: If the target language is the same as source language original view will be rendered regardless of presence of translated view.
So for en-US it looks for /path/to/my/app/views/myCtrl/myview.php file.

Yii2 RBAC check permissions without each actions in controller

How i can check permissions in one place?
I don't want to check each function individually.
My RBAC controller.
I would like check permission for logged in user for all actions in the controller. Now I have to use Yii::$app->user->can('...') individually for each actions in the controller
$admin = $auth->createRole('Admin');
$moderator = $auth->createRole('Moderator');
$createPost=$auth->createPermission('createPost');
$updatePost=$auth->createPermission('updatePost');
$deletePost=$auth->createPermission('deletePost');
$createCategory=$auth->createPermission('createCategory');
$updateCategory=$auth->createPermission('updateCategory');
$deleteCategory=$auth->createPermission('deleteCategory');
$auth->add($admin);
$auth->add($moderator);
$auth->add($createPost);
$auth->add($updatePost);
$auth->add($deletePost);
$auth->add($createCategory);
$auth->add($updateCategory);
$auth->add($deleteCategory);
Here I assign role with permissions, but i never use these permissions because write manually in behavior->(like your example)
What is goal, create permissons in RBAC, if this not working? If I would like add premium user. I could only add action in controller e.g. actionPremium and set in behavior actions for premium user.
e.g
action=>['premium']
roles=>['premiumUser']
and one more question.
How in behavior customize message error?
$auth->addChild($admin,$moderator);
$auth->addChild($admin,$createCategory);
$auth->addChild($admin,$updateCategory);
$auth->addChild($admin,$deleteCategory);
$auth->addChild($moderator, $createPost);
$auth->addChild($moderator, $updatePost);
$auth->addChild($moderator, $deletePost);
$auth->assign($admin,1);
$auth->assign($moderator,2);
You can assign the permission allowed in controller for all action in behaviors
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index','view'], // these action are accessible
//only the yourRole1 and yourRole2
'allow' => true,
'roles' => ['yourRole1', 'yourRole2'],
],
[ // all the action are accessible to superadmin, admin and manager
'allow' => true,
'roles' => ['superAdmin', 'admin', 'manager'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
The role you assigned in behaviors are for action .. allowd or deny .. the if a role had an allowed action in behaviors then he can execute otherwise he get permission denied 403 .. (not authorized) ..
You can also check the role in procedural code with
if ( Yii::$app->User->can('admin') ){
.....
yourdCode
....
}

Yii2 url rule for module and parameters

I am trying to configure Yii2 url manager in a manner that if a controller name is skipped in url it should call the default controller for action. I have managed to achieve this without action parameter. But got stuck when using parameters in action name.
Here is my route config:
return [
'catalog/category/<alias:[\w-]+>' => 'catalog/default/category',
'catalog/<action:\w+>' => 'catalog/default/<action>',
];
Controller File:
namespace app\modules\catalog\controllers;
use yii\base\Controller;
use app\modules\catalog\models\Categories;
class DefaultController extends Controller
{
public function actionShopbydepartment()
{
$data['categories'] = Categories::findParentSubHierarchy();
return $this->renderPartial('shopbydepartment', $data);
}
public function actionCategory($alias = null)
{
die(var_dump($alias));
$data['category'] = Categories::findCategoryBySlug($alias);
return $this->render('category', $data);
}
}
when I access the following url it loads perfectly.
http://domain.com/index.php/catalog/shopbydepartment
But when i access the below url it called the right function but did not pass the $alias value:
http://domain.com/index.php/catalog/category/appliances
UPDATE:
I have used the following approach for module wise url rules declaration:
https://stackoverflow.com/a/27959286/1232366
Here is what i have in the main config file:
'rules' => [
[
'pattern' => 'admin/<controller:\w+>/<action:[\w-]+>/<id:\d+>',
'route' => 'admin/<controller>/<action>'
],
[
'pattern' => 'admin/<module:\w+>/<controller:\w+>/<action:[\w-]+>/<id:\d+>',
'route' => 'admin/<module>/<controller>/<action>'
],
],
the admin is working fine and this is my first module so rest of the rules are mentioned already
Well just to help other fellows I have retrieve the value of $alias using the following approach:
$alias = \Yii::$app->request->get('alias');
But definitely this is not an accurate answer of the question. I still didn't know what i am doing wrong that i didn't get the value using the approach mentioned in question.
It wirk!
[
'name' => 'lang_country_seller_catalog',
'pattern' => '<lang:\w+>-<country:\w+>/seller/catalog/<module>/<controller>/<action>',
'route' => 'seller/catalog/<module>/<controller>/<action>',
],
[
'name' => 'lang_country_seller_catalog_attributes',
'pattern' => '<lang:\w+>-<country:\w+>/seller/catalog/attributes/<module>',
'route' => 'seller/catalog/attributes/<module>',
],

Url management with Yii2

I have a problem with Yii2's urlManager. I have an action with url category/index, where I pass ?par=test as param.
I want to create an alias for my url so that when par is not specified the url will be /test, but when it is specified the url should be /test/some-value. Here is my config for now:
'rules' => [
[
'pattern' => 'test',
'route' => 'category/index',
],
'<subcats: (val|some-value)>' => 'test/<subcats>',
If you need url like category/index/test/some-value. Use that
'category/index/test/<val:\w+>' => 'category/index'
In controller in method index use that:
public function actionIndex($val){
Yii2 automatically provide parameter $val in action.

Override Yii2 assetManager config in controller

I use yii-jui to add some UI elements in the views such as datePicker. In the frontend\config\main-local.php I set the following to change the theme used by the JqueryUI:
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'gjhgjhghjg87hjh8878878',
],
'assetManager' => [
'bundles' => [
'yii\jui\JuiAsset' => [
'css' =>
['themes/flick/jquery-ui.css'],
],
],
],
],
];
I tried the following to override this configuration item in the controller actions method:
public function actions() {
Yii::$app->components['assetManager'] = [
'bundles' => [
'yii\jui\JuiAsset' => [
'css' =>
['themes/dot-luv/jquery-ui.css'],
],
],
];
return parent::actions();
}
Also I tried to set the value of Yii::$app->components['assetManager'] shown above to the view itself (it is partial view of form _form.php) and to the action that calls this view (updateAction). However, all this trying doesn't be succeeded to change the theme. Is there in Yii2 a method like that found in CakePHP such as Configure::write($key, $value);?
You should modify Yii::$app->assetManager->bundles (Yii::$app->assetManager is an object, not an array), e.g.
Yii::$app->assetManager->bundles = [
'yii\jui\JuiAsset' => [
'css' => ['themes/dot-luv/jquery-ui.css'],
],
];
Or if you want to keep other bundles config :
Yii::$app->assetManager->bundles['yii\jui\JuiAsset'] = [
'css' => ['themes/dot-luv/jquery-ui.css'],
];
You are going about this all wrong, you want to change the JUI theme for 1 controller alone because of a few controls. You are applying 2 css files to different parts of the website that have the potential to change styles in the layouts too. The solution you found works but it is incredibly bad practice.
If you want to change just some controls do it the proper way by using JUI scopes.
Here are some links that will help you:
http://www.filamentgroup.com/lab/using-multiple-jquery-ui-themes-on-a-single-page.html
http://jqueryui.com/download/
In this way you are making the website easier to maintain and you do not create a bigger problem for the future than you what solve.

Categories