【问题标题】:Symfony: update form fields after submitting the formSymfony:提交表单后更新表单字段
【发布时间】: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


【解决方案1】:

在您的表单中添加以下内容TaskType.php

public function buildForm(FormBuilderInterface $builder, array $options){
    //YOUR CODE
    $builder->addEventListener(FormEvents::POST_SUBMIT, 
         function (FormEvent $event) { 
           if(!$event->getForm()->isValid()){
             $event->getForm()->get('field1')->setData('value1'); 
           }
         });

【讨论】:

  • 好吧,它看起来并不在正确的位置。我打算修改我的控制器,而不是我的表单。不过,我无法运行此代码:Catchable Fatal Error: Argument 1 passed to AppBundle\Form\Type\TaskType::AppBundle\Form\Type\{closure}() must be an instance of AppBundle\Form\Type\FormEvent, instance of Symfony\Component\Form\FormEvent given
  • 你能把你的TaskType.php贴在这里吗?
【解决方案2】:
<?php
namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TaskType extends AbstractType
{
    public function buildForm (FormBuilderInterface $builder, array $options)
    {
        $builder
          ->add ('field1', TextType::class)
          ->add ('field2', TextType::class)
          ->add ('field3', TextType::class);
    }

    public function configureOptions (OptionsResolver $resolver)
    {
        $resolver->setDefaults (array (
          'data_class' => 'AppBundle\Entity\Task'
        ));
    }
}

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    相关资源
    最近更新 更多