array('type'=> 'string', 'length'=> 100), * primaryKey and validates array('field_name') * * @access public */ public $fieldset = array(); /** * Options used by DateTime fields * * @var array */ private $__options = array( 'day' => array(), 'minute' => array(), 'hour' => array(), 'month' => array(), 'year' => array(), 'meridian' => array() ); /** * List of fields created, used with secure forms. * * @var array */ public $fields = array(); /** * Constant used internally to skip the securing process, * and neither add the field to the hash or to the unlocked fields. * * @var string */ const SECURE_SKIP = 'skip'; /** * Defines the type of form being created. Set by FormHelper::create(). * * @var string * @access public */ public $requestType = null; /** * The default model being used for the current form. * * @var string * @access public */ public $defaultModel = null; /** * Persistent default options used by input(). Set by FormHelper::create(). * * @var array * @access protected */ protected $_inputDefaults = array(); /** * An array of fieldnames that have been excluded from * the Token hash used by SecurityComponent's validatePost method * * @see FormHelper::__secure() * @see SecurityComponent::validatePost() * @var array */ protected $_unlockedFields = array(); /** * Holds the model references already loaded by this helper * product of trying to inspect them out of field names * * @var array */ protected $_models = array(); /** * Holds all the validation errors for models loaded and inspected * it can also be set manually to be able to display custom error messages * in the any of the input fields generated by this helper * * @var array */ public $validationErrors = array(); /** * Copies the validationErrors variable from the View object into this instance * * @param View $View The View this helper is being attached to. * @param array $settings Configuration settings for the helper. */ public function __construct(View $View, $settings = array()) { parent::__construct($View, $settings); $this->validationErrors =& $View->validationErrors; } /** * Guess the location for a model based on its name and tries to create a new instance * or get an already created instance of the model * * @return Model model instance */ protected function _getModel($model) { $object = null; if (!$model || $model === 'Model') { return $object; } if (array_key_exists($model, $this->_models)) { return $this->_models[$model]; } if (ClassRegistry::isKeySet($model)) { $object = ClassRegistry::getObject($model); } elseif (isset($this->request->params['models'][$model])) { $plugin = $this->request->params['models'][$model]['plugin']; $plugin .= ($plugin) ? '.' : null; $object = ClassRegistry::init(array( 'class' => $plugin . $this->request->params['models'][$model]['className'], 'alias' => $model )); } else { $object = ClassRegistry::init($model, true); } $this->_models[$model] = $object; if (!$object) {; return null; } $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null); return $object; } /** * Inspects the model properties to extract information from them. * Currently it can extract information from the the fields, the primary key and required fields * * The $key parameter accepts the following list of values: * * - key: Returns the name of the primary key for the model * - fields: Returns the model schema * - validates: returns the list of fields that are required * - errors: returns the list of validation errors * * If the $field parameter is passed if will return the information for that sole field. * * `$this->_introspectModel('Post', 'fields', 'title');` will return the schema information for title column * * @param string $model name of the model to extract information from * @param string $key name of the special information key to obtain (key, fields, validates, errors) * @param string $field name of the model field to get information from * @return mixed information extracted for the special key and field in a model */ protected function _introspectModel($model, $key, $field = null) { $object = $this->_getModel($model); if (!$object) { return; } if ($key === 'key') { return $this->fieldset[$model]['key']; } if ($key === 'fields') { if (!isset($this->fieldset[$model]['fields'])) { $fields = $this->fieldset[$model]['fields'] = $object->schema(); } if (empty($field)) { foreach ($object->hasAndBelongsToMany as $alias => $assocData) { $this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple'); } return $this->fieldset[$model]['fields']; } elseif (isset($this->fieldset[$model]['fields'][$field])) { return $this->fieldset[$model]['fields'][$field]; } else { return isset($object->hasAndBelongsToMany[$field]) ? array('type' => 'multiple') : null; } } if ($key === 'errors' && !isset($this->validationErrors[$model])) { $this->validationErrors[$model] =& $object->validationErrors; return $this->validationErrors[$model]; } elseif ($key === 'errors' && isset($this->validationErrors[$model])) { return $this->validationErrors[$model]; } if ($key === 'validates' && !isset($this->fieldset[$model]['validates'])) { $validates = array(); if (!empty($object->validate)) { foreach ($object->validate as $validateField => $validateProperties) { if ($this->_isRequiredField($validateProperties)) { $validates[$validateField] = true; } } } $this->fieldset[$model]['validates'] = $validates; } if ($key === 'validates') { if (empty($field)) { return $this->fieldset[$model]['validates']; } else { return isset($this->fieldset[$model]['validates'][$field]) ? $this->fieldset[$model]['validates'] : null; } } } /** * Returns if a field is required to be filled based on validation properties from the validating object * * @return boolean true if field is required to be filled, false otherwise */ protected function _isRequiredField($validateProperties) { $required = false; if (is_array($validateProperties)) { $dims = Set::countDim($validateProperties); if ($dims == 1 || ($dims == 2 && isset($validateProperties['rule']))) { $validateProperties = array($validateProperties); } foreach ($validateProperties as $rule => $validateProp) { if (isset($validateProp['allowEmpty']) && $validateProp['allowEmpty'] === true) { return false; } $rule = isset($validateProp['rule']) ? $validateProp['rule'] : false; $required = $rule || empty($validateProp); if ($required) { break; } } } return $required; } /** * Returns false if given form field described by the current entity has no errors. * Otherwise it returns the validation message * * @return boolean True on errors. */ public function tagIsInvalid() { $entity = $this->entity(); $model = array_shift($entity); if (!empty($entity) && isset($this->validationErrors[$model])) { return Set::classicExtract($this->validationErrors[$model], join('.', $entity)); } if (!empty($entity)) { $errors = $this->_introspectModel($model, 'errors'); return ($errors) ? Set::classicExtract($errors, join('.', $entity)) : false; } } /** * Returns an HTML FORM element. * * ### Options: * * - `type` Form method defaults to POST * - `action` The controller action the form submits to, (optional). * - `url` The url the form submits to. Can be a string or a url array. If you use 'url' * you should leave 'action' undefined. * - `default` Allows for the creation of Ajax forms. * - `onsubmit` Used in conjunction with 'default' to create ajax forms. * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would * be set when using FormHelper::input() can be set here. Options set with `inputDefaults` * can be overridden when calling input() * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')` * * @access public * @param string $model The model object which the form is being defined for * @param array $options An array of html attributes and options. * @return string An formatted opening FORM tag. * @link http://book.cakephp.org/view/1384/Creating-Forms */ public function create($model = null, $options = array()) { $created = $id = false; $append = ''; if (is_array($model) && empty($options)) { $options = $model; $model = null; } if (empty($model) && $model !== false && !empty($this->request->params['models'])) { $model = key($this->request->params['models']); $this->defaultModel = $model; } elseif (empty($model) && empty($this->request->params['models'])) { $model = false; } $key = null; if ($model !== false) { $object = $this->_getModel($model); $key = $this->_introspectModel($model, 'key'); $this->setEntity($model, true); } if ($model !== false && $key) { $recordExists = ( isset($this->request->data[$model]) && !empty($this->request->data[$model][$key]) && !is_array($this->request->data[$model][$key]) ); if ($recordExists) { $created = true; $id = $this->request->data[$model][$key]; } } $options = array_merge(array( 'type' => ($created && empty($options['action'])) ? 'put' : 'post', 'action' => null, 'url' => null, 'default' => true, 'encoding' => strtolower(Configure::read('App.encoding')), 'inputDefaults' => array()), $options); $this->_inputDefaults = $options['inputDefaults']; unset($options['inputDefaults']); if (!isset($options['id'])) { $domId = isset($options['action']) ? $options['action'] : $this->request['action']; $options['id'] = $this->domId($domId . 'Form'); } if ($options['action'] === null && $options['url'] === null) { $options['action'] = $this->request->here(false); } elseif (empty($options['url']) || is_array($options['url'])) { if (empty($options['url']['controller'])) { if (!empty($model) && $model != $this->defaultModel) { $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model)); } elseif (!empty($this->request->params['controller'])) { $options['url']['controller'] = Inflector::underscore($this->request->params['controller']); } } if (empty($options['action'])) { $options['action'] = $this->request->params['action']; } $plugin = null; if ($this->plugin) { $plugin = Inflector::underscore($this->plugin); } $actionDefaults = array( 'plugin' => $plugin, 'controller' => $this->_View->viewPath, 'action' => $options['action'], ); $options['action'] = array_merge($actionDefaults, (array)$options['url']); if (empty($options['action'][0]) && !empty($id)) { $options['action'][0] = $id; } } elseif (is_string($options['url'])) { $options['action'] = $options['url']; } unset($options['url']); switch (strtolower($options['type'])) { case 'get': $htmlAttributes['method'] = 'get'; break; case 'file': $htmlAttributes['enctype'] = 'multipart/form-data'; $options['type'] = ($created) ? 'put' : 'post'; case 'post': case 'put': case 'delete': $append .= $this->hidden('_method', array( 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null, 'secure' => self::SECURE_SKIP )); default: $htmlAttributes['method'] = 'post'; break; } $this->requestType = strtolower($options['type']); $action = $this->url($options['action']); unset($options['type'], $options['action']); if ($options['default'] == false) { if (isset($htmlAttributes['onSubmit']) || isset($htmlAttributes['onsubmit'])) { $htmlAttributes['onsubmit'] .= ' event.returnValue = false; return false;'; } else { $htmlAttributes['onsubmit'] = 'event.returnValue = false; return false;'; } } if (!empty($options['encoding'])) { $htmlAttributes['accept-charset'] = $options['encoding']; unset($options['encoding']); } unset($options['default']); $htmlAttributes = array_merge($options, $htmlAttributes); $this->fields = array(); if (!empty($this->request->params['_Token'])) { $append .= $this->hidden('_Token.key', array( 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand(), 'secure' => self::SECURE_SKIP )); if (!empty($this->request['_Token']['unlockedFields'])) { foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) { $this->_unlockedFields[] = $unlocked; } } } if (!empty($append)) { $append = $this->Html->useTag('block', ' style="display:none;"', $append); } if ($model !== false) { $this->setEntity($model, true); } return $this->Html->useTag('form', $action, $htmlAttributes) . $append; } /** * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden * input fields where appropriate. * * If $options is set a form submit button will be created. Options can be either a string or an array. * * {{{ * array usage: * * array('label' => 'save'); value="save" * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever" * array('name' => 'Whatever'); value="Submit" name="Whatever" * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good')
value="save" name="Whatever" * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good'));
value="save" name="Whatever" * }}} * * @param mixed $options as a string will use $options as the value of button, * @return string a closing FORM tag optional submit button. * @access public * @link http://book.cakephp.org/view/1389/Closing-the-Form */ public function end($options = null) { $out = null; $submit = null; if ($options !== null) { $submitOptions = array(); if (is_string($options)) { $submit = $options; } else { if (isset($options['label'])) { $submit = $options['label']; unset($options['label']); } $submitOptions = $options; } $out .= $this->submit($submit, $submitOptions); } if (isset($this->request['_Token']) && !empty($this->request['_Token'])) { $out .= $this->secure($this->fields); $this->fields = array(); } $this->setEntity(null); $out .= $this->Html->useTag('formend'); $this->_View->modelScope = false; return $out; } /** * Generates a hidden field with a security hash based on the fields used in the form. * * @param array $fields The list of fields to use when generating the hash * @return string A hidden input field with a security hash */ public function secure($fields = array()) { if (!isset($this->request['_Token']) || empty($this->request['_Token'])) { return; } $locked = array(); $unlockedFields = $this->_unlockedFields; foreach ($fields as $key => $value) { if (!is_int($key)) { $locked[$key] = $value; unset($fields[$key]); } } sort($unlockedFields, SORT_STRING); sort($fields, SORT_STRING); ksort($locked, SORT_STRING); $fields += $locked; $locked = implode(array_keys($locked), '|'); $unlocked = implode($unlockedFields, '|'); $fields = Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt')); $out = $this->hidden('_Token.fields', array( 'value' => urlencode($fields . ':' . $locked), 'id' => 'TokenFields' . mt_rand() )); $out .= $this->hidden('_Token.unlocked', array( 'value' => urlencode($unlocked), 'id' => 'TokenUnlocked' . mt_rand() )); return $this->Html->useTag('block', ' style="display:none;"', $out); } /** * Add to or get the list of fields that are currently unlocked. * Unlocked fields are not included in the field hash used by SecurityComponent * unlocking a field once its been added to the list of secured fields will remove * it from the list of fields. * * @param string $name The dot separated name for the field. * @return mixed Either null, or the list of fields. */ public function unlockField($name = null) { if ($name === null) { return $this->_unlockedFields; } if (!in_array($name, $this->_unlockedFields)) { $this->_unlockedFields[] = $name; } $index = array_search($name, $this->fields); if ($index !== false) { unset($this->fields[$index]); } unset($this->fields[$name]); } /** * Determine which fields of a form should be used for hash. * Populates $this->fields * * @param boolean $lock Whether this field should be part of the validation * or excluded as part of the unlockedFields. * @param mixed $field Reference to field to be secured * @param mixed $value Field value, if value should not be tampered with. * @return void */ protected function __secure($lock, $field = null, $value = null) { if (!$field) { $field = $this->entity(); } elseif (is_string($field)) { $field = Set::filter(explode('.', $field), true); } foreach ($this->_unlockedFields as $unlockField) { $unlockParts = explode('.', $unlockField); if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) { return; } } $field = implode('.', $field); if ($lock) { if (!in_array($field, $this->fields)) { if ($value !== null) { return $this->fields[$field] = $value; } $this->fields[] = $field; } } else { $this->unlockField($field); } } /** * Returns true if there is an error for the given field, otherwise false * * @param string $field This should be "Modelname.fieldname" * @return boolean If there are errors this method returns true, else false. * @access public * @link http://book.cakephp.org/view/1426/isFieldError */ public function isFieldError($field) { $this->setEntity($field); return (bool)$this->tagIsInvalid(); } /** * Returns a formatted error message for given FORM field, NULL if no errors. * * ### Options: * * - `escape` bool Whether or not to html escape the contents of the error. * - `wrap` mixed Whether or not the error message should be wrapped in a div. If a * string, will be used as the HTML tag to use. * - `class` string The classname for the error message * * @param string $field A field name, like "Modelname.fieldname" * @param mixed $text Error message as string or array of messages. * If array contains `attributes` key it will be used as options for error container * @param array $options Rendering options for
wrapper tag * @return string If there are errors this method returns an error message, otherwise null. * @access public * @link http://book.cakephp.org/view/1423/error */ public function error($field, $text = null, $options = array()) { $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true); $options = array_merge($defaults, $options); $this->setEntity($field); if (!$error = $this->tagIsInvalid()) { return null; } if (is_array($text)) { if (isset($text['attributes']) && is_array($text['attributes'])) { $options = array_merge($options, $text['attributes']); unset($text['attributes']); } $tmp = array(); foreach ($error as &$e) { if (isset($text[$e])) { $tmp []= $text[$e]; } else { $tmp []= $e; } } $text = $tmp; } if ($text != null) { $error = $text; } if (is_array($error)) { foreach ($error as &$e) { if (is_numeric($e)) { $e = __d('cake', 'Error in field %s', Inflector::humanize($this->field())); } } } if ($options['escape']) { $error = h($error); unset($options['escape']); } if (is_array($error)) { if (count($error) > 1) { $listParams = array(); if (isset($options['listOptions'])) { if (is_string($options['listOptions'])) { $listParams []= $options['listOptions']; } else { if (isset($options['listOptions']['itemOptions'])) { $listParams []= $options['listOptions']['itemOptions']; unset($options['listOptions']['itemOptions']); } else { $listParams []= array(); } if (isset($options['listOptions']['tag'])) { $listParams []= $options['listOptions']['tag']; unset($options['listOptions']['tag']); } array_unshift($listParams, $options['listOptions']); } unset($options['listOptions']); } array_unshift($listParams, $error); $error = call_user_func_array(array($this->Html, 'nestedList'), $listParams); } else { $error = array_pop($error); } } if ($options['wrap']) { $tag = is_string($options['wrap']) ? $options['wrap'] : 'div'; unset($options['wrap']); return $this->Html->tag($tag, $error, $options); } else { return $error; } } /** * Returns a formatted LABEL element for HTML FORMs. Will automatically generate * a for attribute if one is not provided. * * @param string $fieldName This should be "Modelname.fieldname" * @param string $text Text that will appear in the label field. * @param mixed $options An array of HTML attributes, or a string, to be used as a class name. * @return string The formatted LABEL element * @link http://book.cakephp.org/view/1427/label */ public function label($fieldName = null, $text = null, $options = array()) { if (empty($fieldName)) { $fieldName = implode('.', $this->entity()); } if ($text === null) { if (strpos($fieldName, '.') !== false) { $fieldElements = explode('.', $fieldName); $text = array_pop($fieldElements); } else { $text = $fieldName; } if (substr($text, -3) == '_id') { $text = substr($text, 0, strlen($text) - 3); } $text = __d('cake', Inflector::humanize(Inflector::underscore($text))); } if (is_string($options)) { $options = array('class' => $options); } if (isset($options['for'])) { $labelFor = $options['for']; unset($options['for']); } else { $labelFor = $this->domId($fieldName); } return $this->Html->useTag('label', $labelFor, $options, $text); } /** * Generate a set of inputs for `$fields`. If $fields is null the current model * will be used. * * In addition to controller fields output, `$fields` can be used to control legend * and fieldset rendering with the `fieldset` and `legend` keys. * `$form->inputs(array('legend' => 'My legend'));` Would generate an input set with * a custom legend. You can customize individual inputs through `$fields` as well. * * {{{ * $form->inputs(array( * 'name' => array('label' => 'custom label') * )); * }}} * * In addition to fields control, inputs() allows you to use a few additional options. * * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as * the classname for the fieldset element. * - `legend` Set to false to disable the legend for the generated input set. Or supply a string * to customize the legend text. * * @param mixed $fields An array of fields to generate inputs for, or null. * @param array $blacklist a simple array of fields to not create inputs for. * @return string Completed form inputs. */ public function inputs($fields = null, $blacklist = null) { $fieldset = $legend = true; $model = $this->model(); if (is_array($fields)) { if (array_key_exists('legend', $fields)) { $legend = $fields['legend']; unset($fields['legend']); } if (isset($fields['fieldset'])) { $fieldset = $fields['fieldset']; unset($fields['fieldset']); } } elseif ($fields !== null) { $fieldset = $legend = $fields; if (!is_bool($fieldset)) { $fieldset = true; } $fields = array(); } if (empty($fields)) { $fields = array_keys($this->_introspectModel($model, 'fields')); } if ($legend === true) { $actionName = __d('cake', 'New %s'); $isEdit = ( strpos($this->request->params['action'], 'update') !== false || strpos($this->request->params['action'], 'edit') !== false ); if ($isEdit) { $actionName = __d('cake', 'Edit %s'); } $modelName = Inflector::humanize(Inflector::underscore($model)); $legend = sprintf($actionName, __($modelName)); } $out = null; foreach ($fields as $name => $options) { if (is_numeric($name) && !is_array($options)) { $name = $options; $options = array(); } $entity = explode('.', $name); $blacklisted = ( is_array($blacklist) && (in_array($name, $blacklist) || in_array(end($entity), $blacklist)) ); if ($blacklisted) { continue; } $out .= $this->input($name, $options); } if (is_string($fieldset)) { $fieldsetClass = sprintf(' class="%s"', $fieldset); } else { $fieldsetClass = ''; } if ($fieldset && $legend) { return $this->Html->useTag('fieldset', $fieldsetClass, $this->Html->useTag('legend', $legend) . $out); } elseif ($fieldset) { return $this->Html->useTag('fieldset', $fieldsetClass, $out); } else { return $out; } } /** * Generates a form input element complete with label and wrapper div * * ### Options * * See each field type method for more information. Any options that are part of * $attributes or $options for the different **type** methods can be included in `$options` for input().i * Additionally, any unknown keys that are not in the list below, or part of the selected type's options * will be treated as a regular html attribute for the generated input. * * - `type` - Force the type of widget you want. e.g. `type => 'select'` * - `label` - Either a string label, or an array of options for the label. See FormHelper::label() * - `div` - Either `false` to disable the div, or an array of options for the div. * See HtmlHelper::div() for more options. * - `options` - for widgets that take options e.g. radio, select * - `error` - control the error message that is produced * - `empty` - String or boolean to enable empty select box options. * - `before` - Content to place before the label + input. * - `after` - Content to place after the label + input. * - `between` - Content to place between the label + input. * - `format` - format template for element order. Any element that is not in the array, will not be in the output. * - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error') * - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error') * - Hidden input will not be formatted * - Radio buttons cannot have the order of input and label elements controlled with these settings. * * @param string $fieldName This should be "Modelname.fieldname" * @param array $options Each type of input takes different options. * @return string Completed form widget. * @access public * @link http://book.cakephp.org/view/1390/Automagic-Form-Elements */ public function input($fieldName, $options = array()) { $this->setEntity($fieldName); $options = array_merge( array('before' => null, 'between' => null, 'after' => null, 'format' => null), $this->_inputDefaults, $options ); $modelKey = $this->model(); $fieldKey = $this->field(); if (!isset($options['type'])) { $magicType = true; $options['type'] = 'text'; if (isset($options['options'])) { $options['type'] = 'select'; } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) { $options['type'] = 'password'; } elseif (isset($options['checked'])) { $options['type'] = 'checkbox'; } elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) { $type = $fieldDef['type']; $primaryKey = $this->fieldset[$modelKey]['key']; } if (isset($type)) { $map = array( 'string' => 'text', 'datetime' => 'datetime', 'boolean' => 'checkbox', 'timestamp' => 'datetime', 'text' => 'textarea', 'time' => 'time', 'date' => 'date', 'float' => 'text' ); if (isset($this->map[$type])) { $options['type'] = $this->map[$type]; } elseif (isset($map[$type])) { $options['type'] = $map[$type]; } if ($fieldKey == $primaryKey) { $options['type'] = 'hidden'; } } if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') { $options['type'] = 'select'; } if ($modelKey === $fieldKey) { $options['type'] = 'select'; if (!isset($options['multiple'])) { $options['multiple'] = 'multiple'; } } } $types = array('checkbox', 'radio', 'select'); if ( (!isset($options['options']) && in_array($options['type'], $types)) || (isset($magicType) && $options['type'] == 'text') ) { $varName = Inflector::variable( Inflector::pluralize(preg_replace('/_id$/', '', $fieldKey)) ); $varOptions = $this->_View->getVar($varName); if (is_array($varOptions)) { if ($options['type'] !== 'radio') { $options['type'] = 'select'; } $options['options'] = $varOptions; } } $autoLength = (!array_key_exists('maxlength', $options) && isset($fieldDef['length'])); if ($autoLength && $options['type'] == 'text') { $options['maxlength'] = $fieldDef['length']; } if ($autoLength && $fieldDef['type'] == 'float') { $options['maxlength'] = array_sum(explode(',', $fieldDef['length']))+1; } $divOptions = array(); $div = $this->_extractOption('div', $options, true); unset($options['div']); if (!empty($div)) { $divOptions['class'] = 'input'; $divOptions = $this->addClass($divOptions, $options['type']); if (is_string($div)) { $divOptions['class'] = $div; } elseif (is_array($div)) { $divOptions = array_merge($divOptions, $div); } if ($this->_introspectModel($modelKey, 'validates', $fieldKey)) { $divOptions = $this->addClass($divOptions, 'required'); } if (!isset($divOptions['tag'])) { $divOptions['tag'] = 'div'; } } $label = null; if (isset($options['label']) && $options['type'] !== 'radio') { $label = $options['label']; unset($options['label']); } if ($options['type'] === 'radio') { $label = false; if (isset($options['options'])) { $radioOptions = (array)$options['options']; unset($options['options']); } } if ($label !== false) { $label = $this->_inputLabel($fieldName, $label, $options); } $error = $this->_extractOption('error', $options, null); unset($options['error']); $selected = $this->_extractOption('selected', $options, null); unset($options['selected']); if (isset($options['rows']) || isset($options['cols'])) { $options['type'] = 'textarea'; } if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') { $options += array('empty' => false); } if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') { $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY'); $timeFormat = $this->_extractOption('timeFormat', $options, 12); unset($options['dateFormat'], $options['timeFormat']); } $type = $options['type']; $out = array_merge( array('before' => null, 'label' => null, 'between' => null, 'input' => null, 'after' => null, 'error' => null), array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']) ); $format = null; if (is_array($options['format']) && in_array('input', $options['format'])) { $format = $options['format']; } unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']); switch ($type) { case 'hidden': $input = $this->hidden($fieldName, $options); $format = array('input'); unset($divOptions); break; case 'checkbox': $input = $this->checkbox($fieldName, $options); $format = $format ? $format : array('before', 'input', 'between', 'label', 'after', 'error'); break; case 'radio': $input = $this->radio($fieldName, $radioOptions, $options); break; case 'file': $input = $this->file($fieldName, $options); break; case 'select': $options += array('options' => array(), 'value' => $selected); $list = $options['options']; unset($options['options']); $input = $this->select($fieldName, $list, $options); break; case 'time': $options['value'] = $selected; $input = $this->dateTime($fieldName, null, $timeFormat, $options); break; case 'date': $options['value'] = $selected; $input = $this->dateTime($fieldName, $dateFormat, null, $options); break; case 'datetime': $options['value'] = $selected; $input = $this->dateTime($fieldName, $dateFormat, $timeFormat, $options); break; case 'textarea': $input = $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6')); break; default: $input = $this->{$type}($fieldName, $options); } if ($type != 'hidden' && $error !== false) { $errMsg = $this->error($fieldName, $error); if ($errMsg) { $divOptions = $this->addClass($divOptions, 'error'); $out['error'] = $errMsg; } } $out['input'] = $input; $format = $format ? $format : array('before', 'label', 'between', 'input', 'after', 'error'); $output = ''; foreach ($format as $element) { $output .= $out[$element]; unset($out[$element]); } if (!empty($divOptions['tag'])) { $tag = $divOptions['tag']; unset($divOptions['tag']); $output = $this->Html->tag($tag, $output, $divOptions); } return $output; } /** * Extracts a single option from an options array. * * @param string $name The name of the option to pull out. * @param array $options The array of options you want to extract. * @param mixed $default The default option value * @return the contents of the option or default */ protected function _extractOption($name, $options, $default = null) { if (array_key_exists($name, $options)) { return $options[$name]; } return $default; } /** * Generate a label for an input() call. * * @param array $options Options for the label element. * @return string Generated label element */ protected function _inputLabel($fieldName, $label, $options) { $labelAttributes = $this->domId(array(), 'for'); if ($options['type'] === 'date' || $options['type'] === 'datetime') { if (isset($options['dateFormat']) && $options['dateFormat'] === 'NONE') { $labelAttributes['for'] .= 'Hour'; $idKey = 'hour'; } else { $labelAttributes['for'] .= 'Month'; $idKey = 'month'; } if (isset($options['id']) && isset($options['id'][$idKey])) { $labelAttributes['for'] = $options['id'][$idKey]; } } elseif ($options['type'] === 'time') { $labelAttributes['for'] .= 'Hour'; if (isset($options['id']) && isset($options['id']['hour'])) { $labelAttributes['for'] = $options['id']['hour']; } } if (is_array($label)) { $labelText = null; if (isset($label['text'])) { $labelText = $label['text']; unset($label['text']); } $labelAttributes = array_merge($labelAttributes, $label); } else { $labelText = $label; } if (isset($options['id']) && is_string($options['id'])) { $labelAttributes = array_merge($labelAttributes, array('for' => $options['id'])); } return $this->label($fieldName, $labelText, $labelAttributes); } /** * Creates a checkbox input widget. * * ### Options: * * - `value` - the value of the checkbox * - `checked` - boolean indicate that this checkbox is checked. * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include * a hidden input with a value of ''. * - `disabled` - create a disabled input. * - `default` - Set the default value for the checkbox. This allows you to start checkboxes * as checked, without having to check the POST data. A matching POST data value, will overwrite * the default value. * * @param string $fieldName Name of a field, like this "Modelname.fieldname" * @param array $options Array of HTML attributes. * @return string An HTML text input element. * @access public * @link http://book.cakephp.org/view/1414/checkbox */ public function checkbox($fieldName, $options = array()) { $valueOptions = array(); if(isset($options['default'])){ $valueOptions['default'] = $options['default']; unset($options['default']); } $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true); $value = current($this->value($valueOptions)); $output = ""; if (empty($options['value'])) { $options['value'] = 1; } if ( (!isset($options['checked']) && !empty($value) && $value == $options['value']) || !empty($options['checked']) ) { $options['checked'] = 'checked'; } if ($options['hiddenField']) { $hiddenOptions = array( 'id' => $options['id'] . '_', 'name' => $options['name'], 'value' => '0', 'secure' => false ); if (isset($options['disabled']) && $options['disabled'] == true) { $hiddenOptions['disabled'] = 'disabled'; } $output = $this->hidden($fieldName, $hiddenOptions); } unset($options['hiddenField']); return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates a set of radio widgets. Will create a legend and fieldset * by default. Use $options to control this * * ### Attributes: * * - `separator` - define the string in between the radio buttons * - `legend` - control whether or not the widget set has a fieldset & legend * - `value` - indicate a value that is should be checked * - `label` - boolean to indicate whether or not labels for widgets show be displayed * - `hiddenField` - boolean to indicate if you want the results of radio() to include * a hidden input with a value of ''. This is useful for creating radio sets that non-continuous * * @param string $fieldName Name of a field, like this "Modelname.fieldname" * @param array $options Radio button options array. * @param array $attributes Array of HTML attributes, and special attributes above. * @return string Completed radio widget set. * @access public * @link http://book.cakephp.org/view/1429/radio */ public function radio($fieldName, $options = array(), $attributes = array()) { $attributes = $this->_initInputField($fieldName, $attributes); $legend = false; $disabled = array(); if (isset($attributes['legend'])) { $legend = $attributes['legend']; unset($attributes['legend']); } elseif (count($options) > 1) { $legend = __(Inflector::humanize($this->field())); } $label = true; if (isset($attributes['label'])) { $label = $attributes['label']; unset($attributes['label']); } $inbetween = null; if (isset($attributes['separator'])) { $inbetween = $attributes['separator']; unset($attributes['separator']); } if (isset($attributes['value'])) { $value = $attributes['value']; } else { $value = $this->value($fieldName); } if (isset($attributes['disabled'])) { $disabled = $attributes['disabled']; } $out = array(); $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true; unset($attributes['hiddenField']); foreach ($options as $optValue => $optTitle) { $optionsHere = array('value' => $optValue); if (isset($value) && $optValue == $value) { $optionsHere['checked'] = 'checked'; } if (!empty($disabled) && in_array($optValue, $disabled)) { $optionsHere['disabled'] = true; } $tagName = Inflector::camelize( $attributes['id'] . '_' . Inflector::slug($optValue) ); if ($label) { $optTitle = $this->Html->useTag('label', $tagName, '', $optTitle); } $allOptions = array_merge($attributes, $optionsHere); $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName, array_diff_key($allOptions, array('name' => '', 'type' => '', 'id' => '')), $optTitle ); } $hidden = null; if ($hiddenField) { if (!isset($value) || $value === '') { $hidden = $this->hidden($fieldName, array( 'id' => $attributes['id'] . '_', 'value' => '', 'name' => $attributes['name'] )); } } $out = $hidden . implode($inbetween, $out); if ($legend) { $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $out); } return $out; } /** * Missing method handler - implements various simple input types. Is used to create inputs * of various types. e.g. `$this->Form->text();` will create `` while * `$this->Form->range();` will create `` * * ### Usage * * `$this->Form->search('User.query', array('value' => 'test'));` * * Will make an input like: * * `` * * The first argument to an input type should always be the fieldname, in `Model.field` format. * The second argument should always be an array of attributes for the input. * * @param string $method Method name / input type to make. * @param array $params Parameters for the method call * @return string Formatted input method. * @throws CakeException When there are no params for the method call. */ public function __call($method, $params) { $options = array(); if (empty($params)) { throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method)); } if (isset($params[1])) { $options = $params[1]; } if (!isset($options['type'])) { $options['type'] = $method; } $options = $this->_initInputField($params[0], $options); return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates a textarea widget. * * ### Options: * * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true. * * @param string $fieldName Name of a field, in the form "Modelname.fieldname" * @param array $options Array of HTML attributes, and special options above. * @return string A generated HTML text input element * @access public * @link http://book.cakephp.org/view/1433/textarea */ public function textarea($fieldName, $options = array()) { $options = $this->_initInputField($fieldName, $options); $value = null; if (array_key_exists('value', $options)) { $value = $options['value']; if (!array_key_exists('escape', $options) || $options['escape'] !== false) { $value = h($value); } unset($options['value']); } return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => '', 'name' => '')), $value); } /** * Creates a hidden input field. * * @param string $fieldName Name of a field, in the form of "Modelname.fieldname" * @param array $options Array of HTML attributes. * @return string A generated hidden input * @access public * @link http://book.cakephp.org/view/1425/hidden */ public function hidden($fieldName, $options = array()) { $secure = true; if (isset($options['secure'])) { $secure = $options['secure']; unset($options['secure']); } $options = $this->_initInputField($fieldName, array_merge( $options, array('secure' => self::SECURE_SKIP) )); if ($secure && $secure !== self::SECURE_SKIP) { $this->__secure(true, null, '' . $options['value']); } return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates file input widget. * * @param string $fieldName Name of a field, in the form "Modelname.fieldname" * @param array $options Array of HTML attributes. * @return string A generated file input. * @access public * @link http://book.cakephp.org/view/1424/file */ public function file($fieldName, $options = array()) { $options += array('secure' => true); $secure = $options['secure']; $options['secure'] = self::SECURE_SKIP; $options = $this->_initInputField($fieldName, $options); $field = $this->entity(); foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) { $this->__secure($secure, array_merge($field, array($suffix))); } return $this->Html->useTag('file', $options['name'], array_diff_key($options, array('name' => ''))); } /** * Creates a `