spivurno
12/22/2018 - 2:51 AM

Gravity Perks // GP Populate Anything + GP Limit Choices

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 
) );