simple_form、使うとform_forがすっきりするので良いですよね。
そんなsimple_formを使ってラジオボタンのラベルにクラスをつけようとすると、思いっきりはまって、「あれ、simple_form使えない…?」と思ってしまったのでメモ。
結果的にはsimple_formで解決しました。
github.com
※ viewテンプレートはSlimを使っています。
まず普通にラジオボタンを表示させるのであれば、下記のような書き方で問題なく表示されます。
= simple_form_for :sample, url: test_path, html: {method: :post, class: 'sample_form'} do |f|
p 2016年
= f.collection_radio_buttons :plans, plans.to_a, :first, :last
実際の表示↓
HTMLだとこんな感じです。
<form class="simple_form sample_form" novalidate="novalidate" action="/test" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓">
<input type="hidden" name="_method" value="post">
<input type="hidden" name="authenticity_token" value="AUTHENTICITY_TOKEN">
<p>2016年</p>
<span>
<label for="payment_plans_1">
<input type="radio" value="1" name="payment[plans]" id="payment_plans_1">
<label class="collection_radio_buttons" for="payment_plans_1">もう半分終わるらしい</label>
</label>
</span>
<span>
<label for="payment_plans_0">
<input type="radio" value="0" name="payment[plans]" id="payment_plans_0">
<label class="collection_radio_buttons" for="payment_plans_0">まだ半分あるらしい</label>
</label>
</span>
</form>
やりたいことはノーマルラジオボタンでなく、ラベルにクラスをつけて、独自のスタイルを適用することです。
この「ラベルにクラスをつける」方法がわからず、ドはまりしました。
いろいろと調べているうちに、StackOverflow内にて回答を発見。
blockを使えば良いらしい。
ruby - simple_form's collection_radio_button and custom label class - Stack Overflow
= simple_form_for :sample, url: test_path, html: {method: :post, class: 'sample_form'} do |f|
p 2016年
= f.collection_radio_buttons :plans, plans.to_a, :first, :last do |b|
- b.radio_button + b.label(class: 'sample_radio')
実際の表示↓
HTMLだとこんな感じです。
<form class="simple_form sample_form" novalidate="novalidate" action="/test" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓">
<input type="hidden" name="_method" value="post">
<input type="hidden" name="authenticity_token" value="AUTHENTICITY_TOKEN">
<p>2016年</p>
<span>
<label for="payment_plans_1">
<input type="radio" value="1" name="payment[plans]" id="payment_plans_1">
<label class="sample_radio" for="payment_plans_1">もう半分終わるらしい</label>
</label>
</span>
<span>
<label for="payment_plans_0">
<input type="radio" value="0" name="payment[plans]" id="payment_plans_0">
<label class="sample_radio" for="payment_plans_0">まだ半分あるらしい</label>
</label>
</span>
</form>
若干わかりにくいですが、無事、ラベルに「sample_radio」クラスが当たっています。
「item_wrapper_class
オプションでできるよ!」とか「input_html
オプションでいけるかも!」といったものを見たので色々試してみたのですが、あえなく全滅し、「simple_form全然シンプルじゃない!」と思って一瞬form_forに傾きかけました。
シンプルじゃないとか思ってスミマセン。