Form Alter for Node Locations
Publié le 15 décembre, 2009 par Suzanne Kennedy
The location module is a key component to many Drupal projects, but it can be tricky to work with. It's very common to want to alter the way the location form appears, but the location module doesn't make this easy.
For example, we're working on a project with a North American focus, so locations have to be limited to Canada, the United States, and Mexico. So one of the requirements is to only allow users to select these countries when creating a new location.
While locations can't be edited like other fields, it's possible to alter it through the form's after_build property. All this requires is a regular form alter, plus an extra function to unset the unwanted form elements.
<?php
function ew_module_form_alter(&$form, $form_state, $form_id) {
switch($form_id) {
case 'location_node_form':
$form['#after_build'][] = 'remove_location_countries';
}
}
function remove_location_countries(&$form) {
//Remove all the countries from the select list
unset($form['location'][0]['country']['#options']);
//Add Canada, United States, and Mexico
$form['locations'][0]['country']['#options']['ca'] = t('Canada');
$form['locations'][0]['country']['#options']['mx'] = t('Mexico');
$form['locations'][0]['country']['#options']['us'] = t('United States');
return $form;
}
?>




Commentaires
Nice. But shouldn't the after_build function be called "remove_location_countries" to match the name of the function below?
Yes, that must have been a typo on my part. I've updated the code in the post.
Thanks a lot for this article. Finally a way for me to customize that form
Andreas
Thanks for the info on the the location module which is a key component to many Drupal projects, but as you said can be tricky to work with sometimes. The article has been helpful.
- Jeani Hantinia
Resume working on my Drupal projects.
Thanks for the info on the the location module which is a key component to many Drupal projects, but as you said can be tricky to work with sometimes. The article has been helpful.
Poster un nouveau commentaire