sємsєм sємsєм - 1 year ago 72
PHP Question

Yii2 URL manager rules and forms with GET method

I have a global search form that submits to search action of a controller:

<?=Html::beginForm(['/feqh/search'], 'get', ['class' => 'navbar-form navbar-left', 'role' => 'search', 'id' => 'searchForm']);?>
<div class="form-group has-feedback Right">
<input id="q" type="text" class="form-control" placeholder="<?=yii::t('app','Search');?>" name="q" value="<?= Html::encode(\Yii::$app->getRequest()->getQueryParam('q',""));?>" />
<i class="form-control-feedback glyphicon glyphicon-search"></i>
<button type="submit" class="btn btn-default"><?=yii::t('app','Submit');?> <i class="glyphicon glyphicon-ok"></i></button>

I decided to make pretty URL for search through rules as following:

'search/<q:\w+>' => 'feqh/search',

However, submitting the form always generate the following URL:

is accessible. Here the problem with submitting using the form.

I tried to change the form action URL:

i.e removing the initial
but It does not make any difference.

By the way, the following rule is working too:

'search' => 'feqh/search',
it makes
example.com/search?q=anySearchString. However, the applying of this rule prevent

Answer Source

This has nothing to do with your pretty URL configuration (and not even Yii)... It's a browser thing. It only knows how to submit a form is posted as either a GET or a POST.

So since you are posting in GET mode it will simply add the inputs as query parameters to your URL.

If you want the URL in the address bar to represent your pretty URL you'll have to take control over the submit and perhaps issue a redirect instead?

$('#searchForm').submit(function() {
   window.location = $(this).attr("action") + '/' + $('#q').val();
   return false;

It's the only way I can think of right now.