[英]Using Symfony forms without Twig
I have managed to setup the symfony forms to work as standalone in my project. 我已设法将symfony表单设置为在我的项目中独立工作。 However i can only get it to work with twig.
但是我只能让它与树枝一起工作。 Is it possible for me to render the forms without twig?
我可以在没有树枝的情况下渲染表格吗?
The way i currently do it is: 我目前的方式是:
#Controller
echo $twig->render('index.html.twig', array(
'form' => $form->createView(),
));
#Twig File
{{ form_widget(form) }}
Is it possible to render the form without twig? 是否可以在没有树枝的情况下渲染表单?
Any help is greately appreciated 任何帮助都非常感谢
First you have to go to app/config and check if php is included as templating engine 首先,您必须转到app / config并检查是否包含php作为模板引擎
templating:
engines: ['php', 'twig']
And here is one of the ways to render form with php: 这是使用php渲染表单的方法之一:
echo $view['form']->form($form,array('attr' => array('class' => 'Form')));
There are plenty of examples for rendering forms in the symfony2 official site. 在symfony2官方网站上有很多渲染表单的例子。 You can render field by field or the full form as shown i my example.
您可以按字段或完整格式渲染,如我的示例所示。
It is hard to find resources about how to use Symfony's form component 1) without Twig and 2) without Symfony. 如果没有Twig和2)没有Symfony,很难找到有关如何使用Symfony的表单组件1)的资源。
I guess this is not recommended but I made this up for myself as a first starting point: 我想这不推荐,但我为自己做了第一个起点:
<?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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.