Commit cc3209cf by Qiang Xue

Fixes #4502: Added alias support to URL route when calling `Url::toRoute()` and `Url::to()`

parent 83c494e7
......@@ -10,14 +10,13 @@ of Html helper which provides a set of static methods for handling commonly used
with Html helper calls.
Basics <a name="basics"></a>
----------------------------
## Basics <a name="basics"></a>
Since building dynamic HTML by string concatenation is getting messy very fast, Yii provides a set of methods to
manipulate tag options and build tags based on these options.
### Generating tags
### Generating Tags <a name="generating-tags"></a>
The code generating a tag looks like the following:
......@@ -51,7 +50,8 @@ know about:
`'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` becomes
`data-params='{"id":1,"name":"yii"}' data-status="ok"`.
### Forming class and style dynamically
### Forming CSS Classes and Styles <a name="forming-css"></a>
When building options for HTML tag we're often starting with defaults which we need to modify. In order to add or
remove CSS class you can use the following:
......@@ -89,8 +89,7 @@ could be converted there and forth by using [[yii\helpers\Html::cssStyleFromArra
method accepts an array of properties to remove. If it's going to be a single property it could be specified as string.
Encoding and decoding content <a name="encoding-and-decoding-content"></a>
--------------------------------------------------------------------------
### Encoding and Decoding Content <a name="encoding-and-decoding-content"></a>
In order for content to be displayed properly and securely in HTML special characters in the content should be encoded.
In PHP it's done with [htmlspecialchars](http://www.php.net/manual/en/function.htmlspecialchars.php) and
......@@ -107,8 +106,7 @@ $decodedUserName = Html::decode($userName);
```
Forms
-----
## Forms <a name="forms"></a>
Dealing with forms markup is quite repetitive and error prone. Because of that there is a group of methods to help
dealing with them.
......@@ -116,7 +114,7 @@ dealing with them.
> Note: consider using [[yii\widgets\ActiveForm|ActiveForm]] in case you deal with models and need validation.
### Open and close a form
### Creating Forms <a name="creating-forms"></a>
Form could be opened with [[yii\helpers\Html::beginForm()|beginForm()]] method like the following:
......@@ -136,7 +134,7 @@ Closing form tag is simple:
```
### Buttons
### Buttons <a name="buttons"></a>
In order to generate buttons you can use the following code:
......@@ -150,7 +148,7 @@ First argument for all three methods is button title and the second one is optio
getting data from end user, encode it with [[yii\helpers\Html::encode()|Html::encode()]].
### Inputs
### Input Fields <a name="input-fields"></a>
There are two groups on input methods. The ones starting with `active` and called active inputs and the ones not starting
with it. Active inputs are taking data from model and attribute specified while in case of regular input data is specified
......@@ -215,7 +213,7 @@ If not, use radio list:
```
### Labels and errors
### Labels and Errors <a name="labels-and-errors"></a>
Same as inputs there are two methods for generating form labels. Active that's taking data from the model and non-active
that accepts data directly:
......@@ -238,7 +236,7 @@ To display individual error:
```
### Names and values
### Input Names and Values <a name="input-names-and-values"></a>
There are methods to get names, ids and values for input fields based on the model. These are mainly used internally
but could be handy sometimes:
......@@ -273,8 +271,7 @@ echo Html::getAttributeName('dates[0]');
```
Styles and scripts
------------------
## Styles and Scripts <a name="styles-and-scripts"></a>
There two methods to generate tags wrapping embedded styles and scripts:
......@@ -322,8 +319,7 @@ Same as with CSS first argument specifies link to the file to be included. Optio
In options you can specify `condition` in the same way as in options for `cssFile`.
Links
-----
## Hyperlinks <a name="hyperlinks"></a>
There's a method to generate hyperlink conveniently:
......@@ -342,8 +338,7 @@ In you need to generate `mailto` link you can use the following code:
```
Images
------
## Images <a name="images"></a>
In order to generate image tag use the following:
......@@ -359,8 +354,7 @@ Aside [aliases](concept-aliases.md) the first argument can accept routes, parame
[Url::to()](helper-url.md) does.
Lists
-----
## Lists <a name="lists"></a>
Unordered list could be generated like the following:
......
......@@ -4,11 +4,10 @@ Url Helper
Url helper provides a set of static methods for managing URLs.
Getting common URLs
-------------------
## Getting Common URLs <a name="getting-common-urls"></a>
There are two methods you can use to get common URLs: home URL and base URL of the current request. In order to get
home URL use the follwing:
home URL use the following:
```php
$relativeHomeUrl = Url::home();
......@@ -29,8 +28,8 @@ $httpsAbsoluteBaseUrl = Url::base('https');
The only parameter of the method works exactly the same as for `Url::home()`.
Creating URLs
-------------
## Creating URLs <a name="creating-urls"></a>
In order to create URL to a given route use `Url::toRoute()` method. The method uses [[\yii\web\UrlManager]] to create
a URL:
......@@ -62,6 +61,10 @@ route has none (e.g. `site/index` or `index`). A relative route will be converte
and will be prepended with [[\yii\web\Controller::uniqueId]];
- If the route has no leading slash (e.g. `site/index`), it is considered to be a route relative to the current module
and will be prepended with the module's [[\yii\base\Module::uniqueId|uniqueId]].
Starting from version 2.0.2, you may specify a route in terms of an [alias](concept-aliases.md). If this is the case,
the alias will first be converted into the actual route which will then be turned into an absolute route according
to the above rules.
Below are some examples of using this method:
......@@ -72,6 +75,9 @@ echo Url::toRoute('site/index');
// /index?r=site/index&src=ref1#name
echo Url::toRoute(['site/index', 'src' => 'ref1', '#' => 'name']);
// /index?r=post/edit&id=100 assume the alias "@postEdit" is defined as "post/edit"
echo Url::toRoute(['@postEdit', 'id' => 100]);
// http://www.example.com/index.php?r=site/index
echo Url::toRoute('site/index', true);
......@@ -105,6 +111,9 @@ echo Url::to(['site/index']);
// /index?r=site/index&src=ref1#name
echo Url::to(['site/index', 'src' => 'ref1', '#' => 'name']);
// /index?r=post/edit&id=100 assume the alias "@postEdit" is defined as "post/edit"
echo Url::to(['@postEdit', 'id' => 100]);
// the currently requested URL
echo Url::to();
......@@ -121,8 +130,7 @@ echo Url::to('@web/images/logo.gif', true);
echo Url::to('@web/images/logo.gif', 'https');
```
Remember URL for future use
---------------------------
## Remember URLs <a name="remember-urls"></a>
There are cases when you need to remember URL and afterwards use it during processing of the one of sequential requests.
It can be achieved in the following way:
......@@ -145,8 +153,7 @@ $url = Url::previous();
$productUrl = Url::previous('product');
```
Finding out if URL is relative
------------------------------
## Checking Relative URLs <a name="checking-relative-urls"></a>
To find out if URL is relative i.e. it doesn't have host info part, you can use the following code:
......
......@@ -9,6 +9,7 @@ Yii Framework 2 Change Log
- Bug #6557: Link URLs generated by `yii\widgets\Menu` are not encoded (qiangxue)
- Bug #6632: `yii\di\Container::get()` did not handle config parameter correctly when it is passed as a constructor parameter (qiangxue)
- Bug #6648: Added explicit type casting to avoid dblib issues on SQL Server 2014 (o-rey)
- Enh #4502: Added alias support to URL route when calling `Url::toRoute()` and `Url::to()` (qiangxue, lynicidn)
- Enh #6247: Logger and error handler are now using slightly less memory (stepanselyuk, samdark)
- Enh #6434: Added `yii\behaviors\SluggableBehavior::immutable` to support keeping the generated slug unchanged (trntv)
- Enh #6467: `ActiveForm` will scroll to the nearest visible element when the first error input is hidden (newartix)
......
......@@ -103,13 +103,16 @@ class BaseUrl
* - If the route has no leading slash, it is considered to be a route relative
* to the current module and will be prepended with the module's uniqueId.
*
* Starting from version 2.0.2, a route can also be specified as an alias. In this case, the alias
* will be converted into the actual route first before conducting the above transformation steps.
*
* @param string $route the route. This can be either an absolute route or a relative route.
* @return string normalized route suitable for UrlManager
* @throws InvalidParamException a relative route is given while there is no active controller
*/
protected static function normalizeRoute($route)
{
$route = (string) $route;
$route = Yii::getAlias((string) $route);
if (strncmp($route, '/', 1) === 0) {
// absolute route
return ltrim($route, '/');
......
......@@ -82,6 +82,11 @@ class UrlTest extends TestCase
$this->assertEquals('http://example.com/base/index.php?r=stats%2Fuser%2Fview&id=42', Url::toRoute(['user/view', 'id' => 42], true));
$this->assertEquals('https://example.com/base/index.php?r=stats%2Fuser%2Fview&id=42', Url::toRoute(['user/view', 'id' => 42], 'https'));
// alias support
\Yii::setAlias('@userView', 'user/view');
$this->assertEquals('/base/index.php?r=stats%2Fuser%2Fview', Url::toRoute('@userView'));
\Yii::setAlias('@userView', null);
// In case there is no controller, an exception should be thrown for relative route
$this->removeMockedAction();
......@@ -98,6 +103,11 @@ class UrlTest extends TestCase
$this->assertEquals('/base/index.php?r=page%2Fedit', Url::to(['edit']));
$this->assertEquals('/base/index.php?r=page%2Fview', Url::to(['']));
// alias support
\Yii::setAlias('@pageEdit', 'edit');
$this->assertEquals('/base/index.php?r=page%2Fedit&id=20', Url::to(['@pageEdit', 'id' => 20]));
\Yii::setAlias('@pageEdit', null);
$this->assertEquals('http://example.com/base/index.php?r=page%2Fedit&id=20', Url::to(['edit', 'id' => 20], true));
$this->assertEquals('http://example.com/base/index.php?r=page%2Fedit', Url::to(['edit'], true));
$this->assertEquals('http://example.com/base/index.php?r=page%2Fview', Url::to([''], true));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment