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 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

    点赞 评论 复制链接分享

相关推荐