Using 4.6, I have a custom field group, and from that group a profile. It includes a State select dropdown and a Country select dropdown.

How would I go about "linking" the Country custom field to the State, so that when I change the country, it reloads the State, filtered by the country?

In older versions, adding the following script snippet with the specific custom field names worked fine, but it doesn't seem to work on 4.6:

<script language="JavaScript" type="text/javascript">


      countryID       = "#custom_122"
      stateProvinceID = "#custom_99"
      callbackURL     = "/civicrm/ajax/jqState"

  cj(countryID).chainSelect(stateProvinceID, callbackURL, null );


Well, after hunting around on my own, I think I may be able to answer my own question. For others who want to "link" a Profile's custom field Country to a custom field State so that changing the country automatically refreshes the list of States, I was able to do this via the civicrm_buildForm hook. This hook allows one to modify attributes of specific form elements, and that's all I needed to do.

As of 4.5, I think, the Country/State chaining interaction is done through data-callback and data-target attributes, not through a JS snippet. So, one way to make this work is to add those specific "data-" attributes to the custom fields via the hook.

Here is my example code (apologies for bad formatting). My State field is custom_99 and my Country field is custom_122. Once I applied the attributes, my team registration form finally worked as before; changing the Country updates the State list.

function xxx_civicrm_buildForm( $formName, &$form )
  if ( $formName == 'CRM_Event_Form_Registration_Register' ) {
    // Modify the classes/attributes for country and state fields so the country dropdown will dynamically update the state dropdown
    $form->updateElementAttr('custom_99', array('class' => 'crm-select2 crm-chain-select-target crm-form-select', 'data-callback' => 'civicrm/ajax/jqState', 'data-name' => 'custom_99', 'data-select-prompt' => '- select -', 'data-empty-prompt' => 'Choose country first', 'data-none-prompt' => '- N/A -'));
    $form->updateElementAttr('custom_122', array('class' => 'crm-select2 crm-chain-select-control crm-form-select', 'data-target="custom_99"', 'placeholder' => '- select -'));
} // end function

By the way, civicrm_buildForm is a pretty powerful hook, I use it to set defaults and required fields based on the Event Type and values of other custom fields.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.