Title: Widget forms
Last modified: August 20, 2016

---

# Widget forms

 *  [Workshopshed](https://wordpress.org/support/users/workshopshed/)
 * (@workshopshed)
 * [14 years, 11 months ago](https://wordpress.org/support/topic/widget-forms/)
 * All of the examples for the new 2.8 widgets have a rather bad coding technique
   for the form function. They switch back and forth between PHP and HTML which 
   won’t peform well and is difficult to spot errors.
 * To save myself some effort I put together some helper functions.
 *     ```
       public function form_input_text($field,$caption,$value) {
            printf ('<p><label for="%s">%s: <input class="widefat" id="%s" name="%s" type="text" value="%s" " /></label></p>',$this->get_field_id($field),esc_html__($caption),$this->get_field_id($field),$this->get_field_name($field),esc_attr($value));
           }
   
           public function form_input_option($field,$caption,$value,$options){
   
           foreach ($options as $option) {
               if ($option == $value) {$select = 'selected="selected"'; } else {$select = '';}
               $opthtml = sprintf('%s<option %s>%s</option>',$opthtml,$select,$option );
           }
           printf('<p><label for="%s">%s:</label><select id="%s" name="%s" class="widefat" >%s</select></p>',$this->get_field_id($field),esc_html__($caption),$this->get_field_id($field),$this->get_field_name($field),$opthtml);
           }
   
           public function form_input_checkbox($field,$caption,$value){
               if ($value) {
                   $checked = 'checked="checked"';
               }
               else{
                   $checked= '';
               }
               printf ('<p><input id="%s" class="checkbox" type="checkbox" name="%s" %s /><label for="%s"> %s</label></p>',$this->get_field_id($field),$this->get_field_name($field),$checked,$this->get_field_id($field),esc_html__($caption));
           }
       ```
   
 * Then your form code would become
 *     ```
       form_input_text('title','Title',$title);
           form_input_option('Option','Choose Option',$option,array ('Option 1','Option 2'));
           form_input_checkbox('Tick','Tick me',$checked);
       ```
   

The topic ‘Widget forms’ is closed to new replies.

## Tags

 * [Coding](https://wordpress.org/support/topic-tag/coding/)
 * [form](https://wordpress.org/support/topic-tag/form/)
 * [widget](https://wordpress.org/support/topic-tag/widget/)

 * 0 replies
 * 1 participant
 * Last reply from: [Workshopshed](https://wordpress.org/support/users/workshopshed/)
 * Last activity: [14 years, 11 months ago](https://wordpress.org/support/topic/widget-forms/)
 * Status: not a support question

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
