对于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。
无法弄清楚,关于如何实现上述目标。任何帮助赞赏。 非常感谢, 钨
答案 0 :(得分: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');
}
});
答案 1 :(得分:-1)
<?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'
));
}
}