Answer the question
In order to leave comments, you need to log in
How to properly configure Yii2 routing?
There is a form
echo Html::beginForm(['main/search'], 'GET');
echo Html::input('text', 'request');
echo Html::submitButton('Поиск);
echo Html::endForm();
'search/<request:\w+>' => 'main/search'
http://test.com/main/search?request=123
http://test.com/search/123
echo Html::beginForm(['main/search', 'request' => '123' ], 'GET');
echo Html::submitButton('Поиск);
echo Html::endForm();
Answer the question
In order to leave comments, you need to log in
I figured it out, if anyone needs to skin the code in the future
1. Install dmirogin/yii2-js-urlmanager
2. Next, we need to add an id to the form and the input field
echo Html::beginForm(['main/search'], 'GET', $options = ['id' => 'searchForm']);
echo Html::input('text', 'request', '', $options = ['id' => 'searchinput']);
echo Html::submitButton('Поиск');
echo Html::endForm();
$("#searchForm").submit(function (e) {
e.preventDefault();
var url = UrlManager.createUrl('main/search', {request: $("#searchinput").val()});
window.location.replace(url);
});
preventDefault();
- to change the url and send your own, you must definitely prevent the standard form submission, which this function doesUrlManager.createUrl('main/search', {request: $("#searchinput").val()});
- this is where we form our url using the dmirogin / yii2-js-urlmanager extension,
and window.location.replace(url);
here we are already redirecting the user to the previously generated url 'search/<request:\w+>' => 'main/search'
http://test.com/search/123
That's right. What you wrote, he does to you. The browser handles the form submission. How it does it:
1. At submit
the form event, the browser takes a parameter action
2. Takes all the fields enclosed between the tags <form></form>
3. Takes it from each field name
and value
(for textarea type fields, I think it’s clear that it’s not value)
4. Forms from these fields request of the form (in the case of a GET request): name1=value1&name2=value2&...
5. Assigns a request from point 4 to action
point 1 through a question mark ?
6. Redirects to the received url
What should be done to change this behavior? Everything is very simple: you just need to intercept the submit
forms and write your own url generation logic.
Good afternoon.
I recommend reading the documentation and watching this video .
If you have a search form, then describing the options in the configuration will be tricky.
This is because the amount of data in the query string can change.
If the amount of data you have is fixed, then you can start with this.
'rules' => [
// если main у Вас контролер, а search действие
'' => 'main/index',
'<_a:(search)>/<request:\w+>' => 'main/search'
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question