SaidbakR
SaidbakR

Reputation: 13544

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>
        </div>
              <button type="submit" class="btn btn-default"><?=yii::t('app','Submit');?> <i class="glyphicon glyphicon-ok"></i></button>
      </form>

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: example.com/feqh/search?q=anySearchString

However, example.com/search/anySearchString is accessible. Here the problem with submitting using the form.

I tried to change the form action URL:

<?=Html::beginForm(['feqh/search'] 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 preventexample.com/search/anySearchString`

Upvotes: 1

Views: 2770

Answers (3)

Or u can try to make redirect action next to your search action and change the search form so it leads to redirect.

Put this into common/main.php rules(advanced app):

'controller/action/<param:[\w-]+>/<page:[\d]+>' => 'controller/action',

'controller/action/<param>' => 'controller/action',

You need to change "controller","action", and "param" into your controller action and parameter. This is mainly for search problem i encountered so i posted it here in hope it helps someone.

Upvotes: 0

Apoorv Joshi
Apoorv Joshi

Reputation: 399

You can try something like:

'search/<q:w>' => 'feqh/search/variable_name/<q>'

Then in your

actionSearch()

Do something like

$query = isset($_REQUEST['variable_name']) ? $_REQUEST['variable_name'] : '';

Upvotes: 0

Blizz
Blizz

Reputation: 8408

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.

Upvotes: 5

Related Questions