The textfield is the workhorse of the Form API — a single-line text box, and the element type you'll reach for more than any other. Names, titles, search boxes, short IDs: if it fits on one line, it's almost always a textfield.
What you'll learn in this lesson
- The basic textfield definition and its most common properties
- How
#maxlengthand#sizediffer — one is validation, one is purely visual - Using
#placeholderand#descriptionto guide the user without cluttering the label
A basic textfield
$form['name'] = [
'#type' => 'textfield',
'#title' => $this->t('Name'),
'#maxlength' => 255,
'#size' => 30,
'#required' => TRUE,
];
#maxlength is enforced — Drupal actually rejects input longer than this on both the client and server side, so it should always match the database column's real character limit (commonly 255 for a `varchar(255)` field). #size, by contrast, is purely cosmetic — it sets the HTML size attribute, which only controls how wide the box visually appears; a user can still type more characters than #size suggests, right up to #maxlength.
Guiding the user: #placeholder and #description
$form['email'] = [
'#type' => 'textfield',
'#title' => $this->t('Email'),
'#placeholder' => 'you@example.com',
'#description' => $this->t('We will never share your email address.'),
];
#placeholder shows faint example text inside an empty field — but it disappears the instant a user starts typing, so never use it as a substitute for #title or for genuinely important instructions the user needs while filling the field in. #description is the right home for that: persistent, styled help text that stays visible below the field the whole time.
#placeholder and no #title is both an accessibility failure (screen readers have nothing to announce) and a usability trap — the instruction vanishes the moment the user starts typing, right when they might most want to double-check what's expected of them.Quick check: you set
#maxlengthto 50 but#sizeto 20. Can a user type 35 characters into the field? (Yes —#sizeonly affects the box's visual width; the actual character limit enforced by Drupal is#maxlength. The user will just need to scroll within the narrow box to see everything they've typed.)
Key takeaways
#maxlengthis a real, enforced constraint — match it to your storage's actual limit.#sizeis purely visual and never restricts what a user can type.- Use
#descriptionfor instructions the user needs while filling in the field —#placeholderdisappears the moment they start typing, so it's example text only, never a substitute for a label.
Coming up next
Textfields handle one line. The next lesson covers textarea — the element you reach for the moment a user needs to type more than that.