I have 2 controllers account.php and address.php in the same directory APP/controller. For the first controller account.php, I use default router for URI like: account/create, account/login, account/logout... When writing second controller, I want to use all URI of address.php start with account/address/. As you can see here, I'm taking the same URI router matches with account controller.
My first approach:
// Add new address
Route::set('address', 'account/address/<action>')
->defaults(array(
'controller' => 'address',
'action' => 'index',
));
My address controller
public function before()
{
parent::before();
if ( ! Auth::instance()->logged_in())
{
// Redirect to a login page (or somewhere else).
$this->request->redirect('');
}
}
// nothing here
public function action_index()
{
$this->request->redirect('');
}
// create account
public function action_create()
{
// Create an instance of a model
$profile = new Model_Address();
// received the POST
if (isset($_POST) && Valid::not_empty($_POST))
{
// // validate the form
$post = Validation::factory($_POST)
->rule('firstname', 'not_empty')
->rule('lastname', 'not_empty')
->rule('address', 'not_empty')
->rule('phone', 'not_empty')
->rule('city', 'not_empty')
->rule('state', 'not_empty')
->rule('zip', 'not_empty')
->rule('country', 'not_empty')
->rule('primary_email_address', 'email');
// if the form is valid and the username and password matches
if ($post->check())
{
if($profile->create_profile($_POST))
{
$sent = kohana::message('profile', 'profile_created');
}
} else {
// validation failed, collect the errors
$errors = $post->errors('address');
}
}
// display
$this->template->title = 'Create new address';
$this->template->content = View::factory('address/create')
->bind('post', $post)
->bind('errors', $errors)
->bind('sent', $sent);
}
It seems to be ok, but the router account/address/create is not working. Kohana throws 404 message for that URI.
Anyone knows why it happens?
I checked your route on my system and it works fine, so I assume the error is somewhere else.
Check if your controller class name is Controller_Address
, also try to place this route as the first one in the bootstrap, as the docs say:
it is important to understand that routes are matched in the order they are added, and as soon as a URL matches a route, routing is essentially "stopped" and the remaining routes are never tried. Because the default route matches almost anything, including an empty url, new routes must be place before it.
Another thing, not related to the question - you really should place validation inside your model. The controller is not the place for it ;)