|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Gravity Perks // Nested Forms // Duplicate Child Entries via Gravity Flow Form Connector |
| 4 | + * https://gravitywiz.com/documentation/gravity-forms-nested-forms/ |
| 5 | + * |
| 6 | + * This snippet duplicates child entries when a new entry is created via the Gravity Flow Form Connector. |
| 7 | + * The Nested Form field must be mapped to the same child form on the source and target forms. |
| 8 | + */ |
| 9 | +add_action( 'gravityflowformconnector_post_new_entry', function( $entry_id, $entry, $form, $step_new_entry ) { |
| 10 | + |
| 11 | + if ( ! class_exists( 'GPNF_Entry' ) || ! function_exists( 'gp_nested_forms' ) ) { |
| 12 | + return; |
| 13 | + } |
| 14 | + |
| 15 | + $new_entry = GFAPI::get_entry( $entry_id ); |
| 16 | + |
| 17 | + // Loop through each field in the form |
| 18 | + foreach ( $form['fields'] as $field ) { |
| 19 | + |
| 20 | + // Check if it's a Nested Form field |
| 21 | + if ( $field->get_input_type() !== 'form' ) { |
| 22 | + continue; |
| 23 | + } |
| 24 | + |
| 25 | + $child_entries = ( new GPNF_Entry( $new_entry ) )->get_child_entries( $field->id ); |
| 26 | + if ( empty( $child_entries ) ) { |
| 27 | + continue; |
| 28 | + } |
| 29 | + |
| 30 | + $duplicated_child_entries = array(); |
| 31 | + |
| 32 | + // Duplicate the child entries and associate them with this new entry |
| 33 | + foreach ( $child_entries as $child_entry ) { |
| 34 | + |
| 35 | + $child_entry[ GPNF_Entry::ENTRY_PARENT_KEY ] = $new_entry['id']; |
| 36 | + $child_entry[ GPNF_Entry::ENTRY_PARENT_FORM_KEY ] = $new_entry['form_id']; |
| 37 | + $child_entry[ GPNF_Entry::ENTRY_NESTED_FORM_FIELD_KEY ] = $field->id; |
| 38 | + // @todo Add support for fetching Nested Form ID from target Nested Form field. |
| 39 | + //$child_entry['form_id'] = $field->gpnfForm; |
| 40 | + |
| 41 | + $duplicated_child_entry = GFAPI::add_entry( $child_entry ); |
| 42 | + $duplicated_child_entries[] = $duplicated_child_entry; |
| 43 | + } |
| 44 | + |
| 45 | + // Update Nested Form Field value on parent form to use the newly duplicated child entries. |
| 46 | + GFAPI::update_entry_field( $new_entry['id'], $field->id, implode( ',', $duplicated_child_entries ) ); |
| 47 | + |
| 48 | + } |
| 49 | +}, 10, 4 ); |
0 commit comments