Professional CodeIgniter

(singke) #1

Chapter 3: A 10,000 - Foot View of CodeIgniter


62


The Form Helper


One of the most useful helpers in the CodeIgniter toolbox is the Form helper. Forms represent a common
HTML element that developers typically spend a lot of time building, maintaining, and debugging. The
functions present in the Form helper help you keep things straight when working with forms.

To create a form, open a view file in your favorite editor and use the form_open() function to create a
form element. Pass in the URI segment of the controller function that handles the POST data after the
user clicks the Submit button. For example, if you were building a simple search form, you might open it
this way:

echo form_open(‘welcome/search’);

Many forms contain hidden form fields, which you can easily add with the form_hidden() function,
like so:

echo form_hidden(‘id’, ‘414’);
echo form_hidden(‘searchtype’, ‘basic’);

Adding form fields to your form is also easy, using the form_input() function. Although you can call
the function by passing in a name - value pair, it ’ s a good idea to get used to passing in a larger data array,
in which a more complete data set can be organized.

$data = array(
‘name’ = > ‘searchterm’,
‘id’ = > ‘search’,
‘maxlength’ = > ‘100’,
‘size’ = > ‘50’,
‘style’ = > ‘background-color:#f1f1f1’
)
echo form_input($data);

Similarly, you can create password fields with form_password() , file upload fields with form_
upload() , and text areas with form_textarea(). Just set up an array and pass its values into the
function.

Dropdowns are slightly different, in that they require you to pass in an array of choices for the
dropdown, as well as a default value:

$values = array(
‘high’ = > ‘high’,
‘medium’ = > ‘medium’,
‘low’ = > ‘low’
);

echo form_dropdown(‘priority’, $values, ‘medium’);

Other elements, such as radio buttons and checkboxes, can be created with form_checkbox() and
form_radio(). These two functions are covered later in this book.
Free download pdf