TheWeightOfTheWorld
TheWeightOfTheWorld

Reputation: 25

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:

<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.

Upvotes: 2

Views: 3780

Answers (2)

Will Haynes
Will Haynes

Reputation: 758

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' ); ?>[]"

Upvotes: 1

James Thompson
James Thompson

Reputation: 1027

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[]"); ?>">

Upvotes: 2

Related Questions