Search code examples
drupal-7drupal-webform

How do I modify a token's value?


How do I modify a token's value? (See below for more info.)

function hook_webform_submission_insert($node, $submission) {
  // Total_points is a hidden input tag in a web form and initially set as 0.
  // Total points will be calculated here, and assigned to total_points.
  // $total_points = token_replace('[submission:values:total_points]', array("webform-submission" => $submission));

  // How do I modify a token value? e.g.
  $the_token = &drupal_get_token($name_of_token = '[submission:values:total_points]');
  $the_token = "100" // Assign 100 points.
}

  • After understanding the flow of code, I fixed the issue.
  • What I try to do is replace a hidden variable in webform, then use it webform2pdf.
  • If you have some text in the admin setting of webform2pdf. e.g. [submission:values:total_points]
  • Do $replacements['[submission:values:total_points]'] = my_value;
  • webform2pdf will see and insert the value of [submission:values:total_points] (i.e. my_value) in the generated pdf.
  • I realize that I can ask in forum and google the internet. At the end of day, I still need to dig into the code and understand it.

Solution

  • First off, drupal_get_token() is used to generate a value that protects against cross-site request forgeries. It is normally used when creating a link, which is what overlay_disable_message() does, for example.

          'query' => drupal_get_destination() + array(
            // Add a token to protect against cross-site request forgeries.
            'token' => drupal_get_token('overlay'),
          ),
    

    To alter a token like [submission:values:total_points], a module needs to implement hook_tokens_alter(). The code used by webform_tokens() can guide you on the code you should write.

    function mymodule_tokens_alter(array &$replacements, array $context) {
      if ($context['type'] == 'submission' && !empty($context['data']['webform-submission'])) {
        // $submission = $context['data']['webform-submission'];
        // $node = $context['data']['node'] ? $context['data']['node'] : node_load($submission->nid);
    
        // Find any token starting with submission:values.
        if ($value_tokens = token_find_with_prefix($context['tokens'], 'values')) {
          if (!empty($value_tokens['total_points'])) {
            $replacements[$value_tokens['total_points']] = 100;
          }
        }
      }
    }