function 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 64

Code

function token_example_example_form($form, &$form_state) {
    $entities = entity_get_info();
    $token_types = array();
    // Scan through the list of entities for supported token entities.
    foreach ($entities as $entity => $info) {
        $object_callback = "_token_example_get_{$entity}";
        if (function_exists($object_callback) && ($objects = $object_callback())) {
            $form[$entity] = array(
                '#type' => 'select',
                '#title' => $info['label'],
                '#options' => array(
                    0 => t('Not selected'),
                ) + $objects,
                '#default_value' => isset($form_state['storage'][$entity]) ? $form_state['storage'][$entity] : 0,
                '#access' => !empty($objects),
            );
            // Build a list of supported token types based on the available entites.
            if ($form[$entity]['#access']) {
                $token_types[$entity] = !empty($info['token type']) ? $info['token type'] : $entity;
            }
        }
    }
    $form['text'] = array(
        '#type' => 'textarea',
        '#title' => t('Enter your text here'),
        '#default_value' => 'Hello [current-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 ($entities as $entity => $info) {
            if (!empty($form_state['storage'][$entity])) {
                $objects = entity_load($entity, array(
                    $form_state['storage'][$entity],
                ));
                if ($objects) {
                    $data[$token_types[$entity]] = reset($objects);
                }
            }
        }
        // Display the tokenized text.
        $form['text_tokenized'] = array(
            '#type' => 'item',
            '#title' => t('Result'),
            '#markup' => token_replace($form_state['storage']['text'], $data),
        );
    }
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
    );
    if (module_exists('token')) {
        $form['token_tree'] = array(
            '#theme' => 'token_tree',
            '#token_types' => $token_types,
        );
    }
    else {
        $form['token_tree'] = array(
            '#markup' => '<p>' . t('Enable the <a href="@drupal-token">Token module</a> to view the available token browser.', array(
                '@drupal-token' => 'http://drupal.org/project/token',
            )) . '</p>',
        );
    }
    return $form;
}