cake/libs/view/helpers/form.php

1 <?php
2 /**
3 * Automatic generation of HTML FORMs from given data.
4 *
5 * Used for scaffolding.
6 *
7 * PHP versions 4 and 5
8 *
9 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
10 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
11 *
12 * Licensed under The MIT License
13 * Redistributions of files must retain the above copyright notice.
14 *
15 * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
16 * @link http://cakephp.org CakePHP(tm) Project
17 * @package cake
18 * @subpackage cake.cake.libs.view.helpers
19 * @since CakePHP(tm) v 0.10.0.1076
20 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
21 */
22  
23 /**
24 * Form helper library.
25 *
26 * Automatic generation of HTML FORMs from given data.
27 *
28 * @package cake
29 * @subpackage cake.cake.libs.view.helpers
30 * @link http://book.cakephp.org/view/1383/Form
31 */
32 class FormHelper extends AppHelper {
33  
34 /**
35 * Other helpers used by FormHelper
36 *
37 * @var array
38 * @access public
39 */
40 var $helpers = array('Html');
41  
42 /**
43 * Holds the fields array('field_name' => array('type'=> 'string', 'length'=> 100),
44 * primaryKey and validates array('field_name')
45 *
46 * @access public
47 */
48 var $fieldset = array();
49  
50 /**
51 * Options used by DateTime fields
52 *
53 * @var array
54 */
55 var $__options = array(
56 'day' => array(), 'minute' => array(), 'hour' => array(),
57 'month' => array(), 'year' => array(), 'meridian' => array()
58 );
59  
60 /**
61 * List of fields created, used with secure forms.
62 *
63 * @var array
64 * @access public
65 */
66 var $fields = array();
67  
68 /**
69 * Defines the type of form being created. Set by FormHelper::create().
70 *
71 * @var string
72 * @access public
73 */
74 var $requestType = null;
75  
76 /**
77 * The default model being used for the current form.
78 *
79 * @var string
80 * @access public
81 */
82 var $defaultModel = null;
83  
84  
85 /**
86 * Persistent default options used by input(). Set by FormHelper::create().
87 *
88 * @var array
89 * @access protected
90 */
91 var $_inputDefaults = array();
92  
93 /**
94 * Introspects model information and extracts information related
95 * to validation, field length and field type. Appends information into
96 * $this->fieldset.
97 *
98 * @return Model Returns a model instance
99 * @access protected
100 */
101 function &_introspectModel($model) {
102 $object = null;
103 if (is_string($model) && strpos($model, '.') !== false) {
104 $path = explode('.', $model);
105 $model = end($path);
106 }
107  
108 if (ClassRegistry::isKeySet($model)) {
109 $object =& ClassRegistry::getObject($model);
110 }
111  
112 if (!empty($object)) {
113 $fields = $object->schema();
114 foreach ($fields as $key => $value) {
115 unset($fields[$key]);
116 $fields[$key] = $value;
117 }
118  
119 if (!empty($object->hasAndBelongsToMany)) {
120 foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
121 $fields[$alias] = array('type' => 'multiple');
122 }
123 }
124 $validates = array();
125 if (!empty($object->validate)) {
126 foreach ($object->validate as $validateField => $validateProperties) {
127 if ($this->_isRequiredField($validateProperties)) {
128 $validates[] = $validateField;
129 }
130 }
131 }
132 $defaults = array('fields' => array(), 'key' => 'id', 'validates' => array());
133 $key = $object->primaryKey;
134 $this->fieldset[$model] = array_merge($defaults, compact('fields', 'key', 'validates'));
135 }
136  
137 return $object;
138 }
139  
140 /**
141 * Returns if a field is required to be filled based on validation properties from the validating object
142 *
143 * @return boolean true if field is required to be filled, false otherwise
144 * @access protected
145 */
146 function _isRequiredField($validateProperties) {
147 $required = false;
148 if (is_array($validateProperties)) {
149  
150 $dims = Set::countDim($validateProperties);
151 if ($dims == 1 || ($dims == 2 && isset($validateProperties['rule']))) {
152 $validateProperties = array($validateProperties);
153 }
154  
155 foreach ($validateProperties as $rule => $validateProp) {
156 if (isset($validateProp['allowEmpty']) && $validateProp['allowEmpty'] === true) {
157 return false;
158 }
159 $rule = isset($validateProp['rule']) ? $validateProp['rule'] : false;
160 $required = $rule || empty($validateProp);
161 if ($required) {
162 break;
163 }
164 }
165 }
166 return $required;
167 }
168  
169 /**
170 * Returns an HTML FORM element.
171 *
172 * ### Options:
173 *
174 * - `type` Form method defaults to POST
175 * - `action` The Action the form submits to. Can be a string or array,
176 * - `url` The url the form submits to. Can be a string or a url array,
177 * - `default` Allows for the creation of Ajax forms.
178 * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
179 * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
180 * be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
181 * can be overridden when calling input()
182 * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
183 *
184 * @access public
185 * @param string $model The model object which the form is being defined for
186 * @param array $options An array of html attributes and options.
187 * @return string An formatted opening FORM tag.
188 * @link http://book.cakephp.org/view/1384/Creating-Forms
189 */
190 function create($model = null, $options = array()) {
191 $created = $id = false;
192 $append = '';
193 $view =& ClassRegistry::getObject('view');
194  
195 if (is_array($model) && empty($options)) {
196 $options = $model;
197 $model = null;
198 }
199 if (empty($model) && $model !== false && !empty($this->params['models'])) {
200 $model = $this->params['models'][0];
201 $this->defaultModel = $this->params['models'][0];
202 } elseif (empty($model) && empty($this->params['models'])) {
203 $model = false;
204 }
205  
206 $models = ClassRegistry::keys();
207 foreach ($models as $currentModel) {
208 if (ClassRegistry::isKeySet($currentModel)) {
209 $currentObject =& ClassRegistry::getObject($currentModel);
210 if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
211 $this->validationErrors[Inflector::camelize($currentModel)] =& $currentObject->validationErrors;
212 }
213 }
214 }
215  
216 $object = $this->_introspectModel($model);
217 $this->setEntity($model . '.', true);
218  
219 $modelEntity = $this->model();
220 if (isset($this->fieldset[$modelEntity]['key'])) {
221 $data = $this->fieldset[$modelEntity];
222 $recordExists = (
223 isset($this->data[$model]) &&
224 !empty($this->data[$model][$data['key']])
225 );
226  
227 if ($recordExists) {
228 $created = true;
229 $id = $this->data[$model][$data['key']];
230 }
231 }
232  
233 $options = array_merge(array(
234 'type' => ($created && empty($options['action'])) ? 'put' : 'post',
235 'action' => null,
236 'url' => null,
237 'default' => true,
238 'encoding' => strtolower(Configure::read('App.encoding')),
239 'inputDefaults' => array()),
240 $options);
241 $this->_inputDefaults = $options['inputDefaults'];
242 unset($options['inputDefaults']);
243  
244 if (empty($options['url']) || is_array($options['url'])) {
245 if (empty($options['url']['controller'])) {
246 if (!empty($model) && $model != $this->defaultModel) {
247 $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
248 } elseif (!empty($this->params['controller'])) {
249 $options['url']['controller'] = Inflector::underscore($this->params['controller']);
250 }
251 }
252 if (empty($options['action'])) {
253 $options['action'] = $this->params['action'];
254 }
255  
256 $actionDefaults = array(
257 'plugin' => $this->plugin,
258 'controller' => $view->viewPath,
259 'action' => $options['action'],
260 0 => $id
261 );
262 if (!empty($options['action']) && !isset($options['id'])) {
263 $options['id'] = $model . Inflector::camelize($options['action']) . 'Form';
264 }
265 $options['action'] = array_merge($actionDefaults, (array)$options['url']);
266 } elseif (is_string($options['url'])) {
267 $options['action'] = $options['url'];
268 }
269 unset($options['url']);
270  
271 switch (strtolower($options['type'])) {
272 case 'get':
273 $htmlAttributes['method'] = 'get';
274 break;
275 case 'file':
276 $htmlAttributes['enctype'] = 'multipart/form-data';
277 $options['type'] = ($created) ? 'put' : 'post';
278 case 'post':
279 case 'put':
280 case 'delete':
281 $append .= $this->hidden('_method', array(
282 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null
283 ));
284 default:
285 $htmlAttributes['method'] = 'post';
286 break;
287 }
288 $this->requestType = strtolower($options['type']);
289  
290 $htmlAttributes['action'] = $this->url($options['action']);
291 unset($options['type'], $options['action']);
292  
293 if ($options['default'] == false) {
294 if (isset($htmlAttributes['onSubmit']) || isset($htmlAttributes['onsubmit'])) {
295 $htmlAttributes['onsubmit'] .= ' event.returnValue = false; return false;';
296 } else {
297 $htmlAttributes['onsubmit'] = 'event.returnValue = false; return false;';
298 }
299 }
300  
301 if (!empty($options['encoding'])) {
302 $htmlAttributes['accept-charset'] = $options['encoding'];
303 unset($options['encoding']);
304 }
305  
306 unset($options['default']);
307 $htmlAttributes = array_merge($options, $htmlAttributes);
308  
309 if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
310 $append .= $this->hidden('_Token.key', array(
311 'value' => $this->params['_Token']['key'], 'id' => 'Token' . mt_rand())
312 );
313 }
314  
315 if (!empty($append)) {
316 $append = sprintf($this->Html->tags['block'], ' style="display:none;"', $append);
317 }
318  
319 $this->setEntity($model . '.', true);
320 $attributes = $this->_parseAttributes($htmlAttributes, null, '');
321 return sprintf($this->Html->tags['form'], $attributes) . $append;
322 }
323  
324 /**
325 * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
326 * input fields where appropriate.
327 *
328 * If $options is set a form submit button will be created. Options can be either a string or an array.
329 *
330 * {{{
331 * array usage:
332 *
333 * array('label' => 'save'); value="save"
334 * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
335 * array('name' => 'Whatever'); value="Submit" name="Whatever"
336 * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
337 * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
338 * }}}
339 *
340 * @param mixed $options as a string will use $options as the value of button,
341 * @return string a closing FORM tag optional submit button.
342 * @access public
343 * @link http://book.cakephp.org/view/1389/Closing-the-Form
344 */
345 function end($options = null) {
346 if (!empty($this->params['models'])) {
347 $models = $this->params['models'][0];
348 }
349 $out = null;
350 $submit = null;
351  
352 if ($options !== null) {
353 $submitOptions = array();
354 if (is_string($options)) {
355 $submit = $options;
356 } else {
357 if (isset($options['label'])) {
358 $submit = $options['label'];
359 unset($options['label']);
360 }
361 $submitOptions = $options;
362  
363 if (!$submit) {
364 $submit = __('Submit', true);
365 }
366 }
367 $out .= $this->submit($submit, $submitOptions);
368 }
369 if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
370 $out .= $this->secure($this->fields);
371 $this->fields = array();
372 }
373 $this->setEntity(null);
374 $out .= $this->Html->tags['formend'];
375  
376 $view =& ClassRegistry::getObject('view');
377 $view->modelScope = false;
378 return $out;
379 }
380  
381 /**
382 * Generates a hidden field with a security hash based on the fields used in the form.
383 *
384 * @param array $fields The list of fields to use when generating the hash
385 * @return string A hidden input field with a security hash
386 * @access public
387 */
388 function secure($fields = array()) {
389 if (!isset($this->params['_Token']) || empty($this->params['_Token'])) {
390 return;
391 }
392 $locked = array();
393  
394 foreach ($fields as $key => $value) {
395 if (!is_int($key)) {
396 $locked[$key] = $value;
397 unset($fields[$key]);
398 }
399 }
400 sort($fields, SORT_STRING);
401 ksort($locked, SORT_STRING);
402 $fields += $locked;
403  
404 $fields = Security::hash(serialize($fields) . Configure::read('Security.salt'));
405 $locked = str_rot13(serialize(array_keys($locked)));
406  
407 $out = $this->hidden('_Token.fields', array(
408 'value' => urlencode($fields . ':' . $locked),
409 'id' => 'TokenFields' . mt_rand()
410 ));
411 $out = sprintf($this->Html->tags['block'], ' style="display:none;"', $out);
412 return $out;
413 }
414  
415 /**
416 * Determine which fields of a form should be used for hash.
417 * Populates $this->fields
418 *
419 * @param mixed $field Reference to field to be secured
420 * @param mixed $value Field value, if value should not be tampered with.
421 * @return void
422 * @access private
423 */
424 function __secure($field = null, $value = null) {
425 if (!$field) {
426 $view =& ClassRegistry::getObject('view');
427 $field = $view->entity();
428 } elseif (is_string($field)) {
429 $field = Set::filter(explode('.', $field), true);
430 }
431  
432 if (!empty($this->params['_Token']['disabledFields'])) {
433 foreach ((array)$this->params['_Token']['disabledFields'] as $disabled) {
434 $disabled = explode('.', $disabled);
435 if (array_values(array_intersect($field, $disabled)) === $disabled) {
436 return;
437 }
438 }
439 }
440 $field = implode('.', $field);
441 if (!in_array($field, $this->fields)) {
442 if ($value !== null) {
443 return $this->fields[$field] = $value;
444 }
445 $this->fields[] = $field;
446 }
447 }
448  
449 /**
450 * Returns true if there is an error for the given field, otherwise false
451 *
452 * @param string $field This should be "Modelname.fieldname"
453 * @return boolean If there are errors this method returns true, else false.
454 * @access public
455 * @link http://book.cakephp.org/view/1426/isFieldError
456 */
457 function isFieldError($field) {
458 $this->setEntity($field);
459 return (bool)$this->tagIsInvalid();
460 }
461  
462 /**
463 * Returns a formatted error message for given FORM field, NULL if no errors.
464 *
465 * ### Options:
466 *
467 * - `escape` bool Whether or not to html escape the contents of the error.
468 * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a
469 * string, will be used as the HTML tag to use.
470 * - `class` string The classname for the error message
471 *
472 * @param string $field A field name, like "Modelname.fieldname"
473 * @param mixed $text Error message or array of $options. If array, `attributes` key
474 * will get used as html attributes for error container
475 * @param array $options Rendering options for <div /> wrapper tag
476 * @return string If there are errors this method returns an error message, otherwise null.
477 * @access public
478 * @link http://book.cakephp.org/view/1423/error
479 */
480 function error($field, $text = null, $options = array()) {
481 $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
482 $options = array_merge($defaults, $options);
483 $this->setEntity($field);
484  
485 if ($error = $this->tagIsInvalid()) {
486 if (is_array($error)) {
487 list(,,$field) = explode('.', $field);
488 if (isset($error[$field])) {
489 $error = $error[$field];
490 } else {
491 return null;
492 }
493 }
494  
495 if (is_array($text) && is_numeric($error) && $error > 0) {
496 $error--;
497 }
498 if (is_array($text)) {
499 $options = array_merge($options, array_intersect_key($text, $defaults));
500 if (isset($text['attributes']) && is_array($text['attributes'])) {
501 $options = array_merge($options, $text['attributes']);
502 }
503 $text = isset($text[$error]) ? $text[$error] : null;
504 unset($options[$error]);
505 }
506  
507 if ($text != null) {
508 $error = $text;
509 } elseif (is_numeric($error)) {
510 $error = sprintf(__('Error in field %s', true), Inflector::humanize($this->field()));
511 }
512 if ($options['escape']) {
513 $error = h($error);
514 unset($options['escape']);
515 }
516 if ($options['wrap']) {
517 $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
518 unset($options['wrap']);
519 return $this->Html->tag($tag, $error, $options);
520 } else {
521 return $error;
522 }
523 } else {
524 return null;
525 }
526 }
527  
528 /**
529 * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
530 * a for attribute if one is not provided.
531 *
532 * @param string $fieldName This should be "Modelname.fieldname"
533 * @param string $text Text that will appear in the label field.
534 * @param mixed $options An array of HTML attributes, or a string, to be used as a class name.
535 * @return string The formatted LABEL element
536 * @link http://book.cakephp.org/view/1427/label
537 */
538 function label($fieldName = null, $text = null, $options = array()) {
539 if (empty($fieldName)) {
540 $view = ClassRegistry::getObject('view');
541 $fieldName = implode('.', $view->entity());
542 }
543  
544 if ($text === null) {
545 if (strpos($fieldName, '.') !== false) {
546 $text = array_pop(explode('.', $fieldName));
547 } else {
548 $text = $fieldName;
549 }
550 if (substr($text, -3) == '_id') {
551 $text = substr($text, 0, strlen($text) - 3);
552 }
553 $text = __(Inflector::humanize(Inflector::underscore($text)), true);
554 }
555  
556 if (is_string($options)) {
557 $options = array('class' => $options);
558 }
559  
560 if (isset($options['for'])) {
561 $labelFor = $options['for'];
562 unset($options['for']);
563 } else {
564 $labelFor = $this->domId($fieldName);
565 }
566  
567 return sprintf(
568 $this->Html->tags['label'],
569 $labelFor,
570 $this->_parseAttributes($options), $text
571 );
572 }
573  
574 /**
575 * Generate a set of inputs for `$fields`. If $fields is null the current model
576 * will be used.
577 *
578 * In addition to controller fields output, `$fields` can be used to control legend
579 * and fieldset rendering with the `fieldset` and `legend` keys.
580 * `$form->inputs(array('legend' => 'My legend'));` Would generate an input set with
581 * a custom legend. You can customize individual inputs through `$fields` as well.
582 *
583 * {{{
584 * $form->inputs(array(
585 * 'name' => array('label' => 'custom label')
586 * ));
587 * }}}
588 *
589 * @param mixed $fields An array of fields to generate inputs for, or null.
590 * @param array $blacklist a simple array of fields to not create inputs for.
591 * @return string Completed form inputs.
592 * @access public
593 */
594 function inputs($fields = null, $blacklist = null) {
595 $fieldset = $legend = true;
596 $model = $this->model();
597 if (is_array($fields)) {
598 if (array_key_exists('legend', $fields)) {
599 $legend = $fields['legend'];
600 unset($fields['legend']);
601 }
602  
603 if (isset($fields['fieldset'])) {
604 $fieldset = $fields['fieldset'];
605 unset($fields['fieldset']);
606 }
607 } elseif ($fields !== null) {
608 $fieldset = $legend = $fields;
609 if (!is_bool($fieldset)) {
610 $fieldset = true;
611 }
612 $fields = array();
613 }
614  
615 if (empty($fields)) {
616 $fields = array_keys($this->fieldset[$model]['fields']);
617 }
618  
619 if ($legend === true) {
620 $actionName = __('New %s', true);
621 $isEdit = (
622 strpos($this->action, 'update') !== false ||
623 strpos($this->action, 'edit') !== false
624 );
625 if ($isEdit) {
626 $actionName = __('Edit %s', true);
627 }
628 $modelName = Inflector::humanize(Inflector::underscore($model));
629 $legend = sprintf($actionName, __($modelName, true));
630 }
631  
632 $out = null;
633 foreach ($fields as $name => $options) {
634 if (is_numeric($name) && !is_array($options)) {
635 $name = $options;
636 $options = array();
637 }
638 $entity = explode('.', $name);
639 $blacklisted = (
640 is_array($blacklist) &&
641 (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
642 );
643 if ($blacklisted) {
644 continue;
645 }
646 $out .= $this->input($name, $options);
647 }
648  
649 if (is_string($fieldset)) {
650 $fieldsetClass = sprintf(' class="%s"', $fieldset);
651 } else {
652 $fieldsetClass = '';
653 }
654  
655 if ($fieldset && $legend) {
656 return sprintf(
657 $this->Html->tags['fieldset'],
658 $fieldsetClass,
659 sprintf($this->Html->tags['legend'], $legend) . $out
660 );
661 } elseif ($fieldset) {
662 return sprintf($this->Html->tags['fieldset'], $fieldsetClass, $out);
663 } else {
664 return $out;
665 }
666 }
667  
668 /**
669 * Generates a form input element complete with label and wrapper div
670 *
671 * ### Options
672 *
673 * See each field type method for more information. Any options that are part of
674 * $attributes or $options for the different **type** methods can be included in `$options` for input().
675 *
676 * - `type` - Force the type of widget you want. e.g. `type => 'select'`
677 * - `label` - Either a string label, or an array of options for the label. See FormHelper::label()
678 * - `div` - Either `false` to disable the div, or an array of options for the div.
679 * See HtmlHelper::div() for more options.
680 * - `options` - for widgets that take options e.g. radio, select
681 * - `error` - control the error message that is produced
682 * - `empty` - String or boolean to enable empty select box options.
683 * - `before` - Content to place before the label + input.
684 * - `after` - Content to place after the label + input.
685 * - `between` - Content to place between the label + input.
686 * - `format` - format template for element order. Any element that is not in the array, will not be in the output.
687 * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
688 * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
689 * - Hidden input will not be formatted
690 * - Radio buttons cannot have the order of input and label elements controlled with these settings.
691 *
692 * @param string $fieldName This should be "Modelname.fieldname"
693 * @param array $options Each type of input takes different options.
694 * @return string Completed form widget.
695 * @access public
696 * @link http://book.cakephp.org/view/1390/Automagic-Form-Elements
697 */
698 function input($fieldName, $options = array()) {
699 $this->setEntity($fieldName);
700  
701 $options = array_merge(
702 array('before' => null, 'between' => null, 'after' => null, 'format' => null),
703 $this->_inputDefaults,
704 $options
705 );
706  
707 $modelKey = $this->model();
708 $fieldKey = $this->field();
709 if (!isset($this->fieldset[$modelKey])) {
710 $this->_introspectModel($modelKey);
711 }
712  
713 if (!isset($options['type'])) {
714 $magicType = true;
715 $options['type'] = 'text';
716 if (isset($options['options'])) {
717 $options['type'] = 'select';
718 } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
719 $options['type'] = 'password';
720 } elseif (isset($this->fieldset[$modelKey]['fields'][$fieldKey])) {
721 $fieldDef = $this->fieldset[$modelKey]['fields'][$fieldKey];
722 $type = $fieldDef['type'];
723 $primaryKey = $this->fieldset[$modelKey]['key'];
724 }
725  
726 if (isset($type)) {
727 $map = array(
728 'string' => 'text', 'datetime' => 'datetime',
729 'boolean' => 'checkbox', 'timestamp' => 'datetime',
730 'text' => 'textarea', 'time' => 'time',
731 'date' => 'date', 'float' => 'text'
732 );
733  
734 if (isset($this->map[$type])) {
735 $options['type'] = $this->map[$type];
736 } elseif (isset($map[$type])) {
737 $options['type'] = $map[$type];
738 }
739 if ($fieldKey == $primaryKey) {
740 $options['type'] = 'hidden';
741 }
742 }
743 if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
744 $options['type'] = 'select';
745 }
746  
747 if ($modelKey === $fieldKey) {
748 $options['type'] = 'select';
749 if (!isset($options['multiple'])) {
750 $options['multiple'] = 'multiple';
751 }
752 }
753 }
754 $types = array('checkbox', 'radio', 'select');
755  
756 if (
757 (!isset($options['options']) && in_array($options['type'], $types)) ||
758 (isset($magicType) && $options['type'] == 'text')
759 ) {
760 $view =& ClassRegistry::getObject('view');
761 $varName = Inflector::variable(
762 Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey))
763 );
764 $varOptions = $view->getVar($varName);
765 if (is_array($varOptions)) {
766 if ($options['type'] !== 'radio') {
767 $options['type'] = 'select';
768 }
769 $options['options'] = $varOptions;
770 }
771 }
772  
773 $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length']));
774 if ($autoLength && $options['type'] == 'text') {
775 $options['maxlength'] = $fieldDef['length'];
776 }
777 if ($autoLength && $fieldDef['type'] == 'float') {
778 $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1;
779 }
780  
781 $divOptions = array();
782 $div = $this->_extractOption('div', $options, true);
783 unset($options['div']);
784  
785 if (!empty($div)) {
786 $divOptions['class'] = 'input';
787 $divOptions = $this->addClass($divOptions, $options['type']);
788 if (is_string($div)) {
789 $divOptions['class'] = $div;
790 } elseif (is_array($div)) {
791 $divOptions = array_merge($divOptions, $div);
792 }
793 if (
794 isset($this->fieldset[$modelKey]) &&
795 in_array($fieldKey, $this->fieldset[$modelKey]['validates'])
796 ) {
797 $divOptions = $this->addClass($divOptions, 'required');
798 }
799 if (!isset($divOptions['tag'])) {
800 $divOptions['tag'] = 'div';
801 }
802 }
803  
804 $label = null;
805 if (isset($options['label']) && $options['type'] !== 'radio') {
806 $label = $options['label'];
807 unset($options['label']);
808 }
809  
810 if ($options['type'] === 'radio') {
811 $label = false;
812 if (isset($options['options'])) {
813 $radioOptions = (array)$options['options'];
814 unset($options['options']);
815 }
816 }
817  
818 if ($label !== false) {
819 $label = $this->_inputLabel($fieldName, $label, $options);
820 }
821  
822 $error = $this->_extractOption('error', $options, null);
823 unset($options['error']);
824  
825 $selected = $this->_extractOption('selected', $options, null);
826 unset($options['selected']);
827  
828 if (isset($options['rows']) || isset($options['cols'])) {
829 $options['type'] = 'textarea';
830 }
831  
832 if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
833 $options += array('empty' => false);
834 }
835 if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
836 $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
837 $timeFormat = $this->_extractOption('timeFormat', $options, 12);
838 unset($options['dateFormat'], $options['timeFormat']);
839 }
840  
841 $type = $options['type'];
842 $out = array_merge(
843 array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null),
844 array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after'])
845 );
846 $format = null;
847 if (is_array($options['format']) && in_array('input', $options['format'])) {
848 $format = $options['format'];
849 }
850 unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
851  
852 switch ($type) {
853 case 'hidden':
854 $input = $this->hidden($fieldName, $options);
855 $format = array('input');
856 unset($divOptions);
857 break;
858 case 'checkbox':
859 $input = $this->checkbox($fieldName, $options);
860 $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error');
861 break;
862 case 'radio':
863 $input = $this->radio($fieldName, $radioOptions, $options);
864 break;
865 case 'text':
866 case 'password':
867 case 'file':
868 $input = $this->{$type}($fieldName, $options);
869 break;
870 case 'select':
871 $options += array('options' => array());
872 $list = $options['options'];
873 unset($options['options']);
874 $input = $this->select($fieldName, $list, $selected, $options);
875 break;
876 case 'time':
877 $input = $this->dateTime($fieldName, null, $timeFormat, $selected, $options);
878 break;
879 case 'date':
880 $input = $this->dateTime($fieldName, $dateFormat, null, $selected, $options);
881 break;
882 case 'datetime':
883 $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $selected, $options);
884 break;
885 case 'textarea':
886 default:
887 $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
888 break;
889 }
890  
891 if ($type != 'hidden' && $error !== false) {
892 $errMsg = $this->error($fieldName, $error);
893 if ($errMsg) {
894 $divOptions = $this->addClass($divOptions, 'error');
895 $out['error'] = $errMsg;
896 }
897 }
898  
899 $out['input'] = $input;
900 $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error');
901 $output = '';
902 foreach ($format as $element) {
903 $output .= $out[$element];
904 unset($out[$element]);
905 }
906  
907 if (!empty($divOptions['tag'])) {
908 $tag = $divOptions['tag'];
909 unset($divOptions['tag']);
910 $output = $this->Html->tag($tag, $output, $divOptions);
911 }
912 return $output;
913 }
914  
915 /**
916 * Extracts a single option from an options array.
917 *
918 * @param string $name The name of the option to pull out.
919 * @param array $options The array of options you want to extract.
920 * @param mixed $default The default option value
921 * @return the contents of the option or default
922 * @access protected
923 */
924 function _extractOption($name, $options, $default = null) {
925 if (array_key_exists($name, $options)) {
926 return $options[$name];
927 }
928 return $default;
929 }
930  
931 /**
932 * Generate a label for an input() call.
933 *
934 * @param array $options Options for the label element.
935 * @return string Generated label element
936 * @access protected
937 */
938 function _inputLabel($fieldName, $label, $options) {
939 $labelAttributes = $this->domId(array(), 'for');
940 if ($options['type'] === 'date' || $options['type'] === 'datetime') {
941 if (isset($options['dateFormat']) && $options['dateFormat'] === 'NONE') {
942 $labelAttributes['for'] .= 'Hour';
943 $idKey = 'hour';
944 } else {
945 $labelAttributes['for'] .= 'Month';
946 $idKey = 'month';
947 }
948 if (isset($options['id']) && isset($options['id'][$idKey])) {
949 $labelAttributes['for'] = $options['id'][$idKey];
950 }
951 } elseif ($options['type'] === 'time') {
952 $labelAttributes['for'] .= 'Hour';
953 if (isset($options['id']) && isset($options['id']['hour'])) {
954 $labelAttributes['for'] = $options['id']['hour'];
955 }
956 }
957  
958 if (is_array($label)) {
959 $labelText = null;
960 if (isset($label['text'])) {
961 $labelText = $label['text'];
962 unset($label['text']);
963 }
964 $labelAttributes = array_merge($labelAttributes, $label);
965 } else {
966 $labelText = $label;
967 }
968  
969 if (isset($options['id']) && is_string($options['id'])) {
970 $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
971 }
972 return $this->label($fieldName, $labelText, $labelAttributes);
973 }
974  
975 /**
976 * Creates a checkbox input widget.
977 *
978 * ### Options:
979 *
980 * - `value` - the value of the checkbox
981 * - `checked` - boolean indicate that this checkbox is checked.
982 * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
983 * a hidden input with a value of ''.
984 * - `disabled` - create a disabled input.
985 *
986 * @param string $fieldName Name of a field, like this "Modelname.fieldname"
987 * @param array $options Array of HTML attributes.
988 * @return string An HTML text input element.
989 * @access public
990 * @link http://book.cakephp.org/view/1414/checkbox
991 */
992 function checkbox($fieldName, $options = array()) {
993 $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
994 $value = current($this->value());
995 $output = "";
996  
997 if (empty($options['value'])) {
998 $options['value'] = 1;
999 } elseif (!empty($value) && $value === $options['value']) {
1000 $options['checked'] = 'checked';
1001 }
1002 if ($options['hiddenField']) {
1003 $hiddenOptions = array(
1004 'id' => $options['id'] . '_', 'name' => $options['name'],
1005 'value' => '0', 'secure' => false
1006 );
1007 if (isset($options['disabled']) && $options['disabled'] == true) {
1008 $hiddenOptions['disabled'] = 'disabled';
1009 }
1010 $output = $this->hidden($fieldName, $hiddenOptions);
1011 }
1012 unset($options['hiddenField']);
1013  
1014 return $output . sprintf(
1015 $this->Html->tags['checkbox'],
1016 $options['name'],
1017 $this->_parseAttributes($options, array('name'), null, ' ')
1018 );
1019 }
1020  
1021 /**
1022 * Creates a set of radio widgets. Will create a legend and fieldset
1023 * by default. Use $options to control this
1024 *
1025 * ### Attributes:
1026 *
1027 * - `separator` - define the string in between the radio buttons
1028 * - `legend` - control whether or not the widget set has a fieldset & legend
1029 * - `value` - indicate a value that is should be checked
1030 * - `label` - boolean to indicate whether or not labels for widgets show be displayed
1031 * - `hiddenField` - boolean to indicate if you want the results of radio() to include
1032 * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
1033 *
1034 * @param string $fieldName Name of a field, like this "Modelname.fieldname"
1035 * @param array $options Radio button options array.
1036 * @param array $attributes Array of HTML attributes, and special attributes above.
1037 * @return string Completed radio widget set.
1038 * @access public
1039 * @link http://book.cakephp.org/view/1429/radio
1040 */
1041 function radio($fieldName, $options = array(), $attributes = array()) {
1042 $attributes = $this->_initInputField($fieldName, $attributes);
1043 $legend = false;
1044  
1045 if (isset($attributes['legend'])) {
1046 $legend = $attributes['legend'];
1047 unset($attributes['legend']);
1048 } elseif (count($options) > 1) {
1049 $legend = __(Inflector::humanize($this->field()), true);
1050 }
1051 $label = true;
1052  
1053 if (isset($attributes['label'])) {
1054 $label = $attributes['label'];
1055 unset($attributes['label']);
1056 }
1057 $inbetween = null;
1058  
1059 if (isset($attributes['separator'])) {
1060 $inbetween = $attributes['separator'];
1061 unset($attributes['separator']);
1062 }
1063  
1064 if (isset($attributes['value'])) {
1065 $value = $attributes['value'];
1066 } else {
1067 $value = $this->value($fieldName);
1068 }
1069 $out = array();
1070  
1071 $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
1072 unset($attributes['hiddenField']);
1073  
1074 foreach ($options as $optValue => $optTitle) {
1075 $optionsHere = array('value' => $optValue);
1076  
1077 if (isset($value) && $optValue == $value) {
1078 $optionsHere['checked'] = 'checked';
1079 }
1080 $parsedOptions = $this->_parseAttributes(
1081 array_merge($attributes, $optionsHere),
1082 array('name', 'type', 'id'), '', ' '
1083 );
1084 $tagName = Inflector::camelize(
1085 $attributes['id'] . '_' . Inflector::underscore($optValue)
1086 );
1087  
1088 if ($label) {
1089 $optTitle = sprintf($this->Html->tags['label'], $tagName, null, $optTitle);
1090 }
1091 $out[] = sprintf(
1092 $this->Html->tags['radio'], $attributes['name'],
1093 $tagName, $parsedOptions, $optTitle
1094 );
1095 }
1096 $hidden = null;
1097  
1098 if ($hiddenField) {
1099 if (!isset($value) || $value === '') {
1100 $hidden = $this->hidden($fieldName, array(
1101 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
1102 ));
1103 }
1104 }
1105 $out = $hidden . implode($inbetween, $out);
1106  
1107 if ($legend) {
1108 $out = sprintf(
1109 $this->Html->tags['fieldset'], '',
1110 sprintf($this->Html->tags['legend'], $legend) . $out
1111 );
1112 }
1113 return $out;
1114 }
1115  
1116 /**
1117 * Creates a text input widget.
1118 *
1119 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1120 * @param array $options Array of HTML attributes.
1121 * @return string A generated HTML text input element
1122 * @access public
1123 * @link http://book.cakephp.org/view/1432/text
1124 */
1125 function text($fieldName, $options = array()) {
1126 $options = $this->_initInputField($fieldName, array_merge(
1127 array('type' => 'text'), $options
1128 ));
1129 return sprintf(
1130 $this->Html->tags['input'],
1131 $options['name'],
1132 $this->_parseAttributes($options, array('name'), null, ' ')
1133 );
1134 }
1135  
1136 /**
1137 * Creates a password input widget.
1138 *
1139 * @param string $fieldName Name of a field, like in the form "Modelname.fieldname"
1140 * @param array $options Array of HTML attributes.
1141 * @return string A generated password input.
1142 * @access public
1143 * @link http://book.cakephp.org/view/1428/password
1144 */
1145 function password($fieldName, $options = array()) {
1146 $options = $this->_initInputField($fieldName, $options);
1147 return sprintf(
1148 $this->Html->tags['password'],
1149 $options['name'],
1150 $this->_parseAttributes($options, array('name'), null, ' ')
1151 );
1152 }
1153  
1154 /**
1155 * Creates a textarea widget.
1156 *
1157 * ### Options:
1158 *
1159 * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
1160 *
1161 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1162 * @param array $options Array of HTML attributes, and special options above.
1163 * @return string A generated HTML text input element
1164 * @access public
1165 * @link http://book.cakephp.org/view/1433/textarea
1166 */
1167 function textarea($fieldName, $options = array()) {
1168 $options = $this->_initInputField($fieldName, $options);
1169 $value = null;
1170  
1171 if (array_key_exists('value', $options)) {
1172 $value = $options['value'];
1173 if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
1174 $value = h($value);
1175 }
1176 unset($options['value']);
1177 }
1178 return sprintf(
1179 $this->Html->tags['textarea'],
1180 $options['name'],
1181 $this->_parseAttributes($options, array('type', 'name'), null, ' '),
1182 $value
1183 );
1184 }
1185  
1186 /**
1187 * Creates a hidden input field.
1188 *
1189 * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
1190 * @param array $options Array of HTML attributes.
1191 * @return string A generated hidden input
1192 * @access public
1193 * @link http://book.cakephp.org/view/1425/hidden
1194 */
1195 function hidden($fieldName, $options = array()) {
1196 $secure = true;
1197  
1198 if (isset($options['secure'])) {
1199 $secure = $options['secure'];
1200 unset($options['secure']);
1201 }
1202 $options = $this->_initInputField($fieldName, array_merge(
1203 $options, array('secure' => false)
1204 ));
1205 $model = $this->model();
1206  
1207 if ($fieldName !== '_method' && $model !== '_Token' && $secure) {
1208 $this->__secure(null, '' . $options['value']);
1209 }
1210  
1211 return sprintf(
1212 $this->Html->tags['hidden'],
1213 $options['name'],
1214 $this->_parseAttributes($options, array('name', 'class'), '', ' ')
1215 );
1216 }
1217  
1218 /**
1219 * Creates file input widget.
1220 *
1221 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1222 * @param array $options Array of HTML attributes.
1223 * @return string A generated file input.
1224 * @access public
1225 * @link http://book.cakephp.org/view/1424/file
1226 */
1227 function file($fieldName, $options = array()) {
1228 $options = array_merge($options, array('secure' => false));
1229 $options = $this->_initInputField($fieldName, $options);
1230 $view =& ClassRegistry::getObject('view');
1231 $field = $view->entity();
1232  
1233 foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
1234 $this->__secure(array_merge($field, array($suffix)));
1235 }
1236  
1237 $attributes = $this->_parseAttributes($options, array('name'), '', ' ');
1238 return sprintf($this->Html->tags['file'], $options['name'], $attributes);
1239 }
1240  
1241 /**
1242 * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
1243 * You can change it to a different value by using `$options['type']`.
1244 *
1245 * ### Options:
1246 *
1247 * - `escape` - HTML entity encode the $title of the button. Defaults to false.
1248 *
1249 * @param string $title The button's caption. Not automatically HTML encoded
1250 * @param array $options Array of options and HTML attributes.
1251 * @return string A HTML button tag.
1252 * @access public
1253 * @link http://book.cakephp.org/view/1415/button
1254 */
1255 function button($title, $options = array()) {
1256 $options += array('type' => 'submit', 'escape' => false);
1257 if ($options['escape']) {
1258 $title = h($title);
1259 }
1260 return sprintf(
1261 $this->Html->tags['button'],
1262 $options['type'],
1263 $this->_parseAttributes($options, array('type'), ' ', ''),
1264 $title
1265 );
1266 }
1267  
1268 /**
1269 * Creates a submit button element. This method will generate `<input />` elements that
1270 * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
1271 * image path for $caption.
1272 *
1273 * ### Options
1274 *
1275 * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
1276 * FormHelper::input().
1277 * - `before` - Content to include before the input.
1278 * - `after` - Content to include after the input.
1279 * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
1280 * - Other attributes will be assigned to the input element.
1281 *
1282 * ### Options
1283 *
1284 * - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
1285 * FormHelper::input().
1286 * - Other attributes will be assigned to the input element.
1287 *
1288 * @param string $caption The label appearing on the button OR if string contains :// or the
1289 * extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
1290 * exists, AND the first character is /, image is relative to webroot,
1291 * OR if the first character is not /, image is relative to webroot/img.
1292 * @param array $options Array of options. See above.
1293 * @return string A HTML submit button
1294 * @access public
1295 * @link http://book.cakephp.org/view/1431/submit
1296 */
1297 function submit($caption = null, $options = array()) {
1298 if (!$caption) {
1299 $caption = __('Submit', true);
1300 }
1301 $out = null;
1302 $div = true;
1303  
1304 if (isset($options['div'])) {
1305 $div = $options['div'];
1306 unset($options['div']);
1307 }
1308 $options += array('type' => 'submit', 'before' => null, 'after' => null);
1309 $divOptions = array('tag' => 'div');
1310  
1311 if ($div === true) {
1312 $divOptions['class'] = 'submit';
1313 } elseif ($div === false) {
1314 unset($divOptions);
1315 } elseif (is_string($div)) {
1316 $divOptions['class'] = $div;
1317 } elseif (is_array($div)) {
1318 $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
1319 }
1320  
1321 $before = $options['before'];
1322 $after = $options['after'];
1323 unset($options['before'], $options['after']);
1324  
1325 if (strpos($caption, '://') !== false) {
1326 unset($options['type']);
1327 $out .= $before . sprintf(
1328 $this->Html->tags['submitimage'],
1329 $caption,
1330 $this->_parseAttributes($options, null, '', ' ')
1331 ) . $after;
1332 } elseif (preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption)) {
1333 unset($options['type']);
1334 if ($caption{0} !== '/') {
1335 $url = $this->webroot(IMAGES_URL . $caption);
1336 } else {
1337 $caption = trim($caption, '/');
1338 $url = $this->webroot($caption);
1339 }
1340 $out .= $before . sprintf(
1341 $this->Html->tags['submitimage'],
1342 $url,
1343 $this->_parseAttributes($options, null, '', ' ')
1344 ) . $after;
1345 } else {
1346 $options['value'] = $caption;
1347 $out .= $before . sprintf(
1348 $this->Html->tags['submit'],
1349 $this->_parseAttributes($options, null, '', ' ')
1350 ). $after;
1351 }
1352  
1353 if (isset($divOptions)) {
1354 $tag = $divOptions['tag'];
1355 unset($divOptions['tag']);
1356 $out = $this->Html->tag($tag, $out, $divOptions);
1357 }
1358 return $out;
1359 }
1360  
1361 /**
1362 * Returns a formatted SELECT element.
1363 *
1364 * ### Attributes:
1365 *
1366 * - `showParents` - If included in the array and set to true, an additional option element
1367 * will be added for the parent of each option group. You can set an option with the same name
1368 * and it's key will be used for the value of the option.
1369 * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
1370 * created instead.
1371 * - `empty` - If true, the empty select option is shown. If a string,
1372 * that string is displayed as the empty element.
1373 * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
1374 *
1375 * ### Using options
1376 *
1377 * A simple array will create normal options:
1378 *
1379 * {{{
1380 * $options = array(1 => 'one', 2 => 'two);
1381 * $this->Form->select('Model.field', $options));
1382 * }}}
1383 *
1384 * While a nested options array will create optgroups with options inside them.
1385 * {{{
1386 * $options = array(
1387 * 1 => 'bill',
1388 * 'fred' => array(
1389 * 2 => 'fred',
1390 * 3 => 'fred jr.'
1391 * )
1392 * );
1393 * $this->Form->select('Model.field', $options);
1394 * }}}
1395 *
1396 * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
1397 * attribute to show the fred option.
1398 *
1399 * @param string $fieldName Name attribute of the SELECT
1400 * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
1401 * SELECT element
1402 * @param mixed $selected The option selected by default. If null, the default value
1403 * from POST data will be used when available.
1404 * @param array $attributes The HTML attributes of the select element.
1405 * @return string Formatted SELECT element
1406 * @access public
1407 * @link http://book.cakephp.org/view/1430/select
1408 */
1409 function select($fieldName, $options = array(), $selected = null, $attributes = array()) {
1410 $select = array();
1411 $showParents = false;
1412 $escapeOptions = true;
1413 $style = null;
1414 $tag = null;
1415 $showEmpty = '';
1416  
1417 if (isset($attributes['escape'])) {
1418 $escapeOptions = $attributes['escape'];
1419 unset($attributes['escape']);
1420 }
1421 if (isset($attributes['secure'])) {
1422 $secure = $attributes['secure'];
1423 }
1424 if (isset($attributes['empty'])) {
1425 $showEmpty = $attributes['empty'];
1426 unset($attributes['empty']);
1427 }
1428 $attributes = $this->_initInputField($fieldName, array_merge(
1429 (array)$attributes, array('secure' => false)
1430 ));
1431  
1432 if (is_string($options) && isset($this->__options[$options])) {
1433 $options = $this->__generateOptions($options);
1434 } elseif (!is_array($options)) {
1435 $options = array();
1436 }
1437 if (isset($attributes['type'])) {
1438 unset($attributes['type']);
1439 }
1440 if (in_array('showParents', $attributes)) {
1441 $showParents = true;
1442 unset($attributes['showParents']);
1443 }
1444  
1445 if (!isset($selected)) {
1446 $selected = $attributes['value'];
1447 }
1448  
1449 if (isset($attributes) && array_key_exists('multiple', $attributes)) {
1450 $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
1451 $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
1452 $tag = $this->Html->tags[$template];
1453 $hiddenAttributes = array(
1454 'value' => '',
1455 'id' => $attributes['id'] . ($style ? '' : '_'),
1456 'secure' => false
1457 );
1458 $select[] = $this->hidden(null, $hiddenAttributes);
1459 } else {
1460 $tag = $this->Html->tags['selectstart'];
1461 }
1462  
1463 if (!empty($tag) || isset($template)) {
1464 if (!isset($secure) || $secure == true) {
1465 $this->__secure();
1466 }
1467 $select[] = sprintf($tag, $attributes['name'], $this->_parseAttributes(
1468 $attributes, array('name', 'value'))
1469 );
1470 }
1471 $emptyMulti = (
1472 $showEmpty !== null && $showEmpty !== false && !(
1473 empty($showEmpty) && (isset($attributes) &&
1474 array_key_exists('multiple', $attributes))
1475 )
1476 );
1477  
1478 if ($emptyMulti) {
1479 $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
1480 $options = array_reverse($options, true);
1481 $options[''] = $showEmpty;
1482 $options = array_reverse($options, true);
1483 }
1484  
1485 $select = array_merge($select, $this->__selectOptions(
1486 array_reverse($options, true),
1487 $selected,
1488 array(),
1489 $showParents,
1490 array('escape' => $escapeOptions, 'style' => $style)
1491 ));
1492  
1493 $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
1494 $select[] = $this->Html->tags[$template];
1495 return implode("\n", $select);
1496 }
1497  
1498 /**
1499 * Returns a SELECT element for days.
1500 *
1501 * ### Attributes:
1502 *
1503 * - `empty` - If true, the empty select option is shown. If a string,
1504 * that string is displayed as the empty element.
1505 *
1506 * @param string $fieldName Prefix name for the SELECT element
1507 * @param string $selected Option which is selected.
1508 * @param array $attributes HTML attributes for the select element
1509 * @return string A generated day select box.
1510 * @access public
1511 * @link http://book.cakephp.org/view/1419/day
1512 */
1513 function day($fieldName, $selected = null, $attributes = array()) {
1514 $attributes += array('empty' => true);
1515 $selected = $this->__dateTimeSelected('day', $fieldName, $selected, $attributes);
1516  
1517 if (strlen($selected) > 2) {
1518 $selected = date('d', strtotime($selected));
1519 } elseif ($selected === false) {
1520 $selected = null;
1521 }
1522 return $this->select($fieldName . ".day", $this->__generateOptions('day'), $selected, $attributes);
1523 }
1524  
1525 /**
1526 * Returns a SELECT element for years
1527 *
1528 * ### Attributes:
1529 *
1530 * - `empty` - If true, the empty select option is shown. If a string,
1531 * that string is displayed as the empty element.
1532 * - `orderYear` - Ordering of year values in select options.
1533 * Possible values 'asc', 'desc'. Default 'desc'
1534 *
1535 * @param string $fieldName Prefix name for the SELECT element
1536 * @param integer $minYear First year in sequence
1537 * @param integer $maxYear Last year in sequence
1538 * @param string $selected Option which is selected.
1539 * @param array $attributes Attribute array for the select elements.
1540 * @return string Completed year select input
1541 * @access public
1542 * @link http://book.cakephp.org/view/1416/year
1543 */
1544 function year($fieldName, $minYear = null, $maxYear = null, $selected = null, $attributes = array()) {
1545 $attributes += array('empty' => true);
1546 if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
1547 if (is_array($value)) {
1548 extract($value);
1549 $selected = $year;
1550 } else {
1551 if (empty($value)) {
1552 if (!$attributes['empty'] && !$maxYear) {
1553 $selected = 'now';
1554  
1555 } elseif (!$attributes['empty'] && $maxYear && !$selected) {
1556 $selected = $maxYear;
1557 }
1558 } else {
1559 $selected = $value;
1560 }
1561 }
1562 }
1563  
1564 if (strlen($selected) > 4 || $selected === 'now') {
1565 $selected = date('Y', strtotime($selected));
1566 } elseif ($selected === false) {
1567 $selected = null;
1568 }
1569 $yearOptions = array('min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
1570 if (isset($attributes['orderYear'])) {
1571 $yearOptions['order'] = $attributes['orderYear'];
1572 unset($attributes['orderYear']);
1573 }
1574 return $this->select(
1575 $fieldName . '.year', $this->__generateOptions('year', $yearOptions),
1576 $selected, $attributes
1577 );
1578 }
1579  
1580 /**
1581 * Returns a SELECT element for months.
1582 *
1583 * ### Attributes:
1584 *
1585 * - `monthNames` - If false, 2 digit numbers will be used instead of text.
1586 * If a array, the given array will be used.
1587 * - `empty` - If true, the empty select option is shown. If a string,
1588 * that string is displayed as the empty element.
1589 *
1590 * @param string $fieldName Prefix name for the SELECT element
1591 * @param string $selected Option which is selected.
1592 * @param array $attributes Attributes for the select element
1593 * @return string A generated month select dropdown.
1594 * @access public
1595 * @link http://book.cakephp.org/view/1417/month
1596 */
1597 function month($fieldName, $selected = null, $attributes = array()) {
1598 $attributes += array('empty' => true);
1599 $selected = $this->__dateTimeSelected('month', $fieldName, $selected, $attributes);
1600  
1601 if (strlen($selected) > 2) {
1602 $selected = date('m', strtotime($selected));
1603 } elseif ($selected === false) {
1604 $selected = null;
1605 }
1606 $defaults = array('monthNames' => true);
1607 $attributes = array_merge($defaults, (array) $attributes);
1608 $monthNames = $attributes['monthNames'];
1609 unset($attributes['monthNames']);
1610  
1611 return $this->select(
1612 $fieldName . ".month",
1613 $this->__generateOptions('month', array('monthNames' => $monthNames)),
1614 $selected, $attributes
1615 );
1616 }
1617  
1618 /**
1619 * Returns a SELECT element for hours.
1620 *
1621 * ### Attributes:
1622 *
1623 * - `empty` - If true, the empty select option is shown. If a string,
1624 * that string is displayed as the empty element.
1625 *
1626 * @param string $fieldName Prefix name for the SELECT element
1627 * @param boolean $format24Hours True for 24 hours format
1628 * @param string $selected Option which is selected.
1629 * @param array $attributes List of HTML attributes
1630 * @return string Completed hour select input
1631 * @access public
1632 * @link http://book.cakephp.org/view/1420/hour
1633 */
1634 function hour($fieldName, $format24Hours = false, $selected = null, $attributes = array()) {
1635 $attributes += array('empty' => true);
1636 $selected = $this->__dateTimeSelected('hour', $fieldName, $selected, $attributes);
1637  
1638 if (strlen($selected) > 2) {
1639 if ($format24Hours) {
1640 $selected = date('H', strtotime($selected));
1641 } else {
1642 $selected = date('g', strtotime($selected));
1643 }
1644 } elseif ($selected === false) {
1645 $selected = null;
1646 }
1647 return $this->select(
1648 $fieldName . ".hour",
1649 $this->__generateOptions($format24Hours ? 'hour24' : 'hour'),
1650 $selected, $attributes
1651 );
1652 }
1653  
1654 /**
1655 * Returns a SELECT element for minutes.
1656 *
1657 * ### Attributes:
1658 *
1659 * - `empty` - If true, the empty select option is shown. If a string,
1660 * that string is displayed as the empty element.
1661 *
1662 * @param string $fieldName Prefix name for the SELECT element
1663 * @param string $selected Option which is selected.
1664 * @param string $attributes Array of Attributes
1665 * @return string Completed minute select input.
1666 * @access public
1667 * @link http://book.cakephp.org/view/1421/minute
1668 */
1669 function minute($fieldName, $selected = null, $attributes = array()) {
1670 $attributes += array('empty' => true);
1671 $selected = $this->__dateTimeSelected('min', $fieldName, $selected, $attributes);
1672  
1673 if (strlen($selected) > 2) {
1674 $selected = date('i', strtotime($selected));
1675 } elseif ($selected === false) {
1676 $selected = null;
1677 }
1678 $minuteOptions = array();
1679  
1680 if (isset($attributes['interval'])) {
1681 $minuteOptions['interval'] = $attributes['interval'];
1682 unset($attributes['interval']);
1683 }
1684 return $this->select(
1685 $fieldName . ".min", $this->__generateOptions('minute', $minuteOptions),
1686 $selected, $attributes
1687 );
1688 }
1689  
1690 /**
1691 * Selects values for dateTime selects.
1692 *
1693 * @param string $select Name of element field. ex. 'day'
1694 * @param string $fieldName Name of fieldName being generated ex. Model.created
1695 * @param mixed $selected The current selected value.
1696 * @param array $attributes Array of attributes, must contain 'empty' key.
1697 * @return string Currently selected value.
1698 * @access private
1699 */
1700 function __dateTimeSelected($select, $fieldName, $selected, $attributes) {
1701 if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
1702 if (is_array($value) && isset($value[$select])) {
1703 $selected = $value[$select];
1704 } else {
1705 if (empty($value)) {
1706 if (!$attributes['empty']) {
1707 $selected = 'now';
1708 }
1709 } else {
1710 $selected = $value;
1711 }
1712 }
1713 }
1714 return $selected;
1715 }
1716  
1717 /**
1718 * Returns a SELECT element for AM or PM.
1719 *
1720 * ### Attributes:
1721 *
1722 * - `empty` - If true, the empty select option is shown. If a string,
1723 * that string is displayed as the empty element.
1724 *
1725 * @param string $fieldName Prefix name for the SELECT element
1726 * @param string $selected Option which is selected.
1727 * @param string $attributes Array of Attributes
1728 * @param bool $showEmpty Show/Hide an empty option
1729 * @return string Completed meridian select input
1730 * @access public
1731 * @link http://book.cakephp.org/view/1422/meridian
1732 */
1733 function meridian($fieldName, $selected = null, $attributes = array()) {
1734 $attributes += array('empty' => true);
1735 if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
1736 if (is_array($value)) {
1737 extract($value);
1738 $selected = $meridian;
1739 } else {
1740 if (empty($value)) {
1741 if (!$attribues['empty']) {
1742 $selected = date('a');
1743 }
1744 } else {
1745 $selected = date('a', strtotime($value));
1746 }
1747 }
1748 }
1749  
1750 if ($selected === false) {
1751 $selected = null;
1752 }
1753 return $this->select(
1754 $fieldName . ".meridian", $this->__generateOptions('meridian'),
1755 $selected, $attributes
1756 );
1757 }
1758  
1759 /**
1760 * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
1761 *
1762 * ### Attributes:
1763 *
1764 * - `monthNames` If false, 2 digit numbers will be used instead of text.
1765 * If a array, the given array will be used.
1766 * - `minYear` The lowest year to use in the year select
1767 * - `maxYear` The maximum year to use in the year select
1768 * - `interval` The interval for the minutes select. Defaults to 1
1769 * - `separator` The contents of the string between select elements. Defaults to '-'
1770 * - `empty` - If true, the empty select option is shown. If a string,
1771 * that string is displayed as the empty element.
1772 *
1773 * @param string $fieldName Prefix name for the SELECT element
1774 * @param string $dateFormat DMY, MDY, YMD.
1775 * @param string $timeFormat 12, 24.
1776 * @param string $selected Option which is selected.
1777 * @param string $attributes array of Attributes
1778 * @return string Generated set of select boxes for the date and time formats chosen.
1779 * @access public
1780 * @link http://book.cakephp.org/view/1418/dateTime
1781 */
1782 function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $selected = null, $attributes = array()) {
1783 $attributes += array('empty' => true);
1784 $year = $month = $day = $hour = $min = $meridian = null;
1785  
1786 if (empty($selected)) {
1787 $selected = $this->value($fieldName);
1788 }
1789  
1790 if ($selected === null && $attributes['empty'] != true) {
1791 $selected = time();
1792 }
1793  
1794 if (!empty($selected)) {
1795 if (is_array($selected)) {
1796 extract($selected);
1797 } else {
1798 if (is_numeric($selected)) {
1799 $selected = strftime('%Y-%m-%d %H:%M:%S', $selected);
1800 }
1801 $meridian = 'am';
1802 $pos = strpos($selected, '-');
1803 if ($pos !== false) {
1804 $date = explode('-', $selected);
1805 $days = explode(' ', $date[2]);
1806 $day = $days[0];
1807 $month = $date[1];
1808 $year = $date[0];
1809 } else {
1810 $days[1] = $selected;
1811 }
1812  
1813 if (!empty($timeFormat)) {
1814 $time = explode(':', $days[1]);
1815 $check = str_replace(':', '', $days[1]);
1816  
1817 if (($check > 115959) && $timeFormat == '12') {
1818 $time[0] = $time[0] - 12;
1819 $meridian = 'pm';
1820 } elseif ($time[0] == '00' && $timeFormat == '12') {
1821 $time[0] = 12;
1822 } elseif ($time[0] > 12) {
1823 $meridian = 'pm';
1824 }
1825 if ($time[0] == 0 && $timeFormat == '12') {
1826 $time[0] = 12;
1827 }
1828 $hour = $time[0];
1829 $min = $time[1];
1830 }
1831 }
1832 }
1833  
1834 $elements = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
1835 $defaults = array(
1836 'minYear' => null, 'maxYear' => null, 'separator' => '-',
1837 'interval' => 1, 'monthNames' => true
1838 );
1839 $attributes = array_merge($defaults, (array) $attributes);
1840 if (isset($attributes['minuteInterval'])) {
1841 $attributes['interval'] = $attributes['minuteInterval'];
1842 unset($attributes['minuteInterval']);
1843 }
1844 $minYear = $attributes['minYear'];
1845 $maxYear = $attributes['maxYear'];
1846 $separator = $attributes['separator'];
1847 $interval = $attributes['interval'];
1848 $monthNames = $attributes['monthNames'];
1849 $attributes = array_diff_key($attributes, $defaults);
1850  
1851 if (isset($attributes['id'])) {
1852 if (is_string($attributes['id'])) {
1853 // build out an array version
1854 foreach ($elements as $element) {
1855 $selectAttrName = 'select' . $element . 'Attr';
1856 ${$selectAttrName} = $attributes;
1857 ${$selectAttrName}['id'] = $attributes['id'] . $element;
1858 }
1859 } elseif (is_array($attributes['id'])) {
1860 // check for missing ones and build selectAttr for each element
1861 $attributes['id'] += array(
1862 'month' => '', 'year' => '', 'day' => '',
1863 'hour' => '', 'minute' => '', 'meridian' => ''
1864 );
1865 foreach ($elements as $element) {
1866 $selectAttrName = 'select' . $element . 'Attr';
1867 ${$selectAttrName} = $attributes;
1868 ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
1869 }
1870 }
1871 } else {
1872 // build the selectAttrName with empty id's to pass
1873 foreach ($elements as $element) {
1874 $selectAttrName = 'select' . $element . 'Attr';
1875 ${$selectAttrName} = $attributes;
1876 }
1877 }
1878  
1879 $selects = array();
1880 foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
1881 switch ($char) {
1882 case 'Y':
1883 $selects[] = $this->year(
1884 $fieldName, $minYear, $maxYear, $year, $selectYearAttr
1885 );
1886 break;
1887 case 'M':
1888 $selectMonthAttr['monthNames'] = $monthNames;
1889 $selects[] = $this->month($fieldName, $month, $selectMonthAttr);
1890 break;
1891 case 'D':
1892 $selects[] = $this->day($fieldName, $day, $selectDayAttr);
1893 break;
1894 }
1895 }
1896 $opt = implode($separator, $selects);
1897  
1898 if (!empty($interval) && $interval > 1 && !empty($min)) {
1899 $min = round($min * (1 / $interval)) * $interval;
1900 }
1901 $selectMinuteAttr['interval'] = $interval;
1902 switch ($timeFormat) {
1903 case '24':
1904 $opt .= $this->hour($fieldName, true, $hour, $selectHourAttr) . ':' .
1905 $this->minute($fieldName, $min, $selectMinuteAttr);
1906 break;
1907 case '12':
1908 $opt .= $this->hour($fieldName, false, $hour, $selectHourAttr) . ':' .
1909 $this->minute($fieldName, $min, $selectMinuteAttr) . ' ' .
1910 $this->meridian($fieldName, $meridian, $selectMeridianAttr);
1911 break;
1912 default:
1913 $opt .= '';
1914 break;
1915 }
1916 return $opt;
1917 }
1918  
1919 /**
1920 * Gets the input field name for the current tag
1921 *
1922 * @param array $options
1923 * @param string $key
1924 * @return array
1925 * @access protected
1926 */
1927 function _name($options = array(), $field = null, $key = 'name') {
1928 if ($this->requestType == 'get') {
1929 if ($options === null) {
1930 $options = array();
1931 } elseif (is_string($options)) {
1932 $field = $options;
1933 $options = 0;
1934 }
1935  
1936 if (!empty($field)) {
1937 $this->setEntity($field);
1938 }
1939  
1940 if (is_array($options) && isset($options[$key])) {
1941 return $options;
1942 }
1943  
1944 $view = ClassRegistry::getObject('view');
1945 $name = $view->field;
1946 if (!empty($view->fieldSuffix)) {
1947 $name .= '[' . $view->fieldSuffix . ']';
1948 }
1949  
1950 if (is_array($options)) {
1951 $options[$key] = $name;
1952 return $options;
1953 } else {
1954 return $name;
1955 }
1956 }
1957 return parent::_name($options, $field, $key);
1958 }
1959  
1960 /**
1961 * Returns an array of formatted OPTION/OPTGROUP elements
1962 * @access private
1963 * @return array
1964 */
1965 function __selectOptions($elements = array(), $selected = null, $parents = array(), $showParents = null, $attributes = array()) {
1966 $select = array();
1967 $attributes = array_merge(array('escape' => true, 'style' => null), $attributes);
1968 $selectedIsEmpty = ($selected === '' || $selected === null);
1969 $selectedIsArray = is_array($selected);
1970  
1971 foreach ($elements as $name => $title) {
1972 $htmlOptions = array();
1973 if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
1974 if (!empty($name)) {
1975 if ($attributes['style'] === 'checkbox') {
1976 $select[] = $this->Html->tags['fieldsetend'];
1977 } else {
1978 $select[] = $this->Html->tags['optiongroupend'];
1979 }
1980 $parents[] = $name;
1981 }
1982 $select = array_merge($select, $this->__selectOptions(
1983 $title, $selected, $parents, $showParents, $attributes
1984 ));
1985  
1986 if (!empty($name)) {
1987 if ($attributes['style'] === 'checkbox') {
1988 $select[] = sprintf($this->Html->tags['fieldsetstart'], $name);
1989 } else {
1990 $select[] = sprintf($this->Html->tags['optiongroup'], $name, '');
1991 }
1992 }
1993 $name = null;
1994 } elseif (is_array($title)) {
1995 $htmlOptions = $title;
1996 $name = $title['value'];
1997 $title = $title['name'];
1998 unset($htmlOptions['name'], $htmlOptions['value']);
1999 }
2000  
2001 if ($name !== null) {
2002 if (
2003 (!$selectedIsArray && !$selectedIsEmpty && (string)$selected == (string)$name) ||
2004 ($selectedIsArray && in_array($name, $selected))
2005 ) {
2006 if ($attributes['style'] === 'checkbox') {
2007 $htmlOptions['checked'] = true;
2008 } else {
2009 $htmlOptions['selected'] = 'selected';
2010 }
2011 }
2012  
2013 if ($showParents || (!in_array($title, $parents))) {
2014 $title = ($attributes['escape']) ? h($title) : $title;
2015  
2016 if ($attributes['style'] === 'checkbox') {
2017 $htmlOptions['value'] = $name;
2018  
2019 $tagName = Inflector::camelize(
2020 $this->model() . '_' . $this->field().'_'.Inflector::underscore($name)
2021 );
2022 $htmlOptions['id'] = $tagName;
2023 $label = array('for' => $tagName);
2024  
2025 if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
2026 $label['class'] = 'selected';
2027 }
2028  
2029 list($name) = array_values($this->_name());
2030  
2031 if (empty($attributes['class'])) {
2032 $attributes['class'] = 'checkbox';
2033 }
2034 $label = $this->label(null, $title, $label);
2035 $item = sprintf(
2036 $this->Html->tags['checkboxmultiple'], $name,
2037 $this->_parseAttributes($htmlOptions)
2038 );
2039 $select[] = $this->Html->div($attributes['class'], $item . $label);
2040 } else {
2041 $select[] = sprintf(
2042 $this->Html->tags['selectoption'],
2043 $name, $this->_parseAttributes($htmlOptions), $title
2044 );
2045 }
2046 }
2047 }
2048 }
2049  
2050 return array_reverse($select, true);
2051 }
2052  
2053 /**
2054 * Generates option lists for common <select /> menus
2055 * @access private
2056 */
2057 function __generateOptions($name, $options = array()) {
2058 if (!empty($this->options[$name])) {
2059 return $this->options[$name];
2060 }
2061 $data = array();
2062  
2063 switch ($name) {
2064 case 'minute':
2065 if (isset($options['interval'])) {
2066 $interval = $options['interval'];
2067 } else {
2068 $interval = 1;
2069 }
2070 $i = 0;
2071 while ($i < 60) {
2072 $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
2073 $i += $interval;
2074 }
2075 break;
2076 case 'hour':
2077 for ($i = 1; $i <= 12; $i++) {
2078 $data[sprintf('%02d', $i)] = $i;
2079 }
2080 break;
2081 case 'hour24':
2082 for ($i = 0; $i <= 23; $i++) {
2083 $data[sprintf('%02d', $i)] = $i;
2084 }
2085 break;
2086 case 'meridian':
2087 $data = array('am' => 'am', 'pm' => 'pm');
2088 break;
2089 case 'day':
2090 $min = 1;
2091 $max = 31;
2092  
2093 if (isset($options['min'])) {
2094 $min = $options['min'];
2095 }
2096 if (isset($options['max'])) {
2097 $max = $options['max'];
2098 }
2099  
2100 for ($i = $min; $i <= $max; $i++) {
2101 $data[sprintf('%02d', $i)] = $i;
2102 }
2103 break;
2104 case 'month':
2105 if ($options['monthNames'] === true) {
2106 $data['01'] = __('January', true);
2107 $data['02'] = __('February', true);
2108 $data['03'] = __('March', true);
2109 $data['04'] = __('April', true);
2110 $data['05'] = __('May', true);
2111 $data['06'] = __('June', true);
2112 $data['07'] = __('July', true);
2113 $data['08'] = __('August', true);
2114 $data['09'] = __('September', true);
2115 $data['10'] = __('October', true);
2116 $data['11'] = __('November', true);
2117 $data['12'] = __('December', true);
2118 } else if (is_array($options['monthNames'])) {
2119 $data = $options['monthNames'];
2120 } else {
2121 for ($m = 1; $m <= 12; $m++) {
2122 $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
2123 }
2124 }
2125 break;
2126 case 'year':
2127 $current = intval(date('Y'));
2128  
2129 if (!isset($options['min'])) {
2130 $min = $current - 20;
2131 } else {
2132 $min = $options['min'];
2133 }
2134  
2135 if (!isset($options['max'])) {
2136 $max