Dan
Dan

Reputation: 199

Links not relative in cakephp

In my layout, I have a menu that I've included as an element, and it contains a link like so.

<? $html->link('New Part Number','/part_numbers/add'); ?>

The problem that I have is that cake isn't redirecting correctly and it ends up sending me to "http://localhost/part_numbers/add" instead of "http://localhost/my_client_folder/client_app/part_numbers/add" (I'm building this locally). My CakePHP app is stored a few directories below my webroot folder, but I thought CakePHP would autodetect how to build the linking no matter where the application was located, right?

So do I need to configure the application root folder, or create a route or something?

Upvotes: 0

Views: 3060

Answers (4)

Piotr Kaluza
Piotr Kaluza

Reputation: 11

You can also use:

Router::url(array(controller => '', action => '', true))

Upvotes: 1

Dan
Dan

Reputation: 199

Thank you everyone for your solutions, my previous solution was indeed in error:

You have to build it off of "$this" so that it knows where you're coming from, otherwise it can't figure out how to build a relative link.

Html->link("New Part Number", array('controller' => 'part_numbers', 'action' => 'add')); ?>

The REAL reason that the links were not working, as kindly mentioned below, was because of not specifying the array. This should work to fix the link:

<?= $html->link("New Part Number", array('controller' => 'part_numbers', 'action' => 'add')); ?>

Upvotes: 1

Daniel Wright
Daniel Wright

Reputation: 4604

In general, I would recommend always always always using reverse-routing in your views and controller actions, as a matter of discipline. In my experience, "smart URLs" (e.g. /part_numbers/add) break down very quickly once you start trying to use any of the advanced routing features.

It also violates the principle of writing code once, reading it many times – identifying the controller action invoked by a simple route like /part_numbers/add may be simple, but in a larger application with a ton of custom routes, it becomes much simpler to figure out what action your links will invoke if you use reverse-routing arrays consistently.

Upvotes: 1

sibidiba
sibidiba

Reputation: 6360

Your solution is no different if you would use an URL like in your example instead of array('controller', 'action').

Solution is to put <base href="<?php echo 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'); ?>" /> into your headers.

This will make all links (also src tags) relative to your webroot. It won't affect JS/CSS URL-s!

Upvotes: 1

Related Questions