How to set prefix to all keys of url rules? - php

I want to set prefix for all keys of urlManager rules. At the moment I write rules like that:
'rules' => [
'api' => '_public/site/index',
'api/<controller>/<action>' => '_public/<controller>/<action>',
etc
]
I want to avoid copy/past-ing of api prefix to all rules. Because it could be 500 rules.
Is there a way to define somewhere a prefix in order to Yii placed it for every rule key itself?
$prefix and $prefixRoute is setting up prefix for values, but I want for keys.
Maybe this can be done by using .htaccess? But I don't know what should I write there.

The yii\web\GroupUrlRule and its $prefix property is exactly what you are looking for.
In your case:
rules => [
// ...
new \yii\web\GroupUrlRule([
'prefix' => 'api',
'rules' => [
'<controller>/<action>' => '_public/<controller>/<action>',
// ... other /api/_ routes
],
]),
// ... other rules
]
I'm not sure if adding rule like this '/' => '_public/site/index', into the group would work for /api route or if you would have to set that one explicitly outside of group rule. If you are going to set rule for /api outside of group rule it might be better to put it before the group rule.

The GroupUrlRule with properties: prefix, routePrefix and rules will be enough. You can use it as follows:
new GroupUrlRule([
'prefix' => 'api',
'routePrefix' => '',
'rules' => [
'' => '_public/site/index',
'<controller>/<action>' => '_public/<controller>/<action>',
]
])
Add this to the rules under urlManager in the main config file.

I added a line to config file:
$config = [
'components' => [
'request' => [
// some code
'baseUrl' => '/api', // <--- this line
],
]
]
and it worked.
$baseUrl - The relative URL for the application. https://www.yiiframework.com/doc/api/2.0/yii-web-request#$baseUrl-detail

Related

yii2 assetBundle - all absolute links instead of relative

I am trying to figure out, how can I configure AssetBundle via /config/main.php in Yii2 . The reason is, that we need to use globally absolute links for all assets (CSS + JS bundles) instead of relative.
We have set absolute #web alias:
Yii::setAlias('#webabs', empty($_SERVER['SERVER_NAME']) ? '/' : '//'.$_SERVER['SERVER_NAME']);
So the only thing we need to change is the property baseUrl in class \yii\web\AssetBundle:
baseUrl = '#webabs'
Following did not work for me:
'assetBundle' => [
'baseUrl' => '#webabs',
],
because "assetBundle" is not core component.
'yii\web\AssetBundle' => [
'class' => 'yii\web\AssetBundle',
'baseUrl' => '#webabs',
],
because Object configurator will not configure property.
So is there any way to configure "baseUrl" property globally in "\yii\web\AssetBundle"?
Thank you.
Try in configuration:
// ...
'components' => [
// ...
'assetManager' => [
'baseUrl' => '#webabs/assets'
],
],

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.

How to access defined URL in Yii2

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.

Is it posible to create a urlManager Rule which preloads an object based on ID?

Working with Yii 2.0.4, I'm trying to use urlManager Rule to preload an object based on a given ID in the URL.
config/web.php
'components' => [
'urlManager' => [
[
'pattern' => 'view/<id:\d+>',
'route' => 'site/view',
'defaults' => ['client' => Client::findOne($id)],
],
[
'pattern' => 'update/<id:\d+>',
'route' => 'site/update',
'defaults' => ['client' => Client::findOne($id)],
],
]
]
If this works, it will not be necessary to manually find and object each time, for some CRUD actions:
class SiteController extends Controller {
public function actionView() {
// Using the $client from the urlManager Rule
// Instead of using $client = Client::findOne($id);
return $this->render('view', ['client' => $client]);
}
public function actionUpdate() {
// Using $client from urlManager Rule
// Instead of using $client = Client::findOne($id);
if ($client->load(Yii::$app->request->post()) && $client->save()) {
return $this->redirect(['view', 'id' => $client->id]);
} else {
return $this->render('edit', ['client' => $client]);
}
}
}
NOTE: The above snippets are not working. They're the idea of what I want to get
Is it possible? Is there any way to achieve this?
If you look closer: nothing actually changes. You still call Client::findOne($id); but now doing it in an unexpected and inappropriate place, and if you look at the comment about default parameter it says:
array the default GET parameters (name => value) that this rule provides.
When this rule is used to parse the incoming request, the values declared in this property will be injected into $_GET.
default parameter is needed when you want to specify some $_GET parameters for your rule. E.g.
[
'pattern' => '/',
'route' => 'article/view',
'defaults' => ['id' => 1],
]
Here we specify article with id = 1 as default article when you open main page of site e.g. http://example.com/ will be handled as http://example.com/article/view?id=1
I can suggest to you add property clientModel in to your controller and then in beforeAction() method check if its update or view action then set
$this->clientModel = Client::findOne($id);
and in your action:
return $this->render('view', ['client' => $this->clientModel]);

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