将Symfony4表单组件与Twig和Form Extension一起使用

时间:2018-09-26 17:15:07

标签: php symfony twig symfony4

我正在建立一个使用某些symfony组件作为基础的环境。

我想将Form组件用作带有Twig模板的应用程序的表单管理器。我安装:form,twig和twig_bridge

因为我的组件有限,所以我已经在Twig上注册了RuntimeLoader类来管理FormRenderer上的Form扩展依赖项。

按照文档中的说明,使用基本形式设置了简单的测试后:https://symfony.com/doc/current/forms.html,我收到此错误:

An exception has been thrown during the rendering of a template ("No block "form_start" found while rendering the form.").

我所有的工作都从这里开始

 //templating index.php
 $twigLoader = new \Twig_Loader_Filesystem( getcwd() . '/Templates' );
 $twig = new \Twig_Environment( $twigLoader );
 $twig->addRuntimeLoader( new RuntimeLoader( $twig ) );
 $twig->addExtension( new FormExtension() );

RuntimeLoader与在树枝文档中说明的类似:https://twig.symfony.com/doc/2.x/advanced.html#creating-an-extension 这用于兑现FormExender节点对FormRenderer类的依赖关系(Symfony Framework为此使用服务)

namespace Forge\UI;

use Twig\RuntimeLoader\RuntimeLoaderInterface;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;

class RuntimeLoader implements RuntimeLoaderInterface {

 private $twig;

 public function __construct( $twig ) {
  $this->twig = $twig;
 }

 public function load( $class ) {
  //var_dump( $class );
  if ( 'Symfony\Component\Form\FormRenderer' === $class ) {
   return new $class( new TwigRendererEngine( [ 'form.html.twig' ], $this->twig )     );
  }
 }
}

然后,在控制器类中,我将所有汤称为:

  $task = new Task();
  $task->setTask( 'Make somebody happy' );

  $form = $this->createFormBuilder( $task )
   ->add( 'task', TextType::class )
   ->add( 'save', SubmitType::class, [ 'label' => 'Create Task' ] )->getForm();

  $content = $this->renderView( 'form.html.twig', [ 'form'=>$form->createView() ] );

这会引发错误:

object(Twig_Error_Runtime)#258 (12) {
  ["lineno":"Twig_Error":private]=>
  int(1)
  ["name":"Twig_Error":private]=>
  string(14) "form.html.twig"
  ["rawMessage":"Twig_Error":private]=>
  string(122) "An exception has been thrown during the rendering of a template ("No block "form_start" found while rendering the form.")."
  ["sourcePath":"Twig_Error":private]=>
  string(58) "/var/www/../Templates/form.html.twig"
  ["sourceCode":"Twig_Error":private]=>
  string(0) ""
  ["message":protected]=>
   string(122) "An exception has been thrown during the rendering of a template ("No block "form_start" found while rendering the form.")."
  ["string":"Exception":private]=>
  string(0) ""
  ["code":protected]=>
  int(0)
  ["file":protected]=>
   string(58) "/var/www/../Templates/form.html.twig"
  ["line":protected]=>
  int(1)

错误的源路径是一个简单的树枝模板:

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

如何摆脱异常? P.s.我不想安装所有symfony软件包。

0 个答案:

没有答案