Search code examples
twitter-bootstrapcheckboxyiiyii-extensions

How to get value from bootstrap checkbox buttons in yii?


I am using the yii-bootstrap extension and wanted to use the checkbox button group. Rendering it is functioning without problems, but i have no idea how to read which button was checked and which not. Is there maybe a possibility to bind each checkbox to an attribute of the model?

This is what i used so far (it's actually the exact copy from the yii-bootstrap website):

<?php $this->widget('bootstrap.widgets.TbButtonGroup', array(
  'type' => 'primary',
  'toggle' => 'radio', // 'checkbox' or 'radio'
  'buttons' => array(
    array('label'=>'Left'),
    array('label'=>'Middle'),
    array('label'=>'Right'),
  ),
)); ?>

Solution

  • I checked out the source of TbButtonGroup and there doesn't seem to be a way of binding each checkbox to an attribute. However, you could use data attributes to link each button to a hidden field representing a model attribute. That's probably the next closest thing and probably also requires the least amount of code. Here's how you could do that:

    PHP: Requires that you have your model stored in a variable called $model. Place within form tags. Make sure jQuery is loaded.

    $this->widget('bootstrap.widgets.TbButtonGroup', array(
      'type' => 'primary',
      'toggle' => 'radio', // 'checkbox' or 'radio'
      'buttons' => array(
        array('label'=>'Left', 'htmlOptions' => array(
            'data-field' => 'Model_left',
            'data-value' => 1,
        )),
        array('label'=>'Middle', 'htmlOptions' => array(
            'data-field' => 'Model_middle',
            'data-value' => 2,
        )),
        array('label'=>'Right', 'htmlOptions' => array(
            'data-field' => 'Model_right',
            'data-value' => 3,
        )),
      ),
    ));
    echo CHtml::activeHiddenField($model, 'left');
    echo CHtml::activeHiddenField($model, 'middle');
    echo CHtml::activeHiddenField($model, 'right');
    

    In the code above, the word Model needs to be replaced with your model name and the words left, middle, right need to be replaced with your model's attributes. The data-value needs to be set to the value you want each button to represent.

    Javascript:

    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);
    

    Then you can just submit the form normally.