on Basics Tutorials

CakePHP from scratch: Reviewing and changing baked code to fit our needs

3 comments
logo
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

If you did not follow previous tutorials in the CakePHP from scratch series, you can download what we did the last time from here. Just extract the files wherever is your www or htdocs directory.

So, let us see what did our Baking from last time produced. Open up your /app/models/category.php file. CakePHP left us some commented stuff in there, so you can easily understand what to do. We are going to change just a validation message here, so uncomment that line and change your validation criteria to this:

var $validate = array(
		'name' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'The name field can not be empty',
			),
		),
	);

OK that’s it for this model, open /app/models/job.php and just change its validation to this:

var $validate = array(
		'category_id' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
			),
		),
		'user_id' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
			),
		),
		'title' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Title field can not be empty'
			),
		),
		'body' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Body is required field'
			),
		),
		'company' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Company is required field'
			),
		),
		'job_type' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'You must choose job type!'
			),
		),
	);

I will not explain much, as it is quite self explaining. You can test these settings in you application, just try to add new job without writing anything in the fields and CakePHP will return your custom messages below each field.

Now, open /app/models/user.php and change its validation to this:

var $validate = array(
		'username' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Username is required field',
			),
		),
		'pass' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Password is required field',
			),
            'between' => array(
                'rule' => array('between', 5, 15),
                'message' => 'Password must be between 5 to 15 characters'
            )
		),
		'name' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Name is required field',
			),
		),
		'email' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Email is required field',
			),
            'email' => array(
                'rule' => array('email', true),
                'message' => 'Please enter a valid email address'
            )

		),
	);

Here we added some more validation to password and email fields. Interesting part is email validation. This checks whether the data is a valid email address. Passing a boolean true as the second parameter for this rule will also attempt to verify that the host for the address is valid. Fancy and awesome.

We will do some more stuff in user model. If you tested the app, you can see that our password field is plain text input. Let us change that. Open /app/views/users/add.php and change your form to this:

echo $this->Form->input('username');
echo $this->Form->input('pass', array('type' => 'password'));
echo $this->Form->input('pass2', array('type' => 'password', 'label' => 'Repeat password'));
echo $this->Form->input('name');
echo $this->Form->input('location');
echo $this->Form->input('address');
echo $this->Form->input('email');
echo $this->Form->input('web');

We added type to pass field and we added a whole new field: Repeat password. This is a common field you see on most sites and its purpose is to prevent users from making a typing error.

We must add this functionality to our app. Open /app/models/user.php and add this rule:

        'pass2' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Repeat password is required field',
            ),
            'custom' => array(
                'rule' => array('CheckPasswordMatch'),
                'message' => 'Passwords did not match',
            ),
        ),

We are checking that the field is not empty. And adding a custom rule. For this custom rule to work, we will add a function directly above association rules in our user model:

function CheckPasswordMatch($data) {
    return $this->data['User']['pass'] == $this->data['User']['pass2'];
}

This function simply checks if the passwords match, returning true or false. $this->data contains all posted data.

There is one more thing I want to show you today. That is routing. By default, CakePHP responds to a request for the root of your site (i.e. http://www.example.com) using its PagesController, rendering a view called “home”. Instead, we’ll replace this with our JobsController by creating a routing rule.

Cake’s routing is found in /app/config/routes.php. You’ll want to comment out or remove the line that defines the default root route. It looks like this:

Router::connect ('/', array('controller'=>'pages', 'action'=>'display', 'home'));

And add this:

Router::connect ('/', array('controller'=>'jobs', 'action'=>'index'));

This will connect users requesting ‘/’ to the index() action of our JobsController. Point your browser to http://localhost/cake (or wherever you have your application) and you will see that it works awesomely.

This is it for today, stay tuned as next time we will check out layouts and how to change them, styling and other interesting stuff.

Make sure your read our previous tutorials in CakePHP series:

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Mike

    Nice one, as usual. I have a question though.

    Is there a way to add dependent validation rules?

    For example, if user enters an Address, then he must also enter an location.

    • Zvonko

      @Mike, yes you can add dependent rules.

      What you must do is add custom rule to your location field, which will call custom validation function (like we did in the CheckPasswordMatch above) .

      Then you write the function that if Address is empty, it always return true, and if not, it returns true only if Location field is also not empty.

      • Mike

        Well, I should have figured out that myself.

        Thanks for explanation. 🙂