Some notes on using validation in a CakePHP model.

Written by James McDonald

November 10, 2011

Warning: Take all this with a grain of salt. Musing only here.

PHP Nested Arrays – Scratch Scratch
A potentially confusing thing, and the power in CakePHP is the frequent use of nested arrays. Because IANAP (I am not a programmer) it’s taken some time to begin to understand what goes where. Apparently CakePHP uses arrays for configuration and data passing between Model, View and Controllers.

CakePHP Models
Here are some notes on using validation in a CakePHP model.

A CakePHP model is an abstraction between your database and your CakePHP application. As far as I understand it a model allows you to query and insert pre-validated data into a database without having to write much of your own SQL and it presents the data in an easy to use key based array. e.g.:


# how cake php presents database records
# taken from the streets database table
# which has only two fields
# id which is a primary key, auto incrementing int(11)
# name which is a varchar(50) field


Array # A multi-dimensional nameless array
(
    # then numerically indexed (Numeric) array
    [0] => Array 
        ( # then a nested associative (Named) array
            [Street] => Array # model name
                (
                    [id] => 1 # field name and value
                    [name] => Apple  # field name and value
                )

        )

    [1] => Array
        (
            [Street] => Array
                (
                    [id] => 3
                    [name] => Jolie
                )

        )

    [2] => Array
        (
            [Street] => Array
                (
                    [id] => 4
                    [name] => Pitt
                )

        )
)

From there you can use the model name and a key to view and access data in your controller and views (see MVC).

Accessing Model data in controller and views
.e.g.
Inside a controller you can access your model thusly:

$this->Street['name'] 

where $this refers your controller class (located in dbtablename_controller.php i.e. streets_controller.php), Street is your model and ‘name’ is your database field.

Inside a controllers action method (e.g. function index(){} or function add(){}) the model data array is assigned to a variable in a view (you know your *.ctp files) using set():

$this->set('street', $this->Street->read(null, $id));

and then in the view you can iterate through using foreach:

foreach ($streets as $street) {
    echo  $street['name'] . '
'; }

Logging
Use $this->log() to write data to the cakePHP error.log logfile. Log files are located in tmp/logs look for the webroot folder tmp will be on the same level as it.
e.g. in the controller:
$this->log($this->paginate()); # pass the data from the model to log()

Ramblings inside a code snippet

class Street extends AppModel {
	var $name = 'Street'; 
        # this is the model name
        # it maps to a database table named 'streets'
	var $validate = array( 
                # the $validate array holds an array of database field names
                # the field name in turn holds an array of rules
                # here we only have one database field 'name'
		'name' => array( # 'name' is my database field name
                        # there are two validation rules for the 'name' db field
                        # 'notempty' and 'unique' 
                        # 'notempty' array key can be any arbitrary name to hold a rule
			'notempty' => array( 
                                # I tried 'rule' => array('notempty', 'isUnique'), but no joy
				'rule' => array('notempty'), # 'rule' has many options
				'message' => 'You must enter a street name',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
                        # 'unique' array key is arbitrary, however 'rule' and 'message' are not
			'unique' => array(
				'rule'=> array('isUnique'),
				'message' => 'Street name already exists',
			),
		),
	);

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…