A Drupal form textfield example

Drupal form textfield FAQ: Can you share an example of how to create an HTML textfield in a Drupal form (Drupal 6 or Drupal 7)?

Assuming that you're already comfortable with creating a Drupal form, you can create a Drupal form textfield as easily as this:

# an html textfield for our drupal form
$form['first_name'] = array(
  '#title' => t('First Name'),
  '#type' => 'textfield',
);

That code creates an HTML textfield with the label "First Name", as you can see here:

A Drupal form textfield example

(If you're not comfortable with creating a Drupal module or Drupal form, please see my A simple, first Drupal form example/tutorial.

More Drupal textfield options

You can add quite a few more fields to your Drupal textfield definition to help control how the HTML textfield is rendered. Here are a few additional fields added to our first textfield example:

$form['first_name'] = array(
  '#title' => t('First Name'),
  '#type' => 'textfield',
  '#description' => 'Enter your first name',
  '#default_value' => 'Fred',
  '#size' => 32,
  '#maxlength' => 128,
  '#required' => TRUE,
  '#field_prefix' => 'form1'
);

Hopefully those Drupal form fields are self-explanatory, but if not, leave a note in the Comments section below and I'll be glad to add more information here.

You can add even more fields to your Drupal textfield definition. The fields you can add are defined in the grid at this Drupal Form API reference page.

Drupal form textfield example - Summary

I hope this Drupal form textfield example has been helpful. If you have any questions just leave a note in the Comments section below and I'll be glad to help (if I can).