【发布时间】:2020-07-17 12:07:45
【问题描述】:
尝试为我的表单动态创建新字段,因为我正在从 3rd 方 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 );,但这对提交部分没有帮助,尽管它也在后端用新字段更新了我的表单。
有什么想法吗?
【问题讨论】:
-
需要注意的一点是,临时添加到表单中的字段(未保存在数据库中)也应在创建时设置
formId属性。将字段添加到$form['fields']数组是不够的。没有它,GF 无法“看到”提交的数据,即使它存在于$_POST。
标签: wordpress gravity-forms-plugin gravityforms