<?php
App::uses('ClassRegistry', 'Utility');
App::uses('AppHelper', 'View/Helper');
class FormHelper extends AppHelper {
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']);
} elseif (empty($model) && empty($this->request->params['models'])) {
$model = false;
}
$this->defaultModel = $model;
$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)) {
$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($options['onsubmit'])) {
$options['onsubmit'] = '';
}
$htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;';
}
unset($options['default']);
if (!empty($options['encoding'])) {
$htmlAttributes['accept-charset'] = $options['encoding'];
unset($options['encoding']);
}
$htmlAttributes = array_merge($options, $htmlAttributes);
$this->fields = array();
$append .= $this->_csrfField();
if (!empty($append)) {
$append = $this->Html->useTag('block', ' style="display:none;"', $append);
}
if ($model !== false) {
$this->setEntity($model, true);
$this->_introspectModel($model, 'fields');
}
return $this->Html->useTag('form', $action, $htmlAttributes) . $append;
}
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;
}
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);
}
/**
* 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.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-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' => 'number',
'integer' => 'number'
);
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 (
$options['type'] === 'number' &&
$type === 'float' &&
!isset($options['step'])
) {
$options['step'] = 'any';
}
}
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':
if (isset($out['between'])) {
$options['between'] = $out['between'];
$out['between'] = null;
}
$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;
case 'url':
$input = $this->text($fieldName, array('type' => 'url') + $options);
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;
}
/**
* 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.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
*/
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' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '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
* - `between` - the string between legend and input set
* - `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
* - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
*
* @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.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
*/
public function radio($fieldName, $options = array(), $attributes = array()) {
$attributes = $this->_initInputField($fieldName, $attributes);
$legend = false;
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']);
}
$separator = null;
if (isset($attributes['separator'])) {
$separator = $attributes['separator'];
unset($attributes['separator']);
}
$between = null;
if (isset($attributes['between'])) {
$between = $attributes['between'];
unset($attributes['between']);
}
$value = null;
if (isset($attributes['value'])) {
$value = $attributes['value'];
} else {
$value = $this->value($fieldName);
}
$disabled = array();
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 ($disabled && (!is_array($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($separator, $out);
if ($legend) {
$out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $between . $out);
}
return $out;
}
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
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::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.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::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 `<button>` tag. The type attribute defaults to `type="submit"`
* You can change it to a different value by using `$options['type']`.
*
* ### Options:
*
* - `escape` - HTML entity encode the $title of the button. Defaults to false.
*
* @param string $title The button's caption. Not automatically HTML encoded
* @param array $options Array of options and HTML attributes.
* @return string A HTML button tag.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
*/
public function button($title, $options = array()) {
$options += array('type' => 'submit', 'escape' => false, 'secure' => false);
if ($options['escape']) {
$title = h($title);
}
if (isset($options['name'])) {
$name = str_replace(array('[', ']'), array('.', ''), $options['name']);
$this->_secure($options['secure'], $name);
}
return $this->Html->useTag('button', $options, $title);
}
/**
* Create a `<button>` tag with a surrounding `<form>` that submits via POST.
*
* This method creates a `<form>` element. So do not use this method in an already opened form.
* Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
*
* ### Options:
*
* - `data` - Array with key/value to pass in input hidden
* - Other options is the same of button method.
*
* @param string $title The button's caption. Not automatically HTML encoded
* @param mixed $url URL as string or array
* @param array $options Array of options and HTML attributes.
* @return string A HTML button tag.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
*/
public function postButton($title, $url, $options = array()) {
$out = $this->create(false, array('id' => false, 'url' => $url));
if (isset($options['data']) && is_array($options['data'])) {
foreach ($options['data'] as $key => $value) {
$out .= $this->hidden($key, array('value' => $value, 'id' => false));
}
unset($options['data']);
}
$out .= $this->button($title, $options);
$out .= $this->end();
return $out;
}
/**
* Creates an HTML link, but access the url using method POST.
* Requires javascript to be enabled in browser.
*
* This method creates a `<form>` element. So do not use this method inside an existing form.
* Instead you should add a submit button using FormHelper::submit()
*
* ### Options:
*
* - `data` - Array with key/value to pass in input hidden
* - `confirm` - Can be used instead of $confirmMessage.
* - Other options is the same of HtmlHelper::link() method.
* - The option `onclick` will be replaced.
*
* @param string $title The content to be wrapped by <a> tags.
* @param mixed $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
* @param array $options Array of HTML attributes.
* @param string $confirmMessage JavaScript confirmation message.
* @return string An `<a />` element.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
*/
public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
if (!empty($options['confirm'])) {
$confirmMessage = $options['confirm'];
unset($options['confirm']);
}
$formName = uniqid('post_');
$formUrl = $this->url($url);
$out = $this->Html->useTag('form', $formUrl, array('name' => $formName, 'id' => $formName, 'style' => 'display:none;', 'method' => 'post'));
$out .= $this->Html->useTag('hidden', '_method', ' value="POST"');
$out .= $this->_csrfField();
$fields = array();
if (isset($options['data']) && is_array($options['data'])) {
foreach ($options['data'] as $key => $value) {
$fields[$key] = $value;
$out .= $this->hidden($key, array('value' => $value, 'id' => false));
}
unset($options['data']);
}
$out .= $this->secure($fields);
$out .= $this->Html->useTag('formend');
$url = '#';
$onClick = 'document.' . $formName . '.submit();';
if ($confirmMessage) {
$confirmMessage = str_replace(array("'", '"'), array("\'", '\"'), $confirmMessage);
$options['onclick'] = "if (confirm('{$confirmMessage}')) { {$onClick} }";
} else {
$options['onclick'] = $onClick;
}
$options['onclick'] .= ' event.returnValue = false; return false;';
$out .= $this->Html->link($title, $url, $options);
return $out;
}
/**
* Creates a submit button element. This method will generate `<input />` elements that
* can be used to submit, and reset forms by using $options. image submits can be created by supplying an
* image path for $caption.
*
* ### Options
*
* - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
* FormHelper::input().
* - `before` - Content to include before the input.
* - `after` - Content to include after the input.
* - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
* - Other attributes will be assigned to the input element.
*
* ### Options
*
* - `div` - Include a wrapping div? Defaults to true. Accepts sub options similar to
* FormHelper::input().
* - Other attributes will be assigned to the input element.
*
* @param string $caption The label appearing on the button OR if string contains :// or the
* extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
* exists, AND the first character is /, image is relative to webroot,
* OR if the first character is not /, image is relative to webroot/img.
* @param array $options Array of options. See above.
* @return string A HTML submit button
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
*/
public function submit($caption = null, $options = array()) {
if (!is_string($caption) && empty($caption)) {
$caption = __d('cake', 'Submit');
}
$out = null;
$div = true;
if (isset($options['div'])) {
$div = $options['div'];
unset($options['div']);
}
$options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
$divOptions = array('tag' => 'div');
if ($div === true) {
$divOptions['class'] = 'submit';
} elseif ($div === false) {
unset($divOptions);
} elseif (is_string($div)) {
$divOptions['class'] = $div;
} elseif (is_array($div)) {
$divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
}
if (isset($options['name'])) {
$name = str_replace(array('[', ']'), array('.', ''), $options['name']);
$this->_secure($options['secure'], $name);
}
unset($options['secure']);
$before = $options['before'];
$after = $options['after'];
unset($options['before'], $options['after']);
$isUrl = strpos($caption, '://') !== false;
$isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
if ($isUrl || $isImage) {
$unlockFields = array('x', 'y');
if (isset($options['name'])) {
$unlockFields = array(
$options['name'] . '_x', $options['name'] . '_y'
);
}
foreach ($unlockFields as $ignore) {
$this->unlockField($ignore);
}
}
if ($isUrl) {
unset($options['type']);
$tag = $this->Html->useTag('submitimage', $caption, $options);
} elseif ($isImage) {
unset($options['type']);
if ($caption{0} !== '/') {
$url = $this->webroot(IMAGES_URL . $caption);
} else {
$url = $this->webroot(trim($caption, '/'));
}
$url = $this->assetTimestamp($url);
$tag = $this->Html->useTag('submitimage', $url, $options);
} else {
$options['value'] = $caption;
$tag = $this->Html->useTag('submit', $options);
}
$out = $before . $tag . $after;
if (isset($divOptions)) {
$tag = $divOptions['tag'];
unset($divOptions['tag']);
$out = $this->Html->tag($tag, $out, $divOptions);
}
return $out;
}
}