Andy
Andy

Reputation: 5414

How to get CakePHP 2 to keep 'index' in URL when using HTML Helper

In CakePHP 2.x there is a HTML Helper which allows for creating hyperlinks within Views.

If I use this...

<?php
    echo $this->Html->link('Navigation', 
    array('controller' => 'navigations', 'action' => 'foo')
    );
?>

... it will generate a URL to /navigations/foo (NavigationsController::foo).

However if I use index as the action

<?php
    echo $this->Html->link('Navigation', 
    array('controller' => 'navigations', 'action' => 'index')
    );
?>

The URL becomes /navigations.

I understand about "index" being a default when it comes to webpages. However, I actually need the URL to be /navigations/index, or at the very least have a trailing slash (/navigations/).

Is this possible?

Upvotes: 2

Views: 440

Answers (1)

ndm
ndm

Reputation: 60503

Fix the AJAX URLs instead

With regards to the explanation in your comment, I would argue that the "correct" way of fixing this problem is to use proper root relative URLs for the AJAX calls, as changing the URL structure only cloakes the underlying problem, that is targeting non-unique resources.

Personally I alwas use Router::url() to generate the URLs, either in the specific script files when serving them via PHP, or by writing out configuration in for example the layout, being it globally so that the scripts can access it when needed:

<script>
var config = {
    navigationDataUrl: <?php echo json_encode(
        Router::url(array('controller' => 'Navigations', 'action' => 'get_data'))
    ) ?>
};
</script>

or by configuring possibly existing JS objects.

<script>
navigation.dataUrl = <?php echo json_encode(
    Router::url(array('controller' => 'Navigations', 'action' => 'get_data'))
) ?>;
</script>

Connect routes with an explicit index part

That being said, for the sake of completion, it is possible to force the index part to not be dropped, by connecting routes that explicitly define that part, as opposed to using the :action route element, like:

Router::connect('/:controller/index', array('action' => 'index'));

which would match/catch URL arrays like yours before they are being handled by CakePHPs default controller index catchall route, which looks like:

Router::connect('/:controller', array('action' => 'index'), array('defaultRoute' => true));

https://github.com/cakephp/cakephp/blob/2.10.6/lib/Cake/Config/routes.php#L72

Upvotes: 2

Related Questions