如果表单无效,如何在提交后将 firstName 值更改为空字符串?
当我使用$form->get('firstName')->setData('');
时,它会给我
您无法更改已提交表单的数据。
在SUBMIT中同样的错误,在PRE_SUBMIT中,该值尚未知晓。
Symfony 2.8.4。它是我的简化代码:
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', TextType::class, [
'required' => false,
'attr' => ['maxlength' => 30,],
'constraints' => [
new NotBlank(),
new Length(array('min' => 5, 'max' => 30)),
],
])
->add('Submit', SubmitType::class, ['label' => 'Submit first name'])
->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$formData = $event->getData();
$form = $event->getForm();
if (!$form->isValid()) {
//$form->get('firstName')->setData('');
}
});
}
}
class DefaultController extends Controller
{
public function newAction(Request $request)
{
$defaultData = ['firstName' => 'John'];
$form = $this->createForm(TaskType::class, $defaultData);
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
return $this->redirectToRoute('app_homepage');
} else {
//$form->get('firstName')->setData('');
}
}
return $this->render('default/new.html.twig', array(
'form' => $form->createView(),
));
}
}