Widget Form Loop Checkbox and Textbox Values
-
So I am trying to make a widget that grabs all post categories, and loops through to make a checkbox and textbox inputs for each category, see my code so far below:
$args = array( 'post_type' => 'post', 'taxonomy' => 'category', ); $terms = get_terms( $args ); foreach( $terms as $id => $name ) { $checked = ""; if(in_array($name->name,$instance['postCats'])){//check if category checkbox is checked and display as check if so $checked = "checked='checked'"; } echo = '<input type="checkbox" class="checkbox" id="'.$this->get_field_id('postCats').'" name="'.$this->get_field_name('postCats[]').'" value="'.htmlentities($name->name).'" '.$checked.'/> <label for="'.$this->get_field_id('postCats').'">'.$name->name.'</label><br />'; echo = '<input type="text" class="widefat" id="'.$this->get_field_id('postCatDI').'" name="'.$this->get_field_name('postCatDI[]').'" value="'.esc_attr("???What Goes Here???").'" /><br>'; }My problem is simply I can’t figure out what needs to go into the textbox value in order for the save to happen properly. I can get the checkboxes to save just fine, but the same method does not work for the textboxes.
One thing that I did try already was separating the two inputs into their own loops, but then I ran into issues where php complained about undefined offsets for any empty textboxes.
Any direction someone could give me would be great, thanks.
-
Ok, so I figured out that the textbox values were being saved, just not being displayed back on the form. so I added:
$value = ""; if (!empty($instance['postCatDI'][$catDIcount])) { $value = $instance['postCatDI'][$catDIcount]; }And then added $value to the textbox value.
Now my problem/confusion is in the database where this is all saved. For “postCats”, everything looks right, with only checked category names showing. But with “postCatDI” I get for example: “test01,,,test02,,” where all textboxes that weren’t filled in have an empty value in the database. This is an issue when I go to match these two inputs up, as the two arrays don’t share the same length.
How can I either add the empty values to the checkbox, or remove them from the textbox? Thanks again.Yeah, checkboxes are kinda annoying that way. You need to reprocess the the submitted data with code that knows all the available boxes and creates a boolean value for each that is then saved in the DB accordingly. A bit of a hassle, but it makes later processing easier when every box as an assigned value.
Thanks, I actually just got it working in a similar way. I added a [$catDIcount] to the end of the checkbox values that were saved, and then just used preg_split later in the actual widget() function to separate the category name and it’s index value, though your idea may have been a cleaner approach.
The topic ‘Widget Form Loop Checkbox and Textbox Values’ is closed to new replies.