Helpers
Helpers in CakePHP exist primarily to help speed up the development of
your views. There are helpers for HTML, Ajax, JavaScript and more.
Helpers make it easier to insert pieces of HTML code you find yourself
writing multiple times.
Modifying the
users_controller.php file
To start using Helpers, you will need to modify the
users_controller.php file you created earlier. You should give the
controller a name and tell it that you want to use some helpers — in
this case, the HTML and Form helpers. Edit the file to add the
$name and $helpers class variables.
Listing 14. The users controller
<?php
class UsersController extends AppController
{
var $name = 'Users';
var $helpers = array('Html', 'Form' );
function register()
{
...
|
Now that you have included your helpers, you can begin using them.
Making tables easier
Users of Tor should be able to see who else is registered to use the
application. CakePHP has a number of helpers in place to assist with
creating tables. These helpers include many useful bits of
functionality, some of which you have probably written more than once.
To demonstrate this, you will create a view to display
registered users.
Start by creating a knownusers action in the
users controller.
Listing 15. Creating a knownusers action
function knownusers()
{
$this->set('knownusers',
$this->User->findAll(null, array('id', 'username', 'first_name',
'last_name'), 'id DESC')
);
}
|
This calls the built in findAll function on
the user model. The findAll function takes
a field containing conditions (in this case, you passed null
conditions, which will return all all users), an array of fields to be
returned (we don't want all of the user information — just what you
would want everyone to see), and a sort field and order (in this case,
id DESC to sort the fields in descending
order by ID). You can also specify a limit (maximum rows to return),
page (if you are paging the data), and a recursive option, which can
be specified to return models associated with the data (for example,
if you were querying a groups table and several users belong to each
group).
The output from findAll is put into the
knownusers variable. The data can now be
accessed from a view.
Creating the
knownusers view
Create the file app/views/users/knownusers.ctp in a text editor. To see
what the data returned by findAll looks
like, output the knownusers variable using
var_dump.
Listing 16. Output the knownusers variable using var_dump
<pre>
<?php var_dump($knownusers) ?>
</pre>
|
Visit the view at http://localhost/users/knownusers. You should see an
array of user data.
Figure 7. The results
If you only have one user listed, go back to
http://localhost/users/register and register a few more. The end
result will be more impressive.
Got a nice big array of users? Good! Time to turn that into a table.
Replace the contents of knownusers.thtml with the following.
Listing 17. Creating a table
<table>
<?php
echo $html->tableHeaders(array_keys($knownusers[0]['User']));
foreach ($knownusers as $thisuser)
{
echo $html->tableCells($thisuser['User']);
}
?>
</table>
|
The first helper will create a set of table headers from an array of
data — in this case, the list of keys for our users. The second helper will create a set of table cells, wrapped in table
row tags, from an array of data — in this case, the values for each
user.
That's it! Save it, then visit http://localhost/users/knownusers to see
the results.
Figure 8. The results
By using the tableCells helper, you have
eliminated the need to write your own code to iterate through the
array of user data. This is just one example of how to use helpers to
make it easier to work with HTML in CakePHP.
Form generation
Building a Web application without using forms is like milking a
chicken: It's extremely complicated and rarely works. Well-built and
maintainable forms are a foundation to any well-built application.
Given how often you will need to build forms, it only seems natural to
look for ways to make the process easier without cutting corners.
Using helpers in the
registration form
Helpers are especially useful when generating forms. You can use them
to generate the HTML for your input fields, as well as placeholders to
hold validation error messages. Using helpers to generate the form
fields and error message holders for Tor, the register view might look
more like Listing 18.
Listing 18. Using helpers to generate the registration form
<p>Please fill out the form below to register an account.</p>
<?php echo $form->create('User', array('action' => 'register'));?>
<?php
echo $form->input('first_name');
echo $form->input('last_name');
echo $form->input('username');
echo $form->input('email');
echo $form->input('password');
?>
<?php echo $form->end('Register');?>
|
As you can see, making use of CakePHP's helpers can save you quite a
bit of code when writing basic form elements. Now let's look to make
even more use of your helpers.
Making the most of your
helpers
To start getting more payoff from your helpers, you'll need to do two
things: update your users controller and introduce a little data
validation. Open controllers/users_controller.php and change your register function
to match the one in Listing 19.
Listing 19. Updating the users controller
function register()
{
if (!empty($this->data))
{
if ($this->User->save($this->data))
{
$this->Session->setFlash('Your registration information was accepted.');
}
}
}
|
Note that the occurrences of
$this->params['form'] have changed
to $this->data.
Now open the user model and add a little data validation (covered in
detail later). For now, modify your user model to look like the one in
Listing 20.
Listing 20. Modifying your user model
<?php
class User extends AppModel
{
var $name = 'User';
var $validate = array(
'username' => VALID_NOT_EMPTY,
'password' => VALID_NOT_EMPTY,
'email' => VALID_EMAIL
);
}
?>
|
To break this down briefly, the $validate
array contains entries for validation, consisting of a key (the form
field name) and a regular expression used to evaluate the data. It is
not necessary to validate all of the form fields. In Listing 20,
last_name and first_name were left optional. CakePHP comes with
several predefined regular expressions for data validation.
VALID_NOT_EMPTY is used just to make sure
the field is not empty. VALID_EMAIL is used
to verify that a string looks more or less like an e-mail address.
Now take it for a spin. Try submitting the form with no data, with one
or two required fields empty, with an invalid e-mail address. What do
you see?
Figure 9. Data validation first
try
Now try it a second time with different missing data.
Figure 10. Data validation second
try
One thing you should notice is that the CakePHP is turning on and
turning off your error messages for you on the fly. Another thing you
should notice is that CakePHP is remembering and populating the values
for the form fields, without you having to do anything.
That's where the big payoff comes in. What didn't you have to do? For one thing, you didn't have to tell the form fields to repopulate
their information from the _POST array.
CakePHP did that for you. You didn't have to check each field for an
error and conditionally display each message individually. CakePHP did
that for you. You didn't have to make sure you formatted your tags
into valid xhtml. CakePHP did that for you, too.
Helper notes
This tutorial barely scratches the surface of helpers. A whole tutorial
could be written on the subject. Learning how to use helpers well will
go a long way toward helping speed up your development in CakePHP.
CakePHP includes helpers for Ajax (using prototype.js), JavaScript,
number conversion, text handling, dates, times, and more. Review the
manual (see Resources) to get more
familiar with some of these helpers.
|