0

I am trying to save all of the options in a <select> element in a widget. So far I have the following PHP code for the form:

public function form( $instance ) {
    // Code for editing/adding title and adding IDs to the <select> object
    // ...

    <select class="widefat" id="<?php echo $this->get_field_id('ID_list'); ?>" name="<?php echo $this->get_field_name('ID_list'); ?>[]" multiple>
        <?php
            foreach( $instance['ID_list'] as $id )
            {
                echo '<option value="' . $id . '">' . $id . '</option>' . "\n";
            }
        ?>
    </select>
}

I also created a jQuery handler for the save button at the end of the form, which has the following code:

$('input#<?php echo $this->get_field_id('savewidget'); ?>').click( function( event ) {
     $('select#<?php echo $this->get_field_id('ID_list'); ?> option').prop('selected', true);
});

I then use the following code for the update function of the widget:

public function update( $new_instance, $old_instance ) {
     // Update the title, etc...
     $instance['ID_list'] = isset( $new_instance['ID_list'] ) ? $new_instance['ID_list'] : array();

     return $instance;
}

I was hoping that the $instance['ID_list'] would behave like the _POST('ID_list') would in a normal PHP form, and would be a sub-array containing all of the selected elements (in this case all the added IDs), however, this does not appear to happen; what is the idiomatic WordPress way of doing what I want to achieve?

Thanks in advance!

6
+50

I would remove the jQuery save function that was added... and then...

Try this for the form function:

public function form( $instance ) {
    // Code for editing/adding title and adding IDs to the <select> object
    // ...

    <?php
            printf (
                '<select multiple="multiple" name="%s[]" id="%s" class="widefat" size="15" style="margin-bottom:10px">',
                $this->get_field_name('ID_list'),
                $this->get_field_id('ID_list')
            );

            // Each individual option
            foreach( $instance['ID_list'] as $id )
            {
                printf(
                    '<option value="%s" %s style="margin-bottom:3px;">%s</option>',
                    $id,
                    in_array( $id, $instance['ID_list']) ? 'selected="selected"' : '',
                    $id
                );
            }

            echo '</select>';
}

Alright, try this update function:

   <?php
    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;
        $instance['ID_list'] = esc_sql( $new_instance['ID_list'] );
        $instance['title'] = esc_sql( $new_instance['title']);
        return $instance;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.