'
];
/**
* Construct the widgets and binds the default context providers
*
* @param \Cake\View\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()) {
$settings += ['widgets' => [], 'templates' => null, 'registry' => null];
parent::__construct($View, $settings);
$this->initStringTemplates($this->_defaultTemplates);
$this->widgetRegistry($settings['registry'], $settings['widgets']);
unset($this->settings['widgets'], $this->settings['registry']);
$this->_addDefaultContextProviders();
}
/**
* Set the input registry the helper will use.
*
* @param \Cake\View\Widget\WidgetRegistry $instance The registry instance to set.
* @param array $widgets An array of widgets
* @return \Cake\View\Widget\WidgetRegistry
*/
public function widgetRegistry(WidgetRegistry $instance = null, $widgets = []) {
if ($instance === null) {
if ($this->_registry === null) {
$this->_registry = new WidgetRegistry($this->_templater, $widgets);
}
return $this->_registry;
}
$this->_registry = $instance;
return $this->_registry;
}
/**
* Add the default suite of context providers provided by CakePHP.
*
* @return void
*/
protected function _addDefaultContextProviders() {
$this->addContextProvider('array', function ($request, $data) {
if (is_array($data['entity']) && isset($data['entity']['schema'])) {
return new ArrayContext($request, $data['entity']);
}
});
$this->addContextProvider('orm', function ($request, $data) {
if (
$data['entity'] instanceof Entity ||
$data['entity'] instanceof Traversable ||
(is_array($data['entity']) && !isset($data['entity']['schema']))
) {
return new EntityContext($request, $data);
}
});
}
/**
* Returns if a field is required to be filled based on validation properties from the validating object.
*
* @param \Cake\Validation\ValidationSet $validationRules
* @return boolean true if field is required to be filled, false otherwise
*/
protected function _isRequiredField($validationRules) {
if (empty($validationRules) || count($validationRules) === 0) {
return false;
}
$validationRules->isUpdate($this->requestType === 'put');
foreach ($validationRules as $rule) {
if ($rule->skip()) {
continue;
}
return !$validationRules->isEmptyAllowed();
}
return false;
}
/**
* Returns an HTML FORM element.
*
* ### Options:
*
* - `type` Form method defaults to autodetecting based on the form context. If
* the form context's isCreate() method returns false, a PUT request will be done.
* - `action` The controller action the form submits to, (optional). Use this option if you
* don't need to change the controller from the current request's controller.
* - `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. Set this to false to prevent the default event handler.
* Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression
* will be appended.
* - `onsubmit` Used in conjunction with 'default' to create ajax forms.
* - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
* - `context` Additional options for the context class. For example the EntityContext accepts a 'table'
* option that allows you to set the specific Table class the form should be based on.
*
* @param mixed $model The context for which the form is being defined. Can
* be an ORM entity, ORM resultset, or an array of meta data. You can use false or null
* to make a model-less form.
* @param array $options An array of html attributes and options.
* @return string An formatted opening FORM tag.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
*/
public function create($model = null, $options = []) {
$append = '';
if (empty($options['context'])) {
$options['context'] = [];
}
$options['context']['entity'] = $model;
$context = $this->_getContext($options['context']);
unset($options['context']);
$isCreate = $context->isCreate();
$options = $options + [
'type' => $isCreate ? 'post' : 'put',
'action' => null,
'url' => null,
'default' => true,
'encoding' => strtolower(Configure::read('App.encoding')),
];
$action = $this->url($this->_formUrl($context, $options));
unset($options['url'], $options['action']);
$htmlAttributes = [];
switch (strtolower($options['type'])) {
case 'get':
$htmlAttributes['method'] = 'get';
break;
case 'file':
$htmlAttributes['enctype'] = 'multipart/form-data';
$options['type'] = ($isCreate) ? 'post' : 'put';
case 'post':
case 'put':
case 'delete':
case 'patch':
$append .= $this->hidden('_method', array(
'name' => '_method',
'value' => strtoupper($options['type']),
'secure' => static::SECURE_SKIP
));
default:
$htmlAttributes['method'] = 'post';
}
$this->requestType = strtolower($options['type']);
if (!$options['default']) {
if (!isset($options['onsubmit'])) {
$options['onsubmit'] = '';
}
$htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;';
}
if (!empty($options['encoding'])) {
$htmlAttributes['accept-charset'] = $options['encoding'];
}
unset($options['type'], $options['encoding'], $options['default']);
$htmlAttributes = array_merge($options, $htmlAttributes);
$this->fields = array();
if ($this->requestType !== 'get') {
$append .= $this->_csrfField();
}
if (!empty($append)) {
$append = $this->formatTemplate('hiddenblock', ['content' => $append]);
}
$actionAttr = $this->_templater->formatAttributes(['action' => $action, 'escape' => false]);
return $this->formatTemplate('formstart', [
'attrs' => $this->_templater->formatAttributes($htmlAttributes) . $actionAttr
]) . $append;
}
/**
* Create the URL for a form based on the options.
*
* @param \Cake\View\Form\ContextInterface $context The context object to use.
* @param array $options An array of options from create()
* @return string The action attribute for the form.
*/
protected function _formUrl($context, $options) {
if ($options['action'] === null && $options['url'] === null) {
return $this->request->here(false);
}
if (empty($options['url']) || is_array($options['url'])) {
if (isset($options['action']) && empty($options['url']['action'])) {
$options['url']['action'] = $options['action'];
}
$plugin = $this->plugin ? Inflector::underscore($this->plugin) : null;
$actionDefaults = [
'plugin' => $plugin,
'controller' => Inflector::underscore($this->request->params['controller']),
'action' => $this->request->params['action'],
];
$action = (array)$options['url'] + $actionDefaults;
$pk = $context->primaryKey();
if (count($pk)) {
$id = $context->val($pk[0]);
}
if (empty($action[0]) && isset($id)) {
$action[0] = $id;
}
return $action;
}
if (is_string($options['url'])) {
return $options['url'];
}
}
/**
* Return a CSRF input if the request data is present.
* Used to secure forms in conjunction with CsrfComponent &
* SecurityComponent
*
* @return string
*/
protected function _csrfField() {
if (!empty($this->request['_Token']['unlockedFields'])) {
foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
$this->_unlockedFields[] = $unlocked;
}
}
if (empty($this->request->params['_csrfToken'])) {
return '';
}
return $this->hidden('_csrfToken', array(
'value' => $this->request->params['_csrfToken'],
'secure' => static::SECURE_SKIP
));
}
/**
* Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
* input fields where appropriate.
*
* @param array $secureAttributes will be passed as html attributes into the hidden input elements generated for the
* Security Component.
* @return string A closing FORM tag.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
*/
public function end($secureAttributes = []) {
$out = '';
if (
$this->requestType !== 'get' &&
!empty($this->request['_Token'])
) {
$out .= $this->secure($this->fields, $secureAttributes);
$this->fields = array();
}
$out .= $this->formatTemplate('formend', []);
$this->requestType = null;
$this->_context = null;
return $out;
}
/**
* Generates a hidden field with a security hash based on the fields used in
* the form.
*
* If $secureAttributes is set, these html attributes will be merged into
* the hidden input tags generated for the Security Component. This is
* especially useful to set HTML5 attributes like 'form'.
*
* @param array|null $fields If set specifies the list of fields to use when
* generating the hash, else $this->fields is being used.
* @param array $secureAttributes will be passed as html attributes into the hidden
* input elements generated for the Security Component.
* @return string A hidden input field with a security hash
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
*/
public function secure($fields = array(), $secureAttributes = 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'), 'sha1');
$tokenFields = array_merge($secureAttributes, array(
'value' => urlencode($fields . ':' . $locked),
));
$out = $this->hidden('_Token.fields', $tokenFields);
$tokenUnlocked = array_merge($secureAttributes, array(
'value' => urlencode($unlocked),
));
$out .= $this->hidden('_Token.unlocked', $tokenUnlocked);
return $this->formatTemplate('hiddenblock', ['content' => $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.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
*/
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 string|array $field Reference to field to be secured. Can be dot
* separated string to indicate nesting or array of fieldname parts.
* @param mixed $value Field value, if value should not be tampered with.
* @return mixed|null Not used yet
*/
protected function _secure($lock, $field, $value = null) {
if (is_string($field)) {
$field = Hash::filter(explode('.', $field));
}
foreach ($this->_unlockedFields as $unlockField) {
$unlockParts = explode('.', $unlockField);
if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
return;
}
}
$field = implode('.', $field);
$field = preg_replace('/(\.\d+)+$/', '', $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.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
*/
public function isFieldError($field) {
return $this->_getContext()->hasError($field);
}
/**
* Returns a formatted error message for given form field, '' if no errors.
*
* Uses the `error`, `errorList` and `errorItem` templates. The `errorList` and
* `errorItem` templates are used to format multiple error messages per field.
*
* ### Options:
*
* - `escape` boolean - Whether or not to html escape the contents of the error.
*
* @param string $field A field name, like "Modelname.fieldname"
* @param string|array $text Error message as string or array of messages. If an array,
* it should be a hash of key names => messages.
* @param array $options See above.
* @return string Formatted errors or ''.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
*/
public function error($field, $text = null, $options = []) {
$options += ['escape' => true];
$context = $this->_getContext();
if (!$context->hasError($field)) {
return '';
}
$error = (array)$context->error($field);
if (is_array($text)) {
$tmp = [];
foreach ($error as $e) {
if (isset($text[$e])) {
$tmp[] = $text[$e];
} else {
$tmp[] = $e;
}
}
$text = $tmp;
}
if ($text !== null) {
$error = $text;
}
if ($options['escape']) {
$error = h($error);
unset($options['escape']);
}
if (is_array($error)) {
if (count($error) > 1) {
$errorText = [];
foreach ($error as $err) {
$errorText[] = $this->formatTemplate('errorItem', ['text' => $err]);
}
$error = $this->formatTemplate('errorList', [
'content' => implode('', $errorText)
]);
} else {
$error = array_pop($error);
}
}
return $this->formatTemplate('error', ['content' => $error]);
}
/**
* Returns a formatted LABEL element for HTML forms.
*
* Will automatically generate a `for` attribute if one is not provided.
*
* ### Options
*
* - `for` - Set the for attribute, if its not defined the for attribute
* will be generated from the $fieldName parameter using
* FormHelper::_domId().
*
* Examples:
*
* The text and for attribute are generated off of the fieldname
*
* {{{
* echo $this->Form->label('Post.published');
*
* }}}
*
* Custom text:
*
* {{{
* echo $this->Form->label('Post.published', 'Publish');
*
* }}}
*
* Custom class name:
*
* {{{
* echo $this->Form->label('Post.published', 'Publish', 'required');
*
* }}}
*
* Custom attributes:
*
* {{{
* echo $this->Form->label('Post.published', 'Publish', array(
* 'for' => 'post-publish'
* ));
*
* }}}
*
* @param string $fieldName This should be "Modelname.fieldname"
* @param string $text Text that will appear in the label field. If
* $text is left undefined the text will be inflected from the
* fieldName.
* @param array|string $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/2.0/en/core-libraries/helpers/form.html#FormHelper::label
*/
public function label($fieldName, $text = null, $options = array()) {
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, -3);
}
$text = __(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);
}
$attrs = $options + [
'for' => $labelFor,
'text' => $text,
];
return $this->widget('label', $attrs);
}
/**
* Generate an ID suitable for use in an ID attribute.
*
* @param string $value The value to convert into an ID.
* @return string The generated id.
*/
protected function _domId($value) {
return mb_strtolower(Inflector::slug($value, '-'));
}
/**
* Generate a set of inputs for `$fields`. If $fields is null the fields of current model
* will be used.
*
* You can customize individual inputs through `$fields`.
* {{{
* $this->Form->inputs(array(
* 'name' => array('label' => 'custom label')
* ));
* }}}
*
* In addition to controller fields output, `$fields` can be used to control legend
* and fieldset rendering.
* `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
* Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
* for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
*
* @param array $fields An array of fields to generate inputs for, or null.
* @param array $blacklist A simple array of fields to not create inputs for.
* @param array $options Options array. Valid keys are:
* - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
* the class name 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.
* @return string Completed form inputs.
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
*/
public function inputs($fields = null, $blacklist = null, $options = array()) {
$fieldset = $legend = true;
$modelFields = array();
$model = $this->model();
if ($model) {
$modelFields = array_keys((array)$this->_introspectModel($model, 'fields'));
}
if (is_array($fields)) {
if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
$legend = $fields['legend'];
unset($fields['legend']);
}
if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
$fieldset = $fields['fieldset'];
unset($fields['fieldset']);
}
} elseif ($fields !== null) {
$fieldset = $legend = $fields;
if (!is_bool($fieldset)) {
$fieldset = true;
}
$fields = array();
}
if (isset($options['legend'])) {
$legend = $options['legend'];
}
if (isset($options['fieldset'])) {
$fieldset = $options['fieldset'];
}
if (empty($fields)) {
$fields = $modelFields;
}
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) {
if ($legend) {
$out = $this->Html->useTag('legend', $legend) . $out;
}
$out = $this->Html->useTag('fieldset', $fieldsetClass, $out);
}
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().
* - `options` - For widgets that take options e.g. radio, select.
* - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
* error and error messages).
* - `empty` - String or boolean to enable empty select box options.
*
* @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 = []) {
$options += [
'type' => null,
'label' => null,
'error' => null,
'options' => null,
'required' => null,
'templates' => []
];
$options = $this->_parseOptions($fieldName, $options);
$options += ['id' => $this->_domId($fieldName)];
$originalTemplates = $this->templates();
$this->templates($options['templates']);
unset($options['templates']);
$input = $this->_getInput($fieldName, $options);
$label = $this->_getLabel($fieldName, $options);
if ($options['type'] !== 'radio') {
unset($options['label']);
}
$template = 'groupContainer';
$error = null;
if ($options['type'] !== 'hidden' && $options['error'] !== false) {
$error = $this->error($fieldName, $options['error']);
$template = empty($error) ? $template : 'groupContainerError';
unset($options['error']);
}
$groupTemplate = $options['type'] === 'checkbox' ? 'checkboxFormGroup' : 'formGroup';
$result = $this->formatTemplate($groupTemplate, compact('input', 'label'));
if ($options['type'] !== 'hidden') {
$result = $this->formatTemplate($template, [
'content' => $result,
'error' => $error,
'required' => $options['required'] ? ' required' : '',
'type' => $options['type'],
]);
}
$this->templates($originalTemplates);
return $result;
}
/**
* Generates an input element
*
* @param string $fieldName the field name
* @param array $options The options for the input element
* @return string The generated input element
*/
protected function _getInput($fieldName, $options) {
switch ($options['type']) {
case 'select':
$opts = $options['options'];
unset($options['options']);
return $this->select($fieldName, $opts, $options);
case 'url':
$options = $this->_initInputField($fieldName, $options);
return $this->widget($options['type'], $options);
case 'date':
return $this->dateTime($fieldName, $options);
default:
return $this->{$options['type']}($fieldName, $options);
}
}
/**
* Generates input options array
*
* @param string $fieldName the name of the field to parse options for
* @param array $options
* @return array Options
*/
protected function _parseOptions($fieldName, $options) {
$needsMagicType = false;
if (empty($options['type'])) {
$needsMagicType = true;
$options['type'] = $this->_inputType($fieldName, $options);
}
$options = $this->_magicOptions($fieldName, $options, $needsMagicType);
return $options;
}
/**
* Returns the input type that was guessed for the provided fieldName,
* based on the internal type it is associated too, its name and the
* variales that can be found in the view template
*
* @param string $fieldName the name of the field to guess a type for
* @param array $options the options passed to the input method
* @return string
*/
protected function _inputType($fieldName, $options) {
$context = $this->_getContext();
$primaryKey = (array)$context->primaryKey();
if (in_array($fieldName, $primaryKey)) {
return 'hidden';
}
if (substr($fieldName, -3) === '_id') {
return 'select';
}
$internalType = $context->type($fieldName);
$map = $this->settings['typeMap'];
$type = isset($map[$internalType]) ? $map[$internalType] : 'text';
$fieldName = array_slice(explode('.', $fieldName), -1)[0];
switch (true) {
case isset($options['checked']) :
return 'checkbox';
case isset($options['options']) :
return 'select';
case in_array($fieldName, ['passwd', 'password']) :
return 'password';
case in_array($fieldName, ['tel', 'telephone', 'phone']) :
return 'tel';
case $fieldName === 'email':
return 'email';
case isset($options['rows']) || isset($options['cols']) :
return 'textarea';
}
return $type;
}
/**
* Selects the variable containing the options for a select field if present,
* and sets the value to the 'options' key in the options array.
*
* @param string $fieldName the name of the field to find options for
* @param array $options
* @return array
*/
protected function _optionsOptions($fieldName, $options) {
if (isset($options['options'])) {
return $options;
}
$fieldName = array_slice(explode('.', $fieldName), -1)[0];
$varName = Inflector::variable(
Inflector::pluralize(preg_replace('/_id$/', '', $fieldName))
);
$varOptions = $this->_View->get($varName);
if (!is_array($varOptions)) {
return $options;
}
if ($options['type'] !== 'radio') {
$options['type'] = 'select';
}
$options['options'] = $varOptions;
return $options;
}
/**
* Magically set option type and corresponding options
*
* @param string $fieldName the name of the field to generate options for
* @param array $options
* @param boolean $allowOverride whether or not it is allowed for this method to
* overwrite the 'type' key in options
* @return array
*/
protected function _magicOptions($fieldName, $options, $allowOverride) {
$context = $this->_getContext();
if (!isset($options['required']) && $options['type'] !== 'hidden') {
$options['required'] = $context->isRequired($fieldName);
}
$type = $context->type($fieldName);
$fieldDef = $context->attributes($fieldName);
if ($options['type'] === 'number' && !isset($options['step'])) {
if ($type === 'decimal') {
$decimalPlaces = substr($fieldDef['length'], strpos($fieldDef['length'], ',') + 1);
$options['step'] = sprintf('%.' . $decimalPlaces . 'F', pow(10, -1 * $decimalPlaces));
} elseif ($type === 'float') {
$options['step'] = 'any';
}
}
// Missing HABTM
//...
$typesWithOptions = ['text', 'number', 'radio', 'select'];
if ($allowOverride && in_array($options['type'], $typesWithOptions)) {
$options = $this->_optionsOptions($fieldName, $options);
}
if ($options['type'] === 'select' && array_key_exists('step', $options)) {
unset($options['step']);
}
$autoLength = !array_key_exists('maxlength', $options)
&& !empty($fieldDef['length'])
&& $options['type'] !== 'select';
$allowedTypes = ['text', 'email', 'tel', 'url', 'search'];
if ($autoLength && in_array($options['type'], $allowedTypes)) {
$options['maxlength'] = $fieldDef['length'];
}
if (in_array($options['type'], ['datetime', 'date', 'time', 'select'])) {
$options += ['empty' => false];
}
return $options;
}
/**
* Generate label for input
*
* @param string $fieldName
* @param array $options
* @return boolean|string false or Generated label element
*/
protected function _getLabel($fieldName, $options) {
if (in_array($options['type'], ['radio', 'hidden'])) {
return false;
}
$label = null;
if (isset($options['label'])) {
$label = $options['label'];
}
if ($label === false) {
return false;
}
return $this->_inputLabel($fieldName, $label, $options);
}
/**
* 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 mixed 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.
*
* $options can contain a hash of id overrides. These overrides will be
* used instead of the generated values if present.
*
* @param string $fieldName
* @param string $label
* @param array $options Options for the label element. 'NONE' option is deprecated and will be removed in 3.0
* @return string Generated label element
*/
protected function _inputLabel($fieldName, $label, $options) {
$labelAttributes = [];
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.
* @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 = []) {
$options += array('hiddenField' => true, 'value' => 1);
// Work around value=>val translations.
$value = $options['value'];
unset($options['value']);
$options = $this->_initInputField($fieldName, $options);
$options['value'] = $value;
$output = '';
if ($options['hiddenField']) {
$hiddenOptions = array(
'name' => $options['name'],
'value' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '0'),
'secure' => false
);
if (isset($options['disabled']) && $options['disabled']) {
$hiddenOptions['disabled'] = 'disabled';
}
$output = $this->hidden($fieldName, $hiddenOptions);
}
unset($options['hiddenField'], $options['type']);
return $output . $this->widget('checkbox', $options);
}
/**
* Creates a set of radio widgets.
*
* ### Attributes:
*
* - `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.
* - `empty` - Set to `true` to create a input with the value '' as the first option. When `true`
* the radio label will be 'empty'. Set this option to a string to control the label value.
*
* @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 = [], $attributes = []) {
$attributes = $this->_initInputField($fieldName, $attributes);
$out = [];
$hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
unset($attributes['hiddenField']);
$value = $attributes['val'];
$hidden = '';
if ($hiddenField && (!isset($value) || $value === '')) {
$hidden = $this->hidden($fieldName, [
'value' => '',
'name' => $attributes['name']
]);
}
$attributes['options'] = $options;
return $hidden . $this->widget('radio', $attributes);
}
/**
* 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 \Cake\Error\Exception When there are no params for the method call.
*/
public function __call($method, $params) {
$options = [];
if (empty($params)) {
throw new Error\Exception(sprintf('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->widget($options['type'], $options);
}
/**
* 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
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
*/
public function textarea($fieldName, $options = array()) {
$options = $this->_initInputField($fieldName, $options);
return $this->widget('textarea', $options);
}
/**
* 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()) {
$options += array('required' => false, 'secure' => true);
$secure = $options['secure'];
unset($options['secure']);
$options = $this->_initInputField($fieldName, array_merge(
$options, array('secure' => static::SECURE_SKIP)
));
if ($secure === true) {
$this->_secure(true, $this->_secureFieldName($options), $options['val']);
}
$options['type'] = 'hidden';
return $this->widget('hidden', $options);
}
/**
* 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'] = static::SECURE_SKIP;
$options = $this->_initInputField($fieldName, $options);
foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
$this->_secure(
$secure,
$this->_secureFieldName(['name' => $options['name'] . '[' . $suffix . ']'])
);
}
unset($options['type']);
return $this->widget('file', $options);
}
/**
* Creates a `