Download the PHP package flsouto/htfield without Composer
On this page you can find all versions of the php package flsouto/htfield. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package htfield
HtField
Overview
The HtField class is a base class for implementing all kinds of form fields, both widgets and non-widgets. It is basically a wrapper for two things:
- parameter resolution
- tag attribute setting
For understanding these concepts more deeply I recommend you take a look at the two underlying libraries being used by this class:
Installation
Install this library via composer
Usage
As this is an abstract class, it is only useful if you want to build your own form field types. Therefore in this document I will show you how you can extend it in order to implement a very simple widget.
Defining a Simple Widget
Our example widget is going to be poor in functionality but will be enough for demonstrating the base API. We are going to call it 'MyField'. See its definition below:
Rendering the Field
To render a field instance simply print it out:
The output will be:
Changing the ID
By default, all fields have a default, random id. You can change it to a custom string by calling the attributes API. See example below:
The output will be:
Retrieving the ID
Use the $field->id() method for that:
Outputs:
The name attribute
The name is a special attribute that can only be set once via constructor. However you can access it's value later by using the $field->name() getter:
Outputs:
Processing Input
The $field->process()
method returns an object which contains two properties:
- $field->output: contains the value extracted from the specified source of input
- $field->error: contains any error messages occurred during the extraction process
But, before you can process anything you must specify the source of input. In other words, you must set the "context" from which the data is to be extracted. See example:
Outputs:
Observations
- The context method can be chained just like any other setter method of this class.
- The process method accepts an optional context array, which, if provided, will be used instead of the one set by
$field->context()
.
Processing Namespaced Fields
A field can have a fully qualified name in the following form:
This means that the input is expected to be found in a data structure like this:
Here is an example of this concept in action:
Output:
The $field->value() shortcut
Instead of writing the rather verbose statement $field->process()->output
you can simply call $field->value()
which has the same effect:
Results in:
The $field->validate() shortcut
This is an alias to $field->process()->error
: