Mr Goobri
Mr Goobri

Reputation: 1469

Yii: How to get list of checkboxes?

I have a table called Table, it has id and name as attributes.

For each entry in Table, I would like to generate a checkbox.

How can I do this?

I am using the Yii-Boostrap plugin, which I'm expecting I would need use something like this:

foreach(...)
    echo $form->checkBoxRow($model, 'name');

Which I got from the Yii-Bootstrap Documentation.

Upvotes: 0

Views: 4766

Answers (3)

Sarvar Nishonboyev
Sarvar Nishonboyev

Reputation: 13090

Check this example:

Book Model:

'authors' => array(self::MANY_MANY, 'Author', 'authorbook(book_id,author_id)'),

Author Model:

'books' => array(self::MANY_MANY, 'Book', 'authorbook(author_id, book_id)'),

Checkbox List in form:

$books = CHtml::listData(Book::model()->findAll(), 'id', 'name');
$selected_keys = array_keys(CHtml::listData( $model->books, 'id' , 'id'));
echo CHtml::checkBoxList('Author[books][]', $selected_keys, $books);

Upvotes: 0

Ninad
Ninad

Reputation: 1871

Try this simple one

And in this for precheck to work just pass the array as second parameter as shown below

<?$select=array('2','3');?>

<?php echo CHtml::checkBoxList(
        'TableValues',
        '$select',//you can pass the array here which you want to be pre checked 
        CHtml::listData(Table::model()->findAll(),'id','name'),
        array('checkAll'=>'Select all tasks', 'checkAllLast'=>true)
    ); ?>

And you can get the selected checkbox values in the controller using

 print_r($_POST['TableValues']);

UPDATED

For this the precheck to work u have to assign the array to the model attribute as shown below

<?php $model->modelAttributename=array('3','5')//respective checked values as of yours 

<?php echo $form->checkBoxList(
            $model,
            'modelAttributename',
            CHtml::listData(Table::model()->findAll(),'id','name'),
            array('checkAll'=>'Select all tasks', 'checkAllLast'=>true)
        ); ?>

Upvotes: 4

cavaliercyber
cavaliercyber

Reputation: 234

You should see your result array form sql query and see how to access any string you want from result array and then you create array of string that contain list of name. e.g. your result query is $result["name"] = array("a","b","c");

<?php /** @var BootActiveForm $form */
    $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
    'id'=>'horizontalForm',
    'type'=>'horizontal',
    ));
?>    
<fieldset>

<legend>Legend</legend>

<?php    
    $result["name"] = array("a","b","c");     
    echo $form->checkBoxListRow($model, 'checkboxes', $result["name"]);
?>

</fieldset>

Upvotes: 0

Related Questions