GenerateUrl does not respect Localized Routes in Symfony4.4

Introduction

I am using: Symfony v4.4.13 on Windows 10 Pro host (development machine).

In my project i am writing search module.

I have set Localized Routes: en/ru

Requirement

I want to switch locale from english to russian if user inputs search term in russian.

Problem

At the moment i get an error:

No route found for "GET /ru/search/%D1%82%D0%B5%D1%81%D1%82" (from "https://127.0.0.1:8000/en/search")

As seen in error – it happens because it does not translate search keyword to поиск keyword.

Only user’s inputed search term is forwarded to next pageroute goods_searchfrom goods_search_no_term and localized route is, seemingly, not taken into account.

The URL shoud be: "/ru/%D0%BF%D0%BE%D0%B8%D1%81%D0%BA/%D1%82%D0%B5%D1%81%D1%82"

witch translates to utf8 "/ru/поиск/тест" instead of "/ru/search/тест"!

Code

/**
 * @Route({
 *     "en": "/{_locale}/search",
 *     "ru": "/{_locale}/поиск"
 * }, name="goods_search_no_term", utf8=true)
 * @Route({
 *     "en": "/{_locale}/search/{term}",
 *     "ru": "/{_locale}/поиск/{term}"
 * }, name="goods_search", utf8=true)
 *
 * @param $term
 * @param Request $request
 * @param TranslatorInterface $translator
 * @param UltraHelpers $ultraHelpers
 * @return RedirectResponse|Response
 */
public function search(
    $term = '',
    Request $request,
    TranslatorInterface $translator,
    UltraHelpers $ultraHelpers
)
{
    if ($request->getMethod() === 'GET')
    {
        $term = $request->get('term');

        if (($term !== null) && ($term !== ''))
        {
            $lang = $request->getLocale();
            if ($lang === 'en')
            {
                if ($ultraHelpers->isRussianText($term))
                {
                    $link_redirect = $this->generateUrl('goods_search', ['_locale' => 'ru', 'term' => $term]);
                    return $this->redirect($link_redirect);
                }
                $search_items = $repo_item->searchEn($term);
            }
            elseif ($lang === 'ru')
            {
                $search_items = $repo_item->searchRu($term);
            }
        }

        return $this->render('search/search.html.twig',
            [
                'search_items' => null,
                'msg' => null,
                'term' => $term,
                'form' => $form->createView()
            ]
        );
    }
}

public function isRussianText($text)
{
    return preg_match('/[А-Яа-яЁё]/u', $text);
}

Finally

Am i hitting a bug (edge case) or is it misconfiguration on my part?

Thank you for suggestions!

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *