【发布时间】:2018-10-21 11:52:41
【问题描述】:
大家好,我有问题。我需要从实体类填充的 Select 字段中获取数据。
这是我的实体:它是包含月份、第一天和最后一天的字典。
实体
namespace accountant\ReportBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class Calendar
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="month", type="string", length=255)
*/
private $month;
}
我将此表加载到 db 并创建 formBuilder:
表单类型
class ReportFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('month','entity', array(
'class' => 'ReportBundle:Calendar',
'property' => 'month',
'expanded' => false,
'multiple' => false
));
}
}
现在我想获取所选月份到的数据,但$data 是null:
控制器
/**
* @Route("/report", name="report")
* @Template()
*/
public function indexAction(Request $request)
{
$form = $this->createForm(new ReportFormType());
$form->handleRequest($request);
$data = $form->getData();
var_dump($data); // $data is null!
return array('form' => $form->createView());
}
树枝
<form method="get" action="{{ path('report') }}">
<div class="form-group">
{{ form_row(form.month, {'label': 'Select Month:', 'attr': {'class': 'form-control'}}) }}
</div>
<div class="form-group">
<input type="submit" value="Show Report" class="btn btn-warning btn-block"/>
</div>
</form>
更新 1
我添加了“data_class”,但我仍然得到 NULL。
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('month','entity', array(
'class' => 'ReportBundle:Calendar',
'choice_label' => 'month',
'expanded' => false,
'multiple' => false,
));
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Calendar::class
));
}
现在这是我的控制器。
public function indexAction(Request $request)
{
$form = $this->createForm(new ReportFormType());
$form->handleRequest($request);
$data = $form->get('month')->getData();
// i check data
var_dump($data);
return array(
'form' => $form->createView());
}
更新 2
我解决了我的问题,为此我在模板中更改了我的表单:
<form method="post" action="{{ path('report') }}" novalidate="novalidate">
{{ form_errors(form) }}
<div class="form-group">
{{ form_row(form.month, {'label': 'Select month', 'attr': {'class': 'form-control'}}) }}
{{ form_rest(form) }}
</div>
<div class="form-group">
<input type="submit" value="Show report" class="btn btn-warning btn-block"/>
</div>
我将方法更改为post并添加form_rest
【问题讨论】:
-
主窗体需要配置data_class。
-
你的 Symfony 版本?
-
@Trix 2.7 和 7.2.7 php