Improve this page

Form Fields

Overview of built-in form fields.

addText(string|int $name, $label=null): TextInput

Adds single line text field (class TextInput). Automatically trims left and right side whitespace.

$form->addText('zip', 'Postcode:')
	->addRule($form::PATTERN, 'Postcode must have exactly 5 numerals', '([0-9]\s*){5}');

The so-called empty-value can be set for the element, which is something like the default value, but if the user does not overwrite it, returns empty string.

$form->addText('phone', 'Phone:')

addPassword(string|int $name, $label=null): TextInput

Adds password field (class TextInput). Automatically trims left and right side whitespace. Redrawing the form renders the input empty.

$form->addPassword('password', 'Password:')
	->addRule($form::MIN_LENGTH, 'Password has to be at least %d characters long', 3)
	->addRule($form::PATTERN, 'Password must contain a number', '.*[0-9].*');

addTextArea(string|int $name, $label=null): TextArea

Adds a multiline text field (class TextArea). Unlike oneline inputs, it does not trim the input's whitespace on either edge.

$form->addTextArea('note', 'Note:')
	->addRule($form::MAX_LENGTH, 'Your note is way too long', 10000);

addEmail(string|int $name, $label=null): TextInput

Adds email address field with validity check (class TextInput).

$form->addEmail('email', 'Email:');

addInteger(string|int $name, $label=null): TextInput

Adds input field for integer.

$form->addInteger('level', 'Level:')
	->addRule($form::RANGE, 'Level must be between %d and %d.', [0, 100]);

addUpload(string|int $name, $label=null): UploadControl

Adds file upload field (class UploadControl).

$form->addUpload('thumbnail', 'Thumbnail:')
	->setRequired(false) // optional
	->addRule($form::IMAGE, 'Thumbnail must be JPEG, PNG or GIF')
	->addRule($form::MAX_FILE_SIZE, 'Maximum file size is 64 kB.', 64 * 1024 /* size in Bytes */);

addMultiUpload(string|int $name, $label=null): UploadControl

Adds multiple file upload field.

$form->addMultiUpload('files', 'Files');

addHidden(string|int $name, string $default=null): HiddenField

Adds hidden field (class HiddenField).


addCheckbox(string|int $name, $caption=null): Checkbox

Adds a checkbox (class Checkbox). The return value is either Boolean true or false, as checked or not checked.

$form->addCheckbox('agree', 'I agree with terms')
	->setRequired('You must agree with our terms');
$form->addCheckbox('resize', 'Resize image?')

addRadioList(string|int $name, $label=null, array $items=null): RadioList

Adds radio buttons (class RadioList). Array of offered values is passed as the third argument.

$sex = [
	'm' => 'male',
	'f' => 'female',
$form->addRadioList('gender', 'Gender:', $sex);

// to list options within 1 line
$form->addRadioList('gender', 'Gender:', $sex)

addCheckboxList(string|int $name, $label=null, array $items=null): CheckboxList

Adds list of checkboxes for selecting multiple elements (class CheckboxList). Array of values is passed as the third argument. The component checks if the submitted values are from the given range.

$form->addCheckboxList('colors', 'Colors:', [
	'r' => 'red',
	'g' => 'green',
	'b' => 'blue',

addSelect(string|int $name, $label=null, array $items=null): SelectBox

Adds select box (class SelectBox). Array of offered values is passed as third argument. Might as well be two-dimensional. The first item is often used as a call-to-action message, but worthless when actually selected – that's what method setPrompt() is for.

$countries = [
	'Europe' => [
		'CZ' => 'Czech republic',
		'SK' => 'Slovakia',
		'GB' => 'United Kingdom',
	'CA' => 'Canada',
	'US' => 'USA',
	'?'  => 'other',
$form->addSelect('country', 'Country:', $countries)
	->setPrompt('Pick a country');

The element returns the key of the selected item. The key is also specified as the default value:

$form->addSelect('country', 'Country:')

You can also add elements by using the setItems() method. If we want to get their values directly in place of key items, we can do this with the second argument:

$form->addSelect('country', 'Country:')
	->setItems($countries, false);

Individual items may be, in addition to strings, objects Nette\Utils\Html::('option'), which then can set additional HTML attributes. However, the selected and disabled attributes do not set this way, the form itself takes care of it. This also applies to addMultiSelect().

addMultiSelect(string|int $name, $label=null, array $items=null): MultiSelectBox

Adds multichoice select box (class MultiSelectBox).

$form->addMultiSelect('options', 'Pick many:', $options);

addSubmit(string|int $name, $caption=null): SubmitButton

Adds submit button (class SubmitButton).

$form->addSubmit('submit', 'Register');

It's okay to add more than one submit button.

$form->addSubmit('submit', 'Register');
$form->addSubmit('cancel', 'Cancel');

To find out which of them was clicked, use:

if ($form['submit']->isSubmittedBy()) {
  // ...

If you don't want to validate the form when a submit button is pressed (such as Cancel or Preview buttons), you can turn it off with setValidationScope([]).

addButton(string|int $name, $caption)Button

Adds button (class Button) without submit function. It is useful for binding other functionality to id, for example a JavaScript action.

$form->addButton('raise', 'Raise salary')
	->setHtmlAttribute('onclick', 'raiseSalary()');

addImage(string|int $name, $alt=null): ImageButton

Adds submit button in form of an image (class ImageButton).

$form->addImage('submit', '/path/to/image');

addContainer(string|int $name): Container

Adds a sub-form (class Container), or a container, which can be treated the same way as a form. That means you can use methods like setDefaults() or getValues().

$sub1 = $form->addContainer('first');
$sub1->addText('name', 'Your name:');
$sub1->addEmail('email', 'Email:');

$sub2 = $form->addContainer('second');
$sub2->addText('name', 'Your name:');
$sub2->addEmail('email', 'Email:');

Disabling Inputs

In order to disable an input, you can call $control->setDisabled().

$form->addEmail('email', 'Email:')->setDisabled();

The input cannot be written to and its value won't be returned by getValues().

If we need a read-only input (the input will be rendered as disabled but its value will be shown), we disable the input first and set the value afterwards. The reason is that setDisabled() method resets the value of the input.

$form->addText('readonly', 'Readonly:')->setDisabled()->setValue('readonly value');

If you only need to remove input's value but not disabling it, you can use setOmitted(). This option is useful for omitting antispam inputs for example.

$form->addText('antispam', 'Antispam:')->setOmitted();

Other Fields

Besides wide range of built-in form fields you can add custom fields to the form as follows:

$form = new Form;
$form['date'] = new DateInput('Date:');

Use the extension method to add a new method to object form:

Nette\Forms\Container::extensionMethod('addZip', function (Form $form, $name, $label = null) {
	return $form->addText($name, $label)
		->addRule($form::PATTERN, 'At least 5 numbers', '[0-9]{5}');

$form = new Form;
$form->addZip('zip', 'ZIP code:');

Fields are removed using unset:


Low-level Fields

To add an item to the form, you don't have to call $form->addXyz(). Form items can be introduced exclusively in templates instead. This is useful if you, for example, need to generate dynamic items:

{foreach $items as $item}
	<p><input type=checkbox name="sel[]" value={$item->id}> {$item->name}</p>

After submission, you can retrieve the values:

$values = $form->getHttpData($form::DATA_TEXT, 'sel[]');
$values = $form->getHttpData($form::DATA_TEXT | $form::DATA_KEYS, 'sel[]');

In the first parameter, you specify element type (DATA_FILE for type=file, DATA_LINE for one-line inputs like text, password or email and DATA_TEXT for the rest). The second parameter matches HTML attribute name. If you need to preserve keys, you can combine the first parameter with DATA_KEYS. This is useful for select, radioList or checkboxList.

getHttpData() returns sanitized input. In this case, it will always be array of valid UTF-8 strings, no matter what is sent by the form. It's an alternative to working with $_POST or $_GET directly if you want to receive safe data.

Related blog posts