How can I save an array of checkboxes in a wordpress widget?

I’ve created a widget and I need to allow the user to select from a series of options. The options are books coming from another table in the database.

I’m trying to use code like this:

Read More
<input type="text" name="<?PHP $this->get_field_name("books[]"); ?>">

However this fails when trying to save. Is it even possible to pass an array of options like this and save them? If not, what would be an alternative solution. I could pass values like this:

book1
book2
book3

If I do this I would have to have a loop in the update method go through all the books in the database to determine what is checked and what isn’t? I’m open to suggestions.

Related posts

Leave a Reply

2 comments

  1. I’d do something like this:

    First, store the options and pick them as an array:

    $options = get_option("pluginName_books");
    
    update_option("pluginName_books",$_REQUEST['books']);
    

    Use this as the field in your form:

    <input type="text" name="books[]" value="the_value">
    

    or to do it as a checkbox:

    <input type="checkbox" name="<?PHP $this->get_field_name("books[]"); ?>">
    
  2. Just had the same issue. I solved it by attaching the array part of my name tag outside of my get_field_name call:

    name="<?php echo $this->get_field_name( 'breakpoints' ); ?>[]"