Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding style to CakePHP automatically created input div

CakePHP creates a div that automatically wraps any of its input tags that are built with the formhelper as followed:

$this->formhelper->input('something');

Such that the output looks about as followed:

<div class='input'>
    <input />
</div>

I know that there is a way to add classes to the input tag i.e.

$this->formhelper->input('text', array('class' => 'some_css'));

But how would you add a style to the div that is automatically created by CakePHP. This might be something where the core needs to be hacked, but I want to know if there is a better way to do this, so that I get something as followed:

<div class='input other_class_I_want_here'>
    <input />
</div>

Thank you to anyone who can help.

like image 751
usumoio Avatar asked Dec 08 '22 12:12

usumoio


2 Answers

Simply add a new class to the div.

$this->formhelper->input('text', array('div'=>array('class'=>'divClass'),'class' => 'some_css'));

should actually output

<div class='input divClass'>
    <input class='other_class_I_want_here' />
</div>
like image 151
evansLY Avatar answered Dec 30 '22 10:12

evansLY


The above answer is certainly correct. And works beautifully if you only require adding a class in a one (or a few) specific locations.

However, anyone arriving here looking for a way to add a class to input div wrappers application-wide (ex: if you're using a front-end framework which often requires a specific class name be added to input wrappers to enable auto-styles) there is a MUCH better solution. That being, a custom FormHelper.

  1. In the App/View/Helper directory create and save a file "MySuperCoolFormHelper.php"

  2. Place the following code in the file:

    App::uses('FormHelper', 'View/Helper');
    
    class MySuperCoolFormHelper extends FormHelper {

        protected function _divOptions($options) {
            if(isset($options['div'])
                $options['div'] .= ' class1 class2 class3'; //note the prefixing space
            else
                $options['div'] = 'class1 class2 class3';

            return parent::_divOptions($options);
        }
    }
  1. To use this new form helper globally, add the following code to your AppController:
    public $helpers = array(
        'Form' => array(
            'className' => 'MySuperCoolFormHelper'
        )
        //The rest of your helper inits
    );

   

... and BLAMMO you're done!

like image 23
pim Avatar answered Dec 30 '22 09:12

pim