我已经成功地在我的项目中将Symfony表单设置为独立运行。但是,我只能通过Twig让它工作。是否有可能在没有Twig的情况下呈现这些表单?
我目前的做法是:
#Controller
echo $twig->render('index.html.twig', array(
'form' => $form->createView(),
));
#Twig File
{{ form_widget(form) }}
是否有可能在不使用Twig的情况下呈现表单?
非常感谢任何帮助。
我已经成功地在我的项目中将Symfony表单设置为独立运行。但是,我只能通过Twig让它工作。是否有可能在没有Twig的情况下呈现这些表单?
我目前的做法是:
#Controller
echo $twig->render('index.html.twig', array(
'form' => $form->createView(),
));
#Twig File
{{ form_widget(form) }}
是否有可能在不使用Twig的情况下呈现表单?
非常感谢任何帮助。
如果不使用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>
首先,您需要进入app/config并检查是否将php作为模板引擎包含在内。
templating:
engines: ['php', 'twig']
以下是使用PHP渲染表单的其中一种方法:
echo $view['form']->form($form,array('attr' => array('class' => 'Form')));
在Symfony2官方网站上有很多关于渲染表单的示例。您可以像我的示例一样逐个字段地渲染,也可以渲染整个表单。