Change routing basing on language, translate URL parts - php

Is it posible in Symfony 1.2 to change routing basing on lang?
In my system there are 2 langs - EN, PL
Sample route look like this:
produkt_show:
url: /products/:pslug/:idslug
param: { module: product, action: show }
What I want to achieve: I want produkt_show route to match [and generate] different url depending on the current language. So in PL my url would look like this:
/produkty/:pslug/:idslug
It is essential those routes to have the same names. I can't change all url_for/link_to etc. calls and pass different routes names to them.
If anything is unclear -please, ask ahead.
UPDATE
according to the advice of j0k I used plugin. I choosed zxI18nRoutingPlugin. It seems to partialy work - it resolves url to right route if I write it literally in browser address input. But it still generates URLs that are not translated.
e.g.
my route:
contact_form:
url: /contact_form
param: { module: contact_request, action: new}
trans unit:
<trans-unit>
<source>contact_form</source>
<target>formularz-kontaktowy</target>
</trans-unit>
generated url:
Kontakt
But if I type BASE_URL/formularz-kontaktowy - right action is executed.
This is my configuration from dev toolbar:
Request:
parameterHolder:
action: new
module: contact_request
sf_culture: pl
attributeHolder:
sf_route: 'sfRoute Object()'
User
options:
auto_shutdown: false
culture: pl
default_culture: pl_PL
use_flash: true
logging: '1'
timeout: 10800
attributeHolder:
symfony/user/sfUser/attributes: { LAST_CATEGORY_ID_PATH_VAR: null, product_elements_on_page: 50 }
culture: pl_PL
I just can't figure it out, I would appreciate any help, suggestions, anything, because I'm stuck with this.
UPDATE 2
factories.yml:
all:
routing:
# class: sfPatternRouting
# param:
# generate_shortest_url: true
# extra_parameters_as_query_string: true
class: zxPatternI18NRouting
param:
generate_shortest_url: true
extra_parameters_as_query_string: true
use_cultures: [pl, de, en, ru] # destination cultures. Plugin looks for translations for these cultures.
culture_into_url: false # defines if culture should be always placed in url

There are some plugins that can handle such case (or at least gave you a way to do this on your own):
zxI18nRoutingPlugin
The zxI18nRoutingPlugin extends sfPatternRouting class giving possibility to translate routes patterns static text to different languages.
gbI18nRoutePlugin
Easy way to have I18N Routing.
An other option can be to add the culture inside the route, like /pl/product, /en/product, etc ..

Related

TYPO3.CMS 9 LTS - cacheable extbase action but no cHash with new routing

Any idea how to solve this? I have an extbase plugin, that has a list and a show action. Both should be cachable and the detail link should not contain a cache hash
I can not achieve this. As soon as i enable the caches i always get the same result for the detail action.
I configured the plugin to be cacheable:
// add detail plugin
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'Vendor.Extension',
'SomePiName',
[
'ControllerName' => 'show',
],
[],
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::PLUGIN_TYPE_CONTENT_ELEMENT
);
The routing config:
routeEnhancers:
MyEnhanceName:
type: Extbase
extension: Extension
plugin: SomePiName
routes:
- { routePath: '/{localized_entry}/{slug}', _controller: 'ControllerName::show', _arguments: {'slug': 'uuid'} }
defaultController: 'ControllerName::show'
aspects:
localized_entry:
type: LocaleModifier
default: 'show'
localeMap:
- locale: 'de_DE.*|de_AT.*|de_CH.*'
value: 'detail'
- locale: 'it_IT.*'
value: 'dettaglio'
slug:
type: customType
My custom aspect works by mapping the foreign uuid on a generated slug, that is stored in a mysql-table i maintain.
I want a deeplink like:
/path/to/page/show/here-comes-the-slug
But i get
/path/to/page/show/here-comes-the-slug?cHash=...
So i added:
$GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParameters'][] = "tx_extension_somepiname[uuid]";
$GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParameters'][] = "tx_extension_somepiname[controller]";
$GLOBALS['TYPO3_CONF_VARS']['FE']['cacheHash']['excludedParameters'][] = "tx_extension_somepiname[action]";
Now the link looks like:
/path/to/page/show/here-comes-the-slug
But as soon as i activate the caches i always get the same result.
So i need a cache hash calculation but i dont want the fu**er to be in the link...
Links are generated using ContentObjectRenderer->typolink_URL with the config:
[
"parameter" => "t3://myhandler?uuid=someuuid"
]
that handler translates to a subsequent call to ContentObjectRenderer->typolink_URL with the config:
[
"parameter" => "t3://page?uid=someconfiguredpageuid",
"useCacheHash" => 0,
"additionalParams" => "&tx_extension_somepiname[uuid]=uuid&tx_extension_somepiname[controller]=Controller&tx_extension_somepiname[action]=show"
]
So my situation is, that i can EITHER have a cacheHash and a correct result OR nor cacheHash with invalid results.
How is this meant to be done?
You should not exclude parameters that actually distinguish page content from cHash generation. They are really only sane to use with external tracking parameters like fbclid etc.
Also don't use useCacheHash=0 if you rely on caching.
Rather configure the route enhancer to remove the ?cHash.
Okay, i solved this, here the necessary steps:
1) Like Jonas Eberle suggested we remove the extbase arguments from excludedParameters.
2) Configure the details action as cacheable (remove controller->action combination from 2nd array of possible actions in extbase plugin registration / ext_localconf.php)
3) When using a custom aspect, implement the "StaticMappableAspectInterface". I did not find the relevant part in the core but it seems this interface is required! Just have a look at the PersistedAliasMapper.
Now it works...

Symfony generate incorrect url with double /

I'm working on a symfony3 project, and i'm stuck with a problem,
We are sending emails that are twig based, with a button that has a link to our platform.
Button example
And the open document button link is the following one:
app.example.com/books/bookId/pageId
Which is generated through twig:
url("open_book", { bookId: book_id, pageId: page_id })
And the url is defined on a controller file, with annotations
#Route("/book/{bookId}/{pageId}", name="open_book")
So, the link that user gets on the email, is the original, but with double // before books, like this:
app.example.com//books/bookId/pageId
I'm working on last twig version, and I don't know if it can be symfony issue either, since its only happening on our prod environments (it works on local, yey)
If it helps, our routing.yml
app:
resource: "#BooksBundle/Controller/"
type: annotation
prefix: /
host: app.%host%
This is only happening with urls that are generated by twig. We are using jms translation and jms i18n bundles also, so I thought maybe its trying to set a null locale betwen / / like:
app.example.com/en/books/bookId/pageId
But instead of en, an empty language maybe.
Any idea to start with?
UPDATE 3/01/18
Hey! Thanks for all answers. It seems that was a problem with symfony configuration at the end...
On file parameters.yml:
router.request_context.scheme: '%env(ROUTER_REQUEST_CONTEXT_SCHEME)%'
router.request_context.host: '%env(ROUTER_REQUEST_CONTEXT_HOST)%'
router.request_context.base_url: '%env(ROUTER_REQUEST_CONTEXT_BASE_URL)%'
Then our value for base_url was /. Seems that was the real problem. Removing / on that param does the trick.
Thanks!!
For every route in the controller you are using prefix /:
app:
resource: "#BooksBundle/Controller/"
type: annotation
prefix: /
host: app.%host%
This means that every route like:
#Route("/book/{bookId}/{pageId}", name="open_book")
Will be prefixed with /. In the end this route path will be //book/{bookId}/{pageId}. Some libraries truncate path values, the other ones not.
So just remove prefix parameter completly or declare route's path without leading slash:
#Route("book/{bookId}/{pageId}", name="open_book")
try to replace this line
url("open_book", { bookId: book_id, pageId: page_id })
By
url("open_book", { bookId: book_id, pageId: page_id }) | replace({'//': "/"})
OR
{{ app.request.schemeAndHttpHost }} {{ path("open_book", { bookId: book_id, pageId: page_id }) }}

Routing in Symfony2

How to setup default routing in Symfony2?
In Symfony1 it looked something like this:
homepage:
url: /
param: { module: default, action: index }
default_symfony:
url: /symfony/:action/...
param: { module: default }
default_index:
url: /:module
param: { action: index }
default:
url: /:module/:action/...
I was looking through the cookbook for an answer to this, and think I've found it here. By default, all route parameters have a hidden requirement that they match any character except the / character ([^/]+), but this behaviour can be overridden with the requirements keyword, by forcing it to match any character.
The following should create a default route that catches all others - and as such, should come last in your routing config, as any following routes will never match. To ensure it matches "/" as well, a default value for the url parameter is included.
default_route:
pattern: /{url}
defaults: { _controller: AcmeBundle:Default:index, url: "index" }
requirements:
url: ".+"
I don't think it's possible with the standard routing component.
Take a look to this bundle, it might help :
https://github.com/hidenorigoto/DefaultRouteBundle
// Symfony2 PR10
in routing.yml:
default:
pattern: /{_controller}
It enables you to use this kind of urls: http://localhost/MySuperBundle:MyController:myview
Symfony2 standard routing component does not support it, but this bundle fills the gap Symfony1 left:
https://github.com/LeaseWeb/LswDefaultRoutingBundle
It does what you expect. You can default route a bundle using this syntax:
FosUserBundle:
resource: "#FosUserBundle"
prefix: /
type: default
It scans your bundle and automatically adds routes to your router table that you can debug by executing:
app/console router:debug
Example of automatically added default routes:
[router] Current routes
Name Method Pattern
fos_user.user.login_check ANY /user/login_check.{_format}
fos_user.user.logout ANY /user/logout.{_format}
fos_user.user.login ANY /user/login.{_format}
...
You see that it also supports the automatic "format" selection by using a file extension (html, json or xml).
Here is an example: http://docs.symfony-reloaded.org/master/quick_tour/the_big_picture.html#routing
A route definition has only one mandatory parameter pattern and three optionals parameters defaults, requirements and options.
Here's a route from my own project:
video:
pattern: /watch/{id}/{slug}
defaults: { _controller: SiteBundle:Video:watch }
requirements: { id: "\d+", slug: "[\w-]+"
Alternatively, you can use #Route annotation directly in a controller file. see https://github.com/sensio/SensioFrameworkExtraBundle/blob/master/Resources/doc/annotations/routing.rst
As for the default routes, I think Symfony2 encourages explicit route mapping.
Create a default route is not a good way of programming. Why? Because for this reason was implemented Exception.
Symfony2 is built just to do right things in the right way.
If you want to redirect all "not found" routes you should use exception, like NotFound404 or something similar. You can even customise this page at your own.
One route is for one purpose. Always. Other think is bad.
You could create your own bundle that handled all requests and used URL parameters to construct a string to pass to the controller's forward method. But that's pretty crappy, I'd go with well defined routes, it keeps your URLs cleaner, and decouples the URL and controller names. If you rename a bundle or something, do you then have to refactor your URLs?
If you want to create a "catch all", your best bet would be to hook on the KernelEvents::EXCEPTION event. This event gets triggered whenever an Exception falls through to the HttpKernel, this includes the NotFoundHttpException thrown when the router cannot resolve a route to a Controller.
The effect would be similar to Symfony's stylized 404 page that gets rendered when you send the request through app_dev.php. Instead of returning a 404, you perform whatever logic you're looking to.
It depends... Some of mine look like this:
api_email:
resource: "#MApiBundle/Resources/config/routing_email.yml"
prefix: /
and some look like
api_images:
path: /images/{listingId}/{width}/{fileName}
defaults: { _controller: ApiBundle:Image:view, listingId: null, width: null, fileName: null }
methods: [GET]
requirements:
fileName: .+

Passing Params to Symfony Routes

I have a defined route that displays a dynamic page:
page_show:
url: /:domain_slug/:slug
class: sfPropelRoute
options:
model: Page
type: object
method: doSelectByDomain
param: { module: page, action: show }
requirements:
sf_method: [get]
This works great, but now I want my homepage URI to route to a specific page. To do that, I assume that I have to pass the :domain_slug and :slug values of the page I want to display as the homepage. That's fine, but I can't seem to track down any documentation or example that shows me how to go about doing that.
Is it possible to specify specific variable values in a route? In this case, I want to pass :domain_slug => portal, :slug => dashboard (that syntax doesn't work, btw). Essentially, I want to create a homepage route that looks something like this:
homepage:
url: /
class: sfPropelRoute
param: { module: page, action: show, array( :domain_slug => portal, :slug => dashboard ) }
options:
model: Page
type: object
method: doSelectByDomain
But different enough that it, you know, works. :-) I suppose I could create a simple route to a different method, modify the request parameters manually and forward to the executeShow() method, but that's a hack I'd rather avoid if a more elegant solution is available.
Thanks.
You can define values in the param key of the route... for example:
homepage:
url: /
class: sfPropelRoute
param: { module: page, action: show, domain_slug: portal, slug: dashboard}
options:
model: Page
type: object
method: doSelectByDomain
At least thats how it works with a non propel/doctrine route. I assume it should be the same with any type of route in the framework.
I never found a way to do this that worked (or maybe I just couldn't manage to do it correctly). My solution was to create the route and pass it through a custom method that does the work to specify the appropriate page details:
homepage:
url: /
class: sfPropelRoute
options:
model: Page
type: object
method: doSelectHomepage
param: { module: page, action: show ) }
requirements:
sf_method: [get]
The doSelectHomepage() method does all of the work I was hoping I'd be able to do by hardcoding values in the route itself.
Actually it did work, it was just the order in which the routes were defined. The first answer is correct. It may have worked for you if you added "homepage" rule BEFORE the "page_show" rule. So maybe Symfony isn't as stupid as I thought...No, no, it is. It's just not that bad.

Can you force symfony resolve to a specific route?

Say that I have to following 2 routes in this order:
Zip:
url: home/:zip
param: { module: home, action: results }
State:
url: home/:state
param: { module: home, action: results }
and I use a route such as:
'#State?state=CA'
Why does it resolve to the Zip route?
I thought when you specified the route name explicitly: '#State' that it did not parse the entire routing file and just used the specific route you asked for.
I would like to be able to use the same action to display data based on the variable name (zip or state) I don't want to have to create the same action (results) twice just to pass in a different parameter.
You need to add requirements so that it will recognize the different formats
Zip:
url: home/:zip
param: { module: home, action: results }
requirements: { zip: \d{5} } # assuming only 5 digit zips
State:
url: home/:state
param: { module: home, action: results }
requirements: { state: [a-zA-Z]{2} }
That should fix it, although I agree with you that when you use a route name in a helper it should use the named route.
the problem here is that both routing rules resolves to somewhat same url ( /home/) and when generating links it uses correct named route to generate url.
when you click on that generated url( for example /home/CA) withouth requirements addition it will match the first rule in routing.yml file that matches and that is your "Zip" route.
just to explain what is happening.
It does use the named route. The issue is that your URLs are the same (the paramater name is irrelevant) so when you load the URL in your browser, the first route to match will always be Zip as there is no way for Symfony to know which one you want.
Adding requirements: is the way to go.

Categories