Helpers
Helpers are reusable chunks of view-layer logic that CakePHP makes available inside every
template, so you don't hand-write the same HTML boilerplate over and over. Inside any template file you
can reach a loaded helper as a property on $this — for example $this->Html
or $this->Form — both of which are enabled for you by default.
The HtmlHelper
The HtmlHelper generates common tags — links, images, meta tags — while handling
escaping correctly, so you don't accidentally leave a template open to injecting stray markup.
<?= $this->Html->link('Home', '/') ?>
<?= $this->Html->image('logo.png', ['alt' => 'Site logo']) ?>
The first line renders <a href="/">Home</a>; the second renders an
<img> tag pointing at webroot/img/logo.png with the given alt
text, both without you writing a single angle bracket by hand.
The FormHelper: Forms Tied to an Entity
The FormHelper is where helpers really start saving you time. Instead of writing raw
<form> and <input> tags, you hand it an entity and let it build the
form around that entity's fields — including its validation state. Recall from the
Validation page that a failed save() leaves error
messages sitting on the entity via getErrors(). FormHelper reads those same
errors and displays them next to the matching field automatically, with no extra code from you.
<?= $this->Form->create($article) ?>
<?= $this->Form->control('title') ?>
<?= $this->Form->end() ?>
Form->create($article) opens a <form> tag, points it at the right URL
for adding or editing that entity, and includes a CSRF token behind the scenes.
Form->control('title') generates a labeled <input> for the
title field — and if $article->getError('title') has something to say,
it prints that message right under the input, styled as an error. Form->end() simply
closes the </form> tag.
A Full Worked Example: Creating an Article
Putting it together, a minimal add.php template for the ArticlesController::add()
action might look like this:
<h1>Add Article</h1>
<?= $this->Form->create($article) ?>
<?= $this->Form->control('title') ?>
<?= $this->Form->control('body', ['type' => 'textarea']) ?>
<?= $this->Form->control('contact_email') ?>
<?= $this->Form->button('Save Article') ?>
<?= $this->Form->end() ?>
Three Form->control() calls generate a text input for title, a
<textarea> for body (because we told it the type explicitly), and another
text input for contact_email. Submit the form with an empty title, and the same
validationDefault() rules from the previous page kick in on the server: save()
fails, the controller re-renders this template with the same $article, and the
title field now shows its error message automatically — no manual error-checking code
required in the template itself.
templates/Articles/add.php of your own project.