Created
May 2, 2017 03:19
-
-
Save brooke-heaton/080c22015049a33a591a06795d3cb250 to your computer and use it in GitHub Desktop.
Conditionally require Drupal 8 fields and subfields in an address webform
This file contains hidden or 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 | |
/** | |
* Implements hook_form_FORM_ID_alter(). | |
*/ | |
function mymodule_form_webform_submission_registration_form_alter(array &$form, FormStateInterface $form_state) { | |
// Show 'Country' as first field. | |
$form['elements']['personal_information']['address']['#country__weight'] = -2; | |
// Show 'State' next, but conditionally. | |
$form['elements']['personal_information']['address']['#state_province__weight'] = -1; | |
$form['elements']['personal_information']['address']['#city__weight'] = 0; | |
// If user selects 'United States' for Country, State and City fields are required. | |
$form['elements']['personal_information']['address']['#state_province__states'] = [ | |
'required' => [ | |
':input[name="address[country]"]' => ['value' => 'United States'] | |
], | |
]; | |
$form['elements']['personal_information']['address']['#city__states'] = [ | |
'required' => [ | |
':input[name="address[country]"]' => ['value' => 'United States'] | |
], | |
]; | |
$form['#attached']['library'][] = 'mymodule/registration_form'; | |
// Add custom validation to ensure City and State are filled out if Country is 'United States'. | |
$form['#validate'][] = '_mymodule_webform_submission_registration_form_validate'; | |
return $form; | |
} | |
/** | |
* Validates submission values in the FORM_ID() form. | |
*/ | |
function _mymodule_webform_submission_registration_form_validate($form, FormStateInterface $form_state) { | |
$values = $form_state->getValues(); | |
if (!empty($values['address']['country'] && $values['address']['country'] === 'United States')) { | |
if (empty($values['address']['city'])) { | |
$form_state->setErrorByName("address[city]", t('City is a required field for U.S. locations')); | |
} | |
if (empty($values['address']['state_province'])) { | |
$form_state->setErrorByName("address[state_province]", t('State is a required field for U.S. locations')); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment