Lithium Day 2. This time just a simple quick tip about adding different input types using the FormHelper in Lithium. I want to create a button element in my form but there is no native method to do it. The trick is to use FormHelper::field(‘Button Text’, array(‘type’ => ‘button’, ‘label’ => false)); This will output a button element. Setting the ‘label’ to false is also important since by default all FormHelper::field() elements will generate a label. A quick check of the docs for FormHelper::field() gives a full breakdown of options.

Here is some sample code:

<?=$this->form->create($object); ?>
  <?=$this->form->field('title');?>
  <?=$this->form->field('url', array('type' => 'text'));?>
  <?=$this->form->field('Cancel', array('type' => 'button', 'label' => false)); ?>
  <?=$this->form->submit('Submit'); ?>
<?=$this->form->end(); ?>

The markup we get from this will tell us a few things:

<form action="/my_controller/some_action" method="post">
  <div>
    <label for="Title">Title</label>
    <input type="text" name="title" id="Title">
  </div>

  <div>
    <label for="Url">Url</label>
    <input type="text" name="url" id="Url">
  </div>

  <div>
    <button id="Cancel">Cancel</button>
  </div>  <input type="submit" value="Submit"></form>

You can see that the FormHelper::field() method also generates elements with a surrounding div. You can stop prevent this by passing (‘div’ => false) in the options array.

Tagged with:
 
  • Christopher Garvis

    I believe you can just do form->button(‘Cancel’);?>

  • Anonymous

    that actually creates an input element with a button attribute. I actually wanted a button element.

Set your Twitter account name in your settings to use the TwitterBar Section.