depage-forms v1.4.1
html forms made easy
Loading...
Searching...
No Matches
HtmlForm Class Reference

main interface to users More...

Detailed Description

The class HtmlForm is the main tool of the htmlform library. It generates input elements and container elements. It also contains the PHP session handlers.

When you use depage-forms this is probably the only class you will instantiate directly.

In general:

<?php
$form = new Depage\HtmlForm\HtmlForm('simpleForm');
// add form fields
$form->addText('username', array('label' => 'User name', 'required' => true));
$form->addEmail('email', array('label' => 'Email address'));
// process form
$form->process();
if ($form->validate()) {
// do something with your valid data
var_dump($form->getValues());
} else {
// Form was empty or data was not valid:
// Display the form.
echo ($form);
}
$form
Parent form object reference.
Definition Container.php:72
main interface to users
Definition HtmlForm.php:124

You can find a list of available input-class in elements.

See also
Depage\HtmlForm\Elements
Examples
closure.php, elements.php, js-validation.php, lists.php, populate.php, reallife.php, redirect.php, session-timeout.php, simple.php, steps.php, and subclass.php.

Definition at line 123 of file HtmlForm.php.

Public Member Functions

 __construct (string $name, array $parameters=[], HtmlForm|null $form=null)
 HtmlForm class constructor.
 isEmpty ()
 Returns wether form has been submitted before or not.
 checkElementName (string $name)
 Checks for duplicate subelement names.
 registerNamespace (string $namespace)
 Stores element namespaces for adding.
 getNamespaces ()
 Returns list of registered namespaces.
 setCurrentStep (int|null $step=null)
 Validates step number of GET request.
 getUrl ()
 getSteps ()
 Returns an array of steps.
 getCurrentStepId ()
 Returns the current step id.
 getFirstInvalidStep ()
 Returns first step that didn't pass validation.
 buildUrl (array $args=[])
 Builds URL from parts.
 buildUrlQuery (array $args=[])
 Adding step parameter to already existing query.
 updateInputValue (string $name)
 Updates the value of an associated input element.
 clearInputValue (string $name)
 clearInputValue
 populate (array|object $data=[])
 Fills subelement values.
 process ()
 Calls form validation and handles redirects.
 validate ()
 Validates the forms subelements.
 validateAutosave ()
 If the form is autosaving the validation property is defaulted to false.
 getValues ()
 Gets form-data from current PHP session.
 getValuesWithLabel ()
 Gets form-data from current PHP session but also contain elemnt labels.
 redirect (string $url)
 Redirects Browser to a different URL.
 httpResponseCode (int $code)
 Sets the HTTP response code.
 clearSession (bool $clearCsrfToken=true)
 Deletes the current forms' PHP session data.
 __toString ()
 Renders form to HTML.
Public Member Functions inherited from Container
 __construct (string $name, array $parameters, object $form)
 container class constructor
 __call (string $function, array $arguments)
 HTML escaping and add subelements.
 addChildElements ()
 Sub-element generator hook.
 getElements (bool $includeFieldsets=false)
 Returns containers subelements.
 getElement (string $name, bool $includeFieldsets=false)
 Gets subelement by name.
 addHtml (string $html)
 Adds a new custom HTML element to the container.
 addStepNav (array $parameter=[])
 Adds automatic step navigation to output.
 setRequired (bool $required=true)
 Sets required-attribute.
 clearValue ()
 Deletes values of all child elements.
Public Member Functions inherited from Element
 __construct (string $name, array $parameters, object|null $form)
 element class constructor
 setDisabled (bool $disabled=true)
 Sets the HTML disabled-attribute of the current input element.
 getDisabled ()
 Gets if input is currently disabled.
 getName ()
 Returns the element name.

Static Public Member Functions

static clearOldSessions (int $ttl=3600, string $pattern="/^htmlform-.*/")
 clearOldSessions

Data Fields

const priorityCountries
 $valid
 Form validation result/status.
 $isAutoSaveRequest = false
 true if form request is from autosave call
Data Fields inherited from Element
 $valid
 Contains element validation status/result.
 $dataAttr
 Extra information about the data that is saved inside the element.

Protected Member Functions

 setDefaults ()
 Collects initial values across subclasses.
 getNewCsrfToken ()
 Returns new XSRF token.
 addElement (string $type, string $name, array $parameters)
 Adds input or fieldset elements to htmlform.
 onPost ()
 onPost hook
 onValidate ()
 Validation hook.
 htmlDataAttributes ()
 Returns dataAttr escaped as attribute string.
 htmlSubmitURL ()
 Returns form url escaped as attribute string.
Protected Member Functions inherited from Element
 log (string $argument, string $type=null)
 error & warning logger
 htmlEscape (array|string $options=[])
 Escapes HTML in strings and arrays of strings.

Protected Attributes

 $method
 HTML form method attribute.
 $url
 url of the current page
 $submitURL
 HTML form action attribute.
 $successURL
 Specifies where the user is redirected to, once the form-data is valid.
 $cancelURL
 Specifies where the user is redirected to, once the form-data is cancelled.
 $label
 Contains the submit button label of the form.
 $backLabel
 Contains the back button label of the form.
 $cancelLabel
 Contains the cancel button label of the form.
 $class
 Contains the additional class value of the form.
 $validator
 Contains the validator function of the form.
 $jsValidation
 Contains the javascript validation type of the form.
 $jsAutosave
 Contains the javascript autosave type of the form.
 $sessionSlotName
 Contains the name of the array in the PHP session, holding the form-data.
 $sessionSlot
 PHP session handle.
 $ttl
 Time until session expiry (seconds)
 $internalFields
 List of internal fieldnames that are not part of the results.
 $namespaces = ['\\Depage\\HtmlForm\\Elements']
 Namespace strings for addible element classes.
Protected Attributes inherited from Container
 $elements = []
 References to input elements and fieldsets.
 $elementsAndHtml = []
 Input element, fieldset and custom HTML object references.
 $form
 Parent form object reference.
Protected Attributes inherited from Element
 $name
 Element name.
 $validated = false
 True if the element has been validated before.
 $log
 Log object reference.
 $defaults = []
 holds default values for element attributes
 $disabled = false
 wether a input element will be disabled
 $class
 CSS class of the container element.

Constructor & Destructor Documentation

◆ __construct()

__construct ( string $name,
array $parameters = [],
HtmlForm|null $form = null )
Parameters
string$nameform name
array$parametersform parameters, HTML attributes
object$formparent form object reference (not used in this case)
Returns
void

Definition at line 252 of file HtmlForm.php.

Member Function Documentation

◆ __toString()

__toString ( )

Renders the htmlform object to HTML code. If the form contains elements it calls their rendering methods.

Returns
string HTML code

Definition at line 1004 of file HtmlForm.php.

◆ addElement()

addElement ( string $type,
string $name,
array $parameters )
protected

Calls parent class to generate an input element or a fieldset and add it to its list of elements.

Parameters
string$typeinput type or fieldset
string$namename of the element
array$parameterselement attributes: HTML attributes, validation parameters etc.
Returns
object $newElement element object

Reimplemented from Container.

Definition at line 419 of file HtmlForm.php.

◆ buildUrl()

buildUrl ( array $args = [])
Returns
new URL

Definition at line 583 of file HtmlForm.php.

◆ buildUrlQuery()

buildUrlQuery ( array $args = [])
Returns
new query

Definition at line 598 of file HtmlForm.php.

◆ checkElementName()

checkElementName ( string $name)

Checks within the form if an input element or fieldset name is already taken. If so, it throws an exception.

Parameters
string$namename to check
Returns
void

Definition at line 443 of file HtmlForm.php.

◆ clearInputValue()

clearInputValue ( string $name)
Parameters
mixed$name
Returns
void

Definition at line 679 of file HtmlForm.php.

◆ clearOldSessions()

clearOldSessions ( int $ttl = 3600,
string $pattern = "/^htmlform-.*/" )
static
Parameters
mixed
Returns
void

Definition at line 960 of file HtmlForm.php.

◆ clearSession()

clearSession ( bool $clearCsrfToken = true)
Parameters
bool$clearCsrfTokenwhether to clear complete form or just the data values and to keep csrf-token.
Returns
void

Definition at line 937 of file HtmlForm.php.

◆ getCurrentStepId()

getCurrentStepId ( )
Returns
int current step

Definition at line 545 of file HtmlForm.php.

◆ getFirstInvalidStep()

getFirstInvalidStep ( )

Checks steps consecutively and returns the number of the first one that isn't valid (steps need to be submitted at least once to count as valid). Form must have been validated before calling this method.

Returns
int $stepNumber number of first invalid step

If there aren't any invalid steps there must be a fieldset directly attached to the form that's invalid. In this case we don't want to jump back to the first step. Hence, this little hack.

Definition at line 558 of file HtmlForm.php.

◆ getNamespaces()

getNamespaces ( )
Returns
array

Definition at line 490 of file HtmlForm.php.

◆ getNewCsrfToken()

getNewCsrfToken ( )
protected
Returns
array element objects

Definition at line 403 of file HtmlForm.php.

◆ getSteps()

getSteps ( )
Returns
array step objects

Definition at line 536 of file HtmlForm.php.

◆ getUrl()

getUrl ( )

Definition at line 527 of file HtmlForm.php.

◆ getValues()

getValues ( )
Returns
array form-data

Definition at line 875 of file HtmlForm.php.

◆ getValuesWithLabel()

getValuesWithLabel ( )
Returns
array form-data with labels

Definition at line 889 of file HtmlForm.php.

◆ htmlDataAttributes()

htmlDataAttributes ( )
protected

Reimplemented from Element.

Definition at line 980 of file HtmlForm.php.

◆ htmlSubmitURL()

htmlSubmitURL ( )
protected

Definition at line 990 of file HtmlForm.php.

◆ httpResponseCode()

httpResponseCode ( int $code)
Parameters
int$codehttp response code

Definition at line 926 of file HtmlForm.php.

◆ isEmpty()

isEmpty ( )
Returns
bool session status

Definition at line 393 of file HtmlForm.php.

◆ onPost()

onPost ( )
protected

Can be overridden to run a custom method when form is posted

Returns
targetUrl
See also
process()

Definition at line 815 of file HtmlForm.php.

◆ onValidate()

onValidate ( )
protected

Can be overridden with custom validation rules, field-required rules etc.

Returns
void
See also
validate()

Definition at line 828 of file HtmlForm.php.

◆ populate()

populate ( array|object $data = [])

Allows to manually populate the forms' input elements with values by parsing an array of name-value pairs.

Parameters
array$datainput element names (key) and values (value)
Returns
void

Definition at line 695 of file HtmlForm.php.

◆ process()

process ( )

Implememts the Post/Redirect/Get strategy. Redirects to success Address on succesful validation otherwise redirects to first invalid step or back to form.

Returns
void
See also
validate()

Definition at line 728 of file HtmlForm.php.

◆ redirect()

redirect ( string $url)
Parameters
string$urlurl to redirect to

Definition at line 916 of file HtmlForm.php.

◆ registerNamespace()

registerNamespace ( string $namespace)
Parameters
string$nameSpacenamespace name
Returns
void

Definition at line 481 of file HtmlForm.php.

◆ setCurrentStep()

setCurrentStep ( int|null $step = null)

Validates step number of the GET request. If it's out of range it's reset to the number of the first invalid step. (only to be used after the form is completely created, because the step elements have to be counted)

Returns
void

Definition at line 515 of file HtmlForm.php.

◆ setDefaults()

setDefaults ( )
protected

The constructor loops through these and creates settable class attributes at runtime. It's a compact mechanism for initialising a lot of variables.

Returns
void

Reimplemented from Element.

Definition at line 303 of file HtmlForm.php.

◆ updateInputValue()

updateInputValue ( string $name)

Sets the input elements' value. If there is post-data - we'll use that to update the value of the input element and the session. If not - we take the value that's already in the session. If the value is neither in the session nor in the post-data - nothing happens.

Parameters
string$namename of the input element
Returns
void

Definition at line 640 of file HtmlForm.php.

◆ validate()

validate ( )

Form validation - validates form elements returns validation result and writes it to session. Also calls custom validator if available.

Returns
bool validation result
See also
process()

Reimplemented from Container.

Definition at line 785 of file HtmlForm.php.

◆ validateAutosave()

validateAutosave ( )

This function returns the actual state of input validation. It can therefore be used to test autosave fields are correct without forcing the form save.

Returns
bool $partValid - whether the autosave postback data is valid

Definition at line 841 of file HtmlForm.php.

Field Documentation

◆ $backLabel

$backLabel
protected

Definition at line 164 of file HtmlForm.php.

◆ $cancelLabel

$cancelLabel
protected

Definition at line 169 of file HtmlForm.php.

◆ $cancelURL

$cancelURL
protected

Definition at line 154 of file HtmlForm.php.

◆ $class

$class
protected

Definition at line 174 of file HtmlForm.php.

◆ $internalFields

$internalFields
protected
Initial value:
= [
'formIsValid',
'formIsAutosaved',
'formName',
'formTimestamp',
'formStep',
'formFinalPost',
'formCsrfToken',
'formCaptcha',
]

Definition at line 229 of file HtmlForm.php.

◆ $isAutoSaveRequest

$isAutoSaveRequest = false

Definition at line 224 of file HtmlForm.php.

◆ $jsAutosave

$jsAutosave
protected

Definition at line 189 of file HtmlForm.php.

◆ $jsValidation

$jsValidation
protected

Definition at line 184 of file HtmlForm.php.

◆ $label

$label
protected

Definition at line 159 of file HtmlForm.php.

◆ $method

$method
protected

Definition at line 134 of file HtmlForm.php.

◆ $namespaces

$namespaces = ['\\Depage\\HtmlForm\\Elements']
protected

Definition at line 243 of file HtmlForm.php.

◆ $sessionSlot

$sessionSlot
protected

Definition at line 199 of file HtmlForm.php.

◆ $sessionSlotName

$sessionSlotName
protected

Definition at line 194 of file HtmlForm.php.

◆ $submitURL

$submitURL
protected

Definition at line 144 of file HtmlForm.php.

◆ $successURL

$successURL
protected

Definition at line 149 of file HtmlForm.php.

◆ $ttl

$ttl
protected

Definition at line 214 of file HtmlForm.php.

◆ $url

$url
protected

Definition at line 139 of file HtmlForm.php.

◆ $valid

$valid

Definition at line 219 of file HtmlForm.php.

◆ $validator

$validator
protected

Definition at line 179 of file HtmlForm.php.

◆ priorityCountries

const priorityCountries
Initial value:
= [
'en' => ['us','gb','ie','au','nz'],
'de' => ['de','at','ch'],
'fr' => ['fr','ch','be','lu','ca'],
'it' => ['it','ch'],
]

Definition at line 125 of file HtmlForm.php.


The documentation for this class was generated from the following file: