duangang79177 2018-06-22 10:47
浏览 53
已采纳

自定义表单不起作用

I am trying to customize my Form Rendering in Symfony 3.3.2 (https://symfony.com/doc/2.8/form/form_customization.html).

app/Resources/views/form/fields.html.twig

{% block test %}
  <p>TEST</p>
{% endblock %}

app/Resources/views/default/new.html.twig

{% form_theme form 'form/fields.html.twig' %}

{{ form_widget(form.age) }}
{{ block('test') }}

src/AppBundle/Controller/DefaultController.php

class DefaultController extends Controller
{
    public function indexAction(Request $request)
    {
      $test = new Test();
      $test->setAge(8);

      $form = $this->createForm(TestType::class, $test);

      return $this->render('default/new.html.twig', array(
      'form' => $form->createView(),
      ));
    }
}

src/AppBundle/Entity/Test.php

namespace AppBundle\Entity;

class Test
{
    protected $age;

    public function getAge()
    {
        return $this->age;
    }

    public function setAge($age)
    {
        $this->age = $age;
    }
}

src/AppBundle/Form/TestType.php

class TestType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('age')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => Test::class,
        ));
    }
}

app/config/config.yml

twig:
    debug: '%kernel.debug%'
    strict_variables: '%kernel.debug%'
    form_themes:
      - 'form/fields.html.twig'

I suppose than I misunderstood something because I expected to see an input with the 8 number in it and and below the string "TEXT", but insteed, I just have the input. So how insert a custom block in new.html.twig?

  • 写回答

1条回答 默认 最新

  • dsqpx86002 2018-06-22 10:55
    关注

    form_theme is not a way to include other blocks, it's just a style thing with some conventions. If you need to give style to a form, then you simply use the theme and form_widget. If you need to include some other block, create the block (in a separate file, or even in the same file) and choose between embed and include directive. For the difference between embed and include I would suggest to read this SO answer

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!