Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 30 ยท Back Office with Symfony

Twig, Forms and Grids

Build back office screens in a PrestaShop module: Twig templates, Symfony forms with data providers and handlers, and the Grid component with filters and bulk actions.

A back office page that lists records, lets an employee filter and sort them, edit one and delete several at once is the bread and butter of module development. PrestaShop's modern back office has building blocks for exactly that: Twig templates for the markup, the Symfony Form component with small data provider and handler classes for create and edit screens, and a Grid component that renders a filterable, sortable, paginated table with bulk actions.

You will see how each block is defined, what the core already does for you, and where your own code goes. All PrestaShop-specific code on this page is read-only and shortened: namespaces and constructor arguments differ a little between releases, so treat it as the shape of the solution and check the developer documentation of your version for the exact names. The runnable parts are stand-ins that show the logic behind the Grid (filter, sort, page, bulk delete) and the form flow (default data, validation, create, update). They come after the first look at the Symfony controller and routes that call these pieces.

Twig in a module

Twig templates for the back office live in the module's views/templates/admin/ folder and end with .html.twig. A controller renders them with the @Modules/<module>/... namespace. A page normally extends the shared admin layout and fills its content block:

TWIG
{# modules/acmenote/views/templates/admin/index.html.twig (read-only) #}
{% extends '@PrestaShop/Admin/layout.html.twig' %}

{% block content %}
  <div class="card">
    <h3 class="card-header">{{ 'Notes'|trans({}, 'Modules.Acmenote.Admin') }}</h3>
    <div class="card-body">
      {% include '@PrestaShop/Admin/Common/Grid/grid_panel.html.twig' with {'grid': noteGrid} %}
    </div>
  </div>
{% endblock %}

Things to know:

  • {{ value }} is escaped automatically. That is the main protection against cross-site scripting. Avoid |raw unless the value is HTML you generated and trust. More on this in Security in Modules.
  • |trans({}, 'Modules.Acmenote.Admin') translates a string in your module's domain, see Translations and Multilingual Modules.
  • path('acme_note_index') builds a URL from a route name, including the back office token.
  • Keep logic out of templates. Compute lists and flags in the controller or a service, and let the template only display them.

Forms: the shape of a create/edit screen

A form in the modern back office is made of four small parts, each with one job:

flowchart LR
    C["Controller"] --> B["FormBuilder<br/>(builds the form)"]
    B --> P["FormDataProvider<br/>default data or data of id N"]
    B --> T["Form type<br/>fields + constraints"]
    C --> H["FormHandler<br/>validates and saves"]
    H --> D["FormDataHandler<br/>create() / update()"]

The builder asks the provider for data and the type for fields; the handler asks the data handler to save.

  1. The form type is a normal Symfony form class that lists the fields and their validation constraints. In PrestaShop it usually extends TranslatorAwareType, a base class that gives you $this->trans() for labels.
  2. The data provider answers "what are the values?": the defaults for a new record, or the stored values for a given id.
  3. The data handler answers "how do I save?": create(array $data) returns the new id; update($id, array $data) changes an existing record.
  4. The builder and handler are core classes that tie the others together; you configure them in services.yml with the form type, provider and handler as arguments.
PHP
<?php
// modules/acmenote/src/Form/NoteType.php (read-only, shortened)
namespace Acme\Note\Form;

use PrestaShopBundle\Form\Admin\Type\TranslatorAwareType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;

class NoteType extends TranslatorAwareType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder->add('content', TextareaType::class, [
            'label' => $this->trans('Note', 'Modules.Acmenote.Admin'),
            'constraints' => [
                new NotBlank(),
                new Length(['max' => 500]),
            ],
        ]);
    }
}
PHP
<?php
// modules/acmenote/src/Form/NoteFormDataProvider.php (read-only, shortened)
final class NoteFormDataProvider implements FormDataProviderInterface
{
    public function __construct(private readonly NoteRepository $notes)
    {
    }

    public function getData($id): array
    {
        $note = $this->notes->find((int) $id);

        return ['content' => $note['content']];
    }

    public function getDefaultData(): array
    {
        return ['content' => ''];
    }
}
PHP
<?php
// modules/acmenote/src/Form/NoteFormDataHandler.php (read-only, shortened)
final class NoteFormDataHandler implements FormDataHandlerInterface
{
    public function __construct(private readonly NoteRepository $notes)
    {
    }

    public function create(array $data): int
    {
        return $this->notes->insert($data['content']);
    }

    public function update($id, array $data): void
    {
        $this->notes->updateContent((int) $id, $data['content']);
    }
}

In the controller, the flow is the usual Symfony one:

PHP
// read-only, shortened
$form = $this->formBuilder->getFormFor($noteId);   // null id means "new"
$form->handleRequest($request);

$result = $this->formHandler->handleFor($noteId, $form);
if ($result->isSubmitted() && $result->isValid()) {
    $this->addFlash('success', $this->trans('Saved.', [], 'Modules.Acmenote.Admin'));

    return $this->redirectToRoute('acme_note_index');
}

return $this->render('@Modules/acmenote/views/templates/admin/form.html.twig', [
    'noteForm' => $form->createView(),
]);

The core builder and handler services come from factories the core registers (form_builder_factory and form_handler_factory); the module's services.yml calls them with your type, provider and handler. Copy the exact service definitions from the documentation of the version you support instead of writing them from memory.

The separation pays off: the validation rules live in the type, the reading and writing logic lives in classes you can test without a web request, and the controller stays short.

Grids

A Grid is the list screen. It is not one class but a set of configuration objects, so that a list can be filtered, sorted and paginated, and the filter state is remembered per employee. Three pieces are yours to write:

  1. A grid definition factory that says which columns, filters and actions exist.
  2. A query builder that turns the employee's choices (a "search criteria" object) into SQL.
  3. A data factory registration in services.yml that connects them.

The definition describes everything about the screen:

PHP
<?php
// modules/acmenote/src/Grid/NoteGridDefinitionFactory.php (read-only, imports omitted)
final class NoteGridDefinitionFactory extends AbstractGridDefinitionFactory
{
    public const GRID_ID = 'acme_note';

    protected function getId(): string
    {
        return self::GRID_ID;
    }

    protected function getName(): string
    {
        return $this->trans('Notes', [], 'Modules.Acmenote.Admin');
    }

    protected function getColumns(): ColumnCollection
    {
        return (new ColumnCollection())
            ->add((new BulkActionColumn('bulk'))->setOptions(['bulk_field' => 'id_note']))
            ->add((new DataColumn('id_note'))->setName('ID')->setOptions(['field' => 'id_note']))
            ->add((new DataColumn('content'))->setName('Note')->setOptions(['field' => 'content']))
            ->add((new ActionColumn('actions'))->setOptions([
                'actions' => (new RowActionCollection())->add(
                    (new SubmitRowAction('delete'))
                        ->setName('Delete')
                        ->setOptions(['route' => 'acme_note_delete', 'route_param_name' => 'noteId', 'route_param_field' => 'id_note'])
                ),
            ]));
    }

    protected function getFilters(): FilterCollection
    {
        return (new FilterCollection())
            ->add((new Filter('content', TextType::class))->setAssociatedColumn('content'));
    }

    protected function getBulkActions(): BulkActionCollectionInterface
    {
        return (new BulkActionCollection())->add(
            (new SubmitBulkAction('delete_selection'))
                ->setName('Delete selected')
                ->setOptions(['submit_route' => 'acme_note_bulk_delete'])
        );
    }
}

The query builder is where safety lives. The core hands you a criteria object with the filters, the sort column and direction, the offset and the limit. The builder must turn them into SQL without trusting them:

PHP
// modules/acmenote/src/Grid/NoteQueryBuilder.php (read-only, shortened)
public function getSearchQueryBuilder(SearchCriteriaInterface $criteria): QueryBuilder
{
    $qb = $this->connection->createQueryBuilder()
        ->select('n.id_note, n.content')
        ->from($this->prefix . 'acme_note', 'n');

    foreach ($criteria->getFilters() as $name => $value) {
        if ($name === 'content') {
            $qb->andWhere('n.content LIKE :content')
               ->setParameter('content', '%' . $value . '%');
        }
    }

    $qb->orderBy($criteria->getOrderBy(), $criteria->getOrderWay())
       ->setFirstResult($criteria->getOffset())
       ->setMaxResults($criteria->getLimit());

    return $qb;
}

Filter values go in as bound parameters, never concatenated. The sort column is a different story: a column name cannot be a bound parameter. In the core grid the allowed sort columns come from the definition (a column the employee can sort by is one you declared), but when you write queries yourself, compare the requested column against a fixed list. The stand-in below does that.

Rendering is a single Twig include of the grid panel, as in the template above. Bulk actions post the selected ids to the route you named; that route must check the permission and the token like any other write (see The Symfony Back Office).

A grid you can run

The real Grid is Symfony and Doctrine. The stand-in reproduces the flow with SQLite: a criteria object, a whitelist for sorting, bound parameters for filters, a count for the pager and a bulk delete. Nothing here is PrestaShop code; it exists to show what your query builder has to guarantee.

PHP Stand-in: a grid with filter, sort, paging and bulk delete

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The hostile sort column never reaches the SQL; the hostile filter matches nothing because it is only ever a value. The core Grid gives you much more (saved filter state, column visibility, row actions, export), but these two guarantees are yours in any query builder you write.

A form flow you can run

The second stand-in follows the form steps: default data for "new", stored data for an id, validation constraints, then create or update depending on the id. It is a plain PHP model of the roles, not Symfony Form.

PHP Stand-in: data provider, constraints and data handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that nothing is saved while errors exist, and that the same handler serves both screens: an empty id means "create", a given id means "update". That is the same contract as FormDataHandlerInterface.

When to use which tool

  • A settings page with a few options: a Symfony form plus a data provider/handler pair that read and write Configuration, or the older configuration page helpers.
  • A list of records: a Grid. Do not hand-write a table with its own paging and sorting; you would rebuild what the Grid already does and lose the consistent look and the saved filters.
  • A one-off report: a plain Twig page with a query is fine.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the form flow, which class answers 'what values does the form show for note 7'?

    The provider supplies the data of an existing record (getData) or the defaults for a new one (getDefaultData). The handler does the saving.
  2. 2. Why is a sort column not passed to the database as a bound parameter?

    Prepared statements bind values, not identifiers. A requested column name has to be compared with the columns you allow before it is placed in the query.
  3. 3. What does Twig's default behavior do with {{ note.content }}?

    Twig auto-escapes output, which prevents injected markup from running. Use |raw only for HTML you generated and trust.
  4. 4. Which part of a Grid is responsible for turning filters and sorting into SQL?

    The grid definition describes columns and actions; the query builder receives the search criteria and builds the safe query.
  5. 5. A bulk action 'Delete selected' posts to a route. What must that route still do?

    A bulk route is an ordinary write endpoint. It needs the same permission, token and input validation as any other.

Summary

  • Admin templates are Twig files extending the admin layout; output is escaped by default, text is translated with |trans.
  • A create/edit screen is a form type (fields and constraints), a data provider (defaults or stored values) and a data handler (create and update), tied together by core builder and handler services.
  • A list screen is a Grid: a definition factory (columns, filters, row and bulk actions), a query builder and a service registration.
  • Your query builder must bind filter values and whitelist the sort column; bulk routes must check permissions, token and ids.
  • Namespaces and service definitions vary by PrestaShop version, so copy them from the documentation of the version you target.

Next: The Webservice API