By dsdeiz on
Hi! I am trying to add an ip address field in the user profile form. Am I retrieving the value in the correct section?
/**
* Implementation of hook_form_alter()
*/
function mymodule_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'user_profile_form':
// Retrieve IP Address of User depending on the URL
$ip_addr = db_result(db_query('SELECT ip_addr FROM {table} WHERE uid = %d', arg(1)));
$ip_addr = (!empty($ip_addr)) ? $ip_addr : NULL;
$form['ip_profile'] = array(
'#type' => 'fieldset',
'#title' => t('IP Profile'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#weight' => 7,
);
$form['ip_profile']['ip'] = array(
'#type' => 'textfield',
'#title' => t('IP Address'),
'#value' => $ip_addr,
'#maxlength' => 15,
'#size' => 25,
);
$form['#validate'][] = '_validate_ip';
$form['#submit'][] = '_submit_ip_profile';
break;
}
}
Also the database doesn't seem to be updated. $form_state['values']['ip'] seems to be empty. I tried dsm($form_state) and $form_state['values']['ip'] was empty. Any things I should consider?
/**
* Add the ip address submitted to the ip profile db
*/
function _submit_ip_profile($form, &$form_state) {
if (db_result(db_query("SELECT COUNT(ip_addr) FROM {table} WHERE uid = %d", arg(1))) < 1) {
db_query("INSERT INTO {table} (uid, ip_addr) VALUES (%d, '%s')", arg(1), $form_state['values']['ip']);
drupal_set_message(t('IP Address set for the current profile.' . $form_state['values']['ip']));
} else db_query("UPDATE {table} SET ip_addr = '%s' WHERE uid = %d", $form_state['values']['ip'], arg(1));
}
Comments
---
I would rather use hook_user().
When
$opis equal to you add the form fields, when it is equal to you validate the user input, and when it is equal to you save the values in the form.See user_user() for an example of what a core module does.