Version: current

# Class FormField

Represents a field in a form.

A FieldSet contains a number of FormField objects which make up the whole of a form. In addition to single fields, FormField objects can be "composite", for example, the `TabSet` field. Composite fields let us define complex forms without having to resort to custom HTML.

Subclassing

Define a `FormField::dataValue()` method that returns a value suitable for inserting into a single database field. For example, you might tidy up the format of a date or currency field. Define `FormField::saveInto()` to totally customise saving. For example, data might be saved to the filesystem instead of the data record, or saved to a component of the data record instead of the data record itself.

  Object
  ViewableData implements IteratorAggregate
  RequestHandler
  FormField

### Direct known subclasses

`BouncedList`, `CheckboxField`, `HiddenField`, `InlineFormAction`, `InlineFormAction_ReadOnly`, `MoneyField`, `NewsletterList`, `NullableField`, `PasswordField`, `PermissionCheckboxSetField`, `PhoneNumberField`, `ProgressBar`, `CompositeField`, `RangeField`, `ReadonlyField`, `RecipientExportField`, `RecipientImportField`, `SimpleImageField_Disabled`, `SpamProtectorField`, `SubmittedFormReportField`, `TableListField`, `TextareaField`, `TextField`, `ConfirmedPasswordField`, `ThumbnailStripField`, `TreeDropdownField`, `TreeSelectorField`, `UnsubscribedList`, `WidgetAreaEditor`, `DatalessField`, `DatetimeField`, `DropdownField`, `FieldEditor`, `FileField`, `FormAction`

### Indirect known subclasses

`AjaxUniqueTextField`, `AssetManager`, `ComplexTableField`, `ToggleField`, `TreeDropdownField_Readonly`, `TreeMultiselectField`, `TreeMultiselectField_Readonly`, `UniqueRestrictedTextField`, `UniqueTextField`, `VideoManager`, `Widget_TreeDropdownField`, `CountryDropdownField`, `CreditCardField`, `CurrencyField`, `CurrencyField_Disabled`, `CurrencyField_Readonly`, `DataObjectManager`, `DateField`, `DateField_Disabled`, `DatePickerField`, `AssetTableField`, `DatetimeField_Readonly`, `DocumentPageFiles_Manager`, `EmailField`, `FieldGroup`, `FileComplexTableField`, `FileDataObjectManager`, `FileIFrameField`, `FileList`, `Folder_UnusedAssetsField`, `FormAction_WithoutLabel`, `AutoCompleteField`, `GroupedDropdownField`, `HasManyComplexTableField`, `HasManyDataObjectManager`, `HasManyFileDataObjectManager`, `HasOneComplexTableField`, `HasOneDataObjectManager`, `HasOneFileDataObjectManager`, `HeaderField`, `HTMLDropdownField`, `HtmlEditorField`, `AutocompleteTextField`, `HtmlEditorField_Readonly`, `ImageAssetManager`, `ImageDataObjectManager`, `ImageField`, `ImageFormAction`, `LabelField`, `LanguageDropdownField`, `ListboxField`, `LiteralField`, `LookupField`, `CartTableListField`, `ManyManyComplexTableField`, `ManyManyDataObjectManager`, `ManyManyFileDataObjectManager`, `Mediaweb3DPageFiles_Manager`, `MediawebPageFiles_Manager`, `MediawebPagePhoto_Manager`, `MediawebPageTexture_Manager`, `MemberTableField`, `Monument_PolishingTextField`, `MultiUploadField`, `CheckboxField_Disabled`, `MyRangeField`, `NumericField`, `OptionsetField`, `OrderItemField`, `PermissionCheckboxSetField_Readonly`, `PhoneField`, `PhotoAlbumManager`, `PhpCaptchaField`, `PrintableTransformation_TabSet`, `ProductParamValue_BoolValueField`, `CheckboxField_Readonly`, `ProductParamValue_MultiValueField`, `ProductParamValue_MultiValueSetField`, `ProductParamValue_ValueField`, `ResetFormAction`, `RestrictedTextField`, `RestrictionRegionCountryDropdownField`, `RoomRate_PriceField`, `RoomServiceDropdownField`, `SelectionGroup`, `SimpleHTMLEditorField`, `CheckboxSetField`, `SimpleImageField`, `SimpleTinyMCEField`, `SimpleTreeDropdownField`, `SimpleWysiwygField`, `SocleSize_SocleSectionTextField`, `StateDropdownField`, `StateProvinceDropdownField`, `StealthFieldCaptcha`, `SubpageListField`, `SubsiteAgnosticTableListField`, `CommentTableField`, `SubsiteDropdownField`, `SubsitesTreeDropdownField`, `Tab`, `TableField`, `TabSet`, `TextFieldWithEmptyFlag`, `TextLiteralField`, `TimeField`, `TimeField_Readonly`, `ToggleCompositeField`

Package: forms\core
Located at sapphire/forms/FormField.php

## Methods summary

`public static` | # `allow_html5( mixed $val = true )`
`public static` | # `use_html5( )`
`public` | # `allowHTML5( mixed $val )`
`public` | # `useHTML5( )`
`public` | # `__construct( `FormField::$name` $name, `FormField::$title` $title = null, `FormField::$value` $value = null, `FormField::$form` $form = null, maxLength $rightTitle = null )` Create a new field. Create a new field. #### Parameters $name name The internal field name, passed to forms. $title title The field label. $value value The value of the field. $form form Reference to the container form $rightTitle maxLength The Maximum length of the attribute #### Overrides `RequestHandler::__construct`
`public` | # `setHTML5Attribute( mixed $title, mixed $value )`
`public` | # `getHTML5Attribute( mixed $title )`
`public` | # `setAutocomplete( mixed $value )`
`public` | # `Link( mixed $action = null )` Return a Link to this field Return a Link to this field
`public` | # `id( )` Returns the HTML ID of the field - used in the template by label tags. The ID is generated as FormName_FieldName. All Field functions should ensure that this ID is included in the field. Returns the HTML ID of the field - used in the template by label tags. The ID is generated as FormName_FieldName. All Field functions should ensure that this ID is included in the field.
`public string` | # `Name( )` Returns the field name - used by templates. Returns the field name - used by templates. #### Returns `string` string
`public` | # `attrName( )`
`public string` | # `Message( )` Returns the field message, used by form validation. Use `FormField::setError()` to set this property. Returns the field message, used by form validation. Use `FormField::setError()` to set this property. #### Returns `string` string
`public string` | # `MessageType( )` Returns the field message type, used by form validation. Arbitrary value which is mostly used for CSS classes in the rendered HTML, e.g. "required". Use `FormField::setError()` to set this property. Returns the field message type, used by form validation. Arbitrary value which is mostly used for CSS classes in the rendered HTML, e.g. "required". Use `FormField::setError()` to set this property. #### Returns `string` string
`public` | # `Value( )` Returns the field value - used by templates. Returns the field value - used by templates.
`public` | # `saveInto( `DataObjectInterface` $record )` Method to save this form field into the given data object. By default, makes use of $this->dataValue() Method to save this form field into the given data object. By default, makes use of $this->dataValue()
`public` | # `dataValue( )` Returns the field value suitable for insertion into the data object Returns the field value suitable for insertion into the data object
`public` | # `Title( )` Returns the field label - used by templates. Returns the field label - used by templates.
`public` | # `setTitle( mixed $val )`
`public` | # `RightTitle( )`
`public` | # `setRightTitle( mixed $val )`
`public` | # `LeftTitle( )`
`public` | # `setLeftTitle( mixed $val )`
`public` | # `setTabIndex( integer $index )` Set tabindex HTML attribute (defaults to none). Set tabindex HTML attribute (defaults to none). #### Parameters $index int $index
`public integer` | # `getTabIndex( )` Get tabindex (if previously set) Get tabindex (if previously set) #### Returns `integer` int
`protected string` | # `getTabIndexHTML( integer $increment = 0 )` Get tabindex HTML string Get tabindex HTML string #### Parameters $increment int $increment Increase current tabindex by this value #### Returns `string` string
`public String` | # `extraClass( )` Compiles all CSS-classes. Optionally includes a "nolabel"-class if no title was set on the formfield. Uses `FormField::Message()` and `FormField::MessageType()` to add validatoin error classes which can be used to style the contained tags. Compiles all CSS-classes. Optionally includes a "nolabel"-class if no title was set on the formfield. Uses `FormField::Message()` and `FormField::MessageType()` to add validatoin error classes which can be used to style the contained tags. #### Returns `String` CSS-classnames
`public` | # `addExtraClass( mixed $class )` Add a CSS-class to the formfield-container. Add a CSS-class to the formfield-container. #### Parameters $class $class String
`public` | # `removeExtraClass( mixed $class )` Remove a CSS-class from the formfield-container. Remove a CSS-class from the formfield-container. #### Parameters $class $class String
`public `DataObjectSet`` | # `getExtraClasses( )` Return FormField extraClasses as DataObjectSet Return FormField extraClasses as DataObjectSet #### Returns ``DataObjectSet`` DataObjectSet
`public` | # `addExtraAttribute( mixed $name, mixed $value )` Add an attribute Add an attribute #### Parameters $name $name String $value $value String
`public` | # `removeExtraAttribute( mixed $name )` Remove an attribute Remove an attribute #### Parameters $name $name String
`public` | # `attrTitle( )` Returns a version of a title suitable for insertion into an HTML attribute Returns a version of a title suitable for insertion into an HTML attribute
`public` | # `attrValue( )` Returns a version of a title suitable for insertion into an HTML attribute Returns a version of a title suitable for insertion into an HTML attribute
`public` | # `setValue( mixed $value )` Set the field value. Returns $this. Set the field value. Returns $this. #### Used by ``Form::loadDataFrom()``
`public` | # `setName( mixed $name )` Set the field name Set the field name
`public` | # `setForm( mixed $form )` Set the container form. This is called whenever you create a new form and put fields inside it, so that you don't have to worry about linking the two. Set the container form. This is called whenever you create a new form and put fields inside it, so that you don't have to worry about linking the two.
`public `Form`` | # `getForm( )` Get the currently used form. Get the currently used form. #### Returns ``Form`` Form
`public boolean` | # `securityTokenEnabled( )` Return TRUE if security token protection is enabled on the parent `Form`. Return TRUE if security token protection is enabled on the parent `Form`. #### Returns `boolean` bool
`public` | # `setError( mixed $message, mixed $messageType )` Sets the error message to be displayed on the form field Set by php validation of the form Sets the error message to be displayed on the form field Set by php validation of the form
`public` | # `setCustomValidationMessage( String $msg )` Set the custom error message to show instead of the default format of Please Fill In XXX. Different from setError() as that appends it to the standard error messaging Set the custom error message to show instead of the default format of Please Fill In XXX. Different from setError() as that appends it to the standard error messaging #### Parameters $msg String Message for the error
`public String` | # `getCustomValidationMessage( )` Get the custom error message for this form field. If a custom message has not been defined then just return blank. The default error is defined on `Validator`. Get the custom error message for this form field. If a custom message has not been defined then just return blank. The default error is defined on `Validator`. #### Returns `String` String
`public` | # `Field( )` Returns the form field - used by templates. Although FieldHolder is generally what is inserted into templates, all of the field holder templates make use of $Field. It's expected that FieldHolder will give you the "complete" representation of the field on the form, whereas Field will give you the core editing widget, such as an input tag. Returns the form field - used by templates. Although FieldHolder is generally what is inserted into templates, all of the field holder templates make use of $Field. It's expected that FieldHolder will give you the "complete" representation of the field on the form, whereas Field will give you the core editing widget, such as an input tag. Our base FormField class just returns a span containing the value. This should be overridden!
`public` | # `FieldHolder( )` Returns a "Field Holder" for this field - used by templates. Forms are constructed from by concatenating a number of these field holders. The default field holder is a label and form field inside a paragraph tag. Returns a "Field Holder" for this field - used by templates. Forms are constructed from by concatenating a number of these field holders. The default field holder is a label and form field inside a paragraph tag. Composite fields can override FieldHolder to create whatever visual effects you like. It's a good idea to put the actual HTML for field holders into templates. The default field holder is the DefaultFieldHolder template. This lets you override the HTML for specific sites, if it's necessary.
`public` | # `SmallFieldHolder( )` Returns a restricted field holder used within things like FieldGroups. Returns a restricted field holder used within things like FieldGroups.
`public mixed` | # `setTemplate( string $template )` Set name of template (without path or extension). Set name of template (without path or extension). Caution: Not consistently implemented in all subclasses, please check the `FormField::Field()` method on the subclass for support. #### Parameters $template string $template #### Returns `mixed` $this
`public mixed` | # `setFieldHolderTemplate( string $fieldHolderTemplate )` Set name of template (without path or extension) for the holder, which in turn is responsible for rendering `FormField::Field()`. Set name of template (without path or extension) for the holder, which in turn is responsible for rendering `FormField::Field()`. Caution: Not consistently implemented in all subclasses, please check the `FormField::Field()` method on the subclass for support. #### Parameters $fieldHolderTemplate string $fieldHolderTemplate #### Returns `mixed` $this
`public mixed` | # `setSmallFieldHolderTemplate( string $smallFieldHolderTemplate )` Set name of template (without path or extension) for the small holder, which in turn is responsible for rendering `FormField::Field()`. Set name of template (without path or extension) for the small holder, which in turn is responsible for rendering `FormField::Field()`. Caution: Not consistently implemented in all subclasses, please check the `FormField::Field()` method on the subclass for support. #### Parameters $smallFieldHolderTemplate string $smallFieldHolderTemplate #### Returns `mixed` $this
`public array` | # `fieldTemplates( )` Returns an array of templates to use for rendering `FormField::FieldHolder()`. Returns an array of templates to use for rendering `FormField::FieldHolder()`. #### Returns `array` array
`public array` | # `fieldHolderTemplates( )` Returns an array of templates to use for rendering `FormField::FieldHolder()`. Returns an array of templates to use for rendering `FormField::FieldHolder()`. #### Returns `array` array
`public array` | # `smallFieldHolderTemplates( )` Returns an array of templates to use for rendering `FormField::SmallFieldHolder()`. Returns an array of templates to use for rendering `FormField::SmallFieldHolder()`. #### Returns `array` array
`public` | # `isComposite( )` Returns true if this field is a composite field. To create composite field types, you should subclass `CompositeField`. Returns true if this field is a composite field. To create composite field types, you should subclass `CompositeField`.
`public` | # `hasData( )` Returns true if this field has its own data. Some fields, such as titles and composite fields, don't actually have any data. It doesn't make sense for data-focused methods to look at them. By overloading hasData() to return false, you can prevent any data-focused methods from looking at it. Returns true if this field has its own data. Some fields, such as titles and composite fields, don't actually have any data. It doesn't make sense for data-focused methods to look at them. By overloading hasData() to return false, you can prevent any data-focused methods from looking at it. #### See ``FieldSet::collateDataFields()``
`public boolean` | # `isReadonly( )` #### Returns `boolean` boolean
`public` | # `setReadonly( mixed $bool )` Sets readonly-flag on form-field. Please use performReadonlyTransformation() to actually transform this instance. Sets readonly-flag on form-field. Please use performReadonlyTransformation() to actually transform this instance. #### Parameters $bool $bool boolean Setting "false" has no effect on the field-state.
`public boolean` | # `isDisabled( )` #### Returns `boolean` boolean
`public` | # `setDisabled( mixed $bool )` Sets disabed-flag on form-field. Please use performDisabledTransformation() to actually transform this instance. Sets disabed-flag on form-field. Please use performDisabledTransformation() to actually transform this instance. #### Parameters $bool $bool boolean Setting "false" has no effect on the field-state.
`public` | # `performReadonlyTransformation( )` Returns a readonly version of this field Returns a readonly version of this field
`public` | # `performDisabledTransformation( )` Return a disabled version of this field Return a disabled version of this field
`public` | # `transform( `FormTransformation` $trans )`
`public` | # `hasClass( mixed $class )`
`public` | # `Type( )` Returns the field type - used by templates. The field type is the class name with the word Field dropped off the end, all lowercase. It's handy for assigning HTML classes. Returns the field type - used by templates. The field type is the class name with the word Field dropped off the end, all lowercase. It's handy for assigning HTML classes.
`public` | # `createTag( mixed $tag, mixed $attributes, mixed $content = null, mixed $useHTML5 = true )` Construct and return HTML tag. Construct and return HTML tag.
`public` | # `jsValidation( )` javascript handler Functions for each field type by default formfield doesnt have a validation function javascript handler Functions for each field type by default formfield doesnt have a validation function
`public` | # `validate( )` Validation Functions for each field type by default formfield doesnt have a validation function Validation Functions for each field type by default formfield doesnt have a validation function
`public` | # `describe( mixed $description )` Describe this field, provide help text for it. The function returns this so it can be used like this: $action = FormAction::create('submit', 'Submit')->describe("Send your changes to be approved") Describe this field, provide help text for it. The function returns this so it can be used like this: $action = FormAction::create('submit', 'Submit')->describe("Send your changes to be approved")
`public` | # `debug( )`
`public` | # `forTemplate( )` This function is used by the template processor. If you refer to a field as a $ variable, it will return the $Field value. This function is used by the template processor. If you refer to a field as a $ variable, it will return the $Field value.
`public boolean` | # `Required( )` #### Returns `boolean` boolean #### Uses ``Validator::fieldIsRequired()``
`public string` | # `name_to_label( string $fieldName )` Takes a fieldname and converts camelcase to spaced words. Also resolves combined fieldnames with dot syntax to spaced words. Takes a fieldname and converts camelcase to spaced words. Also resolves combined fieldnames with dot syntax to spaced words. Examples: 'TotalAmount' will return 'Total Amount' 'Organisation.ZipCode' will return 'Organisation Zip Code' #### Parameters $fieldName string $fieldName #### Returns `string` string #### Used by ``BookingOrder_StatusLog::fieldLabels()`` ``BookingService::fieldLabels()`` ``ButtonsBlockHomepageWidget_Item::fieldLabels()`` ``CatalogFilter::fieldLabels()`` ``DataObject::fieldLabels()`` ``DataObject::fieldLabel()`` ``DocumentItem::fieldLabels()`` ``Import1CLog::fieldLabels()`` ``LogItem::fieldLabels()`` ``Order::fieldLabels()`` ``Order_StatusLog::fieldLabels()`` ``OrderItem::fieldLabels()`` ``OrderServiceOrder::fieldLabels()`` ``Payment::fieldLabels()`` ``PaymentMethod::fieldLabels()`` ``Poll::fieldLabels()`` ``ProductImportLog::fieldLabels()`` ``ProductParam::fieldLabels()`` ``ProductVariation::fieldLabels()`` ``RealtyImportLog::fieldLabels()`` ``RoomOrder::fieldLabels()`` ``RoomRate::fieldLabels()`` ``RoomServiceOrder::fieldLabels()`` ``SimpleOrderData::fieldLabels()`` ``Tab::__construct()`` ``WebylonWidget::fieldLabels()`` ``WebylonWidget_Item::fieldLabels()``
`public` | # `setContainerFieldSet( `FieldSet` $containerFieldSet )` Set the fieldset that contains this field. Set the fieldset that contains this field. #### Parameters $containerFieldSet FieldSet $containerFieldSet
`public` | # `rootFieldSet( )`

### Methods inherited from RequestHandler

`allowedActions()`, `checkAccessAction()`, `getRequest()`, `handleRequest()`, `hasAction()`, `httpError()`

### Methods inherited from ViewableData

`ATT_val()`, `BaseHref()`, `CSSClasses()`, `ColumnBreak()`, `ColumnCalc()`, `ColumnNumber()`, `ColumnPad()`, `ColumnPos()`, `CurrentMember()`, `CurrentPage()`, `Debug()`, `Even()`, `EvenOdd()`, `First()`, `FirstLast()`, `HasPerm()`, `IsAjax()`, `JS_val()`, `Last()`, `Me()`, `Middle()`, `MiddleString()`, `Modulus()`, `MultipleOf()`, `Odd()`, `Pos()`, `RAW_val()`, `SQL_val()`, `ThemeDir()`, `ThemeName()`, `Top()`, `TotalItems()`, `XML_val()`, `__get()`, `__isset()`, `__set()`, `buildCastingCache()`, `cachedCall()`, `castingClass()`, `castingHelper()`, `castingHelperPair()`, `castingObjectCreator()`, `castingObjectCreatorPair()`, `customise()`, `defineMethods()`, `escapeTypeForField()`, `getField()`, `getIterator()`, `getSecurityID()`, `getXMLValues()`, `hasField()`, `hasValue()`, `i18nLocale()`, `iteratorProperties()`, `obj()`, `renderWith()`, `setCustomisedObj()`, `setField()`

### Methods inherited from Object

`__call()`, `__toString()`, `__wakeup()`, `addMethodsFrom()`, `addStaticVars()`, `addWrapperMethod()`, `add_extension()`, `add_static_var()`, `allMethodNames()`, `cacheToFile()`, `cacheToFileWithArgs()`, `clearCache()`, `combined_static()`, `create()`, `createMethod()`, `create_from_string()`, `exists()`, `extInstance()`, `extend()`, `getCustomClass()`, `getExtensionInstance()`, `getExtensionInstances()`, `get_extensions()`, `get_static()`, `hasExtension()`, `hasMethod()`, `has_extension()`, `invokeWithExtensions()`, `is_a()`, `loadCache()`, `parentClass()`, `parse_class_spec()`, `remove_extension()`, `sanitiseCachename()`, `saveCache()`, `set_stat()`, `set_static()`, `set_uninherited()`, `stat()`, `strong_create()`, `uninherited()`, `uninherited_static()`, `useCustomClass()`

### Magic methods summary

## Properties summary

`protected static boolean` | $use_html5 | #
`protected boolean` | $fieldHTML5 | #
`protected mixed` | $form | #
`protected mixed` | $name | #
`protected mixed` | $title | #
`protected mixed` | $value | #
`protected mixed` | $message | #
`protected mixed` | $messageType | #
`protected mixed` | $extraClass | #
`protected array` | $extraAttributes | #
`protected array` | $html5Attributes | #
`protected boolean` | $autocomplete | #
`protected mixed` | $description | # string Adds a "title"-attribute to the markup. string Adds a "title"-attribute to the markup.
`protected array` | $extraClasses | # array Extra CSS-classes for the formfield-container array Extra CSS-classes for the formfield-container
`public mixed` | $dontEscape | #
`protected string` | $template | # Name of the template used to render this form field. If not set, then will look up the class ancestry for the first matching template where the template name equals the class name. Name of the template used to render this form field. If not set, then will look up the class ancestry for the first matching template where the template name equals the class name. To explicitly use a custom template or one named other than the form field see `FormField::setTemplate()`.
`protected string` | $fieldHolderTemplate | # Name of the template used to render this form field. If not set, then will look up the class ancestry for the first matching template where the template name equals the class name. Name of the template used to render this form field. If not set, then will look up the class ancestry for the first matching template where the template name equals the class name. To explicitly use a custom template or one named other than the form field see `FormField::setFieldHolderTemplate()`.
`protected string` | $smallFieldHolderTemplate | #
`protected mixed` | $rightTitle | # string Used in SmallFieldHolder() to force a right-aligned label. string Used in SmallFieldHolder() to force a right-aligned label.
`protected mixed` | $leftTitle | # string Used in SmallFieldHolder() to force a left-aligned label with correct spacing. Please use $title for FormFields rendered with FieldHolder(). string Used in SmallFieldHolder() to force a left-aligned label with correct spacing. Please use $title for FormFields rendered with FieldHolder().
`protected integer` | $tabIndex | # Set the "tabindex" HTML attribute on the field. Set the "tabindex" HTML attribute on the field.
`protected `FieldSet`` | $containerFieldSet | # Stores a reference to the FieldSet that contains this object. Stores a reference to the FieldSet that contains this object.
`protected boolean` | $readonly | # boolean boolean
`protected boolean` | $disabled | # boolean boolean
`protected Custom` | $customValidationMessage | # Validation Message for the Field Validation Message for the Field
`public static array` | $possible_autocomplete_values | #

### Properties inherited from RequestHandler

`$allowed_actions`, `$brokenOnConstruct`, `$request`, `$url_handlers`

### Properties inherited from ViewableData

`$casting`, `$customisedObject`, `$default_cast`, `$failover`, `$iteratorPos`, `$iteratorTotalItems`

### Properties inherited from Object

`$class`, `$extension_instances`, `$extensions`

[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the Silverstripe Forums to ask development related questions. -