简体   繁体   中英

Symfony 3 - Dynamic form fields from database

I have a table in database with fields : - field_label, field_type, field_case etc

I want to dinamically add fields to forms by field_case.

For exeample: In this form type I want to add all fields from database with 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

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

And save them to database in another table 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;
        // ...
    }    
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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