PLEASE NOTE: These forums are no longer utilized and are provided as an archive for informational purposes only. All support issues will be handled via email using our support ticket system. For more detailed information on this change, please see this blog post.

Populate data before submit

  1. Hi Guys,

    I'm trying to build a nice registration form where users receive a unique (autoincrement) username. Something like:

    t000001
    t000002
    etc..

    I use the pre-populate feature and have the following code in my functions.php

    <?php
    
    function populate_lidnummer($value){
    	global $wpdb;
    	$usernames = $wpdb->get_results("SELECT ID, user_url FROM $wpdb->users ORDER BY ID DESC LIMIT 1");
    
    	foreach ($usernames as $username) {
    		$lastuser = $username->ID;
    		$newuser_temp = $lastuser + 1;
    
    		$num = strlen($newuser_temp);
    		$max = 5;
    		$zeros = $max - $num;
    
    		return 't' . $newuser2 = str_repeat("0",$zeros)."".$newuser_temp;;
    	}
    }?>

    This is not ideal because when several people filling out the form there is a problem with the uniqueness of the username.

    Now i thought it might be easier to populate the field just before the users hitting the submit button on the registration page. So the most recent data is populated from the database.

    How can i do this?

    Posted 12 years ago on Sunday September 16, 2012 | Permalink
  2. Which hook or filter and using to call your function currently?

    Posted 12 years ago on Sunday September 16, 2012 | Permalink
  3. Hi Chris,

    Using the following line of code:

    add_filter("gform_field_value_lidnummer", "populate_lidnummer");

    Posted 12 years ago on Sunday September 16, 2012 | Permalink
  4. Do i need to use different filter?

    Posted 12 years ago on Monday September 17, 2012 | Permalink
  5. Assuming the field has checked "Allow this field to be populated dynamically" and it uses the parameter name of "lidnummer" this should work. Have you done both those things?

    However, your original question was about the uniqueness of this value. I don't know of a better hook to populate the field with. But instead of generating a number like this, you might need to assign numbers from a list, so that each number is used only once. Or, you might be able to check that the number does not exist by using the gform_validation_hook. Since it's nothing the user did wrong, you probably don't want to show an error to them, but just assign the next number, and repeat the process.

    The most foolproof method would be to read the number from a list of numbers and assign it like that. When you generate a number like this there are bound to be situations where you run into this problem.

    http://en.wikipedia.org/wiki/Race_condition

    Posted 12 years ago on Wednesday September 19, 2012 | Permalink