form.php

Go to the documentation of this file.
00001 <?php
00002 /* SVN FILE: $Id: form.php 8173 2009-05-14 03:26:53Z jperras $ */
00003 /**
00004  * Automatic generation of HTML FORMs from given data.
00005  *
00006  * Used for scaffolding.
00007  *
00008  * PHP versions 4 and 5
00009  *
00010  * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
00011  * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00012  *
00013  * Licensed under The MIT License
00014  * Redistributions of files must retain the above copyright notice.
00015  *
00016  * @filesource
00017  * @copyright     Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
00018  * @link          http://www.cakefoundation.org/projects/info/cakephp CakePHP(tm) Project
00019  * @package       cake
00020  * @subpackage    cake.cake.libs.view.helpers
00021  * @since         CakePHP(tm) v 0.10.0.1076
00022  * @version       $Revision: 8173 $
00023  * @modifiedby    $LastChangedBy: jperras $
00024  * @lastmodified  $Date: 2009-05-13 23:26:53 -0400 (Wed, 13 May 2009) $
00025  * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
00026  */
00027 /**
00028  * Form helper library.
00029  *
00030  * Automatic generation of HTML FORMs from given data.
00031  *
00032  * @package       cake
00033  * @subpackage    cake.cake.libs.view.helpers
00034  */
00035 class FormHelper extends AppHelper {
00036 /**
00037  * Other helpers used by FormHelper
00038  *
00039  * @var array
00040  * @access public
00041  */
00042     var $helpers = array('Html');
00043 /**
00044  * Holds the fields array('field_name' => array('type'=> 'string', 'length'=> 100),
00045  * primaryKey and validates array('field_name')
00046  *
00047  * @access public
00048  */
00049     var $fieldset = array('fields' => array(), 'key' => 'id', 'validates' => array());
00050 /**
00051  * Options used by DateTime fields
00052  *
00053  * @var array
00054  */
00055     var $__options = array(
00056         'day' => array(), 'minute' => array(), 'hour' => array(),
00057         'month' => array(), 'year' => array(), 'meridian' => array()
00058     );
00059 /**
00060  * List of fields created, used with secure forms.
00061  *
00062  * @var array
00063  * @access public
00064  */
00065     var $fields = array();
00066 /**
00067  * Defines the type of form being created.  Set by FormHelper::create().
00068  *
00069  * @var string
00070  * @access public
00071  */
00072     var $requestType = null;
00073 /**
00074  * Returns an HTML FORM element.
00075  *
00076  * Options:
00077  *
00078  * - 'type' Form method defaults to POST
00079  * - 'action'  The Action the form submits to. Can be a string or array,
00080  * - 'url'  The url the form submits to. Can be a string or a url array,
00081  * - 'default'  Allows for the creation of Ajax forms.
00082  * - 'onsubmit' Used in conjunction with 'default' to create ajax forms.
00083  *
00084  * @access public
00085  * @param string $model The model object which the form is being defined for
00086  * @param array $options An array of html attributes and options.
00087  * @return string An formatted opening FORM tag.
00088  */
00089     function create($model = null, $options = array()) {
00090         $defaultModel = null;
00091         $view =& ClassRegistry::getObject('view');
00092 
00093         if (is_array($model) && empty($options)) {
00094             $options = $model;
00095             $model = null;
00096         }
00097 
00098         if (empty($model) && $model !== false && !empty($this->params['models'])) {
00099             $model = $this->params['models'][0];
00100             $defaultModel = $this->params['models'][0];
00101         } elseif (empty($model) && empty($this->params['models'])) {
00102             $model = false;
00103         } elseif (is_string($model) && strpos($model, '.') !== false) {
00104             $path = explode('.', $model);
00105             $model = $path[count($path) - 1];
00106         }
00107 
00108         if (ClassRegistry::isKeySet($model)) {
00109             $object =& ClassRegistry::getObject($model);
00110         }
00111 
00112         $models = ClassRegistry::keys();
00113         foreach ($models as $currentModel) {
00114             if (ClassRegistry::isKeySet($currentModel)) {
00115                 $currentObject =& ClassRegistry::getObject($currentModel);
00116                 if (is_a($currentObject, 'Model') && !empty($currentObject->validationErrors)) {
00117                     $this->validationErrors[Inflector::camelize($currentModel)] =& $currentObject->validationErrors;
00118                 }
00119             }
00120         }
00121 
00122         $this->setEntity($model . '.', true);
00123         $append = '';
00124         $created = $id = false;
00125 
00126         if (isset($object)) {
00127             $fields = $object->schema();
00128             foreach ($fields as $key => $value) {
00129                 unset($fields[$key]);
00130                 $fields[$model . '.' . $key] = $value;
00131             }
00132 
00133             if (!empty($object->hasAndBelongsToMany)) {
00134                 foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
00135                     $fields[$alias] = array('type' => 'multiple');
00136                 }
00137             }
00138             $validates = array();
00139             if (!empty($object->validate)) {
00140                 foreach ($object->validate as $validateField => $validateProperties) {
00141                     if (is_array($validateProperties)) {
00142                         $dims = Set::countDim($validateProperties);
00143                         if (($dims == 1 && !isset($validateProperties['required']) || (array_key_exists('required', $validateProperties) && $validateProperties['required'] !== false))) {
00144                             $validates[] = $validateField;
00145                         } elseif ($dims > 1) {
00146                             foreach ($validateProperties as $rule => $validateProp) {
00147                                 if (is_array($validateProp) && (array_key_exists('required', $validateProp) && $validateProp['required'] !== false)) {
00148                                     $validates[] = $validateField;
00149                                 }
00150                             }
00151                         }
00152                     }
00153                 }
00154             }
00155             $key = $object->primaryKey;
00156             $this->fieldset = compact('fields', 'key', 'validates');
00157         }
00158 
00159         $data = $this->fieldset;
00160         $recordExists = (
00161             isset($this->data[$model]) &&
00162             isset($this->data[$model][$data['key']]) &&
00163             !empty($this->data[$model][$data['key']])
00164         );
00165 
00166         if ($recordExists) {
00167             $created = true;
00168             $id = $this->data[$model][$data['key']];
00169         }
00170         $options = array_merge(array(
00171             'type' => ($created && empty($options['action'])) ? 'put' : 'post',
00172             'action' => null,
00173             'url' => null,
00174             'default' => true),
00175         $options);
00176 
00177         if (empty($options['url']) || is_array($options['url'])) {
00178             if (empty($options['url']['controller'])) {
00179                 if (!empty($model) && $model != $defaultModel) {
00180                     $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
00181                 } elseif (!empty($this->params['controller'])) {
00182                     $options['url']['controller'] = Inflector::underscore($this->params['controller']);
00183                 }
00184             }
00185             if (empty($options['action'])) {
00186                 $options['action'] = ($created) ? 'edit' : 'add';
00187             }
00188 
00189             $actionDefaults = array(
00190                 'plugin' => $this->plugin,
00191                 'controller' => $view->viewPath,
00192                 'action' => $options['action'],
00193                 'id' => $id
00194             );
00195             if (!empty($options['action']) && !isset($options['id'])) {
00196                 $options['id'] = $model . Inflector::camelize($options['action']) . 'Form';
00197             }
00198             $options['action'] = array_merge($actionDefaults, (array)$options['url']);
00199         } elseif (is_string($options['url'])) {
00200             $options['action'] = $options['url'];
00201         }
00202         unset($options['url']);
00203 
00204         switch (strtolower($options['type'])) {
00205             case 'get':
00206                 $htmlAttributes['method'] = 'get';
00207             break;
00208             case 'file':
00209                 $htmlAttributes['enctype'] = 'multipart/form-data';
00210                 $options['type'] = ($created) ? 'put' : 'post';
00211             case 'post':
00212             case 'put':
00213             case 'delete':
00214                 $append .= $this->hidden('_method', array(
00215                     'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null
00216                 ));
00217             default:
00218                 $htmlAttributes['method'] = 'post';
00219             break;
00220         }
00221         $this->requestType = strtolower($options['type']);
00222 
00223         $htmlAttributes['action'] = $this->url($options['action']);
00224         unset($options['type'], $options['action']);
00225 
00226         if ($options['default'] == false) {
00227             if (isset($htmlAttributes['onSubmit']) || isset($htmlAttributes['onsubmit'])) {
00228                 $htmlAttributes['onsubmit'] .= ' event.returnValue = false; return false;';
00229             } else {
00230                 $htmlAttributes['onsubmit'] = 'event.returnValue = false; return false;';
00231             }
00232         }
00233         unset($options['default']);
00234         $htmlAttributes = array_merge($options, $htmlAttributes);
00235 
00236         if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
00237             $append .= $this->hidden('_Token.key', array(
00238                 'value' => $this->params['_Token']['key'], 'id' => 'Token' . mt_rand())
00239             );
00240         }
00241 
00242         if (!empty($append)) {
00243             $append = sprintf($this->Html->tags['fieldset'], ' style="display:none;"', $append);
00244         }
00245 
00246         $this->setEntity($model . '.', true);
00247         $attributes = $this->_parseAttributes($htmlAttributes, null, '');
00248         return $this->output(sprintf($this->Html->tags['form'], $attributes)) . $append;
00249     }
00250 /**
00251  * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
00252  * input fields where appropriate.
00253  *
00254  * If $options is set a form submit button will be created.
00255  *
00256  * @param mixed $options as a string will use $options as the value of button,
00257  *  array usage:
00258  *      array('label' => 'save'); value="save"
00259  *      array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
00260  *      array('name' => 'Whatever'); value="Submit" name="Whatever"
00261  *      array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
00262  *      array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
00263  *
00264  * @return string a closing FORM tag optional submit button.
00265  * @access public
00266  */
00267     function end($options = null) {
00268         if (!empty($this->params['models'])) {
00269             $models = $this->params['models'][0];
00270         }
00271         $out = null;
00272         $submit = null;
00273 
00274         if ($options !== null) {
00275             $submitOptions = array();
00276             if (is_string($options)) {
00277                 $submit = $options;
00278             } else {
00279                 if (isset($options['label'])) {
00280                     $submit = $options['label'];
00281                     unset($options['label']);
00282                 }
00283                 $submitOptions = $options;
00284 
00285                 if (!$submit) {
00286                     $submit = __('Submit', true);
00287                 }
00288             }
00289             $out .= $this->submit($submit, $submitOptions);
00290         }
00291         if (isset($this->params['_Token']) && !empty($this->params['_Token'])) {
00292             $out .= $this->secure($this->fields);
00293             $this->fields = array();
00294         }
00295         $this->setEntity(null);
00296         $out .= $this->Html->tags['formend'];
00297 
00298         $view =& ClassRegistry::getObject('view');
00299         $view->modelScope = false;
00300         return $this->output($out);
00301     }
00302 /**
00303  * Generates a hidden field with a security hash based on the fields used in the form.
00304  *
00305  * @param array $fields The list of fields to use when generating the hash
00306  * @return string A hidden input field with a security hash
00307  * @access public
00308  */
00309     function secure($fields = array()) {
00310         if (!isset($this->params['_Token']) || empty($this->params['_Token'])) {
00311             return;
00312         }
00313         $out = '<fieldset style="display:none;">';
00314         $locked = array();
00315 
00316         foreach ($fields as $key => $value) {
00317             if (!is_int($key)) {
00318                 $locked[$key] = $value;
00319                 unset($fields[$key]);
00320             }
00321         }
00322         sort($fields, SORT_STRING);
00323         ksort($locked, SORT_STRING);
00324         $fields += $locked;
00325 
00326         $fields = Security::hash(serialize($fields) . Configure::read('Security.salt'));
00327         $locked = str_rot13(serialize(array_keys($locked)));
00328 
00329         $out .= $this->hidden('_Token.fields', array(
00330             'value' => urlencode($fields . ':' . $locked),
00331             'id' => 'TokenFields' . mt_rand()
00332         ));
00333         return $out .= '</fieldset>';
00334     }
00335 /**
00336  * Determine which fields of a form should be used for hash
00337  *
00338  * @param mixed $field Reference to field to be secured
00339  * @param mixed $value Field value, if value should not be tampered with
00340  * @access private
00341  */
00342     function __secure($field = null, $value = null) {
00343         if (!$field) {
00344             $view =& ClassRegistry::getObject('view');
00345             $field = $view->entity();
00346         } elseif (is_string($field)) {
00347             $field = Set::filter(explode('.', $field), true);
00348         }
00349 
00350         if (!empty($this->params['_Token']['disabledFields'])) {
00351             foreach ((array)$this->params['_Token']['disabledFields'] as $disabled) {
00352                 $disabled = explode('.', $disabled);
00353                 if (array_values(array_intersect($field, $disabled)) === $disabled) {
00354                     return;
00355                 }
00356             }
00357         }
00358         $field = join('.', $field);
00359         if (!in_array($field, $this->fields)) {
00360             if ($value !== null) {
00361                 return $this->fields[$field] = $value;
00362             }
00363             $this->fields[] = $field;
00364         }
00365     }
00366 /**
00367  * Returns true if there is an error for the given field, otherwise false
00368  *
00369  * @param string $field This should be "Modelname.fieldname"
00370  * @return boolean If there are errors this method returns true, else false.
00371  * @access public
00372  */
00373     function isFieldError($field) {
00374         $this->setEntity($field);
00375         return (bool)$this->tagIsInvalid();
00376     }
00377 /**
00378  * Returns a formatted error message for given FORM field, NULL if no errors.
00379  *
00380  * Options:
00381  *
00382  * - 'escape'  bool  Whether or not to html escape the contents of the error.
00383  * - 'wrap'  mixed  Whether or not the error message should be wrapped in a div. If a
00384  *   string, will be used as the HTML tag to use.
00385  * - 'class'  string  The classname for the error message
00386  *
00387  * @param string $field  A field name, like "Modelname.fieldname"
00388  * @param mixed $text  Error message or array of $options
00389  * @param array $options  Rendering options for <div /> wrapper tag
00390  * @return string If there are errors this method returns an error message, otherwise null.
00391  * @access public
00392  */
00393     function error($field, $text = null, $options = array()) {
00394         $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
00395         $options = array_merge($defaults, $options);
00396         $this->setEntity($field);
00397 
00398         if ($error = $this->tagIsInvalid()) {
00399             if (is_array($error)) {
00400                 list(,,$field) = explode('.', $field);
00401                 if (isset($error[$field])) {
00402                     $error = $error[$field];
00403                 } else {
00404                     return null;
00405                 }
00406             }
00407 
00408             if (is_array($text) && is_numeric($error) && $error > 0) {
00409                 $error--;
00410             }
00411             if (is_array($text) && isset($text[$error])) {
00412                 $text = $text[$error];
00413             } elseif (is_array($text)) {
00414                 $options = array_merge($options, $text);
00415                 $text = null;
00416             }
00417 
00418             if ($text != null) {
00419                 $error = $text;
00420             } elseif (is_numeric($error)) {
00421                 $error = sprintf(__('Error in field %s', true), Inflector::humanize($this->field()));
00422             }
00423             if ($options['escape']) {
00424                 $error = h($error);
00425                 unset($options['escape']);
00426             }
00427             if ($options['wrap']) {
00428                 $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
00429                 unset($options['wrap']);
00430                 return $this->Html->tag($tag, $error, $options);
00431             } else {
00432                 return $error;
00433             }
00434         } else {
00435             return null;
00436         }
00437     }
00438 /**
00439  * Returns a formatted LABEL element for HTML FORMs.
00440  *
00441  * @param string $fieldName This should be "Modelname.fieldname"
00442  * @param string $text Text that will appear in the label field.
00443  * @param array $attributes Array of HTML attributes.
00444  * @return string The formatted LABEL element
00445  */
00446     function label($fieldName = null, $text = null, $attributes = array()) {
00447         if (empty($fieldName)) {
00448             $view = ClassRegistry::getObject('view');
00449             $fieldName = implode('.', $view->entity());
00450         }
00451 
00452         if ($text === null) {
00453             if (strpos($fieldName, '.') !== false) {
00454                 $text = array_pop(explode('.', $fieldName));
00455             } else {
00456                 $text = $fieldName;
00457             }
00458             if (substr($text, -3) == '_id') {
00459                 $text = substr($text, 0, strlen($text) - 3);
00460             }
00461             $text = __(Inflector::humanize(Inflector::underscore($text)), true);
00462         }
00463 
00464         if (isset($attributes['for'])) {
00465             $labelFor = $attributes['for'];
00466             unset($attributes['for']);
00467         } else {
00468             $labelFor = $this->domId($fieldName);
00469         }
00470 
00471         return $this->output(sprintf(
00472             $this->Html->tags['label'],
00473             $labelFor,
00474             $this->_parseAttributes($attributes), $text
00475         ));
00476     }
00477 /**
00478  * Will display all the fields passed in an array expects fieldName as an array key
00479  * replaces generateFields
00480  *
00481  * @access public
00482  * @param array $fields works well with Controller::generateFields() or on its own;
00483  * @param array $blacklist a simple array of fields to skip
00484  * @return output
00485  */
00486     function inputs($fields = null, $blacklist = null) {
00487         $fieldset = $legend = true;
00488 
00489         if (is_array($fields)) {
00490             if (array_key_exists('legend', $fields)) {
00491                 $legend = $fields['legend'];
00492                 unset($fields['legend']);
00493             }
00494 
00495             if (isset($fields['fieldset'])) {
00496                 $fieldset = $fields['fieldset'];
00497                 unset($fields['fieldset']);
00498             }
00499         } elseif ($fields !== null) {
00500             $fieldset = $legend = $fields;
00501             if (!is_bool($fieldset)) {
00502                 $fieldset = true;
00503             }
00504             $fields = array();
00505         }
00506 
00507         if (empty($fields)) {
00508             $fields = array_keys($this->fieldset['fields']);
00509         }
00510 
00511         if ($legend === true) {
00512             $actionName = __('New', true);
00513             $isEdit = (
00514                 strpos($this->action, 'update') !== false ||
00515                 strpos($this->action, 'edit') !== false
00516             );
00517             if ($isEdit) {
00518                 $actionName = __('Edit', true);
00519             }
00520             $modelName = Inflector::humanize(Inflector::underscore($this->model()));
00521             $legend = $actionName .' '. __($modelName, true);
00522         }
00523 
00524         $out = null;
00525         foreach ($fields as $name => $options) {
00526             if (is_numeric($name) && !is_array($options)) {
00527                 $name = $options;
00528                 $options = array();
00529             }
00530             $entity = explode('.', $name);
00531             $blacklisted = (
00532                 is_array($blacklist) &&
00533                 (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
00534             );
00535             if ($blacklisted) {
00536                 continue;
00537             }
00538             $out .= $this->input($name, $options);
00539         }
00540 
00541         if (is_string($fieldset)) {
00542             $fieldsetClass = sprintf(' class="%s"', $fieldset);
00543         } else {
00544             $fieldsetClass = '';
00545         }
00546 
00547         if ($fieldset && $legend) {
00548             return sprintf(
00549                 $this->Html->tags['fieldset'],
00550                 $fieldsetClass,
00551                 sprintf($this->Html->tags['legend'], $legend) . $out
00552             );
00553         } elseif ($fieldset) {
00554             return sprintf($this->Html->tags['fieldset'], $fieldsetClass, $out);
00555         } else {
00556             return $out;
00557         }
00558     }
00559 /**
00560  * Generates a form input element complete with label and wrapper div
00561  *
00562  * Options - See each field type method for more information. Any options that are part of 
00563  * $attributes or $options for the different type methods can be included in $options for input().
00564  *
00565  * - 'type' - Force the type of widget you want. e.g. ```type => 'select'```
00566  * - 'label' - control the label
00567  * - 'div' - control the wrapping div element
00568  * - 'options' - for widgets that take options e.g. radio, select
00569  * - 'error' - control the error message that is produced
00570  *
00571  * @param string $fieldName This should be "Modelname.fieldname"
00572  * @param array $options Each type of input takes different options.
00573  * @return string Completed form widget
00574  */
00575     function input($fieldName, $options = array()) {
00576         $view =& ClassRegistry::getObject('view');
00577         $this->setEntity($fieldName);
00578         $entity = join('.', $view->entity());
00579 
00580         $defaults = array('before' => null, 'between' => null, 'after' => null);
00581         $options = array_merge($defaults, $options);
00582 
00583         if (!isset($options['type'])) {
00584             $options['type'] = 'text';
00585 
00586             if (isset($options['options'])) {
00587                 $options['type'] = 'select';
00588             } elseif (in_array($this->field(), array('psword', 'passwd', 'password'))) {
00589                 $options['type'] = 'password';
00590             } elseif (isset($this->fieldset['fields'][$entity])) {
00591                 $fieldDef = $this->fieldset['fields'][$entity];
00592                 $type = $fieldDef['type'];
00593                 $primaryKey = $this->fieldset['key'];
00594             } elseif (ClassRegistry::isKeySet($this->model())) {
00595                 $model =& ClassRegistry::getObject($this->model());
00596                 $type = $model->getColumnType($this->field());
00597                 $fieldDef = $model->schema();
00598 
00599                 if (isset($fieldDef[$this->field()])) {
00600                     $fieldDef = $fieldDef[$this->field()];
00601                 } else {
00602                     $fieldDef = array();
00603                 }
00604                 $primaryKey = $model->primaryKey;
00605             }
00606 
00607             if (isset($type)) {
00608                 $map = array(
00609                     'string'  => 'text',     'datetime'  => 'datetime',
00610                     'boolean' => 'checkbox', 'timestamp' => 'datetime',
00611                     'text'    => 'textarea', 'time'      => 'time',
00612                     'date'    => 'date',     'float'     => 'text'
00613                 );
00614 
00615                 if (isset($this->map[$type])) {
00616                     $options['type'] = $this->map[$type];
00617                 } elseif (isset($map[$type])) {
00618                     $options['type'] = $map[$type];
00619                 }
00620                 if ($this->field() == $primaryKey) {
00621                     $options['type'] = 'hidden';
00622                 }
00623             }
00624 
00625             if ($this->model() === $this->field()) {
00626                 $options['type'] = 'select';
00627                 if (!isset($options['multiple'])) {
00628                     $options['multiple'] = 'multiple';
00629                 }
00630             }
00631         }
00632         $types = array('text', 'checkbox', 'radio', 'select');
00633 
00634         if (!isset($options['options']) && in_array($options['type'], $types)) {
00635             $view =& ClassRegistry::getObject('view');
00636             $varName = Inflector::variable(
00637                 Inflector::pluralize(preg_replace('/_id$/', '', $this->field()))
00638             );
00639             $varOptions = $view->getVar($varName);
00640             if (is_array($varOptions)) {
00641                 if ($options['type'] !== 'radio') {
00642                     $options['type'] = 'select';
00643                 }
00644                 $options['options'] = $varOptions;
00645             }
00646         }
00647 
00648         $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length']));
00649         if ($autoLength && $options['type'] == 'text') {
00650             $options['maxlength'] = $fieldDef['length'];
00651         }
00652         if ($autoLength && $fieldDef['type'] == 'float') {
00653             $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1;
00654         }
00655 
00656         $out = '';
00657         $div = true;
00658         $divOptions = array();
00659 
00660         if (array_key_exists('div', $options)) {
00661             $div = $options['div'];
00662             unset($options['div']);
00663         }
00664 
00665         if (!empty($div)) {
00666             $divOptions['class'] = 'input';
00667             $divOptions = $this->addClass($divOptions, $options['type']);
00668             if (is_string($div)) {
00669                 $divOptions['class'] = $div;
00670             } elseif (is_array($div)) {
00671                 $divOptions = array_merge($divOptions, $div);
00672             }
00673             if (in_array($this->field(), $this->fieldset['validates'])) {
00674                 $divOptions = $this->addClass($divOptions, 'required');
00675             }
00676             if (!isset($divOptions['tag'])) {
00677                 $divOptions['tag'] = 'div';
00678             }
00679         }
00680 
00681         $label = null;
00682         if (isset($options['label']) && $options['type'] !== 'radio') {
00683             $label = $options['label'];
00684             unset($options['label']);
00685         }
00686 
00687         if ($options['type'] === 'radio') {
00688             $label = false;
00689             if (isset($options['options'])) {
00690                 if (is_array($options['options'])) {
00691                     $radioOptions = $options['options'];
00692                 } else {
00693                     $radioOptions = array($options['options']);
00694                 }
00695                 unset($options['options']);
00696             }
00697         }
00698 
00699         if ($label !== false) {
00700             $labelAttributes = $this->domId(array(), 'for');
00701             if (in_array($options['type'], array('date', 'datetime'))) {
00702                 $labelAttributes['for'] .= 'Month';
00703             } else if ($options['type'] === 'time') {
00704                 $labelAttributes['for'] .= 'Hour';
00705             }
00706 
00707             if (is_array($label)) {
00708                 $labelText = null;
00709                 if (isset($label['text'])) {
00710                     $labelText = $label['text'];
00711                     unset($label['text']);
00712                 }
00713                 $labelAttributes = array_merge($labelAttributes, $label);
00714             } else {
00715                 $labelText = $label;
00716             }
00717 
00718             if (isset($options['id'])) {
00719                 $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
00720             }
00721             $out = $this->label($fieldName, $labelText, $labelAttributes);
00722         }
00723 
00724         $error = null;
00725         if (isset($options['error'])) {
00726             $error = $options['error'];
00727             unset($options['error']);
00728         }
00729 
00730         $selected = null;
00731         if (array_key_exists('selected', $options)) {
00732             $selected = $options['selected'];
00733             unset($options['selected']);
00734         }
00735         if (isset($options['rows']) || isset($options['cols'])) {
00736             $options['type'] = 'textarea';
00737         }
00738 
00739         $empty = false;
00740         if (isset($options['empty'])) {
00741             $empty = $options['empty'];
00742             unset($options['empty']);
00743         }
00744 
00745         $timeFormat = 12;
00746         if (isset($options['timeFormat'])) {
00747             $timeFormat = $options['timeFormat'];
00748             unset($options['timeFormat']);
00749         }
00750 
00751         $dateFormat = 'MDY';
00752         if (isset($options['dateFormat'])) {
00753             $dateFormat = $options['dateFormat'];
00754             unset($options['dateFormat']);
00755         }
00756 
00757         $type    = $options['type'];
00758         $before  = $options['before'];
00759         $between = $options['between'];
00760         $after   = $options['after'];
00761         unset($options['type'], $options['before'], $options['between'], $options['after']);
00762 
00763         switch ($type) {
00764             case 'hidden':
00765                 $out = $this->hidden($fieldName, $options);
00766                 unset($divOptions);
00767             break;
00768             case 'checkbox':
00769                 $out = $before . $this->checkbox($fieldName, $options) . $between . $out;
00770             break;
00771             case 'radio':
00772                 $out = $before . $out . $this->radio($fieldName, $radioOptions, $options) . $between;
00773             break;
00774             case 'text':
00775             case 'password':
00776                 $out = $before . $out . $between . $this->{$type}($fieldName, $options);
00777             break;
00778             case 'file':
00779                 $out = $before . $out . $between . $this->file($fieldName, $options);
00780             break;
00781             case 'select':
00782                 $options = array_merge(array('options' => array()), $options);
00783                 $list = $options['options'];
00784                 unset($options['options']);
00785                 $out = $before . $out . $between . $this->select(
00786                     $fieldName, $list, $selected, $options, $empty
00787                 );
00788             break;
00789             case 'time':
00790                 $out = $before . $out . $between . $this->dateTime(
00791                     $fieldName, null, $timeFormat, $selected, $options, $empty
00792                 );
00793             break;
00794             case 'date':
00795                 $out = $before . $out . $between . $this->dateTime(
00796                     $fieldName, $dateFormat, null, $selected, $options, $empty
00797                 );
00798             break;
00799             case 'datetime':
00800                 $out = $before . $out . $between . $this->dateTime(
00801                     $fieldName, $dateFormat, $timeFormat, $selected, $options, $empty
00802                 );
00803             break;
00804             case 'textarea':
00805             default:
00806                 $out = $before . $out . $between . $this->textarea($fieldName, array_merge(
00807                     array('cols' => '30', 'rows' => '6'), $options
00808                 ));
00809             break;
00810         }
00811 
00812         if ($type != 'hidden') {
00813             $out .= $after;
00814             if ($error !== false) {
00815                 $errMsg = $this->error($fieldName, $error);
00816                 if ($errMsg) {
00817                     $out .= $errMsg;
00818                     $divOptions = $this->addClass($divOptions, 'error');
00819                 }
00820             }
00821         }
00822         if (isset($divOptions) && isset($divOptions['tag'])) {
00823             $tag = $divOptions['tag'];
00824             unset($divOptions['tag']);
00825             $out = $this->Html->tag($tag, $out, $divOptions);
00826         }
00827         return $out;
00828     }
00829 /**
00830  * Creates a checkbox input widget.
00831  *
00832  * Options:
00833  *
00834  * - 'value' - the value of the checkbox
00835  * - checked' - boolean indicate that this checkbox is checked.
00836  *
00837  * @param string $fieldName Name of a field, like this "Modelname.fieldname"
00838  * @param array $options Array of HTML attributes.
00839  * @todo Right now, automatically setting the 'checked' value is dependent on whether or not the
00840  *    checkbox is bound to a model.  This should probably be re-evaluated in future versions.
00841  * @return string An HTML text input element
00842  */
00843     function checkbox($fieldName, $options = array()) {
00844         $options = $this->_initInputField($fieldName, $options);
00845         $value = current($this->value());
00846 
00847         if (!isset($options['value']) || empty($options['value'])) {
00848             $options['value'] = 1;
00849         } elseif (!empty($value) && $value === $options['value']) {
00850             $options['checked'] = 'checked';
00851         }
00852         $hiddenOptions = array(
00853             'id' => $options['id'] . '_', 'name' => $options['name'],
00854             'value' => '0', 'secure' => false
00855         );
00856         if (isset($options['disabled']) && $options['disabled'] == true) {
00857             $hiddenOptions['disabled'] = 'disabled';
00858         }
00859         $output = $this->hidden($fieldName, $hiddenOptions);
00860 
00861         return $this->output($output . sprintf(
00862             $this->Html->tags['checkbox'],
00863             $options['name'],
00864             $this->_parseAttributes($options, array('name'), null, ' ')
00865         ));
00866     }
00867 /**
00868  * Creates a set of radio widgets.
00869  *
00870  * Attributes:
00871  *
00872  * - 'separator' - define the string in between the radio buttons
00873  * - 'legend' - control whether or not the widget set has a fieldset & legend
00874  * - 'value' - indicate a value that is should be checked
00875  * - 'label' - boolean to indicate whether or not labels for widgets show be displayed
00876  *
00877  * @param string $fieldName Name of a field, like this "Modelname.fieldname"
00878  * @param array $options Radio button options array.
00879  * @param array $attributes Array of HTML attributes.
00880  * @return string
00881  */
00882     function radio($fieldName, $options = array(), $attributes = array()) {
00883         $attributes = $this->_initInputField($fieldName, $attributes);
00884         $legend = false;
00885 
00886         if (isset($attributes['legend'])) {
00887             $legend = $attributes['legend'];
00888             unset($attributes['legend']);
00889         } elseif (count($options) > 1) {
00890             $legend = __(Inflector::humanize($this->field()), true);
00891         }
00892         $label = true;
00893 
00894         if (isset($attributes['label'])) {
00895             $label = $attributes['label'];
00896             unset($attributes['label']);
00897         }
00898         $inbetween = null;
00899 
00900         if (isset($attributes['separator'])) {
00901             $inbetween = $attributes['separator'];
00902             unset($attributes['separator']);
00903         }
00904 
00905         if (isset($attributes['value'])) {
00906             $value = $attributes['value'];
00907         } else {
00908             $value =  $this->value($fieldName);
00909         }
00910         $out = array();
00911 
00912         foreach ($options as $optValue => $optTitle) {
00913             $optionsHere = array('value' => $optValue);
00914 
00915             if (isset($value) && $optValue == $value) {
00916                 $optionsHere['checked'] = 'checked';
00917             }
00918             $parsedOptions = $this->_parseAttributes(
00919                 array_merge($attributes, $optionsHere),
00920                 array('name', 'type', 'id'), '', ' '
00921             );
00922             $tagName = Inflector::camelize(
00923                 $attributes['id'] . '_' . Inflector::underscore($optValue)
00924             );
00925 
00926             if ($label) {
00927                 $optTitle =  sprintf($this->Html->tags['label'], $tagName, null, $optTitle);
00928             }
00929             $out[] =  sprintf(
00930                 $this->Html->tags['radio'], $attributes['name'],
00931                 $tagName, $parsedOptions, $optTitle
00932             );
00933         }
00934         $hidden = null;
00935 
00936         if (!isset($value) || $value === '') {
00937             $hidden = $this->hidden($fieldName, array(
00938                 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name']
00939             ));
00940         }
00941         $out = $hidden . join($inbetween, $out);
00942 
00943         if ($legend) {
00944             $out = sprintf(
00945                 $this->Html->tags['fieldset'], '',
00946                 sprintf($this->Html->tags['legend'], $legend) . $out
00947             );
00948         }
00949         return $this->output($out);
00950     }
00951 /**
00952  * Creates a text input widget.
00953  *
00954  * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
00955  * @param array  $options Array of HTML attributes.
00956  * @return string An HTML text input element
00957  */
00958     function text($fieldName, $options = array()) {
00959         $options = $this->_initInputField($fieldName, array_merge(
00960             array('type' => 'text'), $options
00961         ));
00962         return $this->output(sprintf(
00963             $this->Html->tags['input'],
00964             $options['name'],
00965             $this->_parseAttributes($options, array('name'), null, ' ')
00966         ));
00967     }
00968 /**
00969  * Creates a password input widget.
00970  *
00971  * @param  string  $fieldName Name of a field, like in the form "Modelname.fieldname"
00972  * @param  array    $options Array of HTML attributes.
00973  * @return string
00974  */
00975     function password($fieldName, $options = array()) {
00976         $options = $this->_initInputField($fieldName, $options);
00977         return $this->output(sprintf(
00978             $this->Html->tags['password'],
00979             $options['name'],
00980             $this->_parseAttributes($options, array('name'), null, ' ')
00981         ));
00982     }
00983 /**
00984  * Creates a textarea widget.
00985  *
00986  * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
00987  * @param array $options Array of HTML attributes.
00988  * @return string An HTML text input element
00989  */
00990     function textarea($fieldName, $options = array()) {
00991         $options = $this->_initInputField($fieldName, $options);
00992         $value = null;
00993 
00994         if (array_key_exists('value', $options)) {
00995             $value = $options['value'];
00996             if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
00997                 $value = h($value);
00998             }
00999             unset($options['value']);
01000         }
01001         return $this->output(sprintf(
01002             $this->Html->tags['textarea'],
01003             $options['name'],
01004             $this->_parseAttributes($options, array('type', 'name'), null, ' '),
01005             $value
01006         ));
01007     }
01008 /**
01009  * Creates a hidden input field.
01010  *
01011  * @param string $fieldName Name of a field, in the form"Modelname.fieldname"
01012  * @param array $options Array of HTML attributes.
01013  * @return string
01014  * @access public
01015  */
01016     function hidden($fieldName, $options = array()) {
01017         $secure = true;
01018 
01019         if (isset($options['secure'])) {
01020             $secure = $options['secure'];
01021             unset($options['secure']);
01022         }
01023         $options = $this->_initInputField($fieldName, array_merge(
01024             $options, array('secure' => false)
01025         ));
01026         $model = $this->model();
01027 
01028         if ($fieldName !== '_method' && $model !== '_Token' && $secure) {
01029             $this->__secure(null, '' . $options['value']);
01030         }
01031 
01032         return $this->output(sprintf(
01033             $this->Html->tags['hidden'],
01034             $options['name'],
01035             $this->_parseAttributes($options, array('name', 'class'), '', ' ')
01036         ));
01037     }
01038 /**
01039  * Creates file input widget.
01040  *
01041  * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
01042  * @param array $options Array of HTML attributes.
01043  * @return string
01044  * @access public
01045  */
01046     function file($fieldName, $options = array()) {
01047         $options = array_merge($options, array('secure' => false));
01048         $options = $this->_initInputField($fieldName, $options);
01049         $view =& ClassRegistry::getObject('view');
01050         $field = $view->entity();
01051 
01052         foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
01053             $this->__secure(array_merge($field, array($suffix)));
01054         }
01055 
01056         $attributes = $this->_parseAttributes($options, array('name'), '', ' ');
01057         return $this->output(sprintf($this->Html->tags['file'], $options['name'], $attributes));
01058     }
01059 /**
01060  * Creates a button tag.
01061  *
01062  * @param string $title  The button's caption
01063  * @param array $options Array of options.
01064  * @return string A HTML button tag.
01065  * @access public
01066  */
01067     function button($title, $options = array()) {
01068         $options = array_merge(array('type' => 'button', 'value' => $title), $options);
01069 
01070         if (isset($options['name']) && strpos($options['name'], '.') !== false) {
01071             if ($this->value($options['name'])) {
01072                 $options['checked'] = 'checked';
01073             }
01074             $name = $options['name'];
01075             unset($options['name']);
01076             $options = $this->_initInputField($name, $options);
01077         }
01078         return $this->output(sprintf(
01079             $this->Html->tags['button'],
01080             $options['type'],
01081             $this->_parseAttributes($options, array('type'), '', ' ')
01082         ));
01083     }
01084 /**
01085  * Creates a submit button element.
01086  *
01087  * @param string $caption The label appearing on the button OR if string contains :// or the
01088  *  extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
01089  *  exists, AND the first character is /, image is relative to webroot,
01090  *  OR if the first character is not /, image is relative to webroot/img.
01091  * @param array $options 
01092  * @return string A HTML submit button
01093  */
01094     function submit($caption = null, $options = array()) {
01095         if (!$caption) {
01096             $caption = __('Submit', true);
01097         }
01098         $out = null;
01099         $div = true;
01100 
01101         if (isset($options['div'])) {
01102             $div = $options['div'];
01103             unset($options['div']);
01104         }
01105         $divOptions = array('tag' => 'div');
01106 
01107         if ($div === true) {
01108             $divOptions['class'] = 'submit';
01109         } elseif ($div === false) {
01110             unset($divOptions);
01111         } elseif (is_string($div)) {
01112             $divOptions['class'] = $div;
01113         } elseif (is_array($div)) {
01114             $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
01115         }
01116 
01117         if (strpos($caption, '://') !== false) {
01118             $out .= $this->output(sprintf(
01119                 $this->Html->tags['submitimage'],
01120                 $caption,
01121                 $this->_parseAttributes($options, null, '', ' ')
01122             ));
01123         } elseif (preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption)) {
01124             if ($caption{0} !== '/') {
01125                 $url = $this->webroot(IMAGES_URL . $caption);
01126             } else {
01127                 $caption = trim($caption, '/');
01128                 $url = $this->webroot($caption);
01129             }
01130             $out .= $this->output(sprintf(
01131                 $this->Html->tags['submitimage'],
01132                 $url,
01133                 $this->_parseAttributes($options, null, '', ' ')
01134             ));
01135         } else {
01136             $options['value'] = $caption;
01137             $out .= $this->output(sprintf(
01138                 $this->Html->tags['submit'],
01139                 $this->_parseAttributes($options, null, '', ' ')
01140             ));
01141         }
01142 
01143         if (isset($divOptions)) {
01144             $tag = $divOptions['tag'];
01145             unset($divOptions['tag']);
01146             $out = $this->Html->tag($tag, $out, $divOptions);
01147         }
01148         return $out;
01149     }
01150 /**
01151  * Returns a formatted SELECT element.
01152  *
01153  * Attributes:
01154  *
01155  * - 'showParents' - If included in the array and set to true, an additional option element
01156  *   will be added for the parent of each option group.
01157  * - 'multiple' - show a multiple select box.  If set to 'checkbox' multiple checkboxes will be
01158  *   created instead.
01159  *
01160  * @param string $fieldName Name attribute of the SELECT
01161  * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
01162  *    SELECT element
01163  * @param mixed $selected The option selected by default.  If null, the default value
01164  *   from POST data will be used when available.
01165  * @param array $attributes The HTML attributes of the select element.
01166  * @param mixed $showEmpty If true, the empty select option is shown.  If a string,
01167  *   that string is displayed as the empty element.
01168  * @return string Formatted SELECT element
01169  */
01170     function select($fieldName, $options = array(), $selected = null, $attributes = array(), $showEmpty = '') {
01171         $select = array();
01172         $showParents = false;
01173         $escapeOptions = true;
01174         $style = null;
01175         $tag = null;
01176 
01177         if (isset($attributes['escape'])) {
01178             $escapeOptions = $attributes['escape'];
01179             unset($attributes['escape']);
01180         }
01181         $attributes = $this->_initInputField($fieldName, array_merge(
01182             (array)$attributes, array('secure' => false)
01183         ));
01184 
01185         if (is_string($options) && isset($this->__options[$options])) {
01186             $options = $this->__generateOptions($options);
01187         } elseif (!is_array($options)) {
01188             $options = array();
01189         }
01190         if (isset($attributes['type'])) {
01191             unset($attributes['type']);
01192         }
01193         if (in_array('showParents', $attributes)) {
01194             $showParents = true;
01195             unset($attributes['showParents']);
01196         }
01197 
01198         if (!isset($selected)) {
01199             $selected = $attributes['value'];
01200         }
01201 
01202         if (isset($attributes) && array_key_exists('multiple', $attributes)) {
01203             $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
01204             $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
01205             $tag = $this->Html->tags[$template];
01206             $select[] = $this->hidden(null, array('value' => '', 'id' => null, 'secure' => false));
01207         } else {
01208             $tag = $this->Html->tags['selectstart'];
01209         }
01210 
01211         if (!empty($tag) || isset($template)) {
01212             $this->__secure();
01213             $select[] = sprintf($tag, $attributes['name'], $this->_parseAttributes(
01214                 $attributes, array('name', 'value'))
01215             );
01216         }
01217         $emptyMulti = (
01218             $showEmpty !== null && $showEmpty !== false && !(
01219                 empty($showEmpty) && (isset($attributes) &&
01220                 array_key_exists('multiple', $attributes))
01221             )
01222         );
01223 
01224         if ($emptyMulti) {
01225             $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
01226             $options = array_reverse($options, true);
01227             $options[''] = $showEmpty;
01228             $options = array_reverse($options, true);
01229         }
01230 
01231         $select = array_merge($select, $this->__selectOptions(
01232             array_reverse($options, true),
01233             $selected,
01234             array(),
01235             $showParents,
01236             array('escape' => $escapeOptions, 'style' => $style)
01237         ));
01238 
01239         $template = ($style == 'checkbox') ? 'checkboxmultipleend' : 'selectend';
01240         $select[] = $this->Html->tags[$template];
01241         return $this->output(implode("\n", $select));
01242     }
01243 /**
01244  * Returns a SELECT element for days.
01245  *
01246  * @param string $fieldName Prefix name for the SELECT element
01247  * @param string $selected Option which is selected.
01248  * @param array  $attributes HTML attributes for the select element
01249  * @param mixed $showEmpty Show/hide the empty select option
01250  * @return string
01251  */
01252     function day($fieldName, $selected = null, $attributes = array(), $showEmpty = true) {
01253         if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
01254             if (is_array($value)) {
01255                 extract($value);
01256                 $selected = $day;
01257             } else {
01258                 if (empty($value)) {
01259                     if (!$showEmpty) {
01260                         $selected = 'now';
01261                     }
01262                 } else {
01263                     $selected = $value;
01264                 }
01265             }
01266         }
01267 
01268         if (strlen($selected) > 2) {
01269             $selected = date('d', strtotime($selected));
01270         } elseif ($selected === false) {
01271             $selected = null;
01272         }
01273         return $this->select(
01274             $fieldName . ".day", $this->__generateOptions('day'), $selected, $attributes, $showEmpty
01275         );
01276     }
01277 /**
01278  * Returns a SELECT element for years
01279  *
01280  * @param string $fieldName Prefix name for the SELECT element
01281  * @param integer $minYear First year in sequence
01282  * @param integer $maxYear Last year in sequence
01283  * @param string $selected Option which is selected.
01284  * @param array $attributes Attribute array for the select elements.
01285  * @param boolean $showEmpty Show/hide the empty select option
01286  * @return string
01287  */
01288     function year($fieldName, $minYear = null, $maxYear = null, $selected = null, $attributes = array(), $showEmpty = true) {
01289         if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
01290             if (is_array($value)) {
01291                 extract($value);
01292                 $selected = $year;
01293             } else {
01294                 if (empty($value)) {
01295                     if (!$showEmpty && !$maxYear) {
01296                         $selected = 'now';
01297 
01298                     } elseif (!$showEmpty && $maxYear && !$selected) {
01299                         $selected = $maxYear;
01300                     }
01301                 } else {
01302                     $selected = $value;
01303                 }
01304             }
01305         }
01306 
01307         if (strlen($selected) > 4 || $selected === 'now') {
01308             $selected = date('Y', strtotime($selected));
01309         } elseif ($selected === false) {
01310             $selected = null;
01311         }
01312         $yearOptions = array('min' => $minYear, 'max' => $maxYear);
01313         return $this->select(
01314             $fieldName . ".year", $this->__generateOptions('year', $yearOptions),
01315             $selected, $attributes, $showEmpty
01316         );
01317     }
01318 /**
01319  * Returns a SELECT element for months.
01320  *
01321  * Attributes:
01322  *
01323  * - 'monthNames' is set and false 2 digit numbers will be used instead of text.
01324  *
01325  * @param string $fieldName Prefix name for the SELECT element
01326  * @param string $selected Option which is selected.
01327  * @param array $attributes Attributes for the select element
01328  * @param boolean $showEmpty Show/hide the empty select option
01329  * @return string
01330  */
01331     function month($fieldName, $selected = null, $attributes = array(), $showEmpty = true) {
01332         if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
01333             if (is_array($value)) {
01334                 extract($value);
01335                 $selected = $month;
01336             } else {
01337                 if (empty($value)) {
01338                     if (!$showEmpty) {
01339                         $selected = 'now';
01340                     }
01341                 } else {
01342                     $selected = $value;
01343                 }
01344             }
01345         }
01346 
01347         if (strlen($selected) > 2) {
01348             $selected = date('m', strtotime($selected));
01349         } elseif ($selected === false) {
01350             $selected = null;
01351         }
01352         $defaults = array('monthNames' => true);
01353         $attributes = array_merge($defaults, (array) $attributes);
01354         $monthNames = $attributes['monthNames'];
01355         unset($attributes['monthNames']);
01356 
01357         return $this->select(
01358             $fieldName . ".month",
01359             $this->__generateOptions('month', array('monthNames' => $monthNames)),
01360             $selected, $attributes, $showEmpty
01361         );
01362     }
01363 /**
01364  * Returns a SELECT element for hours.
01365  *
01366  * @param string $fieldName Prefix name for the SELECT element
01367  * @param boolean $format24Hours True for 24 hours format
01368  * @param string $selected Option which is selected.
01369  * @param array $attributes List of HTML attributes
01370  * @param mixed $showEmpty True to show an empty element, or a string to provide default empty element text
01371  * @return string
01372  */
01373     function hour($fieldName, $format24Hours = false, $selected = null, $attributes = array(), $showEmpty = true) {
01374         if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
01375             if (is_array($value)) {
01376                 extract($value);
01377                 $selected = $hour;
01378             } else {
01379                 if (empty($value)) {
01380                     if (!$showEmpty) {
01381                         $selected = 'now';
01382                     }
01383                 } else {
01384                     $selected = $value;
01385                 }
01386             }
01387         } else {
01388             $value = $selected;
01389         }
01390 
01391         if (strlen($selected) > 2) {
01392             if ($format24Hours) {
01393                 $selected = date('H', strtotime($value));
01394             } else {
01395                 $selected = date('g', strtotime($value));
01396             }
01397         } elseif ($selected === false) {
01398             $selected = null;
01399         }
01400         return $this->select(
01401             $fieldName . ".hour",
01402             $this->__generateOptions($format24Hours ? 'hour24' : 'hour'),
01403             $selected, $attributes, $showEmpty
01404         );
01405     }
01406 /**
01407  * Returns a SELECT element for minutes.
01408  *
01409  * @param string $fieldName Prefix name for the SELECT element
01410  * @param string $selected Option which is selected.
01411  * @param string $attributes Array of Attributes
01412  * @param bool $showEmpty True to show an empty element, or a string to provide default empty element text
01413  * @return string
01414  */
01415     function minute($fieldName, $selected = null, $attributes = array(), $showEmpty = true) {
01416         if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
01417             if (is_array($value)) {
01418                 extract($value);
01419                 $selected = $min;
01420             } else {
01421                 if (empty($value)) {
01422                     if (!$showEmpty) {
01423                         $selected = 'now';
01424                     }
01425                 } else {
01426                     $selected = $value;
01427                 }
01428             }
01429         }
01430 
01431         if (strlen($selected) > 2) {
01432             $selected = date('i', strtotime($selected));
01433         } elseif ($selected === false) {
01434             $selected = null;
01435         }
01436         $minuteOptions = array();
01437 
01438         if (isset($attributes['interval'])) {
01439             $minuteOptions['interval'] = $attributes['interval'];
01440             unset($attributes['interval']);
01441         }
01442         return $this->select(
01443             $fieldName . ".min", $this->__generateOptions('minute', $minuteOptions),
01444             $selected, $attributes, $showEmpty
01445         );
01446     }
01447 /**
01448  * Returns a SELECT element for AM or PM.
01449  *
01450  * @param string $fieldName Prefix name for the SELECT element
01451  * @param string $selected Option which is selected.
01452  * @param string $attributes Array of Attributes
01453  * @param bool $showEmpty Show/Hide an empty option
01454  * @return string
01455  */
01456     function meridian($fieldName, $selected = null, $attributes = array(), $showEmpty = true) {
01457         if ((empty($selected) || $selected === true) && $value = $this->value($fieldName)) {
01458             if (is_array($value)) {
01459                 extract($value);
01460                 $selected = $meridian;
01461             } else {
01462                 if (empty($value)) {
01463                     if (!$showEmpty) {
01464                         $selected = date('a');
01465                     }
01466                 } else {
01467                     $selected = date('a', strtotime($value));
01468                 }
01469             }
01470         }
01471 
01472         if ($selected === false) {
01473             $selected = null;
01474         }
01475         return $this->select(
01476             $fieldName . ".meridian", $this->__generateOptions('meridian'),
01477             $selected, $attributes, $showEmpty
01478         );
01479     }
01480 /**
01481  * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
01482  *
01483  * Attributes:
01484  *
01485  * - 'monthNames' If set and false numbers will be used for month select instead of text.
01486  * - 'minYear' The lowest year to use in the year select
01487  * - 'maxYear' The maximum year to use in the year select
01488  * - 'interval' The interval for the minutes select. Defaults to 1
01489  * - 'separator' The contents of the string between select elements. Defaults to '-'
01490  *
01491  * @param string $fieldName Prefix name for the SELECT element
01492  * @param string $dateFormat DMY, MDY, YMD or NONE.
01493  * @param string $timeFormat 12, 24, NONE
01494  * @param string $selected Option which is selected.
01495  * @param string $attributes array of Attributes
01496  * @param bool $showEmpty Whether or not to show an empty default value.
01497  * @return string The HTML formatted OPTION element
01498  */
01499     function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $selected = null, $attributes = array(), $showEmpty = true) {
01500         $year = $month = $day = $hour = $min = $meridian = null;
01501 
01502         if (empty($selected)) {
01503             $selected = $this->value($fieldName);
01504         }
01505 
01506         if ($selected === null && $showEmpty != true) {
01507             $selected = time();
01508         }
01509 
01510         if (!empty($selected)) {
01511             if (is_array($selected)) {
01512                 extract($selected);
01513             } else {
01514                 if (is_numeric($selected)) {
01515                     $selected = strftime('%Y-%m-%d %H:%M:%S', $selected);
01516                 }
01517                 $meridian = 'am';
01518                 $pos = strpos($selected, '-');
01519                 if ($pos !== false) {
01520                     $date = explode('-', $selected);
01521                     $days = explode(' ', $date[2]);
01522                     $day = $days[0];
01523                     $month = $date[1];
01524                     $year = $date[0];
01525                 } else {
01526                     $days[1] = $selected;
01527                 }
01528 
01529                 if ($timeFormat != 'NONE' && !empty($timeFormat)) {
01530                     $time = explode(':', $days[1]);
01531                     $check = str_replace(':', '', $days[1]);
01532 
01533                     if (($check > 115959) && $timeFormat == '12') {
01534                         $time[0] = $time[0] - 12;
01535                         $meridian = 'pm';
01536                     } elseif ($time[0] == '00' && $timeFormat == '12') {
01537                         $time[0] = 12;
01538                     } elseif ($time[0] > 12) {
01539                         $meridian = 'pm';
01540                     }
01541                     if ($time[0] == 0 && $timeFormat == '12') {
01542                         $time[0] = 12;
01543                     }
01544                     $hour = $time[0];
01545                     $min = $time[1];
01546                 }
01547             }
01548         }
01549 
01550         $elements = array('Day','Month','Year','Hour','Minute','Meridian');
01551         $defaults = array(
01552             'minYear' => null, 'maxYear' => null, 'separator' => '-',
01553             'interval' => 1, 'monthNames' => true
01554         );
01555         $attributes = array_merge($defaults, (array) $attributes);
01556         if (isset($attributes['minuteInterval'])) {
01557             $attributes['interval'] = $attributes['minuteInterval'];
01558             unset($attributes['minuteInterval']);
01559         }
01560         $minYear = $attributes['minYear'];
01561         $maxYear = $attributes['maxYear'];
01562         $separator = $attributes['separator'];
01563         $interval = $attributes['interval'];
01564         $monthNames = $attributes['monthNames'];
01565         $attributes = array_diff_key($attributes, $defaults);
01566 
01567         if (isset($attributes['id'])) {
01568             if (is_string($attributes['id'])) {
01569                 // build out an array version
01570                 foreach ($elements as $element) {
01571                     $selectAttrName = 'select' . $element . 'Attr';
01572                     ${$selectAttrName} = $attributes;
01573                     ${$selectAttrName}['id'] = $attributes['id'] . $element;
01574                 }
01575             } elseif (is_array($attributes['id'])) {
01576                 // check for missing ones and build selectAttr for each element
01577                 foreach ($elements as $element) {
01578                     $selectAttrName = 'select' . $element . 'Attr';
01579                     ${$selectAttrName} = $attributes;
01580                     ${$selectAttrName}['id'] = $attributes['id'][strtolower($element)];
01581                 }
01582             }
01583         } else {
01584             // build the selectAttrName with empty id's to pass
01585             foreach ($elements as $element) {
01586                 $selectAttrName = 'select' . $element . 'Attr';
01587                 ${$selectAttrName} = $attributes;
01588             }
01589         }
01590 
01591         $opt = '';
01592 
01593         if ($dateFormat != 'NONE') {
01594             $selects = array();
01595             foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
01596                 switch ($char) {
01597                     case 'Y':
01598                         $selects[] = $this->year(
01599                             $fieldName, $minYear, $maxYear, $year, $selectYearAttr, $showEmpty
01600                         );
01601                     break;
01602                     case 'M':
01603                         $selectMonthAttr['monthNames'] = $monthNames;
01604                         $selects[] = $this->month($fieldName, $month, $selectMonthAttr, $showEmpty);
01605                     break;
01606                     case 'D':
01607                         $selects[] = $this->day($fieldName, $day, $selectDayAttr, $showEmpty);
01608                     break;
01609                 }
01610             }
01611             $opt = implode($separator, $selects);
01612         }
01613 
01614         switch ($timeFormat) {
01615             case '24':
01616                 $selectMinuteAttr['interval'] = $interval;
01617                 $opt .= $this->hour($fieldName, true, $hour, $selectHourAttr, $showEmpty) . ':' .
01618                 $this->minute($fieldName, $min, $selectMinuteAttr, $showEmpty);
01619             break;
01620             case '12':
01621                 $selectMinuteAttr['interval'] = $interval;
01622                 $opt .= $this->hour($fieldName, false, $hour, $selectHourAttr, $showEmpty) . ':' .
01623                 $this->minute($fieldName, $min, $selectMinuteAttr, $showEmpty) . ' ' .
01624                 $this->meridian($fieldName, $meridian, $selectMeridianAttr, $showEmpty);
01625             break;
01626             case 'NONE':
01627             default:
01628                 $opt .= '';
01629             break;
01630         }
01631         return $opt;
01632     }
01633 /**
01634  * Gets the input field name for the current tag
01635  *
01636  * @param array $options
01637  * @param string $key
01638  * @return array
01639  */
01640     function __name($options = array(), $field = null, $key = 'name') {
01641         if ($this->requestType == 'get') {
01642             if ($options === null) {
01643                 $options = array();
01644             } elseif (is_string($options)) {
01645                 $field = $options;
01646                 $options = 0;
01647             }
01648 
01649             if (!empty($field)) {
01650                 $this->setEntity($field);
01651             }
01652 
01653             if (is_array($options) && isset($options[$key])) {
01654                 return $options;
01655             }
01656             $name = $this->field();
01657 
01658             if (is_array($options)) {
01659                 $options[$key] = $name;
01660                 return $options;
01661             } else {
01662                 return $name;
01663             }
01664         }
01665         return parent::__name($options, $field, $key);
01666     }
01667 /**
01668  * Returns an array of formatted OPTION/OPTGROUP elements
01669  * @access private
01670  * @return array
01671  */
01672     function __selectOptions($elements = array(), $selected = null, $parents = array(), $showParents = null, $attributes = array()) {
01673         $select = array();
01674         $attributes = array_merge(array('escape' => true, 'style' => null), $attributes);
01675         $selectedIsEmpty = ($selected === '' || $selected === null);
01676         $selectedIsArray = is_array($selected);
01677 
01678         foreach ($elements as $name => $title) {
01679             $htmlOptions = array();
01680             if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
01681                 if (!empty($name)) {
01682                     if ($attributes['style'] === 'checkbox') {
01683                         $select[] = $this->Html->tags['fieldsetend'];
01684                     } else {
01685                         $select[] = $this->Html->tags['optiongroupend'];
01686                     }
01687                     $parents[] = $name;
01688                 }
01689                 $select = array_merge($select, $this->__selectOptions(
01690                     $title, $selected, $parents, $showParents, $attributes
01691                 ));
01692 
01693                 if (!empty($name)) {
01694                     if ($attributes['style'] === 'checkbox') {
01695                         $select[] = sprintf($this->Html->tags['fieldsetstart'], $name);
01696                     } else {
01697                         $select[] = sprintf($this->Html->tags['optiongroup'], $name, '');
01698                     }
01699                 }
01700                 $name = null;
01701             } elseif (is_array($title)) {
01702                 $htmlOptions = $title;
01703                 $name = $title['value'];
01704                 $title = $title['name'];
01705                 unset($htmlOptions['name'], $htmlOptions['value']);
01706             }
01707 
01708             if ($name !== null) {
01709                 if ((!$selectedIsEmpty && $selected == $name) || ($selectedIsArray && in_array($name, $selected))) {
01710                     if ($attributes['style'] === 'checkbox') {
01711                         $htmlOptions['checked'] = true;
01712                     } else {
01713                         $htmlOptions['selected'] = 'selected';
01714                     }
01715                 }
01716 
01717                 if ($showParents || (!in_array($title, $parents))) {
01718                     $title = ($attributes['escape']) ? h($title) : $title;
01719 
01720                     if ($attributes['style'] === 'checkbox') {
01721                         $htmlOptions['value'] = $name;
01722 
01723                         $tagName = Inflector::camelize(
01724                             $this->model() . '_' . $this->field().'_'.Inflector::underscore($name)
01725                         );
01726                         $htmlOptions['id'] = $tagName;
01727                         $label = array('for' => $tagName);
01728 
01729                         if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
01730                             $label['class'] = 'selected';
01731                         }
01732 
01733                         list($name) = array_values($this->__name());
01734 
01735                         if (empty($attributes['class'])) {
01736                             $attributes['class'] = 'checkbox';
01737                         }
01738                         $label = $this->label(null, $title, $label);
01739                         $item = sprintf(
01740                             $this->Html->tags['checkboxmultiple'], $name,
01741                             $this->_parseAttributes($htmlOptions)
01742                         );
01743                         $select[] = $this->Html->div($attributes['class'], $item . $label);
01744                     } else {
01745                         $select[] = sprintf(
01746                             $this->Html->tags['selectoption'],
01747                             $name, $this->_parseAttributes($htmlOptions), $title
01748                         );
01749                     }
01750                 }
01751             }
01752         }
01753 
01754         return array_reverse($select, true);
01755     }
01756 /**
01757  * Generates option lists for common <select /> menus
01758  * @access private
01759  */
01760     function __generateOptions($name, $options = array()) {
01761         if (!empty($this->options[$name])) {
01762             return $this->options[$name];
01763         }
01764         $data = array();
01765 
01766         switch ($name) {
01767             case 'minute':
01768                 if (isset($options['interval'])) {
01769                     $interval = $options['interval'];
01770                 } else {
01771                     $interval = 1;
01772                 }
01773                 $i = 0;
01774                 while ($i < 60) {
01775                     $data[$i] = sprintf('%02d', $i);
01776                     $i += $interval;
01777                 }
01778             break;
01779             case 'hour':
01780                 for ($i = 1; $i <= 12; $i++) {
01781                     $data[sprintf('%02d', $i)] = $i;
01782                 }
01783             break;
01784             case 'hour24':
01785                 for ($i = 0; $i <= 23; $i++) {
01786                     $data[sprintf('%02d', $i)] = $i;
01787                 }
01788             break;
01789             case 'meridian':
01790                 $data = array('am' => 'am', 'pm' => 'pm');
01791             break;
01792             case 'day':
01793                 $min = 1;
01794                 $max = 31;
01795 
01796                 if (isset($options['min'])) {
01797                     $min = $options['min'];
01798                 }
01799                 if (isset($options['max'])) {
01800                     $max = $options['max'];
01801                 }
01802 
01803                 for ($i = $min; $i <= $max; $i++) {
01804                     $data[sprintf('%02d', $i)] = $i;
01805                 }
01806             break;
01807             case 'month':
01808                 if ($options['monthNames']) {
01809                     $data['01'] = __('January', true);
01810                     $data['02'] = __('February', true);
01811                     $data['03'] = __('March', true);
01812                     $data['04'] = __('April', true);
01813                     $data['05'] = __('May', true);
01814                     $data['06'] = __('June', true);
01815                     $data['07'] = __('July', true);
01816                     $data['08'] = __('August', true);
01817                     $data['09'] = __('September', true);
01818                     $data['10'] = __('October', true);
01819                     $data['11'] = __('November', true);
01820                     $data['12'] = __('December', true);
01821                 } else {
01822                     for ($m = 1; $m <= 12; $m++) {
01823                         $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
01824                     }
01825                 }
01826             break;
01827             case 'year':
01828                 $current = intval(date('Y'));
01829 
01830                 if (!isset($options['min'])) {
01831                     $min = $current - 20;
01832                 } else {
01833                     $min = $options['min'];
01834                 }
01835 
01836                 if (!isset($options['max'])) {
01837                     $max = $current + 20;
01838                 } else {
01839                     $max = $options['max'];
01840                 }
01841                 if ($min > $max) {
01842                     list($min, $max) = array($max, $min);
01843                 }
01844                 for ($i = $min; $i <= $max; $i++) {
01845                     $data[$i] = $i;
01846                 }
01847                 $data = array_reverse($data, true);
01848             break;
01849         }
01850         $this->__options[$name] = $data;
01851         return $this->__options[$name];
01852     }
01853 /**
01854  * Sets field defaults and adds field to form security input hash
01855  * 
01856  * Options
01857  *  - secure - boolean whether or not the the field should be added to the security fields.
01858  * 
01859  * @param string $field
01860  * @param array $options
01861  * @return array
01862  * @access protected
01863  */
01864     function _initInputField($field, $options = array()) {
01865         if (isset($options['secure'])) {
01866             $secure = $options['secure'];
01867             unset($options['secure']);
01868         } else {
01869             $secure = (isset($this->params['_Token']) && !empty($this->params['_Token']));
01870         }
01871         $result = parent::_initInputField($field, $options);
01872 
01873         if ($secure) {
01874             $this->__secure();
01875         }
01876         return $result;
01877     }
01878 }
01879 
01880 ?>

Generated on Sun Nov 22 00:30:54 2009 for CakePHP 1.2.x.x (v1.2.4.8284) by doxygen 1.4.7