I needed this button group to choose which details are supposed to be used for filtering in a search. That's why i had some helper attributes in my model called (sticking to the naming convention in these examples) $leftSearch, $middleSearch and $rightSearch.
I wanted the buttons to stay pushed in or out depending on the choice of the user (otherwise it would get confusing because the buttons would be unpressed after every refresh but the search attributes would be stored in the hidden fields, which the user does not see).
I achieved that using
'active' => ($model->leftSearch)?true:false,
Another thing was the data-value which would differ depending on what the user chose before submitting the page. That was done with:
'data-value' => ($model->leftSearch)?0:1,
The complete code in the view looks like this:
$this->widget('bootstrap.widgets.TbButtonGroup', array(
'type' => 'primary',
'toggle' => 'checkbox',
'buttons' => array(
array('label'=>'Left',
'active' => ($model->leftSearch)?true:false,
'htmlOptions'=>array(
'data-field' => 'Model_leftSearch',
'data-value' => ($model->leftSearch)?0:1,
),),
array('label'=>'Middle',
'active' => ($model->middleSearch)?true:false,
'htmlOptions'=>array(
'data-field' => 'Model_middleSearch',
'data-value' => ($model->middleSearch)?0:1,
),),
array('label'=>'Right',
'active' => ($model->rightSearch)?true:false,
'htmlOptions'=>array(
'data-field' => 'Model_rightSearch',
'data-value' => ($model->rightSearch)?0:1,
),),
),
));
echo CHtml::activeHiddenField($model, 'leftSearch');
echo CHtml::activeHiddenField($model, 'middleSearch');
echo CHtml::activeHiddenField($model, 'rightSearch');
The javascript stays exactly the same as what frostyterrier posted
Yii::app()->clientScript->registerScript('buttonGroup', "
$(function(){
$('.btn-group a').click(function(){
var fieldId = $(this).data('field');
var value = $(this).data('value');
$('#' + fieldId).val(value);
});
});
", CClientScript::POS_END);
The only thing i don't understand about the javascript part is that it works when inserted into the view as above, but doesn't work if included in some external .js file. I presume it has something to do with POS_END, but i'm no javascript expert.