Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Using Symphony Forms Component with Grav

Started by Muut Archive 10 years ago · 3 replies · 489 views
10 years ago

It would be cool if we could use Symfony's forms component with Grav, in order to create more flexible forms.
Right now, I'm just trying to get it to work in a theme, but in the future there will be a standalone 'advanced forms' plugin.
So Far
composer require symfony/form

In the theme's main file
require_once __DIR__ . '/vendor/autoload.php';

I'm following the examples in the Symfony Book: https://symfony.com/doc/master/book/forms.html

Importing stuff

PHP
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

This runs when the onTwigSiteVariables event fires:

PHP
$formFactory = Forms::createFormFactory();

$form = $formFactory->createBuilder()
  ->add('task', TextType::class)
  ->add('dueDate', DateType::class)
  ->add('save', SubmitType::class, array('label' => 'Create Task'))
  ->getForm();

And a form object actually gets created. Hooray!

The Question

How do I actually render the form using:

TWIG
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

...in one of the theme's template files?

10 years ago

You need to expose those functions to Twig. For example see how the Comments plugin exposes the comments: https://github.com/getgrav/grav-plugin-comments/blob/develop/comments.php#L56-L64 or how Admin adds Twig filters (a similar approach is for Twig functions): https://github.com/getgrav/grav-plugin-admin/blob/develop/twig/AdminTwigExtension.php - https://github.com/getgrav/grav/blob/develop/system/src/Grav/Common/Twig/TwigExtension.php.

That said, Grav has a Form Plugin that could be extended with proposals to make it more powerful and flexible. What do you miss in it now?

10 years ago

I'll check out those examples.
There are two features that would make the Form plugin really great:

  1. The ability to output a form anywhere in a page (maybe with something like a short code, or twig function)
  2. Being able to add arbitrary HTML between the form inputs

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1354 9 years ago
Archive · by Muut Archive, 9 years ago
2 935 9 years ago
Archive · by Muut Archive, 9 years ago
2 4065 9 years ago
Archive · by Muut Archive, 9 years ago
1 2953 9 years ago
Archive · by Muut Archive, 9 years ago
3 1119 9 years ago