diff --git a/gp-nested-forms/gpnf-sort-nested-form-entries.php b/gp-nested-forms/gpnf-sort-nested-form-entries.php new file mode 100644 index 000000000..154d8f1e7 --- /dev/null +++ b/gp-nested-forms/gpnf-sort-nested-form-entries.php @@ -0,0 +1,114 @@ +_args = wp_parse_args( $args, array( + 'parent_form_id' => false, + 'nested_field_id' => false, + 'sort_field_id' => false, + 'sort_order' => 'asc', + ) ); + + add_action( 'init', array( $this, 'init' ) ); + } + + public function init() { + add_filter( "gpnf_template_args_{$this->_args['parent_form_id']}_{$this->_args['nested_field_id']}", array( $this, 'sort_entries_php' ) ); + add_filter( 'gform_pre_render', array( $this, 'load_form_script' ), 10, 2 ); + } + + public function sort_entries_php( $args ) { + $field_id = $this->_args['sort_field_id']; + $order = strtolower( $this->_args['sort_order'] ); + + if ( isset( $args['entries'] ) ) { + usort( $args['entries'], function( $a, $b ) use ( $field_id, $order ) { + $first = rgar( $a, $field_id ); + $second = rgar( $b, $field_id ); + + if ( $first == $second ) { + return 0; + } + + if ( $order === 'asc' ) { + return ( $first < $second ) ? -1 : 1; + } else { + return ( $first > $second ) ? -1 : 1; + } + } ); + } + + return $args; + } + + public function load_form_script( $form, $is_ajax_enabled ) { + if ( $form['id'] == $this->_args['parent_form_id'] && ! has_action( 'wp_footer', array( $this, 'output_script' ) ) ) { + add_action( 'wp_footer', array( $this, 'output_script' ) ); + add_action( 'gform_preview_footer', array( $this, 'output_script' ) ); + } + + return $form; + } + + public function output_script() { + $args = array( + 'parentFormId' => (int) $this->_args['parent_form_id'], + 'nestedFieldId' => (int) $this->_args['nested_field_id'], + 'sortFieldId' => (int) $this->_args['sort_field_id'], + 'sortOrder' => strtolower( $this->_args['sort_order'] ), + ); + ?> + + + + 184, + 'nested_field_id' => 1, + 'sort_field_id' => 2, // field on child form to sort by + 'sort_order' => 'asc', // or 'desc' +) );