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 UsersController.php file
To start using Helpers, modify the users_controller.php file you created earlier.
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 (see Listing 17).
Listing 17. The Users controller
<?php
class UsersController extends AppController
public $helpers = array('Html', 'Form');
function register() {
...
|
Now that you have included your helpers, you can begin using them.
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 (see Listing 18).
Listing 18. Creating a
knownusers action
function knownusers()
{
$this->set('knownusers', $this->User->find(
'all',
array(
'fields' => array('id','username', 'first_name', 'last_name'),
'order' => 'id DESC'
)
));
}
|
This calls the built in find function on
the User model. The find function takes a
type (all, first, count, list, neighbors or threaded), and an array of parameters,
such as matching conditions (in this case, you passed all instead
of some matching conditions), an array of fields to be
returned (you don't want all of the user information—just what you
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), offset, and a recursive option (can
be specified to return data from other associated models), and a callbacks option
to determine how (or if) to use model callbacks.
The output from find is put into the
knownusers variable. The data can now be
accessed from a 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 (see Listing 19).
Listing 19. 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, shown in Figure 7.
Figure 7. The resulting array of user data
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.
When you have a big array of users, it's time to turn that into a table. Replace the contents of knownusers.ctp with the following from Listing 20.
Listing 20. Creating a table
<table>
<?php
echo $this->Html->tableHeaders(array("ID", "Username", "First Name",
"Last Name"));
foreach ($knownusers as $thisuser) {
echo $this->Html->tableCells($thisuser['User']);
}
?>
</table>
|
The first helper will create a set of table headers from an array of field names we provide. 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 (see Figure 8).
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.
Building a web application without using forms is like milking a chicken: It's extremely complicated and it seldom 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.
Listing 21. 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 22.
Listing 22. Using helpers to generate the registration form
<p>Please fill out the form below to register an account.</p>
<?php echo $this->Form->create('User');?>
<?php
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('password');
?>
<?php echo $this->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
Open the User model and add a little data validation (covered in detail later). For now, modify model to look like the one in Listing 23.
Listing 23. Updating the users controller
<?php
class User extends AppModel {
public $validate = array (
'username' => array (
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.'
),
'password' => array (
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.'
),
'email' => array(
'rule' => 'email',
'message' => 'Please supply a valid email address.'
)
);
}
|
To break this down briefly, the $validate
array contains entries for validation. The entries consist of a key (the form
field name) and an array of parameters used to evaluate the data—the rule
to be invoked, and the message to be displayed when the rule is violated. It is
not necessary to validate all of the form fields. In Listing 23, the
last_name and first_name fields were left optional.
CakePHP comes with several predefined regular expressions for data validation. The
notEmpty rule is used just to make sure
the field is not empty, while the email rule is used
to verify that a string looks more or less like an email address. There are many other predefined validation rules available.
Now take your form for a spin. Try submitting the form with no data, with one or two required fields empty, with an invalid email address (see Figure 9). What do you see?
Figure 9. Data validation first try
Now try the form a second time with different missing data (see Figure 10).
Figure 10. Data validation second try
Notice that the CakePHP toggles your error messages for you on the fly. Also notice that CakePHP remembers and populates 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.
This tutorial barely scratches the surface of helpers. A whole tutorial could be written on the subject. Learning to use helpers well to 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.




