2

In CakePHP, I want to convert this URL

example.com/FAQ/What-came-first-the-chicken-or-the-egg

to

example.com/FAQ#What-came-first-the-chicken-or-the-egg

using the routes.php and have the browser scroll to that anchor.

I tried this:

Router::connect('/FAQ/:faq',
    array('controller' => 'pages', 'action' => 'faq', '#' => ':faq'),
    array('faq' => '[A-Za-z-_]+')
);

If I then do debug($this->request->params), is says

array(
    'plugin' => null,
    'controller' => 'pages',
    'action' => 'FAQ',
    'named' => array(),
    'pass' => array(),
    'faq' => 'What-came-first-the-chicken-or-the-egg',
    '#' => ':faq'
)

and the browser doesn't scroll anywhere.

Joe Z
  • 306
  • 1
  • 3
  • 12

2 Answers2

0

Not possible

A webserver has no visibility whatsoever of the url fragment, as such routes based on the url fragment will never work.

Your route needs to match the received url

If you request the url /Foo/#hash in a browser, the server will only receive /Foo/ - this is the url that cake sees, this is the url that must match a route if you don't want to see errors. As such your route needs to be:

Router::connect('/FAQ',
    array('controller' => 'pages', 'action' => 'faq')
);

Incidentally that's an odd route - the pages controller comes with a dynamic display function, it's not normal to create actions in this controller, rather use it like so:

Router::connect('/FAQ',
    array('controller' => 'pages', 'action' => 'display', 'faq')
);
Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123
  • Good point. However, according to [this answer](http://stackoverflow.com/a/940923/2483765), [`parse_url()`](http://www.php.net/manual/en/function.parse-url.php) CAN access the fragment (after the hashmark **#**) `PHP_URL_FRAGMENT` – Joe Z Jul 03 '13 at 14:10
  • Parse url can _parse_ a url with a url fragment. It can't however see the url fragment of the current request as it never leaves the browser, it is used exclusively for [client-side indirect referencing](http://tools.ietf.org/html/rfc3986#section-3.5). – AD7six Jul 03 '13 at 14:37
-1

I have not tested it:

Router::connect('/FAQ/#:faq',
    array('controller' => 'pages', 'action' => 'faq'),
    array(
        'pass' => array('faq'),
        'faq' => '[A-Za-z-_]+'
    )
);
Fortuna
  • 611
  • 6
  • 18