Skip to content

Instantly share code, notes, and snippets.

@thsutton
Created October 14, 2010 05:25
Show Gist options
  • Save thsutton/625623 to your computer and use it in GitHub Desktop.
Save thsutton/625623 to your computer and use it in GitHub Desktop.

Munge a form field into a multiple select (and back!)

This is a sample Drupal module that modifies an existing form field to display it as a multiple select without having to modify the handling code. As far as the form's "owner" is concerned, the user enters a comma-separated list of values.

The goal is, as you can probably tell from the $form_id, to turn a profile field into a multiple select of values from elsewhere. This is probably less than ideal, but I can't figure out a better way to achieve this.

<?php
/**
* Attempt to do strange things to the profile edit form.
*/
function munge_form_alter(&$form, &$form_state, $form_id)
{
if ('user_profile_form' == $form_id) {
$form['test']['profile_ids']['#process'] = array('munge_into_multiselect');
}
}
function munge_into_multiselect($element)
{
$data = array('one', 'two', 'miss', 'a few', '99', 'one hundred');
if (count($element['#post'])>0) {
// Turn it back into a text-field so that it'll save
$selected = $element['#value'];
$element['#value'] = implode(',', $selected);
} else {
// Turn it into a multiple select
$selected = explode(',', $element['#value']);
$element['#type'] = 'select';
$element['#multiple'] = TRUE;
$element['#options'] = $data;
$element['#value'] = $selected;
}
return $element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment