Form Alter for Node Locations

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;
}
?>
Étiquettes:

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.

Poster un nouveau commentaire

  • Les adresses de pages web et de messagerie électronique sont transformées en liens automatiquement.
  • Tags HTML autorisés : <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Les lignes et les paragraphes vont à la ligne automatiquement.

Plus d'informations sur les options de formatage