Last active
January 5, 2022 07:43
-
-
Save spivurno/70ab25d52955829465e5c6136e8e127d to your computer and use it in GitHub Desktop.
Gravity Perks // GP Populate Anything + GP Limit Choices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class GW_Limit_Populated_Choices { | |
public function __construct( $args = array() ) { | |
// set our default arguments, parse against the provided arguments, and store for use throughout the class | |
$this->_args = wp_parse_args( $args, array( | |
'form_id' => false, | |
'field_id' => false, | |
'choice_limit' => false, | |
) ); | |
// do version check in the init to make sure if GF is going to be loaded, it is already loaded | |
add_action( 'init', array( $this, 'init' ) ); | |
} | |
public function init() { | |
$this->set_limit_on_populated_choices(); | |
} | |
function set_limit_on_populated_choices() { | |
if( is_callable( 'gp_limit_choices' ) ) { | |
add_filter( "gform_pre_process_{$this->_args['form_id']}", array( $this, 'enable_limits' ) ); | |
add_filter( "gppa_input_choices_{$this->_args['form_id']}_{$this->_args['field_id']}", array( $this, 'apply_limits'), 10, 2 ); | |
} | |
} | |
public function enable_limits( $form ) { | |
foreach( $form['fields'] as $field ) { | |
if( $field->id == $this->_args['field_id'] ) { | |
$field->{gp_limit_choices()->key( 'enableLimits' )} = true; | |
} | |
} | |
return $form; | |
} | |
public function apply_limits( $choices, $field ) { | |
foreach( $choices as &$choice ) { | |
$choice['limit'] = $this->_args['choice_limit']; | |
} | |
$choices = gp_limit_choices()->apply_choice_limits( $choices, $field, GFAPI::get_form( $field->formId ) ); | |
return $choices; | |
} | |
} | |
# Configuration | |
new GW_Limit_Populated_Choices( array( | |
'form_id' => 123, | |
'field_id' => 4, | |
'choice_limit' => 1 | |
) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@claygriffiths
which fields should I make changes to? I'm starting and I had some doubts.