HighND.com

Just another blog?

Yii Reference 1 – Create Url, Links and Redirections

This post will be a reference on how deal with urls, links and browser redirects in Yii Framework. It will guide you on how to use different built-in functions in Yii like createUrl(), createAbsoluteUrl(), CHtml::link(), redirect().

Create URL

$url = Yii::app()->createUrl('site/index');


Result: index.php?r=site/index
You will obtain this format of URL if you’re not using the URL Manager to make your links more user-friendly.

$url = Yii::app()->createUrl('site/index', array('id'=>100));

Result: index.php?r=site/index&id=100

 

Create URL from Controller

Yii::app()->controller->createUrl("index", array("id"=>100));

Result: index.php?r=site/index&id=100
You will obtain this result if your current controller is “SiteController”.

If you are in a controller you can simply write

$this->createUrl('index',array('id'=>100));

 

Create absolute URL:

In order to create an absolute path url you need to use createAbsoluteUrl() function:

Yii::app()->createAbsoluteUrl('site/index',array('id'=>100));

Result: http:⁄⁄yourdomain.tld⁄index.php?r=site⁄index&id=100

 

Create Link

You can use the CHTML helper to quickly create an anchor in HTML:

echo CHtml::link('text', array('site/index', 'id'=>100));

Result: <a href=”/ABC/index.php?r=site/index&amp;id=100″>text</a>

 

Redirect Browser

$this->redirect(array('site/index','id'=>100));

It will redirect the browser to index.php?r=site/index&id=100

, ,

3 thoughts on “Yii Reference 1 – Create Url, Links and Redirections

  • ariston kombi says:

    Cool article. It’s about time to find interesting content for a change.

  • Mark says:

    Hi, this is a nice post, I am totally new to Yii, I came from other frameworks like Joomla, and my own applications, but I am trying to make a simple application that will bring under my footer under main.php some link values from a data base, and render it using for example Chtml::link like you posted above, but I am not able to understand how to do that using the Controller, Model, View, concept, do you have any clue? thanks in advance

    • admin says:

      Sorry for the late reply,
      If you mean that you need to add dynamic link values inside the layout,
      you can directly write your db call in the layout or for a better MVC implementation you can add a function to the Controller class ‘components/Controller.php’ and call it inside the layout ($this->functionName())

Leave a Reply

Your email address will not be published. Required fields are marked *

*


× 4 = thirty six

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>