Download the PHP package b2pweb/bdf-form without Composer

On this page you can find all versions of the php package b2pweb/bdf-form. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package bdf-form

BDF Form

Library for handle form, and request validation.

build codecov Packagist Version Total Downloads Type Coverage

Table of content

Installation using composer

Basic usage

To create a form, simply extends the class CustomForm and implements method CustomForm::configure() :

To display the form, call the ElementInterface::view() method on the form object, and use the view object :

Now, you can submit data to the form, and perform validation :

Handle entities

The form system can be use to import, create or fill an entity using accessors :

Declaration :

Usage :

Transformation process

Here a description, step by step, of the transformation process, from HTTP value to model value. This process is reversible to generate HTTP value from model.

Note: This example is for leaf element contained into a form. For an embedded for or array, simply replace the leaf element process by the form process.

1 - Submit to buttons (scope: RootForm)

The first step perform by the RootForm is to check the submit buttons. If the HTTP data contains the button name, and the value match with the configured one, the button is marked as clicked.

Note: in reverse process, the clicked button value will be added to HTTP value

See :

2 - Call transformers of the form (scope: Form)

Transformers of the container form are called. There are used to normalize input HTTP data to usable array value.

Note: the transformers are called in reverse order (i.e. last registered is first executed) when transform from HTTP to PHP and called in order for PHP to HTTP transformation

See:

3 - Extract the HTTP field value (scope: Child)

At this step, the normalized HTTP value is passed to the child, and the current field value is extracted. If the value is not available, null is returned.

There is two extraction strategy :

See:

4 - Apply filters (scope: Child)

Once the field value is extracted, filters are applied. There are used for normalize and remove illegal values. It's a destructive operation by definition (cannot be reversed), unlike transformers. There can be used for perform trim or array_filter.

Note: Unlike transformers, filters are only applied during transformation from HTTP to PHP. Do not use if it's a "view" operation, like decoding a string.

See:

5 - Set default value (scope: Child)

Set the default value is the filtered field value is considered as empty and a default value is provided. A value is empty is it's an empty string '' or array [], or it's null. 0, 0.0 or false are not considered as empty. If not default value is given, the filtered value will be used.

Note: To set a default value, you should call ChildBuilderInterface::default() with PHP value

See:

6 - Call element transformers (scope: Element)

Works like Form transformers (step 2), but on the element value. If a transformer throws an exception, the submit process will be stopped, the raw HTTP value will be kept, and the element will be marked as invalid with the exception message as error.

The transformer exception behavior can be changed on the ElementBuilder. If the exception is ignored by calling ignoreTransformerException() on the builder, the validation process will be performed on the raw HTTP value.

See:

7 - Cast to PHP value (scope: Element)

The value is converted from HTTP value to usable PHP value, like a cast to int on IntegerElement.

Note: this step is only performed on LeafElement implementations

See:

8 - Validation (scope: Element)

Validate the PHP value of the element, using constraints.

See:

9 - Generate the form value (scope: Form)

Create the entity to fill by form values.

See:

10 - Apply model transformer (scope: Child)

Call the model transformer, for transform input data to model data.

See:

11 - Call accessor (scope: Child)

The accessor is used to fill the entity (in case of HTTP to PHP), or form import from entity (in case of PHP to form).

See:

12 - Validate the form value (scope: Form)

Once the value is hydrated, it will be validated by the form constraints.

See:

Embedded and array

Complex form structure can be created using embedded form and generic array element. Embedded form is useful for reuse a form into another.

This form will handle data like :

Or in HTTP format :

To improve readability and reusability, each embedded form can be declared in its own class :

You can also "flatten" the HTTP fields by using ChildBuilderInterface::prefix(). The embedded form will use a prefix instead of a sub-array.

Using prefix, the new data format is :

Or in HTTP format :

Field path and dependencies

In some cases, a field value should be validated or transformed using another field value. It's for this goal that field dependencies are added : when a field depends on other, you can declare it using ChildBuilderInterface::depends(). Field path are used to access to the specific field.

Note: dependencies add complexity to the form, it's advisable to use a constraint on the parent form if possible.

To create a field path (and access to the desired field), you should use FieldPath::parse(), or FieldFinderTrait.

The format works like unix file system path, with / as field separator, . for the current field, and .. for the parent. Use / at the start will define path as absolute. Unlike unix path, by default, the path starts from the parent of the field (i.e. equivalent to ../).

Format:

With :

Usage:

The FieldPath can also be used outside the form, and with embedded forms :

Choices

Choice system is use to allow only a set of values, like with HTML <selecte> element. To define a choice, simply call choice() on the element builder, if supported. A label can be defined using the key of associative array for the list of available values.

Once defined, the view system will automatically transform simple input elements to <select>. To render manually the choice, you can also call FieldViewInterface::choices() to get choices array :

Buttons

Submit button can be defined to handle multiple action on the same form.

The form :

The view :

The controller :

Elements

StringElement

Email

String element with Email constraint

Url

String element with Url constraint

IntegerElement

FloatElement

BooleanElement

Handle boolean value, like a checkbox. The value will be considered as true if it's present, and is equals to the defined one (by default 1).

Note: in HTTP a falsy value is an absent value, so a default value cannot be defined on a boolean element. To define a "view default" value, use ElementBuilderInterface::value() instead of ChildElementBuilder::default()

The default renderer will render a <input type="checkbox" /> with the defined http value and checked state.

DateTimeElement

PhoneElement

Handle phone number. The package giggsey/libphonenumber-for-php is required to use this element. This element will not return a string but a PhoneNumber instance.

CsrfElement

This element allows to mitigate CSRF. The package symfony/security-csrf is required for this element. Some element methods are disallowed, like import(), any constraints, transformer or default. The view will be rendered as <input type="hidden" />.

AnyElement

An element for handle any value types. This is useful for create an inline custom element. But it's strongly discouraged : prefer use one of the native element, or create a custom one.

EnumElement

Handle PHP 8.1 enum values. Both backed enum and simple unit enum are supported. If the enum is not backed, it's name will be used as HTTP value. Otherwise, the backed value will be used.

Create a custom element

You can declare custom elements to handle complex types, and reuse into any forms. The examples bellow are for declare an element to handle UriInterface objects, created using PSR-17 UriFactoryInterface

Using custom form

You can use a CustomForm to declare an element. The advantage of this method is that it don't need to implements low level interfaces, and require only to extends the CustomForm class. But it has the consequence of using more resources, has a lower flexibility, and cannot define a custom builder.

Using LeafElement

If declaring an element using the CustomForm is not enough, or if you want to optimise this element, you can use the low level class LeafElement to declare a custom element.

Usage

To use the custom element, simply call FormBuilderInterface::add() with the element class name as second parameter :

Custom child builder

In some case, defining a custom child builder can be relevant, like for register model transformers. To declare the child, simply extends ChildBuilder class, and register to the Registry :

Error Handling

When an error occurs on the form, a FormError object is created with all errors.

Simple usage

If an error is on a child, use FormError::children() to get the error. If there is no error on children, but on the parent element, use FormError::global() instead. To get a simple string representation of errors, cast the errors to string. To get an array representation in form [fieldName => error], use FormError::toArray().

Printer

To format errors with reusable way, a FormErrorPrinterInterface can be implemented.

Using PHP 8 attributes

You can usePHP 8 attributes and typed properties to declare form elements and configure them, instead of using the "classical" way by overriding configure() method.

Declare a form class

To create a form using PHP 8 attributes, first you have to extend AttributeForm.

Then declare all input elements and buttons as property :

Finally, use attributes on properties (or form class) for configure elements, add constraints, transformers...

Adaptation of example from BDF Form : Handle entities

Supported attributes

This library supports various attributes types for configure form elements :

Generate the configurator code from attributes

To improve performance, and to do without the use of reflection, attributes can be used to generate the PHP code of the configurator, instead of dynamically configure the form.

To do that, use CompileAttributesProcessor as argument of form constructor.

Available attributes

On form class

Attribute Example Translated to Purpose
Generates Generates(MyEntity::class) $builder->generates(MyEntity::class) Define the entity class generated by the form.
CallbackGenerator CallbackGenerator('generate') $builder->generates([$this, 'generate']) Define the method to use for generate the form value. The method must be declared as public on the form class.
Csrf Csrf(tokenId: 'MyToken') $builder->csrf()->tokenId('MyToken') Add a CSRF element on the form.

On method

Attribute Example Translated to Purpose
AsConstraint AsConstraint('validateFoo') $builder->satisfy([$this, 'validateFoo']) Use the method as constraint for the target element.
AsArrayConstraint AsArrayConstraint('validateFoo') $builder->arrayConstraint([$this, 'validateFoo']) Use the method as constraint for the target array element.
AsFilter AsFilter('filterFoo') $builder->filter([$this, 'filterFoo']) Use the method as filter for the target element.
AsTransformer AsTransformer('transformFoo') $builder->transformer([$this, 'transformFoo']) Use the method as HTTP transformer for the target element.
AsModelTransformer AsModelTransformer('transformFoo') $builder->modelTransformer([$this, 'transformFoo']) Use the method as model transformer for the target element.

On button property

Attribute Example Translated to Purpose
Groups Groups('foo', 'bar') ...->groups(['foo', 'bar']) Define validation groups to use when the given button is clicked.
Value Value('foo') ...->value('foo') Define the button value.

On element property

Attribute Example Translated to Purpose
Child
ModelTransformer ModelTransformer(MyTransformer::class, ['ctroarg']) ...->modelTransformer(new MyTransformer('ctorarg)) Define a model transformer on the current child.
CallbackModelTransformer CallbackModelTransformer(toEntity: 'parseInput', toInput: 'normalize') ...->modelTransformer(fn ($value, $input, $toEntity) => $toEntity ? $this->parseInput($value, $input) : $this->normalize($value, $input)) Define a model transformer using a form method.
Configure Configure('configureInput') ...->configureField($elementBuilder) Manually configure the element builder using a form method. The method must be public and declared on the form class.
DefaultValue DefaultValue(42) ...->configureField($elementBuilder) Define the default value of the input.
Dependencies Dependencies('foo', 'bar') ...->depends('foo', 'bar') Declare dependencies on the current input. Dependencies will be submitted before the current field.
GetSet GetSet('realField') ...->getter('realField')->setter('realField') Enable hydration and extraction of the entity.
CallbackFilter CallbackFilter('filterMethod') ...->filter([$this, 'filterMethod']) Add a filter on the current child using a method.
HttpField HttpField('_field') ...->httpField(new ArrayOffsetHttpField('_field')) Define the http field name to use on the current child, instead of use the property name.
Element
CallbackConstraint CallbackConstraint('validateInput') ...->satisfy([$this, 'validateInput']) Validate an input using a method.
Satisfy Satisfy(MyConstraint::class, ['opt' => 'val']) ...->satisfy(new MyConstraint(['opt' => 'val'])) Add a constraint on the input. Prefer directly use the constraint class as attribute if possible.
Transformer Transformer(MyTransformer::class, ['ctorarg']) ...->transformer(new MyTransformer('ctorarg)) Add a transformer on the input. Prefer directly use the transformer class as attribute if possible.
CallbackTransformer CallbackTransformer(fromHttp: 'parse', toHttp: 'stringify') ...->transformer(fn ($value, $input, $toPhp) => $toPhp ? $this->parse($value, $input) : $this->stringify($value, $input)) Add a transformer using a form method.
Choices Choices(['foo', 'bar']) ...->choices(['foo', 'bar']) Define the values choices of the input. Supports using a method as choices provider.
Raw Raw ...->raw() For number elements. Use native PHP cast instead of locale parsing for convert number.
TransformerError TransformerError(message: 'Invalid value provided') ...->transformerErrorMessage('Invalid value provided') Configure error handling of transformer exceptions.
IgnoreTransformerException IgnoreTransformerException ...->ignoreTransformerException() Ignore transformer exception. If enable and an exception occurs, the raw value will be used.
Required Required ...->required() Mark the element as required. The error message can be defined as parameter of the attribute.
DateTimeElement
DateFormat DateFormat('d/m/Y H:i') ...->format('d/m/Y H:i') Define the input date format.
DateTimeClass DateTimeClass(Carbon::class) ...->className(Carbon::class) Define date time class to use on for parse the date.
ImmutableDateTime ImmutableDateTime ...->immutable() Use DateTimeImmutable as date time class.
Timezone Timezone('Europe/Paris') ...->timezone('Europe/Paris') Define the parsing and normalized timezone to use.
AfterField AfterField('otherField') ...->afterField('otherField') Add a greater than an other field constraint to the current element.
BeforeField BeforeField('otherField') ...->beforeField('otherField') Add a less than an other field constraint to the current element.
ArrayElement
ArrayConstraint ArrayConstraint(MyConstraint::class, ['opt' => 'val']) ...->arrayConstraint(new MyConstraint(['opt' => 'val'])) Add a constraint on the whole array element.
CallbackArrayConstraint CallbackArrayConstraint('validateInput') ...->arrayConstraint([$this, 'validateInput']) Add a constraint on the whole array element, using a form method.
Count Count(min: 3, max: 6) ...->arrayConstraint(new Count(min: 3, max: 6)) Add a Count constraint on the array element.
ElementType ElementType(IntegerElement::class, 'configureElement') ...->element(IntegerElement::class, [$this, 'configureElement']) Define the array element type. A configuration callback method can be define for configure the inner element.
ArrayTransformer ArrayTransformer(MyTransformer::class, ['ctroarg']) ...->arrayTransformer(new MyTransformer('ctorarg)) Add a transformer for the whole array input.

All versions of bdf-form with dependencies

PHP Build Version
Package Version
Requires php Version >=7.4
symfony/property-access Version ~4.3|~5.0|~6.0|~7.0
symfony/validator Version ~4.3|~5.0|~6.0|~7.0
symfony/polyfill-php80 Version ~1.22
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package b2pweb/bdf-form contains the following files

Loading the files please wait ...