Skip to content

Instantly share code, notes, and snippets.

@spivurno
Last active January 5, 2022 07:43
Show Gist options
  • Save spivurno/70ab25d52955829465e5c6136e8e127d to your computer and use it in GitHub Desktop.
Save spivurno/70ab25d52955829465e5c6136e8e127d to your computer and use it in GitHub Desktop.
Gravity Perks // GP Populate Anything + GP Limit Choices
<?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
) );
@claygriffiths
Copy link

@ivanfiosf
Copy link

ivanfiosf commented Jan 5, 2022

@claygriffiths

which fields should I make changes to? I'm starting and I had some doubts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment