We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

URL and Tag inconsistency

Hi, Just started using phalcon and am having some trouble understanding how to generating urls. First, my goal is to have a url like this: mysite.com/project/overview?pid=13

using the url service I can create the url as expected by:

$url->get('project/overview', array('pid'=>13));
// output:
/project/overview?pid=13

The documentation says internally Tag::linkTo uses Phalcon\Mvc\Url to generate the url. However, Tag::linkTo() doesnt seem to support arrays the same as Url::get(). Arrays in Tag::linkTo() seem to only work for either named routes (using a nested array) or simple array('route', 'text'). How can I generate a url like above using linkTo? I could manually do

Tag::linkTo("project/overview?pid=13", "Project 13")

But then I have to construct the route myself. Also, prefixing the route with a "/" seems to behave differently in Tag::linkTo and Url::get(). Am I missing something?

For the routes and slashes try adding this to fix end of line slashes: php$router->removeExtraSlashes(true);



16.2k

Jesse thanks for the tip, However I was say referring to the the prefix: /project/overview vs project/overview.

To clarify, what im referring to is reverse routing: building a url based on defined (or default) routes and creating a url string with appended $_GET vars. Url::get() seems to do this correctly, but Tag::linkTo() doesn't seem to have that ability unless its a named route. Looking through the sample application code, it seems people are doing one of two things:

$pid = 13
\\ 1:
<a href="<?php $this->url->get( array('project/overview', 'pid'=>$pid)); ?>">Project 13</a>

\\ 2:
$this->tag->linkTo('project/overview?pid=' . $pid, 'Project 13'); 

So either they are manually building the <a> element and using $url->get() for the href attribute, or they are using linkTo with a string. Correct me if I'm wrong, but would the string even be handled by the reverse router? For example, would /project/overview?pid=13 be changed to /project/overview/13 if routes were defined that way?



16.2k

So the "/" inconsistency seems to be caused by having baseUri set to "/" in the router. Having $router->setBaseUri("") to an empty string seems to solve that problem.



13.1k

How to solve this problem



16.2k
Accepted
answer
edited Oct '14

@ikphp, unfortunately, I dont think theres a way to use Tag::linkTo and Url::get with the type of array argument I listed above. The "/" issue can be easily solved by setting Url::setBaseUri(""). In dependency injector it would look like this:

$di->set('url', function() {
    $url = new \Phalcon\Mvc\Url();
    $url->setBaseUri("");
    return $url;
}, TRUE);

Or just $url->setBaseUri("") in your specific view I believe would override the default behavior.