2009年9月16日星期三

Re: [fw-mvc] howto: generate url with separators &, ? and =

-- Exception e <exceptione@hotmail.com> wrote
(on Wednesday, 16 September 2009, 08:06 AM -0700):
> Matthew Weier O'Phinney-3 wrote:
> >
> > Simply build a form, set the method to "get", and when it submits, it
> > will supply query parameters:
> >
> >
> > <form action="/search/process" method="get">
> > <input type="text" name="q" value="" />
> > <input type="submit" name="search" value="Search" />
> > </form>
> >
>
> Well the problem here is that submitting the form results in
>
> /search/process?q=text
>
> if I then want to use the view helper Url, to create a query url for me to
> use in a hyperlink, it will generate something like
>
> /search/process/q/text
>
> spot the difference?

So build the url only to /search/process, and then append the query
string:

<?php echo $this->url(array(
'controller' => 'search',
'action' => 'process',
), null, true) . '?q=' . $this->escape($this->query) ?>

If you need to build a query string out of multiple parameters, use
http_build_query() -- as it looks you've already found.

The url() helper is primarily a mechanism to allow assembling URLs based
on defined routes - which typically do not utilize a query string in
order to perform matching.

> Here a more detailed explanation why this is a problem.
>
> I generate a zend_form with no absolute action uri, and method get
>
> 1) submit form → uri is now /search/process?q=text
> 2) click on a link built from the url helper → leads to
> /search/process/q/different
> 3) submit form again, note that action is now /search/process/q/text → lead
> to /search/process/q/different?q=other
>
> I hope it is more clear now?
>
> As a workaround, I use the native http_build_query now. If the url helper
> doesn't perform any
> http://framework.zend.com/manual/en/zend.uri.html#zend.uri.validation.allowunwise
> sanity checks , then there is no reason to avoid http_build_query (which
> seems the case to me).

--
Matthew Weier O'Phinney
Project Lead | matthew@zend.com
Zend Framework | http://framework.zend.com/

没有评论: