在Symfony 4中动态访问表单数据

时间:2018-07-13 10:06:43

标签: forms symfony4

我已经在symfony 4中创建了以下简单形式。

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class)
        ->add('email', EmailType::class)
        ->add('message',TextareaType::class)
    ;
}

我从如下所示的控制器方法访问这些数据:

$form = $this->createForm(ContactType::class);
$form->handleRequest($request);
$formdata = $form->getData();

$concatenatedData = implode (",", array("Name: ".$formdata['name'], "E-mail: ".$formdata['email'], "Message: ".$formdata['message']));

现在我需要在表单中添加更多字段。在这种情况下,我需要遍历$ formdata并在$ concatenatedData中获得这些值。我是symfony的新手。任何人都可以给我任何提示,如何在symfony 4中动态地做到这一点? 预先非常感谢。

1 个答案:

答案 0 :(得分:0)

在表单类中定义后创建所需的类

class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name');
    $builder->add('price');
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => Content::class,
    ));
}
}

关注

$content = new Content();
$form = $this->createForm(ContactType::class, $content);
$form->handleRequest($request);
$formdata = $form->getData();

$content->getName();
$content->getOther();
...