Hi
I have a custom js file in my custom module, which generates a 3-digit ID,

function genRand() {
  return Math.floor(Math.random()*899+100);
}

I would like to make this ID available in my webform, which I've created using the Webform 7.x-4.2 module.
My scenario is as such:
1. When a user opens a webform page, the js is loaded
2. The generated unique ID is passed automatically to the webform (preferably hidden from browser display)
3. When submitting the form, the ID is saved as well alongside the other data.

On a side note, will I get any issue with the user login form, since I do not want the ID to be loaded at any point in time there?

How can I achieve this?

Comments

waqarit’s picture

You can use Hook_FORM_ID_ALTER for this purpose and attach your JS with desired form.

lordrt21’s picture

Can you be more explicit on how to do this? This is the first time am having to do something like this.

vijaythummar’s picture

You can write something like below in hook_form_alter


  if ($form_id == 'webform_client_form_<n>') {

    $form['hidded_test'] = array(
      '#type' => 'hidden',
      '#title' => t('Hidden'),
      '#default_value' => '',
      '#attributes' => array('id' => array('hidded-test')),
    );

     drupal_add_js(
        'jQuery(document).ready(function(){
          jQuery("#hidded-test").val(Math.floor(Math.random()*899+100));
      });',
      'inline'
      );
  }

Thanks,
Vijay Thummar

lordrt21’s picture

thanks
Is there a way to make the form id a dynamic one in the code?

this part: if ($form_id == 'webform_client_form_<n>') {

waqarit’s picture

The form id is generated by the webform automatically and you will have to trace that what is the id of your form.

vijaythummar’s picture

If you don't want to hard code webform_id then you can make that variable as a configurable value through variable table.

Use system settings form and use that variable in code.

Thanks,
Vijay Thummar

lordrt21’s picture

Can you pls provide me with an example of doing so?

vijaythummar’s picture

Thanks,
Vijay Thummar

lordrt21’s picture

Using Vijay's inline jquery, how can I modify it to accept DDMMYYYY values before the random number? I tried adding a simple string value infront but got an error when running the code.

vijaythummar’s picture

Write something like


         drupal_add_js(
            'jQuery(document).ready(function(){
              var d = new Date();
              jQuery("#hidded-test").val(d.getDate()(d.getMonth() + 1)d.getFullYear()+"|"+Math.floor(Math.random()*899+100));
          });',
          'inline'
          );

Thanks,
Vijay Thummar

lordrt21’s picture

I've tried the new code, replacing the element id with mine, but am getting a blank value when inspecting with firebug:

<input id="form-gen-id" type="hidden" value="" name="Generated ID">