0

我有下面的代码来动态填充下拉字段:

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;
}

我正在使用带有函数 ibs_id 的 post 方法获取帖子的 id。该功能运行良好,但是当我单击输入无效的提交时(例如,我没有填写必填字段),下拉选择消失了。

我不得不提一下,其他用 ibs_id 函数动态填充以获取帖子 ID 的字段仍然被填充。

4

1 回答 1

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;
        }
于 2018-06-12T11:04:39.123 回答