Yii2 URL manager rules and forms with GET method

送分小仙女□ 提交于 2019-12-13 20:02:49

问题


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`


回答1:


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.




回答2:


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'] : '';



回答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.



来源:https://stackoverflow.com/questions/30516476/yii2-url-manager-rules-and-forms-with-get-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!