Cakephp custom error page for all errors - cakephp

I have this created:
<?php
class AppExceptionHandler
{
public static function handle($error)
{
$this->controller->redirect('www.google.com');
//echo 'Oh noes! ' . $error->getMessage();
// ...
}
// ...
}
?>
The echo will output fine but how do I use a layout or view? I keep getting this erro:
Fatal error: Using $this when not in object context in ...

Try to add the following method in you AppController.php
public function appError($error) {
//Do whatever you want
debug($error);
}

Related

Declaration of validationDefault in Cakephp 4.0

I'm trying to create a site with CakePHP 4.0, but can't get the validation rules to work. I read the documentation, but wasn't sure where I was supposed to put the validationDefault function. I've put it in UsersTable.php, which looks like this:
<?php
namespace App\Model\Table;
use App\Model\Entity\User;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Rule\IsUnique;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table {
public function initialize(array $config): void {
$this->addBehavior('Timestamp');
$this->hasMany('Requests')
->setDependent(true);
$this->hasMany('Offers')
->setDependent(true);
}
public function validationDefault(Validator $validator) {
$validator->notEmptyString('email', 'Please enter your email address')
->notEmptyString('name', 'Please enter a name');
return $validator;
}
}
?>
So I'm expecting that if a user tries to sign in without an email or name, it should throw an error.
The form I have for registration is:
echo $this->Form->create();
echo $this->Form->control('name');
echo $this->Form->control('email');
echo $this->Form->control('password', array('type' => 'password'));
echo $this->Form->control('confirm_password', array('type' => 'password'));
echo $this->Form->button('Register');
echo $this->Form->end();
and that sends the data to UsersController.php, which contains:
public function login() {
// Otherwise, we're registering
$users = TableRegistry::getTableLocator()->get('Users');
$user = $users->newEntity($this->request->getData());
if ($users->save($user)) {
$result = $this->Authentication->getResult();
if ($result->isValid()) {
$target = '/users/home';
return $this->redirect($target);
}
}else {
$this->Flash->error('Please fix errors below');
}
exit;
}
}
}
When I try to register without entering a name and email, I get the following error message:
Fatal error: Declaration of App\Model\Table\UsersTable::validationDefault(Cake\Validation\Validator $validator) must be compatible with Cake\ORM\Table::validationDefault(Cake\Validation\Validator $validator): Cake\Validation\Validator in /Applications/MAMP/htdocs/src/Model/Table/UsersTable.php on line 26
I can't see any obvious problems with my code. Where am I going wrong?
The declaration of the validationDefault function in Cake is:
public function validationDefault(Validator $validator): Validator
Your declaration is just
public function validationDefault(Validator $validator)
You need to add the return type declaration at the end in order to match. The docs don't seem to mention that, you might want to raise an issue on that.

CakePHP 'autoRender = false' does not working. Still gives missing view error

I am using cakephp 2.0.4 (Doing Changes in existing project)
My controller function is..
class PagesController extends AppController {
public function getlocations($string = ''){
$this->autoRender = false;
$aResult = array(0=>'Florida', 1=>'London');
echo json_encode($aResult);
}
}
And also I have try $this->autoLayout = $this->autoRender = false;
When I am calling this action directly in browser mysite/app/pages/getlocations it will give following error
View file "/home/mysite/public_html/testing/app/View/Pages/g.ctp" is missing.
Create a /View/Ajax/json.ctp view:
<?php
if(!empty($data)) echo json_encode($data);
Then in the action:
$this->set('data', array(0=>'Florida', 1=>'London'));
$this->layout = false;
$this->render('/Ajax/json');
You could also make it work following the Cake way.
First you have to add the following code to your routes file:
Router::parseExtensions('json');
Next, in the controller add the 'RequestHandler' to your components array and serialize your result in your getlocations function:
public $components = array('RequestHandler');
public function getlocations($string = ''){
$this->set('aResult', array(0=>'Florida', 1=>'London'));
$this->set('_serialize', 'aResult');
}
Finally, you can see the results in your browser mysite/app/pages/getlocations.json
Doing this way CakePHP will add the application/json headers automatically.
More info: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

Set page title when handling errors in CakePHP

I need to change page title from default "Error" when handling errors like 404. So I need to put my the title in the variable $title_for_layout for my Layout. I tried to create custom error handling function by changing configuration in app/Config/core.php and setting the page title as in controllers
Configure::write('Error.handler', function($code, $description, $file = null, $line = null, $context = null) {
$this->set('title_for_layout', 'Vyskytla sa chyba');
});
As I expected, I got a PHP error (line 59 is the second line in the code sample)
Fatal error: Using $this when not in object context in /var/www/web/app/Config/core.php on line 59
So how I can set the title for my default.ctp layout?
Thanks.
In CakePHP 2.0, you can try the following code to achieve the same you needed.
Try this:
/app/Config/core.php
Exception render need to set as an AppExceptionRender. Example:
Configure::write('Exception', array(
'handler' => 'ErrorHandler::handleException',
'renderer' => 'AppExceptionRenderer',
'log' => true
));
/app/Controller/ErrorsController.php
class ErrorsController extends AppController {
public $name = 'Errors';
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('error404');
}
public function error404() {
//$this->layout = 'default';
$this->set('title_for_layout', 'Vyskytla sa chyba');
}
}
/app/Lib/Error/AppExceptionRenderer.php
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer {
public function notFound($error) {
$this->controller->redirect(array('controller' => 'errors', 'action' => 'error404'));
}
}
/app/View/Errors/error404.ctp
<div class="inner404">
<h2>404 Error - Page Not Found</h2>
</div>
Insert it where you need: throw new NotFoundException();
Ref: CakePHP 2.0 - How to make custom error pages?
For < CakePHP 2.x:
If you create a custome error page view in app/views/errors then in a
php section on that error view page you can use:
$this->setLayout("Title for the error page here");
Then when you see the error page, it will have your title. Again, that
is if you set a custom error page.
Here is another way to do the same you needed.
// Create an error.php file in your /app folder with the following code:
<?php
class AppError extends ErrorHandler {
function error404($params) {
$this->controller->layout = "error";
$this->set('title_for_layout', 'Vyskytla sa chyba');
parent::error404($params);
}
}
?>

CakePHP - Cannot redeclare class

I have a simple class that I've added to the components folder called mixpanel.php. Within the file is:
<?php
class MetricsTracker {
public $token;
public $host = 'http://api.mixpanel.com/';
public function __construct($token_string) {
$this->token = $token_string;
}
function track($event, $properties=array()) {
$params = array(
'event' => $event,
'properties' => $properties
);
if (!isset($params['properties']['token'])){
$params['properties']['token'] = $this->token;
}
$url = $this->host . 'track/?data=' . base64_encode(json_encode($params));
//you still need to run as a background process
exec("curl '" . $url . "' >/dev/null 2>&1 &");
}
}
?>
In users_controller.php I do:
require 'components/mixpanel.php';
however I'm getting an error:
Fatal error: Cannot redeclare class MetricsTracker in /Users/Hooman/Sites/askedout/app/controllers/components/mixpanel.php on line 11
Why is this happening? I do the same thing with a different php class and it works fine. This is very odd to me as I am not repeating the require definition anywhere. Please help, thanks.
In your component code, please change the code from
class MetricsTracker to
class MetricsTracker extends Object
In your controller code , please add the following code :
var $components=array('MetricsTracker');
instead of using require() function

Validation doesn't working in cakephp2.x

I am new in cakephp. I wrote a validation ctpfile in cakephp 2.6.7 for viewing login and logout word but the validation doesn't work.
My code is:-
<?php
if (!$authUser) {
echo $this->element('logout-header');
} else {
echo $this->element('login-header');
}
?>
How can I write validation in ctp file for viewing login and logout word in my page header?
Why you wrote a validation ctp? put your validation rules in model
http://book.cakephp.org/2.0/en/models/data-validation.html
In your AppController's beforeRender() callback set the authUser view variable by retrieving the logged in user:-
public function beforeRender() {
parent::beforeRender();
$this->set('authUser', $this->Auth->user());
}
Then the view code in your question should work as expected.
I have a solution, which I regularly use when I worked in cakephp.
in AppController.php
class AppController extends Controller{
public function beforeFilter() {
parent::beforeFilter();
$userInfo = array();
if($this->Auth->user('_id')){
$userInfo['User'] = $this->Auth->user();
Configure::write($userInfo);
}
}
}
And after this in view .ctp file
<?php
$authUser = Configure::read('User');
if (!$authUser) {
echo $this->element('logout-header');
} else {
echo $this->element('login-header');
}
?>

Resources