Symfony2: populating a select list from a yaml file

I have a multilingual site, and depending on the language I want the drop-down list to be selected with the category of the movie.

I want to manage my categories in a yaml file (categories.yml), for example

category: {en: Movies,de: Filme } {en: Series,de: Serien } {en: Cartoons,de: Zeichentrick } 

a category is a whole field in Movie Entity / Table

so i need to generate a dropdown like this

 <select> <option value="1">Movies</option> <option value="2">Series</option> <option value="3">Cartoons</option> </select> 

in the correct language text

how can i generate form element from yaml file? and for clean file management, where should it be placed? by resources / languages? or in the / config application?

+4
source share
2 answers

You can implement a selection list.

First update your form class so that your field implements choice_list with a new class that you create as follows:

 <?php namespace Acme\DemoBundle\Form; $builder ->add('myChoiceField', 'choice', array( 'choice_list' => new \Acme\DemoBundle\Form\ChoiceList\DemoChoice(), )) ; 

Then do \Acme\DemoBundle\Form\ChoiceList\DemoChoice :

 <?php namespace Acme\DemoBundle\Form\ChoiceList; use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList, Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList, Symfony\Component\Yaml\Parser; class DemoChoice extends LazyChoiceList { public function loadChoiceList () { // read the Yaml file, $data will be an array $yaml = new Parser(); $data = $yaml->parse(file_get_contents(__DIR__ . '/../Resources/config/data.yml')); // the keys of the array will be used as the option value // the values of the array will be used as the option text // ie: <option value="option-1">First Option</option> $choices = array( 'option-1' => 'First Option', 'option-2' => 'Second Option', ); return new SimpleChoiceList($choices); } } 
+2
source

You are better off using one yML file for each locale, just like translation files. For example, in messages.en.yml:

 category: movies: Movies series: Series cartoons: Cartoons 
0
source

Source: https://habr.com/ru/post/1399736/


All Articles