PHPackages                             heimrichhannot/contao-form-type-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. heimrichhannot/contao-form-type-bundle

ActiveContao-bundle[Utility &amp; Helpers](/categories/utility)

heimrichhannot/contao-form-type-bundle
======================================

Add types to contao form generator.

0.2.12(2mo ago)11.8k↓33.3%[1 issues](https://github.com/heimrichhannot/contao-form-type-bundle/issues)2LGPL-3.0-or-laterPHPPHP ^8.2CI failing

Since Sep 5Pushed 2mo ago5 watchersCompare

[ Source](https://github.com/heimrichhannot/contao-form-type-bundle)[ Packagist](https://packagist.org/packages/heimrichhannot/contao-form-type-bundle)[ Docs](https://github.com/heimrichhannot/contao-form-type-bundle)[ RSS](/packages/heimrichhannot-contao-form-type-bundle/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (23)Versions (28)Used By (2)

Form Type Bundle
================

[](#form-type-bundle)

Form type bundle is an extension for the Contao CMS to provide a generic way to create forms for specific approaches with contao form generator. It is aimed at developers and contains no build-in form types.

Feature
-------

[](#feature)

- Generic way to create forms for specific approaches with contao form generator
- Options event for select, checkbox and radio form fields
- Form types can support a first time wizard to setup basic form fields

Installation
------------

[](#installation)

Install the bundle via composer and update your database afterwards:

```
composer require heimrichhannot/contao-form-type-bundle

```

Usage
-----

[](#usage)

### Create a new form type

[](#create-a-new-form-type)

Create a new class that extends `AbstractFormType`. Register it as service with autoconfiguration enabled.

A label can be set within `$GLOBALS['TL_LANG']['tl_form']['FORMTYPE']`:

```
# contao/languages/de/tl_form.php
$GLOBALS['TL_LANG']['tl_form']['FORMTYPE']['huh_mediathek'] = 'Mediathek';
```

### First time wizard

[](#first-time-wizard)

You can add a first time wizard to your form type by implementing `getDefaultFields()` method. It expects field definitions in array format as return values. These fields will be created when executing the wizard.

```
public function getDefaultFields(FormModel $formModel): array
{
    return [
        [
            'type' => 'text',
            'name' => 'title',
            'label' => $this->translator->trans('tl_example.title.0', [], 'contao_tl_example'),
            'mandatory' => '1',
        ],
        [
            'type' => 'textarea',
            'name' => 'text',
            'label' => $this->translator->trans('tl_example.text.0', [], 'contao_tl_example'),
        ],
    ];
}
```

### Form events

[](#form-events)

You can register event listeners for events during form livecycle. These events are mappings of the corresponding contao form hooks but will only fire for the specific form type.

Following events are available:

EventNameCompileFormFieldsEventhuh.form\_type.\[TYPE\].compile\_form\_fieldsLoadFormFieldEventhuh.form\_type.\[TYPE\].load\_form\_fieldPrepareFormDataEventhuh.form\_type.\[TYPE\].prepare\_form\_dataProcessFormDataEventhuh.form\_type.\[TYPE\].process\_form\_dataStoreFormDataEventhuh.form\_type.\[TYPE\].store\_form\_dataValidateFormFieldEventhuh.form\_type.\[TYPE\].validate\_form\_field### Options event

[](#options-event)

If you want to provide options for a select, checkbox or radio form field, you can register an event listener. The event name is `huh.form_type...options'`.

```
// src/EventListener/OptionsEventListener.php
use HeimrichHannot\FormTypeBundle\Event\FieldOptionsEvent;

class OptionsEventListener implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            'huh.form_type.huh_media_library.licence.options' => 'onLicenceOptions',
        ];
    }

    public function onLicenceOptions(FieldOptionsEvent $event): void
    {
        $event->addOption('free', 'Free');
        $event->addOption('adobe', 'Adobe');
        $event->addOption('istock', 'iStock');
    }

    public function onTopicOptions(FieldOptionsEvent $event): void
    {
        $event->addOption('cinema', 'Cinema', 'entertainment');
        $event->addOption('music', 'Music', 'entertainment');

        $event->addOption('politics', 'Politics', 'news');
        $event->addOption('sport', 'Sport', 'news');
        $event->addOption('culture', 'Culture', 'news');
    }
}
```

#### Unified Dispatcher for Field Options

[](#unified-dispatcher-for-field-options)

Use `FieldOptionsDispatcherTrait` to dispatch `FieldOptionsEvent` `huh.form_type...options` and Contao `fields..options` callbacks alike.

Example:

```
use HeimrichHannot\MediaLibraryBundle\Trait\FieldOptionsDispatcherTrait;

class MyContainerOrFormType
{
    use FieldOptionsDispatcherTrait;

    #[AsCallback(table: 'tl_ml_product', target: 'fields.licence.options')]
    #[AsEventListener('huh.form_type.huh_media_library.licence.options')]
    public function getLicenceOptions(): array
    {
        return $this->dispatchFieldOptions([
            'free' => 'Released for use under indication of copyright',
            'locked' => 'Subject to licence'
        ]);
    }
}
```

### Get form options

[](#get-form-options)

Use the `FormTypeCollection` class to get form options to use in your dca fields or wherever you need them.

```
use Contao\CoreBundle\DependencyInjection\Attribute\AsCallback;
use HeimrichHannot\EventRegistrationBundle\FormType\EventRegistrationFormType;
use HeimrichHannot\FormTypeBundle\FormType\FormTypeCollection;

#[AsCallback(table: 'tl_calendar', target: 'fields.reg_form.options')]
class FieldsRegFormOptionsListener
{
    private readonly FormTypeCollection $formTypeCollection,

    public function __invoke(): array
    {
        return $this->formTypeCollection->getFormsForFormType(EventRegistrationFormType::TYPE);
    }
}
```

### Form Context

[](#form-context)

Implementing a form context evaluator on your from type allows you to change the form's behavior depending on the context it is used in. This can be used e.g. to load existing data into the form fields, perhaps to create an editing form.

#### Built-in Form Edit Context

[](#built-in-form-edit-context)

A basic default form context evaluator providing editing functionality is built into the bundle. Just override `DEFAULT_FORM_CONTEXT_TABLE` in your form type to allow editing the respective database model:

```
protected const DEFAULT_FORM_CONTEXT_TABLE = 'tl_my_table';
```

- Create your form in Contao.
- Name your form fields like the database fields you want to edit, e.g. `title` for `tl_my_table.title`.
- Append the query parameter `?edit=` to the url of the page your form is included in to edit the existing row with a primary key of ``.

If no `DEFAULT_FORM_CONTEXT_TABLE` is set, the form will be treated as a creation form by default.

#### Create your own Form Context

[](#create-your-own-form-context)

To implement your own form context evaluator, override `evaluateFormContext()` in your form type:

```
protected function evaluateFormContext(): FormContext
{
    $request = $this->container->get('request_stack')->getCurrentRequest();
    $editParameter = 'edit';
    $databaseTable = 'tl_my_table';

    if ($modelPk = $request->query->get($editParameter))
    {
        /** @var class-string $modelClass */
        $modelClass = Model::getClassFromTable($databaseTable);
        $modelInstance = $modelClass::findByPk($modelPk);
        if ($modelInstance === null) {
            return FormContext::invalid($databaseTable, 'Could not find object.');
        }
        return FormContext::update($databaseTable, $modelInstance->row());
    }

    return FormContext::create($databaseTable);
}
```

The example shows the implementation of a form context evaluator that allows editing a database model with a primary key given by the query parameter `edit`.

To retrieve the current form context, call the getter on your form type:

```
$formContext = $this->getFormContext();
```

We do not recommend to call `$this->evaluateFormContext()` directly, as it will skip future cache implementations if you do.

#### Form Context Actions

[](#form-context-actions)

Most commonly used form context actions are already implemented.

```
use HeimrichHannot\FormTypeBundle\FormType\FormContextAction;

FormContextAction::CREATE;
FormContextAction::READ;
FormContextAction::UPDATE;
FormContextAction::DELETE;
FormContextAction::CLONE;
FormContextAction::INVALID;
```

`FormContextAction::INVALID` can be used to indicate that the form should not be processed.

To instantiate a `FormContext` object with a built-in action, use the static factory methods:

```
use HeimrichHannot\FormTypeBundle\FormType\FormContext;

$createContext  = FormContext::create('tl_my_table');
$readContext    = FormContext::read('tl_my_table', $data);
$updateContext  = FormContext::update('tl_my_table', $data);
$deleteContext  = FormContext::delete('tl_my_table', $data);

$cloneContext   = FormContext::clone('tl_my_table', $data);

$invalidContext = FormContext::invalid('tl_my_table', 'This is error detail.', $additionalData ?? []);
```

Alternatively, you may also use the `FormContext` constructor:

```
use HeimrichHannot\FormTypeBundle\FormType\FormContext;
use HeimrichHannot\FormTypeBundle\FormType\FormContextAction;

$formContext = new FormContext(FormContextAction::UPDATE, 'tl_my_table', $data);
```

However, you may also specify your own actions when constructing a `FormContext` object, or by overriding the action of an existing object.

```
use HeimrichHannot\FormTypeBundle\FormType\FormContext;
use HeimrichHannot\FormTypeBundle\FormType\FormContextAction;

$formContext = new FormContext('my_custom_action', 'tl_my_table', $data);
// or
$formContext->setAction('this_can_be_any_string_or_action');
// or
$formContext->setAction(FormContextAction::DELETE);
```

This way you are not bound to the built-in actions.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance67

Regular maintenance activity

Popularity22

Limited adoption so far

Community16

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~38 days

Recently: every ~23 days

Total

25

Last Release

63d ago

PHP version history (3 changes)0.1.0PHP ^7.4 || ^8.0

0.1.9PHP ^8.1

0.2.7PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/28ad3224d8727b622ebd229840eea6b9dbcb83eb0bd609e6ce65b614830ff538?d=identicon)[digitales@heimrich-hannot.de](/maintainers/digitales@heimrich-hannot.de)

---

Top Contributors

[![ericges](https://avatars.githubusercontent.com/u/25957923?v=4)](https://github.com/ericges "ericges (68 commits)")[![koertho](https://avatars.githubusercontent.com/u/12064642?v=4)](https://github.com/koertho "koertho (43 commits)")[![vvohh](https://avatars.githubusercontent.com/u/75325799?v=4)](https://github.com/vvohh "vvohh (2 commits)")

---

Tags

contaocontao5formscontaoForms

###  Code Quality

Static AnalysisPHPStan, Rector

Code StyleECS

Type Coverage Yes

### Embed Badge

![Health badge](/badges/heimrichhannot-contao-form-type-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/heimrichhannot-contao-form-type-bundle/health.svg)](https://phpackages.com/packages/heimrichhannot-contao-form-type-bundle)
```

###  Alternatives

[codefog/contao-haste

haste extension for Contao Open Source CMS

42650.8k139](/packages/codefog-contao-haste)[shopware/platform

The Shopware e-commerce core

3.3k1.5M3](/packages/shopware-platform)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao-community-alliance/dc-general

Universal data container for Contao

1578.3k86](/packages/contao-community-alliance-dc-general)[codefog/contao-news_categories

News Categories bundle for Contao Open Source CMS

3183.3k6](/packages/codefog-contao-news-categories)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
