简体   繁体   English

Symfony 3-数据库中的动态表单字段

[英]Symfony 3 - Dynamic form fields from database

I have a table in database with fields : - field_label, field_type, field_case etc 我在数据库中有一个表,其中包含以下字段 :-field_label,field_type,field_case等

I want to dinamically add fields to forms by field_case. 我想通过field_case将字段动态添加到表单中。

For exeample: In this form type I want to add all fields from database with field_case = 1 例如:在此表单类型中,我想使用field_case = 1添加数据库中的所有字段

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add("companie_uid", HiddenType::class);
    $builder->add("companie_denumire", TextType::class, array('label' => 'companie_denumire'));
    $builder->add("companie_cui", TextType::class, array('label' => 'companie_cui', 'required' => false));
    $builder->add("companie_j", TextType::class, array('label' => 'companie_j', 'required' => false));
    $builder->add("companie_mail", EmailType::class, array('label' => 'companie_mail', 'required' => false));
    $builder->add("companie_website", TextType::class, array('label' => 'companie_website', 'required' => false));
    $builder->add("companie_status", HiddenType::class);
    $builder->add("companie_descriere", TextAreaType::class, array('label' => 'companie_descriere', 'required' => false));
    $builder->add("companie_telefon", TextType::class, array('label' => 'companie_telefon', 'required' => false));
    $builder->add("companie_iban", TextType::class, array('label' => 'companie_iban', 'required' => false));
    $builder->add("companie_banca", TextType::class, array('label' => 'companie_banca', 'required' => false));
    $builder->add("file", FileType::class, array('label' => 'companie_file', 'mapped' => false, 'required' => false));
    $builder->add("save", SubmitType::class, array('label' => 'companie_save'));
    $builder->add(
        $builder->create('address', CompanyAddressType::class, Array('by_reference' => false,))
    );
}

And i want to add from table fields where field_case = 1 我想从表字段中添加其中field_case = 1

$builder->add(field_id, field_type, array('label' => 'field_label'));

And save them to database in another table field_values . 并将它们保存到另一个表field_values中的数据库中。

You can use a form listener 您可以使用表单侦听器

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
    $data = $event->getData();

    switch($data->getFieldCase())
    {
        case 1:
        $builder->add(field_id, field_type, array('label' => 'field_label'));
        break;
        // ...
    }    
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM