Setting id of input wrapper div in cakephp and hiding by default

It might be a simple thing for most of CakePHP pro’s but at the same time it could be a tricky thing for CakePHP newbies. I just caught one newbie CakePHP developer of my team spending time on figuring this out thus adding it here for future reference. I hope it helps someone else as well.

So this about setting a ID of the wrapper div which contains label and input field in a CakePHP form. Consider the following example:

echo $this->Form->input(‘username’);

which outputs:

<div class=”input text”>
<label for=”BookPrice”>Price</label>
<input name=”data[Book][Price]” maxlength=”150″ type=”text” id=”BookPrice”>
</div>

Imagine that in a case you wanted to hide this entire div and wanted to show some click event and for this to happen you want a ID attached to this div element. By the virtue of CakePHP it is quite simple provided you have read related documentation. To add an ID to hide it by default you obviously would want to add id=”price-wrapper” and style=”display:none” to the <div> element with classes “input text”. Just revisit the line above and write it as:

echo $this->Form->input(‘username’, array(‘div’=>array(‘id’ => ‘price-wrapper’, ‘style’=>’display:none;’)));

and it will output:

<div  class=”input text” id=”price-wrapper” style=”display:none;”>
<label for=”BookPrice”>Price</label>
<input name=”data[Book][Price]” maxlength=”150″ type=”text” id=”BookPrice”>
</div>

which you wanted. Isn’t that simple!

5 thoughts on “Setting id of input wrapper div in cakephp and hiding by default

  1. Thanks for this info.
    But the question is how do i add the javascript onclick event? i am currently using cakephp 2.3.

    1. Which element do you want to add onclick event to? If you want to add it to element with ID “price-wrapper” this is how you do it using jQuery:

      jQuery(document).ready(function() {
      jQuery("#price-wrapper").onclick(function() {
      //do somethings..
      })
      })

      If you use core javascript you can create a function like the following to attach an onclick event to an element:

      window.onload = function()	{
      var ele = document.getElementById('price-wrapper');
      ele.onclick = function() {
      //do somethings..
      }
      }
  2. You’ve got a typo in your code example:

    echo $this->Form->input(‘username’, array(‘div’=>array(‘style’ => ‘price-wrapper’, ‘style’=>’display:none;’)));

    should be:

    echo $this->Form->input(‘username’, array(‘div’=>array(‘id’ => ‘price-wrapper’, ‘style’=>’display:none;’)));

Leave a Reply