I am working on a website where an URL is composed after submitting a GET form. The form values are passed as an array of variables of which at least one must be defined for the search on the database to work. I would like to shorten the URL by removing the empty form elements and to make it more user-friendly by simplifying the variable names.
At the moment, the URL looks like this (just with a lot more variables):
http://localhost/example/search?FormName[name]=lorem+ipsum&FormName[id]=&FormName[age]=&yt0=Search
I aim to make it look like this:
http://localhost/example/search?name=lorem+ipsum
In order to do this, I’ve got the following questions:
I’ve read that it’s not possible to remove the empty form elements with only PHP when using the GET method because this is the standard behaviour of the html form. Is there a way to do this with the urlManager from yii?
Can I replace “FormName[name]” with something shorter like “name” without changing the variable name, e.g., with regular expressions?
- And at last but not least: What does the “yt0=Search” signify and how can I remove it from the URL?
Any help would be greatly appreciated.
Simple method, if jQuery is an option:
The parameter names come from the form's fields'
name
attributes.So to make the form query for
name=lorem+ipsum
the input would have to look like this:You should look at the
name
attributes, I'm guessing they are generated by some code you are using to create the code? The empty query parameters come from other input fields in the form. If you want full control of the query string, create the form by hand.I recommend you following solution: First, you need to define html form with POST method:
Second, you need to define
getSearchTerms
action in yourExampleController
:Then, you need to define main search action:
Finally, you need to add a url-manager rule:
In this solution,
getSearchTerms
action is responsible for receiving user entered text, and then pass values to search action. Now your url can behttp://localhost/example/search/sampleText
. Note you can skip adding url-manager rule if you like. In this case, your url must be likehttp://localhost/example/search/name/sampleText
. In fact, we can remove "name" part from url by adding url-manager rule.