Way to define cakephp inputDefaults at site level Way to define cakephp inputDefaults at site level php php

Way to define cakephp inputDefaults at site level


TLDR:

Paste the 2 chunks of code below in their respective spots, then change the $defaultOptions array to whatever you want - voila. It doesn't alter any of the FormHelper's functions except adds defaults to the Form->create's inputDefaults.

Explanation & Code:

You can extend the FormHelper (easier than it sounds) by making your own custom MyFormHelper:

<?php//create this file called 'MyFormHelper.php' in your View/Helper folderApp::uses('FormHelper', 'View/Helper');class MyFormHelper extends FormHelper {    public function create($model = null, $options = array()) {        $defaultOptions = array(            'inputDefaults' => array(                'div' => false,                'label' => false            )        );              if(!empty($options['inputDefaults'])) {            $options = array_merge($defaultOptions['inputDefaults'], $options['inputDefaults']);        } else {            $options = array_merge($defaultOptions, $options);        }        return parent::create($model, $options);    }}

Then, in your AppController, include the Form helper in the following way (if you already have a $helpers variable, just add 'Form' => ... to it):

public $helpers = array(    'Form' => array(        'className' => 'MyForm'    ));

This makes it so whenever you call $this->Form, it actually calls your custom 'MyFormHelper' - and the only thing it does is set the inputDefaults if they're not specified, then continue on to do the normal logic found in Cake's FormHelper.


This is really great - I did change this a bit, so that you use Hash::merge, instead of array merge to keep it to the Cake Api. Also, I named mine "AppFormHelper" - but that is just my own naming: naming helpers is pretty loose. Thanks for the tip!

Hash Class: http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html

<?php/** * @file AppFormHelper. *  This allows you to create defaults for your forms. */App::uses('FormHelper', 'View/Helper');class AppFormHelper extends FormHelper {  public function create($model = null, $options = array()) {    $default = array(      'inputDefaults' => array(        'div' => false,        'class' => 'form-control',        'autocomplete' => 'off',      ),    );    $options = Hash::merge($default, $options);    return parent::create($model, $options);  }}


Can I please add that Dave's code above has a bug in it. The line:

$options = array_merge($defaultOptions['inputDefaults'], $options['inputDefaults']);

Causes a "Notice (8): Array to string conversion [CORE/Cake/View/Helper.php, line 486]" when inputDefaults is specified in both the the extended FormHelper as well as in the form itself.

This bug is not present in kirikintha's version.