Skip to content

Instantly share code, notes, and snippets.

@mecachisenros
Created July 28, 2016 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mecachisenros/d0eec1f657ae0ee39f383a13a32e5ccd to your computer and use it in GitHub Desktop.
Save mecachisenros/d0eec1f657ae0ee39f383a13a32e5ccd to your computer and use it in GitHub Desktop.
<?php
add_filter( 'gform_pre_render', 'populate_civicrm_localization' );
add_filter( 'gform_pre_validation', 'populate_civicrm_localization' );
add_filter( 'gform_pre_submission_filter', 'populate_civicrm_localization' );
add_filter( 'gform_admin_pre_render', 'populate_civicrm_localization' );
function populate_civicrm_localization( $form ) {
foreach ( $form['fields'] as &$field ) {
// CIVICRM COUNTRY FIELD
// If field is dropdown and has class "civicrm-country" populate it with Civi data
if ( $field->type === 'select' && $field->cssClass === 'civicrm-country' ) {
// Initialize Civi
if ( !civi_wp()->initialize() ) return;
// Get Civi countries through API
$countries = civicrm_api3('Country', 'get', array(
'sequential' => 1,
'options' => array('limit' => 0),
));
// Prepare array to hold country data
$choices = array();
// Loop thorugh returned countries from Civi
foreach ( $countries['values'] as $key=>$country ) {
$choices[] = array( 'text' => $country['name'], 'value' => $country['id'] );
}
$field->placeholder = 'Select a Country';
$field->choices = $choices;
}
// CIVICRM STATE/PROVINCE FIELD
// If field is dropdown and has class "civicrm-state-province" populate it with Civi data
if ( $field->type === 'select' && $field->cssClass === 'civicrm-state-province' ) {
// Initialize Civi
if ( !civi_wp()->initialize() ) return;
// Get Civi state/provinces
// Prepare query
$query = "SELECT name,id,country_id FROM civicrm_state_province";
$dao = CRM_Core_DAO::executeQuery($query);
// Prepare array to hold state data
$states = array();
while ( $dao->fetch() ) {
$states[$dao->id] = array('name' => $dao->name, 'country_id' => $dao->country_id );
}
$choices = array();
// Loop thorugh returned states from Civi
foreach ( $states as $state_id=>$state ) {
// I dont't think the $field object supports 'attributes'
$choices[] = array( 'text' => $state['name'], 'value' => $state_id, 'attributes' => array( 'data-country-id' => $state['country_id'] ) );
}
$field->placeholder = 'Select a State/Province';
$field->choices = $choices;
}
}
return $form;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment