Form
class Form extends ViewableData implements HasRequestHandler (View source)
Base class for all forms.
The form class is an extensible base for all forms on a SilverStripe application. It can be used either by extending it, and creating processor methods on the subclass, or by creating instances of form whose actions are handled by the parent controller.
In either case, if you want to get a form to do anything, it must be inextricably tied to a controller. The constructor is passed a controller and a method on that controller. This method should return the form object, and it shouldn't require any arguments. Parameters, if necessary, can be passed using the URL or get variables. These restrictions are in place so that we can recreate the form object upon form submission, without the use of a session, which would be too resource-intensive.
You will need to create at least one method for processing the submission (through FormAction). This method will be passed two parameters: the raw request data, and the form object. Usually you want to save data into a DataObject} by using {@link saveInto(). If you want to process the submitted data in any way, please use getData() rather than the raw request data.
Validation
Each form needs some form of Validator} to trigger the {@link FormField->validate() methods for each field. You can't disable validator for security reasons, because crucial behaviour like extension checks for file uploads depend on it. The default validator is an instance of RequiredFields. If you want to enforce serverside-validation to be ignored for a specific FormField, you need to subclass it.
URL Handling
The form class extends RequestHandler, which means it can be accessed directly through a URL. This can be handy for refreshing a form by ajax, or even just displaying a single form field. You can find out the base URL for your form by looking at the
Traits
This trait can be applied to a ViewableData class to add the logic to render attributes in an SS template.
Form component which contains a castable message
Allows an object to have extensions applied to it.
A class that can be instantiated or replaced via DI
Provides extensions to this object to integrate it with standard config API methods.
Allows an object to declare a set of custom methods
Constants
DEFAULT_NAME |
|
ENC_TYPE_URLENCODED |
Form submission data is URL encoded |
ENC_TYPE_MULTIPART |
Form submission data is multipart form |
MERGE_DEFAULT |
|
MERGE_CLEAR_MISSING |
|
MERGE_IGNORE_FALSEISH |
|
MERGE_AS_INTERNAL_VALUE |
|
MERGE_AS_SUBMITTED_VALUE |
|
Config options
extensions | array | An array of extension names and parameters to be applied to this object upon construction. |
from Extensible |
unextendable_classes | array | Classes that cannot be extended |
from Extensible |
casting | array | ||
default_cast | string | The default object to cast scalar fields to if casting information is not specified, and casting to an object is required. |
from ViewableData |
casting_cache | array | from ViewableData | |
default_classes | array |
Properties
protected static | array | $extra_methods | Custom method sources |
from CustomMethods |
protected | array | $extra_method_registers | Name of methods to invoke by defineMethods for this instance |
from CustomMethods |
protected static | array | $built_in_methods | Non-custom public methods. |
from CustomMethods |
protected | Extension[] | $extension_instances | from Extensible | |
protected | callable[][] | $beforeExtendCallbacks | List of callbacks to call prior to extensions having extend called on them, each grouped by methodName. |
from Extensible |
protected | callable[][] | $afterExtendCallbacks | List of callbacks to call after extensions having extend called on them, each grouped by methodName. |
from Extensible |
protected | ViewableData | $failover | A failover object to attempt to get data from if it is not present on this object. |
from ViewableData |
protected | ViewableData | $customisedObject | from ViewableData | |
protected | array | $attributes | Any custom form attributes set through setAttributes(). |
|
protected | string | $message | from FormMessage | |
protected | string | $messageType | from FormMessage | |
protected | string | $messageCast | Casting for message |
from FormMessage |
public | bool | $IncludeFormTag | Accessed by Form.ss. |
|
protected | FieldList | $fields | ||
protected | FieldList | $actions | ||
protected | RequestHandler | $controller | Parent (optional) request handler |
|
protected | string | $name | ||
protected | Validator | $validator | ||
protected | callable | $validationResponseCallback | ||
protected | string | $formMethod | ||
protected | bool | $strictFormMethodCheck | ||
protected | ViewableData|null | $record | Populated by loadDataFrom(). |
|
protected | bool | $hasDefaultAction | Keeps track of whether this form has a default action or not. |
|
protected | string|null | $target | Target attribute of form-tag. |
|
protected | string|null | $legend | Legend value, to be inserted into the |
|
protected | string|array|null | $template | The SS template to render this form HTML into. |
|
protected | bool | $redirectToFormOnValidationError | Should we redirect the user back down to the the form on validation errors rather then just the page |
|
protected | bool | $security | ||
protected | SecurityToken|null | $securityToken | ||
protected | array | $extraClasses | List of additional CSS classes for the form tag. |
|
protected | string|null | $encType | ||
protected | array | $validationExemptActions | ||
protected | string | $formActionPath | Custom form action path, if not linking to itself. |
|
protected | bool | $securityTokenAdded | ||
protected | bool | $notifyUnsavedChanges | ||
protected | FormRequestHandler | $requestHandler | Current request handler, build by buildRequestHandler(), accessed by getRequestHandler() |
Methods
Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located
Adds any methods from Extension instances attached to this object.
Register an callback to invoke that defines extra methods
Return TRUE if a method exists on this object
Determines if a custom method with this name is defined.
Get meta-data details on a named method
Return the names of all the methods available on this object
Get all public built in methods for this class
Find all methods on the given object.
Add all the methods from an object property.
Add all the methods from an object property (which is an Extension) to this object.
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
Add callback as a method.
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
Adds any methods from Extension instances attached to this object.
Add an extension to a specific class.
No description
Get extra config sources for this class
Return TRUE if a class has a specified extension.
Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed
Get an extension instance attached to this object by name.
Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Get all extension instances for this specific object instance.
An implementation of the factory method, allows you to create an instance of a class
Creates a class instance by the "singleton" design pattern.
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
Gets the uninherited value for the given config option
Create a new form, with the given fields an action buttons.
Check if a field exists on this object or its failover.
Get the value of a property/field on this object. This will check if a method called get{$property} exists, then check if a field is available using ViewableData::getField(), then fall back on a failover object.
Set a property/field on this object. This will check for the existence of a method called set{$property}, then use the ViewableData::setField() method.
Set a failover object to attempt to get data from if it is not present on this object.
Check if a field exists on this object. This should be overloaded in child classes.
Get the value of a field on this object. This should be overloaded in child classes.
Set a field on this object. This should be overloaded in child classes.
Merge some arbitrary data in with this object. This method returns a ViewableData_Customised instance with references to both this and the new custom data.
Return true if this object "exists" i.e. has a sensible value
Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object. This helper will be a subclass of DBField.
Get the class name a field on this object will be casted to.
Return the string-format type for the given field.
Render this object into the template, and get the result as a string. You can pass one of the following as the $template parameter:
- a template name (e.g. Page)
- an array of possible template names - the first valid one will be used
- an SSViewer instance
Generate the cache name for a field
Store a value in the field cache
Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified.
A simple wrapper around ViewableData::obj() that automatically caches the result so it can be used again without re-running the method.
Checks if a given method/field has a valid value. If the result is an object, this will return the result of the exists method, otherwise will check if the result is not just an empty paragraph tag.
Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.
Get an array of XML-escaped values by field name
Return a single-item iterator so you can iterate over the fields of a single record.
Find appropriate templates for SSViewer to use to render this object
When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.
Get part of the current classes ancestry to be used as a CSS class.
Return debug information about this object that can be rendered into a template
Retrieve the value of an HTML attribute
Allows customization through an 'updateAttributes' hook on the base class.
Custom attributes to process. Falls back to getAttributes().
Casting type for this message. Will be 'text' or 'html'
Sets the error message to be displayed on the form field.
Appends a message to the existing message if the types and casts match.
Get casting helper for message cast, or null if not known
Return any ValidationResult instance stored for this object
Sets the ValidationResult in the session to be used with the next view of this form.
Populate this form with messages from the given ValidationResult.
Set message on a given field name. This message will not persist via redirect.
set up the default classes for the form. This is done on construct so that the default classes can be removed after instantiation
Overrules validation error behaviour in httpSubmission() when validation has failed. Useful for optional handling of a certain accepted content type.
Set whether the user should be redirected back down to the form on the page upon validation errors in the form or if they just need to redirect back to the page
Get whether the user should be redirected back down to the form on the page upon validation errors
Passed a FormAction, returns true if that action is exempt from Form validation
Generate extra special fields - namely the security token field (if required).
Return all fields in a form - including fields nested in CompositeFields.
Set the target of this form to any value - useful for opening the form contents in a new window or refreshing another frame
Return a FormTemplateHelper for this form. If one has not been set, return the default helper.
Set the target of this form to any value - useful for opening the form contents in a new window or refreshing another frame.
Set the SS template that this form should use to render with. The default is "Form".
Returns the ordered list of preferred templates for rendering this form If the template isn't set, then default to the form class name e.g "Form".
Sets the form encoding type. The most common encoding types are defined in ENC_TYPE_URLENCODED} and {@link ENC_TYPE_MULTIPART.
Returns the real HTTP method for the form: GET, POST, PUT, DELETE or HEAD.
Set the form method: GET, POST, PUT, DELETE.
If set to true (the default), enforces the matching of the form method.
Returns an object where there is a method with the same name as each data field on the form.
Set a message to the session, for display next time this form is shown.
Set an error to the session, for display next time this form is shown.
Set an error message for a field in the session, for display next time this form is shown.
Returns the record that has given this form its data through loadDataFrom().
Load data from the given record or array.
Save the contents of this form into the given data object.
Get the submitted data from this form through FieldList->dataFields(), which filters out any form-specific data like form-actions.
Return a rendered version of this form, suitable for ajax post-back.
Render this form using the given template, and return the result as a string You can pass either an SSViewer or a template name
Return the default button that should be clicked when another one isn't available.
Disable the requirement of a security token on this form instance. This security protects against CSRF attacks, but you should disable this if you don't want to tie a form to a session - eg a search form.
Returns the security token for this form (if any exists).
Add a CSS-class to the form-container. If needed, multiple classes can be added by delimiting a string with spaces.
Remove a CSS-class from the form-container. Multiple class names can be passed through as a space delimited string
Details
mixed
__call(string $method, array $arguments)
Attempts to locate and call a method dynamically added to a class at runtime if a default cannot be located
You can add extra methods to a class using Extensions}, {@link Object::createMethod() or Object::addWrapperMethod()
protected
defineMethods()
Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
protected
registerExtraMethodCallback(string $name, callable $callback)
Register an callback to invoke that defines extra methods
bool
hasMethod(string $method)
Return TRUE if a method exists on this object
This should be used rather than PHP's inbuild method_exists() as it takes into account methods added via extensions
protected bool
hasCustomMethod($method)
Determines if a custom method with this name is defined.
protected array
getExtraMethodConfig(string $method)
Get meta-data details on a named method
array
allMethodNames(bool $custom = false)
Return the names of all the methods available on this object
static protected array
findBuiltInMethods(string|object $class = null)
Get all public built in methods for this class
protected array
findMethodsFrom(object $object)
Find all methods on the given object.
protected
addMethodsFrom(string $property, string|int $index = null)
Add all the methods from an object property.
protected
removeMethodsFrom(string $property, string|int $index = null)
Add all the methods from an object property (which is an Extension) to this object.
protected
addWrapperMethod(string $method, string $wrap)
Add a wrapper method - a method which points to another method with a different name. For example, Thumbnail(x) can be wrapped to generateThumbnail(x)
protected
addCallbackMethod(string $method, callable $callback)
Add callback as a method.
protected
beforeExtending(string $method, callable $callback)
Allows user code to hook into Object::extend prior to control being delegated to extensions. Each callback will be reset once called.
protected
afterExtending(string $method, callable $callback)
Allows user code to hook into Object::extend after control being delegated to extensions. Each callback will be reset once called.
protected
defineExtensionMethods()
Adds any methods from Extension instances attached to this object.
All these methods can then be called directly on the instance (transparently mapped through __call()}), or called explicitly through {@link extend().
static bool
add_extension(string $classOrExtension, string $extension = null)
Add an extension to a specific class.
The preferred method for adding extensions is through YAML config, since it avoids autoloading the class, and is easier to override in more specific configurations.
As an alternative, extensions can be added to a specific class directly in the Object::$extensions array. See SiteTree::$extensions for examples. Keep in mind that the extension will only be applied to new instances, not existing ones (including all instances created through singleton()).
static
remove_extension(string $extension)
Remove an extension from a class.
Note: This will not remove extensions from parent classes, and must be called directly on the class assigned the extension.
Keep in mind that this won't revert any datamodel additions of the extension at runtime, unless its used before the schema building kicks in (in your _config.php). Doesn't remove the extension from any Object instances which are already created, but will have an effect on new extensions. Clears any previously created singletons through singleton() to avoid side-effects from stale extension information.
static array
get_extensions(string $class = null, bool $includeArgumentString = false)
No description
static array|null
get_extra_config_sources(string $class = null)
Get extra config sources for this class
static bool
has_extension(string $classOrExtension, string $requiredExtension = null, bool $strict = false)
Return TRUE if a class has a specified extension.
This supports backwards-compatible format (static Object::has_extension($requiredExtension)) and new format ($object->has_extension($class, $requiredExtension))
array
invokeWithExtensions(string $method, mixed ...$arguments)
Calls a method if available on both this object and all applied Extensions, and then attempts to merge all results into an array
array
extend(string $method, mixed ...$arguments)
Run the given function on all of this object's extensions. Note that this method originally returned void, so if you wanted to return results, you're hosed
Currently returns an array, with an index resulting every time the function is called. Only adds returns if they're not NULL, to avoid bogus results from methods just defined on the parent extension. This is important for permission-checks through extend, as they use min() to determine if any of the returns is FALSE. As min() doesn't do type checking, an included NULL return would fail the permission checks.
The extension methods are defined during __construct()} in {@link defineMethods().
Extension|null
getExtensionInstance(string $extension)
Get an extension instance attached to this object by name.
bool
hasExtension(string $extension)
Returns TRUE if this object instance has a specific extension applied in $extension_instances. Extension instances are initialized at constructor time, meaning if you use add_extension() afterwards, the added extension will just be added to new instances of the extended class. Use the static method has_extension() to check if a class (not an instance) has a specific extension.
Caution: Don't use singleton(
Extension[]
getExtensionInstances()
Get all extension instances for this specific object instance.
See get_extensions() to get all applied extension classes for this class (not the instance).
This method also provides lazy-population of the extension_instances property.
static Injectable
create(mixed ...$args)
An implementation of the factory method, allows you to create an instance of a class
This method will defer class substitution to the Injector API, which can be customised via the Config API to declare substitution classes.
This can be called in one of two ways - either calling via the class directly, or calling on Object and passing the class name as the first parameter. The following are equivalent: $list = DataList::create(SiteTree::class); $list = SiteTree::get();
static Injectable
singleton(string $class = null)
Creates a class instance by the "singleton" design pattern.
It will always return the same instance for this class, which can be used for performance reasons and as a simple way to access instance methods which don't rely on instance data (e.g. the custom SilverStripe static handling).
static Config_ForClass
config()
Get a configuration accessor for this class. Short hand for Config::inst()->get($this->class, .....).
mixed
uninherited(string $name)
Gets the uninherited value for the given config option
__construct(RequestHandler $controller = null, string $name = Form::DEFAULT_NAME, FieldList $fields = null, FieldList $actions = null, Validator $validator = null)
Create a new form, with the given fields an action buttons.
bool
__isset(string $property)
Check if a field exists on this object or its failover.
Note that, unlike the core isset() implementation, this will return true if the property is defined and set to null.
mixed
__get(string $property)
Get the value of a property/field on this object. This will check if a method called get{$property} exists, then check if a field is available using ViewableData::getField(), then fall back on a failover object.
__set(string $property, mixed $value)
Set a property/field on this object. This will check for the existence of a method called set{$property}, then use the ViewableData::setField() method.
setFailover(ViewableData $failover)
Set a failover object to attempt to get data from if it is not present on this object.
ViewableData|null
getFailover()
Get the current failover object if set
bool
hasField(string $field)
Check if a field exists on this object. This should be overloaded in child classes.
mixed
getField(string $field)
Get the value of a field on this object. This should be overloaded in child classes.
$this
setField(string $field, mixed $value)
Set a field on this object. This should be overloaded in child classes.
mixed
getDynamicData(string $field)
No description
ViewableData
setDynamicData(string $field, mixed $value)
No description
bool
hasDynamicData(string $field)
No description
ViewableData_Customised
customise(array|ViewableData $data)
Merge some arbitrary data in with this object. This method returns a ViewableData_Customised instance with references to both this and the new custom data.
Note that any fields you specify will take precedence over the fields on this object.
bool
exists()
Return true if this object "exists" i.e. has a sensible value
This method should be overridden in subclasses to provide more context about the classes state. For example, a DataObject class could return false when it is deleted from the database
string
__toString()
No description
ViewableData
getCustomisedObj()
No description
setCustomisedObj(ViewableData $object)
No description
string
castingHelper(string $field)
Return the "casting helper" (a piece of PHP code that when evaluated creates a casted value object) for a field on this object. This helper will be a subclass of DBField.
string
castingClass(string $field)
Get the class name a field on this object will be casted to.
string
escapeTypeForField(string $field)
Return the string-format type for the given field.
DBHTMLText
renderWith(string|array|SSViewer $template, array $customFields = null)
Render this object into the template, and get the result as a string. You can pass one of the following as the $template parameter:
- a template name (e.g. Page)
- an array of possible template names - the first valid one will be used
- an SSViewer instance
protected string
objCacheName(string $fieldName, array $arguments)
Generate the cache name for a field
protected mixed
objCacheGet(string $key)
Get a cached value from the field cache
protected $this
objCacheSet(string $key, mixed $value)
Store a value in the field cache
protected $this
objCacheClear()
Clear object cache
object|DBField
obj(string $fieldName, array $arguments = [], bool $cache = false, string $cacheName = null)
Get the value of a field on this object, automatically inserting the value into any available casting objects that have been specified.
object|DBField
cachedCall(string $fieldName, array $arguments = [], string $identifier = null)
A simple wrapper around ViewableData::obj() that automatically caches the result so it can be used again without re-running the method.
bool
hasValue(string $field, array $arguments = [], bool $cache = true)
Checks if a given method/field has a valid value. If the result is an object, this will return the result of the exists method, otherwise will check if the result is not just an empty paragraph tag.
string
XML_val(string $field, array $arguments = [], bool $cache = false)
Get the string value of a field on this object that has been suitable escaped to be inserted directly into a template.
array
getXMLValues(array $fields)
Get an array of XML-escaped values by field name
Traversable
getIterator()
deprecated
deprecated
Return a single-item iterator so you can iterate over the fields of a single record.
This is useful so you can use a single record inside a <% control %> block in a template - and then use to access individual fields on this object.
array
getViewerTemplates(string $suffix = '')
Find appropriate templates for SSViewer to use to render this object
ViewableData
Me()
When rendering some objects it is necessary to iterate over the object being rendered, to do this, you need access to itself.
string
CSSClasses(string $stopAtClass = ViewableData::class)
Get part of the current classes ancestry to be used as a CSS class.
This method returns an escaped string of CSS classes representing the current classes ancestry until it hits a stop point - e.g. "Page DataObject ViewableData".
ViewableData_Debugger
Debug()
Return debug information about this object that can be rendered into a template
$this
setAttribute($name, $value)
Set an HTML attribute
mixed|null
getAttribute(string $name)
Retrieve the value of an HTML attribute
protected array
getDefaultAttributes()
No description
array
getAttributes()
Allows customization through an 'updateAttributes' hook on the base class.
Existing attributes are passed in as the first argument and can be manipulated, but any attributes added through a subclass implementation won't be included.
string
getAttributesHTML(array $attributes = null)
Custom attributes to process. Falls back to getAttributes().
If at least one argument is passed as a string, all arguments act as excludes, by name.
string
getMessage()
Returns the field message, used by form validation.
Use setError() to set this property.
string
getMessageType()
Returns the field message type.
Arbitrary value which is mostly used for CSS classes in the rendered HTML, e.g "required".
Use setError() to set this property.
string
getMessageCast()
Casting type for this message. Will be 'text' or 'html'
$this
setMessage(string $message, string $messageType = ValidationResult::TYPE_ERROR, string $messageCast = ValidationResult::CAST_TEXT)
Sets the error message to be displayed on the form field.
Allows HTML content, so remember to use Convert::raw2xml().
FormMessage
appendMessage(string $message, string $messageType = ValidationResult::TYPE_ERROR, string $messageCast = ValidationResult::CAST_TEXT, bool $force = false)
Appends a message to the existing message if the types and casts match.
If either is different, the $force argument determines the behaviour.
Note: to prevent duplicates, we check for the $message string in the existing message. If the existing message contains $message as a substring, it won't be added.
protected string
getMessageCastingHelper()
Get casting helper for message cast, or null if not known
array|null
getSchemaMessage()
Get form schema encoded message
bool
getNotifyUnsavedChanges()
No description
setNotifyUnsavedChanges(bool $flag)
No description
$this
restoreFormState()
Load form state from session state
$this
clearFormState()
Flush persistent form state details
protected HTTPRequest|null
getRequest()
Helper to get current request for this form
protected Session
getSession()
Get session for this form
array
getSessionData()
Return any form data stored in the session
$this
setSessionData(array $data)
Store the given form data in the session
ValidationResult|null
getSessionValidationResult()
Return any ValidationResult instance stored for this object
$this
setSessionValidationResult(ValidationResult $result, bool $combineWithExisting = false)
Sets the ValidationResult in the session to be used with the next view of this form.
$this
clearMessage()
Clear form message (and in session)
$this
loadMessagesFrom(ValidationResult $result)
Populate this form with messages from the given ValidationResult.
Note: This will try not to clear any pre-existing messages, but will clear them if a new message has a different message type or cast than the existing ones.
$this
setFieldMessage(string $fieldName, string $message, string $messageType = ValidationResult::TYPE_ERROR, string $messageCast = ValidationResult::CAST_TEXT)
Set message on a given field name. This message will not persist via redirect.
protected
setupDefaultClasses()
set up the default classes for the form. This is done on construct so that the default classes can be removed after instantiation
callable
getValidationResponseCallback()
No description
Form
setValidationResponseCallback($callback)
Overrules validation error behaviour in httpSubmission() when validation has failed. Useful for optional handling of a certain accepted content type.
The callback can opt out of handling specific responses by returning NULL, in which case the default form behaviour will kick in.
$this
makeReadonly()
Convert this form into a readonly form
$this
setRedirectToFormOnValidationError(bool $bool)
Set whether the user should be redirected back down to the form on the page upon validation errors in the form or if they just need to redirect back to the page
bool
getRedirectToFormOnValidationError()
Get whether the user should be redirected back down to the form on the page upon validation errors
transform(FormTransformation $trans)
No description
Validator
getValidator()
Get the Validator attached to this form.
$this
setValidator(Validator $validator)
Set the Validator on this form.
unsetValidator()
Remove the Validator from this from.
$this
setValidationExemptActions(array $actions)
Set actions that are exempt from validation
array
getValidationExemptActions()
Get a list of actions that are exempt from validation
bool
actionIsValidationExempt(FormAction $action)
Passed a FormAction, returns true if that action is exempt from Form validation
FieldList
getExtraFields()
Generate extra special fields - namely the security token field (if required).
FieldList
Fields()
Return the form's fields - used by the templates
FieldList
HiddenFields()
Return all fields in a form - including fields nested in CompositeFields.
Useful when doing custom field layouts.
VisibleFields()
Return all fields except for the hidden fields.
Useful when making your own simplified form layouts.
$this
setFields(FieldList $fields)
Setter for the form fields.
FieldList
Actions()
Return the form's action buttons - used by the templates
$this
setActions(FieldList $actions)
Setter for the form actions.
unsetAllActions()
Unset all form actions
FormAttributes()
No description
setTemplateHelper(string|FormTemplateHelper $helper)
Set the target of this form to any value - useful for opening the form contents in a new window or refreshing another frame
FormTemplateHelper
getTemplateHelper()
Return a FormTemplateHelper for this form. If one has not been set, return the default helper.
$this
setTarget(string $target)
Set the target of this form to any value - useful for opening the form contents in a new window or refreshing another frame.
$this
setLegend(string $legend)
Set the legend value to be inserted into the
$this
setTemplate(string|array $template)
Set the SS template that this form should use to render with. The default is "Form".
string|array
getTemplate()
Return the template to render this form with.
array
getTemplates()
Returns the ordered list of preferred templates for rendering this form If the template isn't set, then default to the form class name e.g "Form".
getEncType()
Returns the encoding type for the form.
By default this will be URL encoded, unless there is a file field present in which case multipart is used. You can also set the enc type using setEncType.
$this
setEncType(string $encType)
Sets the form encoding type. The most common encoding types are defined in ENC_TYPE_URLENCODED} and {@link ENC_TYPE_MULTIPART.
string
FormHttpMethod()
Returns the real HTTP method for the form: GET, POST, PUT, DELETE or HEAD.
As most browsers only support GET and POST in form submissions, all other HTTP methods are added as a hidden field "_method" that gets evaluated in HTTPRequest::detect_method(). See FormMethod() to get a HTTP method for safe insertion into a
string
FormMethod()
Returns the form method to be used in the
$this
setFormMethod(string $method, bool $strict = null)
Set the form method: GET, POST, PUT, DELETE.
$this
setStrictFormMethodCheck($bool)
If set to true (the default), enforces the matching of the form method.
This will mean two things:
- GET vars will be ignored by a POST form, and vice versa
- A submission where the HTTP method used doesn't match the form will return a 400 error.
If set to false then the form method is only used to construct the default form.
bool
getStrictFormMethodCheck()
No description
string
FormAction()
Return the form's action attribute.
This is build by adding an executeForm get variable to the parent controller's Link() value
$this
setFormAction(string $path)
Set the form action attribute to a custom URL.
Note: For "normal" forms, you shouldn't need to use this method. It is recommended only for situations where you have two relatively distinct parts of the system trying to communicate via a form post.
string
FormName()
Returns the name of the form.
$this
setHTMLID(string $id)
Set the HTML ID attribute of the form.
string
getHTMLID()
No description
RequestHandler
getController()
Get the controller or parent request handler.
$this
setController(RequestHandler $controller = null)
Set the controller or parent request handler.
string
getName()
Get the name of the form.
Form
setName(string $name)
Set the name of the form.
FieldMap()
Returns an object where there is a method with the same name as each data field on the form.
That method will return the field itself.
It means that you can execute $firstName = $form->FieldMap()->FirstName()
sessionMessage(string $message, string $type = ValidationResult::TYPE_ERROR, string|bool $cast = ValidationResult::CAST_TEXT)
Set a message to the session, for display next time this form is shown.
sessionError(string $message, string $type = ValidationResult::TYPE_ERROR, string|bool $cast = ValidationResult::CAST_TEXT)
Set an error to the session, for display next time this form is shown.
sessionFieldError(string $message, string $fieldName, string $type = ValidationResult::TYPE_ERROR, string|bool $cast = ValidationResult::CAST_TEXT)
Set an error message for a field in the session, for display next time this form is shown.
ViewableData
getRecord()
Returns the record that has given this form its data through loadDataFrom().
string
getLegend()
Get the legend value to be inserted into the
ValidationResult
validationResult()
Processing that occurs before a form is executed.
This includes form validation, if it fails, we throw a ValidationException
This includes form validation, if it fails, we redirect back to the form with appropriate error messages. Always return true if the current form action is exempt from validation
Triggered through httpSubmission().
Note that CSRF protection takes place in httpSubmission(), if it fails the form data will never reach this method.
$this
loadDataFrom(array|ViewableData $data, int $mergeStrategy = 0, array $fieldList = null)
Load data from the given record or array.
It will call $object->MyField to get the value of MyField. If you passed an array, it will call $object[MyField]. Doesn't save into dataless FormFields (DatalessField), as determined by FieldList->dataFields().
By default, if a field isn't set (as determined by isset()), its value will not be saved to the field, retaining potential existing values.
Passed data should not be escaped, and is saved to the FormField instances unescaped. Escaping happens automatically on saving the data through saveInto().
Escaping happens automatically on saving the data through saveInto().
saveInto(DataObjectInterface $dataObject, string[]|null $fieldList = null)
Save the contents of this form into the given data object.
It will make use of setCastedField() to do this.
array
getData()
Get the submitted data from this form through FieldList->dataFields(), which filters out any form-specific data like form-actions.
Calls FormField->dataValue() on each field, which returns a value suitable for insertion into a record property.
DBHTMLText
forTemplate()
Return a rendered version of this form.
This is returned when you access a form as $FormObject rather than <% with FormObject %>
DBHTMLText
forAjaxTemplate()
Return a rendered version of this form, suitable for ajax post-back.
It triggers slightly different behaviour, such as disabling the rewriting of # links.
DBHTMLText
renderWithoutActionButton(string|array $template)
Render this form using the given template, and return the result as a string You can pass either an SSViewer or a template name
FormAction|null
defaultAction()
Return the default button that should be clicked when another one isn't available.
Form
disableDefaultAction()
Disable the default button.
Ordinarily, when a form is processed and no action_XXX button is available, then the first button in the actions list will be pressed. However, if this is "delete", for example, this isn't such a good idea.
Form
disableSecurityToken()
Disable the requirement of a security token on this form instance. This security protects against CSRF attacks, but you should disable this if you don't want to tie a form to a session - eg a search form.
Check for token state with getSecurityToken() and SecurityToken->isEnabled().
Form
enableSecurityToken()
Enable SecurityToken protection for this form instance.
Check for token state with getSecurityToken() and SecurityToken->isEnabled().
SecurityToken|null
getSecurityToken()
Returns the security token for this form (if any exists).
Doesn't check for securityTokenEnabled().
Use SecurityToken::inst() to get a global token.
string
extraClass()
Compiles all CSS-classes.
bool
hasExtraClass(string $class)
Check if a CSS-class has been added to the form container.
$this
addExtraClass(string $class)
Add a CSS-class to the form-container. If needed, multiple classes can be added by delimiting a string with spaces.
$this
removeExtraClass(string $class)
Remove a CSS-class from the form-container. Multiple class names can be passed through as a space delimited string
debug()
No description
RequestHandler
getRequestHandler()
Get request handler for this form
$this
setRequestHandler(FormRequestHandler $handler)
Assign a specific request handler for this form
protected FormRequestHandler
buildRequestHandler()
Scaffold new request handler for this form
protected bool
canBeCached()
Can the body of this form be cached?