1 token_example.module token_example_example_form($form, &$form_state)

Form builder; display lists of supported token entities and text to tokenize.

Related topics

File

modules/examples/token_example/token_example.module, line 51
Hook implementations for the Token Example module.

Code

function token_example_example_form($form, &$form_state) {
  $config = config_get('filter.format.filtered_html', 'format');
  $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 entities.
      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'),
  );

  $form['token_tree'] = array(
    '#theme' => 'token_tree',
    '#token_types' => $token_types,
  );

  return $form;
}