src/Twig/Functions/FormExtension.php line 47

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Twig\Functions;
  4. use Symfony\Component\Form\FormFactoryInterface;
  5. use Twig\Environment;
  6. use Twig\Error\LoaderError;
  7. use Twig\Error\RuntimeError;
  8. use Twig\Error\SyntaxError;
  9. use Twig\Extension\AbstractExtension;
  10. use Twig\TwigFunction;
  11. /**
  12. * Extension for showing forms globally
  13. *
  14. * @package App\Twig\Functions
  15. */
  16. class FormExtension extends AbstractExtension
  17. {
  18. private FormFactoryInterface $formFactory;
  19. /**
  20. * FormExtension constructor.
  21. *
  22. * @param FormFactoryInterface $formFactory
  23. */
  24. public function __construct(FormFactoryInterface $formFactory)
  25. {
  26. $this->formFactory = $formFactory;
  27. }
  28. /**
  29. * Create empty form
  30. *
  31. * @param Environment $twig
  32. * @param string $formName
  33. * @param string $template
  34. *
  35. * @throws LoaderError
  36. * @throws RuntimeError
  37. * @throws SyntaxError
  38. *
  39. * @return string
  40. */
  41. public function createForm(Environment $twig, string $formName, string $template): string
  42. {
  43. return $twig->render($template, ['form' => $this->formFactory->create($formName)->createView()]);
  44. }
  45. /**
  46. * Get twig functions
  47. *
  48. * @return array
  49. */
  50. public function getFunctions(): array
  51. {
  52. return [
  53. new TwigFunction(
  54. 'create_form',
  55. [
  56. $this, 'createForm'
  57. ],
  58. [
  59. 'is_safe' => ['html'],
  60. 'needs_environment' => true
  61. ]
  62. ),
  63. ];
  64. }
  65. }