CakePHP

Page 99

09775ch06final

7/1/08

9:44 PM

Page 77

CHAPTER 6 ■ CUSTOMIZING VIEWS

In the $this->data['Tag']['Tag'] array, each selected item’s ID is placed as a separate element in the array, since the Tag model is associated with the Post model as a “has and belongs to many” relationship. User form submissions can get more complex quickly. Also in the posts’ Add action is a datetime field. Working with dates and times can be rather cumbersome; differentiating between months, days, minutes, and hours can be a nightmare considering each has a specific set of numbers by which it may be represented (for example, one month may have 30 days, another may have 31, and February changes between 28 and 29 days every four years). When used in conjunction with the Form helper, $this->data can dramatically shave off code for dealing with dates and times. When done correctly in the view with the Form helper, Cake parses a form containing dates and times for the $this->data array like so: Array ( [Post] => Array ( [date] => Array ( [month] => 07 [day] => 04 [year] => 2008 [hour] => 12 [min] => 00 [meridian] => pm ) ) ) Whether in the view or the controller, you can pull user-submitted data from $this->data like any PHP array. For example, checking for the year can easily be done by examining the $this->data['Post']['date']['year'] value. Or, you can fetch the meridian by calling the $this->data['Post']['date']['meridian'] value. Dates and times in Cake are all the more attractive when considering that in the view all the necessary date and time fields are supplied with a single line: <?=$form->input('date');?> Back in line 2 of Listing 6-3, the Add action checks for a user submission by looking at the $this->data array: if it is empty, then the user has not submitted anything; if not, a form has been submitted, and the action must handle the data. Lines 3–6 in Listing 6-3 save the data to the database, provided a test of $this->data has passed successfully. The rest of the action behaves like a simple page request. If no data has been supplied, the action pulls some associated data from the Tag and User models and passes it along to the view.

Saving Forms When $this->data is formatted according to Cake’s conventions (which is mostly managed by implementing the Form helper in the view), saving data is easy. Cake performs saves through the use of the create() and save() model functions.

77


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.