【问题标题】:Symfony2: populating select list from a yaml fileSymfony2:从 yaml 文件中填充选择列表
【发布时间】:2012-03-05 08:44:06
【问题描述】:

我有一个多语种电影网站,根据语言环境,我希望有一个包含电影类别的下拉选择。

我想在一个 yaml 文件 (categories.yml) 中管理我的类别,像这样

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

类别是一个整数字段,在MovieEntity/Table中

所以我需要像这样生成一个下拉列表

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

当然在正确的语言环境文本中

如何从 yaml 文件生成表单项?对于干净的文件管理,它应该放在哪里?在资源/语言下?还是在 app/config 下?

【问题讨论】:

    标签: forms symfony yaml


    【解决方案1】:

    您可以实现选择列表。

    首先,更新您的表单类,以便您的字段使用您接下来将创建的新类来实现 choice_list

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

    接下来,实现\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】:

      您最好为每个语言环境使用一个 yml 文件,就像翻译文件一样。 例如,在 messages.en.yml 中:

      category:
          movies: Movies
          series: Series
          cartoons: Cartoons
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多