Skip to content

Instantly share code, notes, and snippets.

@benclark
Created January 21, 2013 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benclark/4590019 to your computer and use it in GitHub Desktop.
Save benclark/4590019 to your computer and use it in GitHub Desktop.
Example of how to take a textarea form element and explode it into an array before saving it to a variable via `system_settings_form()`.
<?php
/**
* @file
* Example of how to take a textarea form element and explode it into an array
* before saving it to a variable via `system_settings_form()`.
*/
/**
* Admin settings form.
*/
function D6MODULE_admin_settings_form() {
$form = array();
$form['D6MODULE_textarea_to_array'] = array(
'#type' => 'textarea',
'#value_callback' => 'D6MODULE_admin_textarea_to_array_value_callback',
'#element_validate' => array('D6MODULE_admin_textarea_to_array_validate'),
);
return system_settings_form($form);
}
/**
* Value callback for the `D6MODULE_textarea_to_array` field.
*/
function D6MODULE_admin_textarea_to_array_value_callback($element, $edit = FALSE) {
if (func_num_args() == 1) {
// No value yet, so use #default_value if available.
if (isset($element['#default_value']) && is_array($element['#default_value'])) {
// Convert to textarea value (key|value).
$joined_values = array();
foreach ($element['#default_value'] as $key => $value) {
$joined_values[] = "$key|$value";
}
return implode("\n", $joined_values);
}
return '';
}
return $edit;
}
/**
* Element validate callback for the `D6MODULE_textarea_to_array` field.
*/
function D6MODULE_admin_textarea_to_array_validate($element, &$form_state) {
if (!empty($element['#value'])) {
// Convert from textarea value to $values array.
$values = array();
foreach (explode("\n", trim($element['#value'])) as $value) {
// Format of the textarea is key|value.
list($key, $value) = explode('|', $value);
$values[trim($key)] = trim($value);
}
// Check that all $values are valid (optional).
if (!empty($values)) {
// This is an example validation routine that checks whether the contents
// of the array values reference valid CCK field names on a content type.
$type_name = 'page';
$type = content_types($type_name);
foreach ($values as $value) {
if (!isset($type['fields'][$value])) {
form_error($element, t('All CCK fields must be valid CCK fields on the %type node type.', array('%type' => $type_name)));
// Exit here on the first error found.
return;
}
}
// If no error, set the value on the element to the validated $values array.
form_set_value($element, $values, $form_state);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment