In my app I need to implement a functionality where in if the controller name and/or action name in the URL are wrong (i.e. misspelled and hence not found) or missing altogether then I should be able to show a custom 404 page.
For ex:
CORRECT: https://my-app/correct-controller-name/correct-action-name
WRONG: https://my-app/wrong-controller-name/wrong-action-name : I should be able to show custom 404 page.
WRONG: https://my-app/correct-controller-name/ : Here action name is missing altogether and I should be able to show a custom 404 page.
I have tried various permutations and combinations in my code based on the solutions I found on the Web but I am getting an "Phalcon\DI\Exception: Service 'view' was not found in the dependency injection container" error everytime and 404 page is not showing up.
Any help would be greatly appreciated. Thank you.
Code below:
class ControllerBase extends \Phalcon\Mvc\Controller
{
public $breadcrumb;
public $show_breadcrumb = 1;
public function indexAction()
{
$id = (int)$this->getId($param);
if ($id > 0) {
// do you stuff
} else {
$this->dispatcher->forward(array(
'controller' => 'error', 'action' => 'show404')
);
}
}
}
---------------------------------------
//Set 404 paths
$router->notFound(array(
"controller" => "error",
"action" => "show404"
));
/**
* Backend routes
*/
//echo "<pre>";print_r($router);
return $router;
---------------------------------------
class ErrorController extends \Phalcon\Mvc\Controller
{
public function initialize()
{
global $config;
$this->config = $config;
}
public function indexAction()
{
echo 'Sorry';exit;
}
public function show404Action()
{
$this->view->setLayout("forms");
Tag::setTitle('404');
$this->view->setVar("config", $this->config);
}
}
------------------------------------------
$di->set(
'dispatcher',
function() use ($di) {
$eventsManager = $di->getShared('eventsManager');
$eventsManager->attach(
'dispatch:beforeException',
function($event, $dispatcher, $exception) {
switch ($exception->getCode()) {
case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'show404',
)
);
return false;
break; // for checkstyle
default:
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'uncaughtException',
)
);
return false;
break; // for checkstyle
}
//if ($exception instanceof \Phalcon\Mvc\Dispatcher\Exception) {
/*if ($exception) {
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'show404',
)
);
return false;
}*/
}
);
$dispatcher = new Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
},
true
);