如何为Symfony 4“ ChoiceType”项标签添加类?

时间:2019-04-18 09:36:50

标签: html css symfony class label

我这里有四个单选按钮,我想为每个单选按钮标签添加一个CSS类。我怎样才能做到这一点?我尝试了两种方法,但都没有用:

尝试1:

        ->add('background', ChoiceType::class, ['label'=>'2. Dein Hintergrund: ', 
        //this adds class to the parent div
        'attr' => ['class' => 'label'],
        'choices'  => [
            1 => 1,
            2 => 2,
            3 => 3,
            4 => 4
        ], 'choice_value' => null,
        'expanded' => true,
        'multiple' => false,
        // this adds class to all radios/input elements
        'choice_attr' => function($choice, $key, $value){
            return ['class' => 'radio radio_'.($key)];
         },
         //this does NOT work, no error but it will not render a class to the label! Why?
         'label_attr' => function($choice, $key, $value){
            return ['class' => 'label'.($key)];
         },
        ])

尝试2:

 <div class="container">
   {{ form_label(form.background, {'attr': {'class': 'label'}}) }}
            {{ form_widget(form.background) }}
            <button class="button_main">Übernehmen</button>
        </div>

使用数字2时出现以下错误:

  

在呈现模板的过程中引发了异常(“注意:数组到字符串的转换”)。

我已经看过多次documentation,但无法弄清楚!

3 个答案:

答案 0 :(得分:1)

您需要自己实现模板:

    const connectToDB = async uri => {
   if (cachedDb) {
      return Promise.resolve(cachedDb);
   }
   return MongoClient.connect(config[STAGE].dbUrls[uri], { useNewUrlParser: true, useUnifiedTopology: true }).then(db => {
      cachedDb = db;
      return cachedDb;
   });
};

exports.handler = (event, context, callback) => {
   console.log("[Find All] [event] : ", event);
   context.callbackWaitForEmptyEventLoop = false;
   connectToDB('MONGODB_URI_FIND').then(database => {
      let db = database.db(config[STAGE].dbUrls.DB_NAME);
      console.log("db connection  ", db);
      fetchDataFromDb(db, event, callback);

   });
};

const fetchDataFromDb = (db, event, callback) => {
   const { table, query } = event;
   const options = { ...query.options };
   delete query.options;
   const { sortFields, limit, skip } = options || {};
   db.collection(table).find(query, options).sort(sortFields || {}).limit(limit || 999).skip(skip || 0).toArray((error, result) => {
      console.log("Fetched data[] : ", { error, result });
      if (error)
         callback(null, { body: error });
      else
         callback(null, { body: result });
   });
};

无法将您自己的类添加到 FormType 中的标签。

答案 1 :(得分:0)

您需要像this documentation

中那样创建自己的表单模板

答案 2 :(得分:0)

显然,您不能修改ChoiceType的选择标签的属性。此功能暂时不在Symfony核心中。请看看this