How to make Yii checkBoxList selected

How to make Yii checkBoxList selected

Many people find it hard to make the Yii checkBoxList selected on update view, but believe me in fact its very easy and straight forward. This post will help you in showing user’s last selection by showing them a preselected checkbox list.

Need help? You can Email me or Skype chat

I Suppose you have created a MANY_MANY relation as given below.

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)'),

Note: authorbook is the table name containing ids

Make a selected checkBoxList

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

checkBoxList function is taking three parameters.

  • Field name
  • Array of models ids those were previously selected
  • Options data

2nd parameter is important here, because it makes the checkBoxList selected.

Author: Tahir Yasin

Tahir is a Passionate Web Developer from Lahore, Pakistan and a guy with NEVER-STOP-LEARNING attitude who keeps an eye on emerging technologies and customer trends.

10 thoughts on “How to make Yii checkBoxList selected”

  1. I have a checkboxList that i am adding data to from with in a loop how can I add the value to the list item after i have set the text. I can’t bind a datatable to the control because I am getting text from 2 different columns and even then I can’t style the control the way that I would like. Is there any way to do this any help will be appreciated thanks.

  2. I have 3 checkbox lists that also have a textbox associated with them. it is a survey, and if “other” is not selected in the checkbox list then I want it to be disabled or greyed out so no information can be recorded in it. It has to be client side however, so I need to use javascript in my html.

    I also have the same scenario with a radio button list instead of a checkbox list. Any help would be greatly appreciated! If anyone can write some example code for me that would be awesome. Thanks guys.

    1. Make the textbox disabled by default and bind onclick event with `Other` checkbox/radiobutton. Inside the onclick event handler removed the disabled property of checkbox/radiobutton.

      I Hope this helps you.

  3. Pingback: Google

Leave a Reply

Your email address will not be published. Required fields are marked *