function token_example_example_form in Examples for Developers 6
Same name and namespace in other branches
- 7 token_example/token_example.module \token_example_example_form()
Form builder; display lists of supported token entities and text to tokenize.
Related topics
1 string reference to 'token_example_example_form'
- token_example_menu in token_example/
token_example.module - Implements hook_menu().
File
- token_example/
token_example.module, line 59 - The Token API module.
Code
function token_example_example_form($form_state) {
$entities = token_entity_info();
$token_types = array();
foreach ($entities as $entity_type => $info) {
$object_callback = "_token_example_get_{$entity_type}";
if (function_exists($object_callback) && ($objects = $object_callback())) {
$form[$entity_type] = array(
'#type' => 'select',
'#title' => $info['label'],
'#options' => array(
0 => t('Not selected'),
) + $objects,
'#default_value' => isset($form_state['storage'][$entity_type]) ? $form_state['storage'][$entity_type] : 0,
'#access' => !empty($objects),
);
// Build a list of supported token types based on the available entites.
if ($form[$entity_type]['#access']) {
$token_types[] = $entity_type;
}
}
}
$form['text'] = array(
'#type' => 'textarea',
'#title' => t('Enter your text here'),
'#default_value' => 'Hello [user-name]!',
);
// Display the results of tokenized text.
if (!empty($form_state['storage']['text'])) {
$form['text']['#default_value'] = $form_state['storage']['text'];
$data = array();
foreach (array_keys($entities) as $entity_type) {
if (!empty($form_state['storage'][$entity_type])) {
$object = token_entity_load($entity_type, $form_state['storage'][$entity_type]);
$data[$entity_type] = $object;
}
}
// Display the tokenized text.
$form['text_tokenized'] = array(
'#type' => 'item',
'#title' => t('Result'),
'#value' => token_replace_multiple($form_state['storage']['text'], $data),
);
// If raw tokens were used, escape the output and add a warning.
if (strpos($form_state['storage']['text'], '-raw') !== FALSE) {
$form['text_tokenized']['#value'] = check_plain($form['text_tokenized']['#value']);
$form['text_tokenized']['#description'] = t('Note that dangerous token results will still be filtered.');
}
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
$form['token_tree'] = array(
'#value' => theme('token_tree', $token_types),
);
return $form;
}