PHP生成HTML多选下拉框问题:缺失multiple属性求助
Let's break down what's going wrong here and walk through how to fix it:
First, looking at your generated HTML, there are two clear red flags:
- The
idyou set asproperty_featuregot incorrectly changed toproperty_feature[]— this is a bug in theselect_formmethod's parameter handling, where it's incorrectly syncing thenameattribute's suffix to theid. - Your
multiple => trueparameter isn't appearing in the final<select>tag at all, meaning the method isn't properly processing boolean-type attributes.
Step 1: Fix the missing multiple attribute
Many custom form-building functions struggle with boolean attributes like multiple. Instead of passing a boolean true, try passing the attribute as a string value (since HTML boolean attributes only need to exist to take effect):
$select_features = New_Options::select_form( Property_A::get_property_features( 'id' ), array( 'id' => 'property_feature', 'name' => 'property_feature[]', 'multiple' => 'multiple', // Swap boolean true for string value 'default' => esc_html__( 'Select', 'name-estate-agent' ), 'echo' => false, ) );
This is a common fix for form generators that expect explicit string values for attributes instead of boolean flags.
Step 2: Fix the corrupted id attribute
This issue lives directly in the New_Options::select_form method's code. You'll need to access that class file and inspect how it handles the id parameter:
- It's almost certainly taking the
namevalue (which includes[]) and incorrectly applying that suffix to theid— this is invalid HTML, asidattributes shouldn't contain square brackets. - Look for logic that auto-modifies the
idbased on thenameattribute, and remove or adjust that code to preserve your originalidvalue.
Bonus: Example of proper multiple handling if you control the select_form method
If you can edit the select_form function, add this logic to ensure boolean attributes like multiple are rendered correctly:
function select_form($options, $args) { $attr_string = ''; // Handle ID if (!empty($args['id'])) { $attr_string .= ' id="' . esc_attr($args['id']) . '"'; } // Handle Name if (!empty($args['name'])) { $attr_string .= ' name="' . esc_attr($args['name']) . '"'; } // Handle Multiple (supports both boolean true and string 'multiple') if (!empty($args['multiple']) && $args['multiple'] !== false) { $attr_string .= ' multiple'; // HTML5 shorthand, or use ' multiple="multiple"' for older standards } // Add other attribute handling here... // Build and return the full select element $select = '<select' . $attr_string . '>'; // Add options logic here... $select .= '</select>'; return $select; }
内容的提问来源于stack exchange,提问作者Marc Hughes

