WordPress-重力形式-动态创建字段

时间:2020-04-05 13:59:30

标签: wordpress gravity-forms-plugin gravityforms

当我从第三方API获取json时,尝试为表单动态创建新字段。基于此json,我需要在表单中添加一些字段-不是固定数字。因此,我正在执行此操作,将其挂接到gform_pre_render上:

add_filter( 'gform_pre_process', 'create_products_gforms' );
add_filter( 'gform_admin_pre_render', 'create_products_gforms' );
add_filter( 'gform_pre_render', 'create_products_gforms' );
function create_products_gforms( $form ) {

    $helper = new NSHelper();
    $state_name = $_POST['input_7'] ?? '';

    $code_value = $helper->get_state_code_by_name( $state_name );

    // Only fetch products if current form id is 33, state code is defined
    // and if there are products for this state.

    if ( $form['id'] != 33 || !$code_value ) {
       return $form;
    }

    // Get product list from NetSuit API based on state code
    $products_json_data = get_products_data( $code_value );

    $products = json_decode( json_decode( $products_json_data ) );

    $new_field_id = 0;
    foreach( $form['fields'] as $field ) {
        if( $field->id > $new_field_id ) {
            $new_field_id = $field->id;
        }
    }

    $new_field_id++;

    foreach ( $products as $product_object ) {
        // Prepare field properties
        $props = array(
            'id'        => $new_field_id,
            'type'      => 'singleproduct',
            'label'     => $product_object->onlinedisplayname,
            'basePrice' => floatval( $product_object->price ),
            'enableCalculation' => true
        );

        // Create new gravity forms field and add it to the form object
        $nf = GF_Fields::create( $props );

        // Hack - insert into array at specific position
        // Needed to display product fields before other fields
        // in the form
        array_splice( $form['fields'], 11, 0, array($nf) );

        $new_field_id++;
    }

    GFAPI::update_form( $form );

    $form['dynamic_fields_ids'] = $added_fields_ids;

    return $form;
}

这有效,即,它在前端正确显示了字段。现在,问题在于,提交表单后,除了这些动态添加的字段外,所有其他字段都在提交中。但是这些不是。我认为必须这样做,因为这些字段未在表单中注册,因此我也尝试了GFAPI::update_form( $form );,但这对提交部分没有帮助,尽管它也会在后端添加新字段来填充我的表单。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

根据您的用例Milos,我建议使用gform_form_post_get_meta过滤器:

https://docs.gravityforms.com/gform_form_post_get_meta/

这将在每次从数据库中获取表单时触发,并且会出现最肯定的保证您的字段的方式。

如果您希望更外科手术并坚持使用gform_pre_render方法,则可以将相同的功能应用于其他几个过滤器:

gform_pre_process
gform_admin_pre_render