【发布时间】:2016-03-02 03:23:37
【问题描述】:
对 Symfony 来说非常陌生,并且正在学习中。我只是挣扎如下:
在我的控制器类中,我想在提交后更新一些输入字段。函数'indexAction'的代码类似如下:
public function indexAction (Request $request) {
$myentity = new TestEntity();
$myentity->setField1 ('value1');
$form = $this->createForm (TaskType::class,$myentity);
$form->handleRequest ($request);
if ($form->isValid())
return $this->redirectToRoute ('nextPage');
else
{
// and here is my problem. I would like to set Field1 to 'value2',
// but I cannot, as the form is already submitted. Or with the
// following command directly setting the entity, the change is not
// taken into account anymore.
$myentity->setField1 ('value2');
}
return $this->render ('test.html.twig', array (
'form' => $form->createView());
}
Field1 是一个输入字段,如果第一次调用表单,我想将其设置为 value1。一旦我按下“提交”按钮(并且表单无效),应该会显示相同的表单,但随后将 Field1 设置为 value2。
想不通,关于如何实现上述。任何帮助表示赞赏。 非常感谢, 沃尔夫拉姆
【问题讨论】:
-
你能不能把
$myentity->setField1 ('value2');换成$form->get('field1')->setData('value'); -
我之前这样做过并收到消息:'您无法更改已提交表单的数据。'
-
我认为这是因为您的表单已经绑定到实体。表单已获取实体的数据,并且在实体更改时不会更新。使用
$form['field1']->setData( 'value2' ); -
不,不起作用。与上述相同的错误。
-
那么最好在
else部分重新创建整个表单。else { $myentity->setField1 ('value2'); $form = $this->createForm (TaskType::class,$myentity); }
标签: symfony