好的,在深入研究 QuickForm 文档之后,我发现了这一点。解决方案是不使用数组填充选择小部件,而是手动构建选择元素将其添加到表单中。
最初,我有这个:
function dbArray( $tableName, $fieldName ) {
$query = <<< EOT
SELECT `id`, `$fieldName`
FROM `$tableName`
ORDER BY `$fieldName`
EOT;
$link = connectToDatabase();
$result = mysql_query( $query, $link );
while ( $rec = mysql_fetch_assoc( $result ) );
{
$array[$rec['id']] = $rec[$fieldName];
}
return $array;
}
function statesArray() {
return dbArray( 'states', 'name' );
}
$form = new HTML_QuickForm( 'account', 'POST' );
$form->addElement( 'select', 'state_id', 'State:', statesArray() );
在将数组返回到调用代码之前,我做了一个array( 'none' => 'Please select a State' )
预先添加到调用的版本dbArray
,但这并没有禁用该选项。添加规则以确认选择是数字是解决方法 ( $form->addRule( 'state_id', 'You must select a state.', 'numeric' )
)。但我仍然不喜欢它是可选择的。这是我找到的解决方案。
function statesSelect() {
$select = HTML_QuickForm::createElement( 'select' );
$select->addOption( 'Select a State', '', array( 'disabled' => 'disabled' ) );
$select->addOption( '-', '', array( 'disabled' => 'disabled' ) );
$statesArray = dbArray( 'states', 'name' );
foreach ( $statesArray as $id => $name ) {
$select->addOption( $name, $id );
}
return $select;
}
$form = new HTML_QuickForm( 'account', 'POST' );
$form->addElement( statesSelect() );
$form->addRule( 'state_id', 'You must select a state.', 'required' );
我希望这对其他人有帮助。:)