Drupal: How to make a form that captures a value from $_REQUEST[]
-
26-07-2021 - |
Domanda
This is a clone of: https://drupal.stackexchange.com/questions/47865/how-to-make-a-form-that-captures-a-value-from-request (currently no answers)
I have been trying to make a form that captures a value passed in from $_REQUEST
.
- A field is displayed only if a $_REQUEST variable exists (done)
- The user can modify the field
- The field is validated in whatever way
- The (modified) value gets used
In this specific case, I am using a hook_user
function, but I hope that the solution is applicable to any Drupal form.
Here's a simplified version of my code where the user would have an extra field to specify that they have a favorite fruit if they were to register using the following URL:
http://example.com/user/register?fruit=pineapple
function fruity_user($op, &$edit, &$user, $category = NULL){
switch($op) {
// Add extra fields if $_REQUEST contains values for them
case 'register':
if($_REQUEST['fruit'] == 'pineapple'){
$fields['user_reg_info']['profile_fruit'] = array(
'#type' => 'textfield'
,'#description' => 'Your favorite fruit (if applicable)'
,'#locked' => 0
,'#value' => $_REQUEST['fruit']
);
}
return $fields;
break;
// check registration for mistakes
case 'validate':
if ($edit['form_id'] == 'user_register') {
if ($edit['profile_fruit']){
verify_fruit($edit['profile_fruit']);
}
}
break;
// runs after the new user is inserted
case 'insert':
if($_REQUEST['fruit']){
db_query('INSERT INTO user_fruits SET `uid`=%d `fruit`="%s"',array($user->uid, $edit['profile_fruit']));
}
// record information
watchdog('user', t('user %user picked out a fruit',array('%user' => $user->name)));
break;
}
}
With the above code, the field does make itself visible only when $_REQUEST['fruit']
is present but if you change your fruit to "watermelon" on the form, insert
still uses "pineapple".
Soluzione 2
The answer was to use #default_value
instead of #value
.
http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/6#default_value
Altri suggerimenti
I think you are using two different keys while inserting and registering. You are using $fields['user_reg_info']['profile_fruit'] in register and $edit['fruit'] in insert. Try using ['fruit'] key in both the places. Also use the same in edit.