jeffsenso/prestashop-skills / skills/prestashop-module-development
prestashop-module-development
VerifiedComplete PrestaShop module development workflow using modern architecture and best practices. Use when: creating new PrestaShop modules, updating legacy modules to modern code, implementing hooks and actions, setting up module configuration pages, adding front office features, handling database operations, implementing security measures, managing translations, creating cart rules and vouchers, building Symfony console commands, or modernizing existing PrestaShop modules from legacy patterns to current standards.
references/forms.md
View on GitHub# Symfony form types — universal rules
These rules apply to **every** Symfony form in a PrestaShop module: configuration forms, CRUD entity forms, filter forms, inline forms.
---
## Boolean / toggle fields — always use `SwitchType`, NEVER `RadioType`
For any boolean/on-off field, **always use `SwitchType`** (PS UI Kit component). Never use `RadioType` or `ChoiceType` with radio buttons.
```php
use PrestaShopBundle\Form\Admin\Type\SwitchType;
$builder->add('active', SwitchType::class, [
'label' => $this->trans('Active', 'Admin.Global'),
'required' => false,
]);
```
- `SwitchType` renders a proper PS toggle switch (Bootstrap + PS UI Kit) with `Yes` / `No` labels.
- The Yes option appears **second** in the underlying `<input type="radio">` pair — `SwitchType` handles this automatically.
- Works correctly with `form_theme '@PrestaShop/Admin/TwigTemplateForm/prestashop_ui_kit.html.twig'`.
- Submitted value is `'1'` (true) or `'0'` (false) as a string — cast with `(bool)` when saving.
**Why not `RadioType`?** `RadioType` / `ChoiceType expanded=true` renders plain HTML radio inputs with no PS styling. They appear broken/unstyled in the admin UI Kit and confuse users.
**Applies to:** configuration forms, CRUD create/edit forms, bulk action forms, any in-modal form.
---
## Form theme
Always set the PS UI Kit form theme so all widgets render with correct PS Bootstrap styling:
```php
// Option A — in FormType::configureOptions (preferred)
$resolver->setDefaults([
'form_theme' => '@PrestaShop/Admin/TwigTemplateForm/prestashop_ui_kit.html.twig',
]);
// Option B — in Twig template
{% form_theme myForm '@PrestaShop/Admin/TwigTemplateForm/prestashop_ui_kit.html.twig' %}
```
Both approaches achieve the same result; Option A keeps the theme with the form type class.
---
## ⚠️ IntegerType with optional/empty values
**Problem:** `IntegerType` throws "Expected a numeric" error when the field is empty or the database value is an empty string.
**Cause:** `IntegerType` expects a numeric value. When loading from `Configuration::get()` that returns an empty string `''` or when the field is left empty, Symfony's form data transformer fails.
**Solution:** Always handle empty values properly in both directions:
### 1. In ConfigurationDataConfiguration::getConfiguration()
Return `0` (integer) instead of empty string:
```php
public function getConfiguration(): array
{
return [
// ✅ CORRECT - cast to int and provide default
'selection_id' => (int) ($this->configuration->get('MYMODULE_SELECTION_ID') ?: 0),
// ❌ WRONG - empty string causes "Expected a numeric" error
'selection_id' => $this->configuration->get('MYMODULE_SELECTION_ID') ?? '',
];
}
```
### 2. In ConfigurationDataConfiguration::updateConfiguration()
Cast to int when saving:
```php
public function updateConfiguration(array $configuration): array
{
$this->configuration->set(
'MYMODULE_SELECTION_ID',
(int) ($configuration['selection_id'] ?? 0) // ✅ Cast to int
);
return [];
}
```
### 3. In ConfigurationInstaller
Set default to `0` (integer), not empty string:
```php
private array $configurations = [
self::MYMODULE_SELECTION_ID => 0, // ✅ Integer default
// NOT: self::MYMODULE_SELECTION_ID => '', // ❌ Empty string
];
```
### 4. In FormType (optional but recommended)
Add `empty_data` option:
```php
$builder->add('selection_id', IntegerType::class, [
'label' => $this->trans('Selection ID', 'Modules.Mymodule.Admin'),
'required' => false,
'empty_data' => '0', // ✅ Provides default when empty
'constraints' => [
new Positive(['message' => 'Must be a positive number']),
],
]);
```
**Key rule:** For `IntegerType` fields that are optional, **always use integer `0` as the empty/default value**, never empty string `''`.
---
---
## TranslatableType — per-language fields
Use `TranslatableType` when a field must store a **different value per installed language** (e.g. title templates, meta descriptions). It renders one input per language plus a language-selector dropdown.
### ⚠️ Required: locale-switcher JS bundle
`TranslatableType` renders `.js-locale-item` / `.js-locale-input` / `.js-locale-btn` elements whose visibility is controlled by a custom JS bundle — **not** by Bootstrap tabs alone. Without this bundle, clicking a language in the dropdown has no effect.
**Step 1 — Copy the template bundle:**
```bash
cp skills/.agents/skills/prestashop-module-development/scripts/translatable-form.bundle.js \
views/js/{modulename}.form.bundle.js
# Then replace every MODULENAME with your actual module name (lowercase):
sed -i 's/MODULENAME/{modulename}/g' views/js/{modulename}.form.bundle.js
```
**Step 2 — Load it in the Twig template:**
```twig
{% block javascripts %}
{{ parent() }}
<script src="{{ asset('../modules/{modulename}/views/js/{modulename}.form.bundle.js') }}"></script>
{% endblock %}
```
> The `{% block javascripts %}{{ parent() }}` is mandatory — `parent()` preserves the admin layout's default JS (jQuery, Bootstrap, etc.).
### FormType — adding TranslatableType fields
```php
use PrestaShopBundle\Form\Admin\Type\TranslatableType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
$builder->add('title', TranslatableType::class, [
'type' => TextType::class,
'label' => $this->trans('Title', 'Modules.Mymodule.Admin'),
'options' => ['attr' => ['maxlength' => 255]],
'help' => $this->trans('Available tokens: %token%', 'Modules.Mymodule.Admin'),
'required' => false,
]);
```
The service for the FormType must declare `parent: form.type.translatable.aware`:
```yaml
# config/components/form/my_form.yml
mymodule.form.type.my_configuration:
class: Vendor\MyModule\Form\MyConfigurationFormType
parent: form.type.translatable.aware
tags:
- { name: form.type }
```
### DataConfiguration — storing per-lang values
Values are stored in the PS `configuration` table as `KEY_{id_lang}`:
```php
final class MyConfigurationDataConfiguration implements DataConfigurationInterface
{
public const KEY_TITLE = 'MYMODULE_TITLE';
public const DEFAULT_TITLE = 'Default title with %token%';
public function getConfiguration(): array
{
$title = [];
foreach (\Language::getLanguages(true) as $lang) {
$idLang = (int) $lang['id_lang'];
$title[$idLang] = $this->configuration->get(self::KEY_TITLE . '_' . $idLang)
?: self::DEFAULT_TITLE;
}
return ['title' => $title];
}
public function updateConfiguration(array $configuration): array
{
foreach ($configuration['title'] ?? [] as $idLang => $value) {
$this->configuration->set(self::KEY_TITLE . '_' . (int) $idLang, $value);
}
return [];
}
public function validateConfiguration(array $configuration): bool { return true; }
}
```
### Controller — always pass `$form->getData()`
```php
if ($form->isSubmitted() && $form->isValid()) {
$errors = $formDataHandler->save($form->getData()); // ✅ NOT $form
...
}
```
> **Common bug:** passing `$form` (the Form object) instead of `$form->getData()` (the array) to `save()` causes:
> `Handler::save(): Argument #1 ($data) must be of type array, Form given`
---
## Common PS form types quick reference
| Field type | PS type class | Notes |
|-----------------------|----------------------------------------------|-------|
| Boolean toggle | `SwitchType` | Always use this; never RadioType |
| Short text | `TextType` (Symfony) | |
| Long text | `TextareaType` (Symfony) | |
| Integer | `IntegerType` (Symfony) or `NumberType` | |
| Per-language text | `TranslatableType` | Requires locale-switcher JS bundle (see above) |
| Color picker | `ColorPickerType` | `PrestaShopBundle\Form\Admin\Type` |
| Country select | `CountryChoiceType` | `PrestaShopBundle\Form\Admin\Type` |
| Category tree | `CategoryChoiceTreeType` | `PrestaShopBundle\Form\Admin\Type` |
| Image upload | `FileType` (Symfony) | validate MIME + size at boundary |
| Money | `MoneyType` (Symfony) | |
| Date/time | `DatePickerType` | `PrestaShopBundle\Form\Admin\Type` |
All PS-specific types are in `PrestaShopBundle\Form\Admin\Type\`.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |