我刚刚开始使用symfony,我想知道在哪里编写代码以在php中使用表单输出。基本上我不知道如何使用表单的输出在代码中作为条目数据实现它。
这是index.html.twig文件
{% extends 'base.html.twig' %}
{% block body %}
<h1> Calculator prim</h1>
{{ include('_form.html.twig') }}
{% endblock %}
这是_form.html.twig
<form name="Prime" method="post" action="">
Write the number you want to check <input type="number" name="input"><br />
<input type="submit" name="submit" value="Verifica">
</form>
这是我的控制器
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\calculator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class ToDoController extends Controller
{
/**
* @Route("/todo")
*/
public function ListAction()
{
// replace this example code with whatever you need
return $this->render('todo/index.html.twig');
}
}
将使用数字的PHP代码:
<?php
namespace AppBundle\Entity;
class calculator
{
public function calculator($number)
{
if($num == 1 || $num == 0)
{
$value = True;
}
for ($i = 2; $i <= ($num/2); $i++)
{
if ($num % $i == 0)
{
$value= True;
}
}
if (isset($value) && $value)
{
echo "Numarul ". $num . ' nu este prim';
}
else
{
echo 'Numarul '. $num . ' este prim';
}
}
}
答案 0 :(得分:0)
我要使用Symfony 2.8,因为它是LTS。
好的,首先创建一个FormType:
class MyFormType extends Symfony\Component\Form\AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('name', 'text')
->add('save', 'submit')
->setMethod('post');
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults([
'data_class' => 'My\Entity';
]);
}
public function getName() { return 'some_demo_form'; }
}
请注意以下事项:
现在在service.yml
my.form.type:
class: MyFormType
tags:
- { name: form.type, alias: some_demo_form }
alias
必须等于表单类型的getName()
函数的返回值。
现在使用控制器中的表单:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller;
class SomeController extends Controller {
public function showAction(Request $request) {
$form = $this->createForm('some_demo_form', new My\Entity());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// process data
}
return $this->render('template.html.twig', [
'form' => $form->createView()
];
}
}
但是,实际上,这只是对Symfony CookBook中所写内容的细分:http://symfony.com/doc/current/forms.html