WordPress.org

Ready to get started?Download WordPress

Forums

Adding multiple select data to widget database (3 posts)

  1. Allen
    Member
    Posted 1 year ago #

    I'm trying to what I thought was simple, namely use a select element in a form that allows for multiple selections, and add that information to a widget database. Here is the relevant code for the widget

    public function update( $new_instance, $old_instance ) {
    	$instance = array();
    	$instance['numoption[]'] = $new_instance['numoption[]'];
    	return $instance;
    }	
    
    	public function form( $instance ) {
    
    		$numoption =$instance['numoption[]'];
        ?>
    		<p>
    				<label for="<?php echo $this->get_field_id('numoption'); ?>"><?php _e('How many results displayed?'); ?></label>
    				<select name="<?php echo $this->get_field_name('numoption[]'); ?>" id="<?php echo $this->get_field_id('numoption'); ?>" class="widefat" multiple="multiple">
    					<option value="1">1</option>
    						<option value="2">2</option>
    						<option value="3">3</option>
    						<option value="4">4</option>
    						<option value="5">5</option>
    
    						<?php
    						}

    But here is what shows up in the database
    a:2:{i:4;a:1{s:11:"numoption[]";N;}s:12:"_multiwidget";i:1;}

    Any ideas how to make this work properly so that if you choose multiple selections they go in the database table?

    [Moderator Note: Please post code or markup snippets between backticks or use the code button. Or better still - use the pastebin. As it stands, your code may now have been permanently damaged/corrupted by the forum's parser.]

  2. michael.mariart
    Member
    Posted 1 year ago #

    This line is wrong:

    $instance['numoption[]'] = $new_instance['numoption[]'];

    It should be:

    $instance['numoption'] = $new_instance['numoption'];

    The [] after numoption is not valid. Removing that will give you the array that you want to get.

    For now that's all that I can see that stands out as not being correct. Just remember that in order to store an array of values like this in the database, it needs to be ran thorugh seralize() which makes it look like you've given here so that's completely normal.

  3. Allen
    Member
    Posted 1 year ago #

    Thanks Michael...turns out the main issue was this line

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

    that needed to be this

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

    and yes, the instances I had were wrong..thanks for pointing this out.

Topic Closed

This topic has been closed to new replies.

About this Topic