不使用Twig的Symfony表单

10

我已经成功地在我的项目中将Symfony表单设置为独立运行。但是,我只能通过Twig让它工作。是否有可能在没有Twig的情况下呈现这些表单?

我目前的做法是:

#Controller
echo $twig->render('index.html.twig', array(
    'form' => $form->createView(),
));

#Twig File
{{ form_widget(form) }}

是否有可能在不使用Twig的情况下呈现表单?

非常感谢任何帮助。


嗨,你能接受我的答案吗? - Michael Käfer
2个回答

3

如果不使用Twig和Symfony,关于如何使用Symfony的表单组件1)很难找到资源。

我猜这并不被推荐,但作为第一个起点,我自己构建了以下内容:

<?php

require 'vendor/autoload.php';

use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;

$form = Forms::createFormFactory()->createBuilder()
    ->add('firstname', TextType::class, ['label' => 'My firstname'])
    ->add('age', IntegerType::class, ['label' => 'My age'])
    ->getForm();

$form->handleRequest(); // Looks into superglobals and detects if the user submitted the form, if so it submits the form with $form->submit()

if ($form->isSubmitted() && $form->isValid()) {
    $data = $form->getData();
    var_dump($data);
}

$formView = $form->createView();

?>

<html>
    <body>
        <form
            action="<?php echo $form->getConfig()->getAction(); ?>"
            method="<?php echo $form->getConfig()->getMethod(); ?>"
        >
            <?php foreach ($formView->getIterator() as $field) { ?>

                <div>

                    <label
                        for="<?php echo $field->vars['id']; ?>"
                    >
                        <?php echo $field->vars['label']; ?>
                    </label>

                    <input
                        type="<?php echo $field->vars['block_prefixes'][1]; ?>"
                        id="<?php echo $field->vars['id']; ?>"
                        name="<?php echo $field->vars['full_name']; ?>"
                        value="<?php echo $field->vars['value']; ?>"
                    />

                    <?php if ($field->vars['required']) { ?>
                        <span>This field is required</span>
                    <?php } ?>

                </div>

            <?php } ?>

            <input type="submit" />
        </form>
    </body>
</html>

2

首先,您需要进入app/config并检查是否将php作为模板引擎包含在内。

templating:
    engines: ['php', 'twig']

以下是使用PHP渲染表单的其中一种方法:

echo $view['form']->form($form,array('attr' => array('class' => 'Form')));

在Symfony2官方网站上有很多关于渲染表单的示例。您可以像我的示例一样逐个字段地渲染,也可以渲染整个表单。


1
我正在使用在这里找到的独立库(https://github.com/bschussek/standalone-forms)。他在setup.php文件中明确加载了twig库。我是否可以不使用模板引擎来呈现表单? - Sajuna Fernando
1
我的建议是使用Symfony2的默认表单生成器,因为它有非常详细的文档,并且您可以在论坛中很容易地找到解决问题的答案。 - gprusiiski
2
作者询问如何在没有Symfony框架的情况下使用“独立”表单组件,而您的$view['form']->是Symfony助手... - Igor Mancos
除了表单之外,还有其他可用的方法,如start、widget、row和end:https://api.symfony.com/4.0/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.html - Stephane BEAUFORT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接