dmertl.com

validation

Custom Errors in CakePHP

March 29, 2010 by dmertl Leave a Comment

I like CakePHP’s error validation quite a lot. I use it in nearly every case because it’s easy and it works. There are times when the standard error validation scheme does not work. Like when you have a field that you want to validate manually in the controller, but still use CakePHP’s error display method. There is no method to simply inject an error into the existing validation system. After a bit of searching I finally found where the error messages are being stored. The error messages are stored on the model instance in the controller, such as $this->User->validationErrors. When the controller renders the view it copies each model’s validationErrors into the view. To add your error it’s as simple as adding another item to that array that matches your field.

For registration that requires a promotional code:

<?php echo $form->input('promo'); ?>

Then after checking the promo code you can set an error message like this:

$this->User->validationErrors['promo'] = 'Invalid promo code';

The promo code isn’t really part of our User model, it’s only used during registration. However, as far as I see you must have the field associated with a model to add that error message. I suppose an alternate option would be to make a Promo model and associate that with your controller, but that seems like too much work.

Posted in: CakePHP Tagged: CakePHP, errors, validation

Blogroll

  • Antarctica
  • Non-coding stuff
  • Photos
  • Rainbows

Recent Posts

  • Resizing optimized animated GIFs in Photoshop
  • Saving an animated GIF in Photoshop with “combine” instead of “replace” frames
  • Mimicking Django Admin Change Form Styling in a Custom Form
  • Installing custom Plex plugins on a Drobo 5N
  • Bug in CakePHP Containable Behavior, Related Records not Being Returned When Parent Contains a Single Field

Categories

  • CakePHP
  • Canon
  • Django
  • Doctrine
  • iPhone
  • mac
  • Magento
  • MS Access
  • MSSQL
  • Photography
  • Python
  • SQL
  • Uncategorized
  • Zend

Tags

@@IDENTITY adapter authentication breadcrumbs CakePHP Canon cocoa Doctrine email eos utility errors iPhone leopard lost cd mac Magento MS Access MS SQL mysql mysqli nosuchtable os x override parse pdo_mysql.php php programming raw redirect smtp SQL sqlite SQL Server triggers updater validation xcode Zend zend_mail_message

Copyright © 2021 dmertl.com.

Omega WordPress Theme by ThemeHall