Is there a way to convert "+" to "-" in URL Yii2? - php

I am trying to change the paramlinks to include the name of a post in my yii2 application.
example.com/item/hello+world
to
example.com/item/hello-world
These are the rules of in my urlmanager in frontend/config/main.php
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => false,
'rules' => [
'/' => 'site/index',
'item/<title:[A-Za-z0-9 -_.]+>' => 'item/view',
],
]

$hi = 'example.com/item/hello+world';
$hi = str_replace('+', '-', $hi);
echo $hi;
like this you can replace what you need replacing with str_replace
output:
example.com/item/hello-world
The output url you displayed is put in a variable, then i fill in what I want replaced +, what should overwrite it is the - sign and then store it again in a variable called $hi again.

Your problem is the Url::toRoute method. By default, it will replace empty spaces by a "+". And there is no configuration to change that (at least I did not find).
You could use a str_replace like #baboizk mentioned, or, if you want to cover any accents, symbols, etc. You can use BaseInflector::slug. Example:
Url::toRoute(['item/view', 'title' => BaseInflector::slug($model->title)]);
But i'm still not sure how your actionItem works, because it probably needs to search the model by it's title and you are changing it.

Related

URL not accepting alpha numeric parameter - Yii2-app-basic

As soon, i'm passing 41 in URL. confirm.php prints 41.
http://localhost/yii2-app-basic/web/site/confirm/41
But, when i pass "cfeb70c4c627167ee56d6e09b591a3ee" or "41a" in URL,
http://localhost/yii2-app-basic/web/site/confirm/41a
it shows error
NOT FOUND (#404)
Page not found.
The above error occurred while the Web server was processing your request. Please contact us if you think
this is a server error. Thank you.
I want to send confirmation id to user to confirm their account.
That's why random number "cfeb70c4c627167ee56d6e09b591a3ee" is being passed.
So, what can i do to make URL accept alpha numeric parameter.
config/web.php
'urlManager' => [
'showScriptName' => false,
'enablePrettyUrl' => true,
'enableStrictParsing' => false,
'rules' => [
'<controller>/<action>/<id:\d+>' => '<controller>/<action>'
],
],
SiteController.php
public function actionConfirm($id)
{
$id = Yii::$app->request->get('id');
$this->view->params['customParam'] = $id;
return $this->render("confirm",array("id"=>$id));
}
Change this line
'<controller>/<action>/<id:\d+>' => '<controller>/<action>'
to this
'<controller>/<action>/<id:[a-z0-9]+>' => '<controller>/<action>'
That should do it
The current rule states that id is a number(\d+) hence it not working in your examples. Instead of modifying the current rule, I would add one specifically for this case:
'rules' => [
'site/confirm/<id:\w+>' => 'site/confirm',
'<controller>/<action>/<id:\d+>' => '<controller>/<action>'
],

Yii routing - how to put that controller

I need to perform routing for the following url schemas:
website.com/some-category-name
website.com/some-category-name/entryName
some-category-name will be variable - some name of category
How to configure routing for this? I need to enter previous controllers, for example:
website.com/account
website.com/regiter
and want to everything that does not have controller name (so will be category name) going to controller Category.
I can't work it out.
use
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'rules' => array(
'categoryName/<categoryName:\w+>' => array('site/category'),
'register' => array('site/register'),
'account' => array('site/account')
),
),
At first you must declare all rules for "non Category" actions, and after that dynamic rules (associated with category and antry):
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false,
'rules' => array(
// for example if your account and register actions in user controller
// ... you can write
'account' => 'user/account',
'register' => 'user/register',
// or with one rule
'<action(account|register)>' => 'user/<action>',
// and for all other 'static actions', such as login, logout ...
// after yhat you can declire dynamic rules
'<categoryName:\w+>' => 'category/index',
'<categoryName:\w+>/<entryName:\w+>' => 'category/entry'
),
),
So the code Yii::app()->createUrl('user/register') will generate url website.com/register, and accordingly the url website.com/register "goes to" register action of user controller (all other static rules like this way).
Now dynamic rules: code
Yii::app()->createUrl('category/index', array(
'categoryName' => 'first-category-name'
))
will generate url website.com/first-category-name, and vice versa: the url website.com/first-category-name "goes to" category/index action and in it will be available $_GET['categoryName'] parameter, which will be equal to "second-category-name"․
Accordingly code
Yii::app()->createUrl('category/index', array(
'categoryName' => 'some-category-name',
'entryName' => 'some-entry-name'
))
will generate url website.com/some-category-name/some-entry-name, and in category/entry action you can get $_GET['categoryName'] equal to "some-category-name" and $_GET['entryName'] equal to some-entry-name.
I hope this help you to understand how works rules in Yii.
Thanks!

Allowing only clean URLs in Yii

I have configured the CUrlManager in the config/main.php to use clean URL:
'urlManager' => array(
'showScriptName' => FALSE,
'urlFormat' => 'path',
'rules' => require(dirname(__FILE__) . '/routes.php'),
),
The clean URL function works perfectly, but I would like to prevent the default <controller>/<action> pattern match to occur.
This is my config/route.php:
<?php
return array(
'books' => 'book/index'
);
Now people can go to the same book page by 2 different URLs:
http://www.mysite.com/books
http://www.mysite.com/book/index
I want to disable the second URL pattern. Is this possible?
You can enable useStrictParsing in your url manager component.

Yii routes and creation of URLs with multiple parameters

I would like to get the URL as follow:
http://domain.com/post/1/some-titles-here
But I'm getting:
http://domain.com/post/1?title=some-titles-here
I am using this config:
'urlFormat' => 'path',
...
//'post/<id:\d+>/<title>' => 'post/view/',
'post/<id:\d+>/<title:\w+>' => 'post/view/',
'post/<id:\d+>' => 'post/view/',
...
Then to get the URL I am executing:
Yii::app()->createAbsoluteUrl('post/view', array('id' => $this->id,'title' => $this->title));
im following the third rule here:
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#using-named-parameters
The regular expression you're using to match the title is incorrect: <title:\w+> will only match single words but your title has hyphens as well.
Tuan is correct; it's matching the next rule. That's because the URL manager works its way down the rules until it finds one that matches.
Use this rule instead:
'post/<id:\d+>/<title:([A-Za-z0-9-]+)>' => 'post/view/',
That will match titles with letters, numbers, and hyphens.
This is a code that work for me:
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName' => false,
'rules'=>array(
'' => 'site/index',
'article/<id:\d+>/<alias:[-\w]+>' => 'article/view',
'article/cat/<id:\d+>-<alias:[-\w]+>' => 'category/view',
Result urls:
http://wowjp.black.dragon/article/2/test-zagolovka
http://wowjp.black.dragon/article/cat/3-345435

CakePHP custom route w/ %20 in url want to replace w/ "-" not sure how to make this happen in the route

My link:
echo $link->link($planDetailsByCompany['PlanDetail']['name'],
array('controller' => 'plan_details', 'action' => 'view_benefit_schedule',
'id' => $planDetailsByCompany['PlanDetail']['id'],
'slug' => $planDetailsByCompany['PlanDetail']['name']));
My custom route:
Router::connect('/pd/:id-:slug',
array('controller' => 'plan_details', 'action' => 'view_benefit_schedule'),
array('pass' => array('id', 'slug'),
'id' => '[0-9]+'));
My url is displaying like so:
..pd/44-Primary%20Indemnity
I cannot determine how to remove the %20 and replace it with a "-". There is a space in the company name that is causing this. Is this possible within the CakePHP router functionality? If so, how? Or another method.
Geeze.. I just solved this!
In my link above, replace the 'slug' line with:
...'slug' => Inflector::slug($planDetailsByCompany['PlanDetail']['name'])...
The Inflector handles the spaces in the url. And my result url is:
...pd/44-Primary_Indemnity

Categories