PHP-Symfony 3:提交表单后设置值
作者:互联网
我有一个表单集合,并希望在提交表单后根据field1的值设置field2. field2在表单中不可编辑,但必填.
我尝试了每个FormEvent(FormEvents::),但收到错误消息:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘field2’ cannot be null
// 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 !!!
}
});
我究竟做错了什么?提前致谢!
解决方法:
试试这个代替
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);
}
});
标签:symfony,symfony-forms,php 来源: https://codeday.me/bug/20191118/2026629.html