Symfony : Dynamic add select box ( Add Dynamically select Language )

前端 未结 1 902
灰色年华
灰色年华 2020-12-21 23:54

I\'m searching how to implement a system of choosing languages dynamically using form builder.

<script

相关标签:
1条回答
  • 2020-12-22 00:13

    I think you need a Collection of Forms.

    so we must have two html array inputs field : name="langues[]" and the second will be name="langes_level[]"

    (..)

    3- Twig Level: should i make some change in the twig as well?

    (..)

    4- Javascript Level, i can develop it when the inputs are clean created in the html.

    No, no and no. Describing how your 'array input fields' should be named exactly is not the right mentality if you're using a framework like Symfony. Describe your entity fields, describe your form fields and Symfony will give all form elements a name. Symfony Forms will render and handle the form for you, so there is (very likely) no need to be bothered what the form element names are exactly.

    Your entity class:

    class LanguageLevel
    {
        protected $user;
        protected $language;
        protected $level;
    
        //getters and setters
    }
    

    Create a form type:

    class UserType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('languages', CollectionType::class, array(
                'entry_type' => LanguageLevelType::class,
                'allow_add' => true,
            ));
        }
    }
    

    And a LanguageLevelType:

    class LanguageLevelType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
            ->add('language', LanguageType::class)
            ->add('level', ChoiceType::class, array(
                'choices'  => array(
                    'Good' => 5,
                    'Bad' => 1,
                 ),
            ));
        }
    }
    

    If the rendered output is not what you want, check the documentation if you can configure the Form Types. Manually changing the twig template, your controller and/or javascripts for a specific case is possible, but I think the 'Collection of Forms' from above will cover your use case.

    0 讨论(0)
提交回复
热议问题