我有以下代码填充动态下拉字段:
add_filter( 'gform_pre_render_1', 'populate_dates' );
add_filter( 'gform_pre_validation_1', 'populate_dates' );
add_filter( 'gform_pre_submission_filter_1', 'populate_dates' );
add_filter( 'gform_admin_pre_render_1', 'populate_dates' );
function populate_dates( $form ) {
$post_id = ibs_id();
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-dates' ) === false ) {
continue;
}
$the_date = array();
$DatesArr = array();
for($i=0;$i<20;$i++)
{
$the_date[$i] = get_post_meta($post_id, 'date' . $i);
if(!empty($the_date[$i]))
{ array_push($DatesArr, $the_date[$i][0]); }
}
$choices = array();
foreach ( $DatesArr as $Date ) {
$choices[] = array( 'text' => $Date, 'value' => $Date);
}
$field->choices = $choices;
}
return $form;
}
我使用post方法使用函数ibs_id获取帖子的id。该功能工作正常,但当我点击提交时输入无效(例如我没有填写必填字段),下拉选项正在消失。
我必须提到其他用ibs_id函数动态填充以获取帖子ID的字段仍然填写。
答案 0 :(得分:0)
您需要使用isSelected
将其保留为已选中状态。检查以下完整代码。
function populate_dates( $form ) {
$post_id = ibs_id();
foreach ( $form['fields'] as &$field ) {
if ( $field->type != 'select' || strpos( $field->cssClass, 'populate-dates' ) === false ) {
continue;
}
$the_date = array();
$DatesArr = array();
for($i=0;$i<20;$i++)
{
$the_date[$i] = get_post_meta($post_id, 'date' . $i);
if(!empty($the_date[$i]))
{ array_push($DatesArr, $the_date[$i][0]); }
}
$choices = array();
foreach ( $DatesArr as $Date ) {
$isselected=false;
if($_POST['input_'.$field->id]==$Date) $isselected=true;
$choices[] = array( 'text' => $Date, 'value' => $Date,'isSelected' => $isselected );
}
$field->choices = $choices;
}
return $form;
}