简体   繁体   English

提交后的Symfony3丑陋的URL路径(URL重写或发情)

[英]Symfony3 ugly URL paths after submit (url rewrite or ruting)

I am using: 我在用:

  • Symfony v3.0.6; Symfony v3.0.6;
  • Doctrine v2.5.4 教义v2.5.4

I have built site search with LIKE in the doctrine query. 我在学说查询中使用LIKE建立了站点搜索。

// My search query 
$query = $em->createQueryBuilder()
    ->select('i')
    ->from('AppBundle:Item', 'i')
    ->where('i.name_lv LIKE :term')
    ->andWhere('i.description_lv LIKE :term')
    ->setParameter('term', '%' . $term . '%')
    ->orderBy('i.price', 'DESC')
    ->getQuery();

It works fine if I write requests manually into the browsers address bar. 如果我将请求手动写入浏览器地址栏中,则效果很好。

For example: 例如:

returns page with products that was searched. 返回包含搜索到的产品的页面。

PROBLEM: 问题:

Though when I use search button in the form (like every user should) 虽然当我在表单中使用搜索按钮时(就像每个用户都应该一样)

// Relevant part of twig template showing my search form
<div class="search-box row clearfix text-center">
    <form id="search-form" method="GET">
        <fieldset>
            <p>{{ "goods.msg.searchSomething"|trans }}</p>
            <input type="text" class="input-term" name="term" />
            <p>{{ msg }}</p>
            <input type="submit" class="input-submit button small success" value="{{ "goods.button.search"|trans }}" />
        </fieldset>
    </form>
</div>

I have problem with paths - because 我的路径有问题-因为

then I get ugly URLs like these: 然后我会收到类似以下的丑陋网址:

I suspect, that this might be URL rewrite or routing problem 我怀疑这可能是URL重写路由问题

I need pretty URLs always - not only when manually typing URL, but also when using form to search products. 我总是需要漂亮的URL-不仅是在手动键入URL时,而且在使用表单搜索产品时。

Here is relevant code from search controller: 这是来自搜索控制器的相关代码:

// start of function: searchAction
// getting GET parameter
$term = $request->get('term');

// end of function: searchAction
// rendering template with additional parameters 
return $this->render('search/search.html.twig', array(
    'search_items' => $search_items,
    'msg' => '', 
    'term' => $term
));

Here is my routing: 这是我的路线:

goods_search_show:
    path: /{_locale}/search-show/{id}/{term}
    defaults: { _controller: 'AppBundle:Search:searchShow', id: 1, term: '' }
    requirements:
        _locale: lv|en|ru
        id: \d+

goods_search_no_term:
    path:     /{_locale}/search
    defaults: { _controller: 'AppBundle:Search:search' }
    requirements:
        _locale: lv|en|ru

goods_search:
    path:     /{_locale}/search/{term}
    defaults: { _controller: 'AppBundle:Search:search', term: '' }
    requirements:
        _locale: lv|en|ru

Please advise. 请指教。 Thank you for your time and knowledge. 感谢您的时间和知识。

UPDATE 1: 更新1:

I need to pass GET parameters, because I have two pages: [1] search and [2] searchShow (that shows detailed view of only one item) and on that page there is link back to page [1] that needs "term" parameter in order to display the search with same parameters 我需要传递GET参数,因为我有两个页面:[1] search和[2] searchShow (仅显示一项的详细视图),并且在该页面上有指向“ [term]”页面的链接。参数以显示具有相同参数的搜索

An example: 一个例子:

  • On the search page [1] when I press submit button, after writing in search term, I get URL like http://localhost:8000/en/search?term=productName 在搜索页面[1]上,当您按“提交”按钮时,在输入搜索词后,我得到的URL是http://localhost:8000/en/search?term=productName
  • On the same page with search results list there are some links to details page [2]. 在具有搜索结果列表的同一页面上,有一些指向详细信息页面[2]的链接。 Links are made with path() function 使用path()函数进行链接

     <li><a class="button secondary small" href="{{ path('goods_search_show', {'id': search_item.id, 'term': term}) }}">{{ "goods.button.view"|trans }}</a></li> 

    and produces URL like http://localhost:8000/en/search-show/162/productName 并生成类似http://localhost:8000/en/search-show/162/productName URL

  • on this page [2] I have to create link back to search page [1] with search parameter term that is passed along in link from search page [1]. 在此页面[2]上,我必须创建具有返回到搜索页面[1]的链接中传递的搜索参数term搜索页面[1]的链接。 To do so, I use path() function again 为此,我再次使用path()函数

     <li><a class="button secondary small" href="{{ path('goods_search', app.request.get('_route_params')|merge({'term': term})) }}">{{ "goods.button.backToList"|trans }}</a></li> 

    and get URL like http://localhost:8000/en/search/productName 并获取网址,例如http://localhost:8000/en/search/productName

  • Now - following that link I get back to search page [1] with previous search results displaying. 现在-在该链接之后,我返回到显示先前搜索结果的搜索页面[1]。

  • Then, when trying another search term and pushing submit button I get URL genereated [A] instead of [B] or [C] 然后,当尝试另一个搜索词并按“提交”按钮时,URL生成为[A],而不是[B]或[C]

     [A] http://localhost:8000/en/search/productName?term=anotherProductName [B] http://localhost:8000/en/search/anotherProductName [C] http://localhost:8000/en/search?term=anotherProductName 
  • As you can see from routing - route goes to goods_search . 从路由中可以看到,路由转到goods_search Search is performed for productName , but anotherProductName is completely ignored (in fact term is part of the URL twice). 搜索是进行productName ,但anotherProductName完全被忽略(实际上term是URL的一部分两次)。

I feel like there must be better solution than using POST or passing term in session. 我觉得必须有比使用POST或在会话中传递term更好的解决方案。 Maybe some additional parameters for .htaccess file for Apache server could solve bad URL to become nice. 也许Apache服务器的.htaccess文件的一些其他参数可以解决错误的URL变得不错的问题。

UPDATE 2: 更新2:

I took advice from Alvin Bunk and implemented form and updated template to use Form widgets instead of basic html. 我接受了Alvin Bunk的建议,并实现了表单和更新的模板,以使用表单小部件而不是基本的html。

Unfortunately when I press search instead of nice URL i get this one 不幸的是,当我按搜索而不是漂亮的URL时,我得到了这个

`http://localhost:8000/ru/search?term=productName&submit=&_token=IvGAvN-nCR40-PKm--rA92AzGXTbI94y2rDCPZxa5D0`

and when I change the term to otherProductName I get 当我将术语更改为otherProductName时,我得到

`http://localhost:8000/ru/search/productName?term=otherProductName&submit=&_token=IvGAvN-nCR40-PKm--rA92AzGXTbI94y2rDCPZxa5D0`

So the problem stays the same - meaning term is part of the URL twice. 因此问题仍然存在-意思是term两次是URL的一部分。

So maybe this question is really routing or URL rewrite problem? 因此,也许这个问题确实是路由或URL重写问题? (Routing that I use is mentioned in the question and .htaccess file is default that ships with Symfony3). (问题中提到了我使用的路由,并且.htaccess文件是Symfony3附带的默认文件)。

My form 我的表格

{{ form_start(form, {'attr': {'id': 'search-form'}, 'action': path('goods_search', {'_locale': lang, 'term': term}), 'method': 'GET'}) }}
    <fieldset>
        {{ form_row(form.term, {'name': term, 'attr': {'class': 'input-term'}}) }}
        {{ form_row(form.submit, {'attr': {'class': 'input-submit small success'}}) }}
    </fieldset>
{{ form_end(form) }}

Ths is ItemType 这是ItemType

<?php

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class ItemType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('term', TextType::class, array('mapped' => false, 'label' => false))
            ->add('submit', SubmitType::class, array('label' => 'Test label for SUBMIT button'))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Item',
        ));
    }

    public function getBlockPrefix()
    {
        return null;
    }
}

This is how I create form in SearchController 这就是我在SearchController创建表单的方式

$item = new Item();
$form = $this->createForm(ItemType::class, $item);

return $this->render('search/search_show.html.twig', array('term' => $term, 'form' => $form->createView()));

UPDATE 3: 更新3:

Found a couple workarounds for my problem, after applying both site seems to work as intended. 在将两个站点都应用后似乎找到了预期的工作,从而找到了解决我问题的几种解决方法。

WORKAROUND 1 解决方法1

Simply omitting form's action attribute makes an URL work and overwrite term in the URL instead of displaying it twice. 只需省略表单的action属性即可使URL工作并覆盖URL中的term ,而不是显示两次。

my form now 我现在的表格

{{ form_start(form, {'attr': {'id': 'search-form'}, 'method': 'GET'}) }}
    <fieldset>
        {{ form_row(form.term, {'name': term, 'attr': {'class': 'input-term'}}) }}
        {{ form_row(form.submit, {'attr': {'class': 'input-submit small success'}}) }}
    </fieldset>
{{ form_end(form) }}

WORKAROUND 2 解决方法2

On the second page there is link back to the search page with term in the URL like search?term=productName 在第二页上有链接回到搜索页面, term在这样的URL search?term=productName

So in the second search page template I create custom ugly URL with this code: 因此,在第二个搜索页面模板中,我使用以下代码创建了自定义的丑陋URL

{% set link_back = path('goods_search') ~ '?term=' ~ term %}
<li><a href="{{ link_back }}">link back to main search page</a></li>

instead of merging term with route parameters 而不是将term与路线参数合并

{% set link_back = path('goods_search', app.request.get('_route_params')|merge({'term': term})) %}
<li><a href="{{ link_back }}">link back to main search page</a></li>

It is normal to have such URL using GET method, try using POST. 使用GET方法获得这样的URL是正常的,请尝试使用POST。

But the best would be to use Ajax. 但是最好的方法是使用Ajax。

You could do something like this in your twig template: 您可以在树枝模板中执行以下操作:

{{ form_start(form, 
    {'action': path('/en/search-show',
        {'id':search_items.getID,
        'term':term}),
    'method': 'GET'}) }}

Then, I like to use annotations in my controller (instead of a YAML file) and do something like this to handle the parameters: 然后,我喜欢在控制器中使用注解(而不是YAML文件),并执行以下操作来处理参数:

/**
 * @Route("/search-show/{id}/{term}",
 *  defaults={"id" = 0,"term" = 0},
 *  name="submitPetHasProgram")
 */
public function searchShowAction($id, $term, Request $request){
...

Then the URL would look like: http://localhost:8000/lv/search/someId/someTerm 然后,URL看起来像: http:// localhost:8000 / lv / search / someId / someTerm

I show "someId" and "someTerm", but would be the actual id and term passed in coming from the twig template. 我显示“ someId”和“ someTerm”,但将是从树枝模板传入的实际ID和术语。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM