我是form collection
并希望在提交表单后设置field2
,具体取决于field1
的值。 field2
在表单中不可编辑,但必须。
我尝试了每个FormEvent
(FormEvents ::),但收到错误:
SQLSTATE [23000]:违反完整性约束:1048列' field2'不能为空
// AppBundle/Form/MyFormType.php
// ...
$builder->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $even) {
$data = $event->getData();
$form = $event->getForm();
if (isset($data['field1'])) { // isset
$field2 = $this->container->get('repository')->find($data['field1'])->getValue(); // service works
$data['field2'] = $field2; // !!! doesn't work !!!
$data->setField2($field2); // !!! doesn't work !!!
}
});
我做错了什么?提前谢谢!
答案 0 :(得分:3)
try this instead
use Symfony\Component\Form\FormEvents;
$builder->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (isset($data['field1'])) {
$field2 = $this->container->get('repository')->find($data['field1'])->getValue();
$data['field2'] = $field2;
$event->setData($data);
}
});