cakephp

Validating empty fields

Validating an optional field is a snap with CakePHP’s allowEmpty. But what if the field is only optional sometimes and under certain circumstances? A custom validation method, right? Well, actually no. See, if a field is optional (or, more accurately, ‘allowEmpty’ => true) then CakePHP will ignore any validation method, custom or otherwise. As it […]

Creating a custom validation method

CakePHP offers a lot of handy built-in validation methods for common field types, such as email addresses, dates, even credit card numbers. If you can’t find what you need among these methods and your needs are pretty straightforward, you can write a custom regular expression. If your needs are a little more complicated, you can […]

Validation on optional fields

CakePHP’s allowEmpty option makes performing validation on optional fields remarkably simple, even ones with multiple validation rules. Let’s assume we want to collect a user’s zip code. We configure an entry in our model’s $validate array, taking advantage of CakePHP’s built-in numeric validation: public $validate = array( ‘zip’ => array( ‘rule’ => ‘numeric’, ‘message’ => […]

using a helper to wrap injected markup

CakePHP’s FormHelper comes with several, intuitively-named options for injecting markup into a form element. The option I use most frequently is “after”, a very simple way to append an explanatory note after a particular form element. For example, as part of my “Venues” view let’s assume I have an input field for a phone number […]

Reading and writing to association tables in CakePHP

When two models have a HABTM relationship (resisting the urge to make a joke) there is necessarily a shared association table. But what if we want to store more information in that table? While, for example, an association table between Events and Waiters (with Events HABTM Waiters) would be very useful, it would be even […]

Finding the Base URL in CakePHP

If you need the base url in a view, use this: <?php echo $this->webroot; ?> If you need the base url in a controller, use this: Router::url(‘/’, true);

Using “OR” conditions in CakePHP

Qualifying a query in CakePHP is as simple as adding conditions to the conveniently-named “conditions” array, like so: // return array of all musicians $all = $this->Musician->find(‘all’); // return array of all available reed players $only_available_reeds = $this->Musician->find(‘all’, array( ‘conditions’ => array( ‘category’ => ‘reeds’, ‘status’ => ‘available’ ) )); If the array contains multiple […]