6

I'm creating a simple CRUD for adding links to a category. Each category has an id. I have a view that lists all the links for a certain category. In that view I have a link to the add-form which is:

http://example.com/link/add/categoryId/3

I currently build that link in the view using the following syntax.

<?php echo $this->baseUrl();?>/link/add/categoryId/<?php echo $this->category['id']; ?>

I think this can be done cleaner by using the Url View Helper.

<?php echo $this->url(array('controller'=>'link','action'=>'add','categoryId'=>$this->category['id'])); ?>

But that gives me the following url

http://example.com/link/add/id/3/categoryId/3

..which has an extra "id/3". I read but did not fully understand the code of the Url View Helper. How come there's an extra id/3 in there?

Thanks!

@Fge gave the correct answer, below is my updated complete syntax.

echo $this->url(array('controller'=>'link','action'=>'add','categoryId'=>$this->category['id']),null,true);
Niels Bom
  • 8,728
  • 11
  • 46
  • 62
  • Is there any parameter 'id' in your current request? – Fge Nov 18 '10 at 13:49
  • 1
    Yes, I have a view that lists all the links for a certain category. That "certain category" has an id, the url is http://example.com/category/view/id/3 – Niels Bom Nov 18 '10 at 13:55

1 Answers1

9

By default the Url ViewHelper merges and overrides the given parameters with the current request parameters. Like in your case the id-parameter. If you want to reset all parameters you have to use the 3rd parameter of the view-helper: 'reset':

$this->url(array(), 'route'( = null to use the default), true);

This will force the viewhelper not to use the current request as "fallback" for not set parameters. The default behaviour is especially usefull if you only want to change one or two parameters of the current request (like the action) but don't want to set all parameters (or maybe you don't even know them all).

Fge
  • 2,971
  • 4
  • 23
  • 37
  • Thanks! I'll edit my question to add the full syntax I used to get the URL I wanted. Don't you think this is kind of strange behaviour for being the default? – Niels Bom Nov 18 '10 at 14:21
  • No the behaviour is perfect. This shortens the syntax for many uses. Imagine you have a server-side sortable list with pagination. For the pageination and the sortable headers you just have to use $this->url('order' => 'ASC'); to change the order. All other parameters like page, filters etc... will remain intact. You don't have to care about them at all in your view :) – Fge Nov 18 '10 at 14:32
  • That is the perfect use case for it indeed! – Niels Bom Nov 18 '10 at 14:48