Tuesday, 15 February 2011

Drupal Form create & submits to database

<?phpfunction my_module_menu($may_cache) {
 
$items = array();
 
$items['my_module/form'] = array(
   
'title' => t('My form'),
   
'page callback' => 'my_module_form',
   
'access arguments' => array('access content'),
   
'description' => t('My form'),
   
'type' => MENU_CALLBACK,
  );
  return
$items;
}

function
my_module_form() {
  return
drupal_get_form('my_module_my_form');
}

function
my_module_my_form($form_state) {
 
$form['name'] = array(
   
'#type' => 'fieldset',
   
'#title' => t('Name'),
   
'#collapsible' => TRUE,
   
'#collapsed' =>true,
  );
$form['name']['first']=array('#type'=>'textfield','#title'=>t('sn'),'#size'=>56,

);
$form['name']['second']=array('#type'=>'textfield','#title'=>t('name'),'#size'=>64,

);

function
my_module_my_form_submit($form_id, $form_values){
$sn=$form_values['sn'];
$name=$form_values['name'];
db_query("INSERT INTO {test} (sn,name) VALUES ('%d', '%d')") ;drupal_set_message(t('your data is saved'));}

    
$form['submit']=array(
   
'#type' => 'submit',
   
'#value' => 'Submit',
      );



  return
$form;
  }
?>
while($row = db_fetch_array($inbound_recordset)){
$page_content .= drupal_get_form('_submit_inquiry_form', $row['inbound_id']);
}
And here is the form and submit handler
function _submit_inquiry_form(&$form_state, $inbound_id) {
$form['inbound_id'] = array(
    '#type' => 'hidden',
'#value' => $inbound_id,
    '#description' => t('inbound_id through the argument')
    );
$form['comment'] = array(
    '#type' => 'textarea',
    '#title' => t('Comments'),
    '#description' => t('Enter your query'),
/*'#required' => TRUE*/
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Place Inquiry')
    );
    return $form;
}

function _submit_inquiry_form_submit($form, &$form_state) {
global $user;
$fields=array(
$user->uid,
$form_state['values']['inbound_id'],
$form_state['values']['comment'],
);

$sql = "INSERT INTO {inquiry} (u_id, inbound_id, comment) VALUES (%d, %d, '%s')";
if(!db_query($sql, $fields)) {
drupal_set_message(t('Something went wrong, please try placing your inquiry again...'), "error");
} else {
drupal_set_message(t('We have received your inquiry and will get back to you.'));
}
}
function mymodule_form($form_state = array(), $op, $category = NULL) {
if (empty($category) || ($category_op == 'add') {
      $category = array(
       'category' => '',
      'mymodule_term' => '',
     'tid' => NULL
);
}
  $form['category_op'] = array('#type' => 'value', '#value' => $op);
  $form['category'] = array(
    '#type' => 'textfield',
'#title' => t(' Name of Category'),
'#size' => 60,
'#default_value' => $category['category'],
'#weight' => -10
);
   $form['mymodule_term'] = array (
    '#type'           => 'textarea',
    '#title'          => t('Term'),
    '#default_value'  => $category['mymodule_term'],
   '#description'    => t('Term for node. Separated by comma'),
   '#weight' => -9
  );

  $form['tid'] = array('#type' => 'value',
    '#value' => $category['tid'],
  );
  $form['submit'] = array('#type' => 'submit',
    '#value' => t('Save'),
  );

  return $form;
}
<?phpfunction user_save($account, $array = array(), $category = 'account') {
  // Dynamically compose a SQL query:  $user_fields = user_fields();
  if (is_object($account) && $account->uid) {
    user_module_invoke('update', $array, $account, $category);
    $query = '';
    $data = unserialize(db_result(db_query('SELECT data FROM {users} WHERE uid = %d', $account->uid)));
    // Consider users edited by an administrator as logged in, if they haven't    // already, so anonymous users can view the profile (if allowed).    if (empty($array['access']) && empty($account->access) && user_access('administer users')) {
      $array['access'] = time();
    }
    foreach ($array as $key => $value) {
      if ($key == 'pass' && !empty($value)) {
        $query .= "$key = '%s', ";
        $v[] = md5($value);
      }
      else if ((substr($key, 0, 4) !== 'auth') && ($key != 'pass')) {
        if (in_array($key, $user_fields)) {
          // Save standard fields.          $query .= "$key = '%s', ";
          $v[] = $value;
        }
        else if ($key != 'roles') {
          // Roles is a special case: it used below.          if ($value === NULL) {
            unset($data[$key]);
          }
          elseif (!empty($key)) {
            $data[$key] = $value;
          }
        }
      }
    }
    $query .= "data = '%s' ";
    $v[] = serialize($data);

    $success = db_query("UPDATE {users} SET $query WHERE uid = %d", array_merge($v, array($account->uid)));
    if (!$success) {
      // The query failed - better to abort the save than risk further data loss.      return FALSE;
    }

    // Reload user roles if provided.    if (isset($array['roles']) && is_array($array['roles'])) {
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $account->uid);

      foreach (array_keys($array['roles']) as $rid) {
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $account->uid, $rid);
        }
      }
    }

    // Delete a blocked user's sessions to kick them if they are online.    if (isset($array['status']) && $array['status'] == 0) {
      sess_destroy_uid($account->uid);
    }

    // If the password changed, delete all open sessions and recreate    // the current one.    if (!empty($array['pass'])) {
      sess_destroy_uid($account->uid);
      if ($account->uid == $GLOBALS['user']->uid) {
        sess_regenerate();
      }
    }

    // Refresh user object.    $user = user_load(array('uid' => $account->uid));

    // Send emails after we have the new user object.    if (isset($array['status']) && $array['status'] != $account->status) {
      // The user's status is changing; conditionally send notification email.      $op = $array['status'] == 1 ? 'status_activated' : 'status_blocked';
      _user_mail_notify($op, $user);
    }

    user_module_invoke('after_update', $array, $user, $category);
  }
  else {
    // Allow 'created' to be set by the caller.    if (!isset($array['created'])) {
      $array['created'] = time();
    }
    // Consider users created by an administrator as already logged in, so    // anonymous users can view the profile (if allowed).    if (empty($array['access']) && user_access('administer users')) {
      $array['access'] = time();
    }

    // Note: we wait to save the data column to prevent module-handled    // fields from being saved there. We cannot invoke hook_user('insert') here    // because we don't have a fully initialized user object yet.    foreach ($array as $key => $value) {
      switch ($key) {
        case 'pass':
          $fields[] = $key;
          $values[] = md5($value);
          $s[] = "'%s'";
          break;
        case 'mode':
        case 'sort':
        case 'timezone':
        case 'threshold':
        case 'created':
        case 'access':
        case 'login':
        case 'status':
          $fields[] = $key;
          $values[] = $value;
          $s[] = "%d";
          break;
        default:
          if (substr($key, 0, 4) !== 'auth' && in_array($key, $user_fields)) {
            $fields[] = $key;
            $values[] = $value;
            $s[] = "'%s'";
          }
          break;
      }
    }
    $success = db_query('INSERT INTO {users} (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $s) . ')', $values);
    if (!$success) {
      // On a failed INSERT some other existing user's uid may be returned.      // We must abort to avoid overwriting their account.      return FALSE;
    }

    // Build the initial user object.    $array['uid'] = db_last_insert_id('users', 'uid');
    $user = user_load(array('uid' => $array['uid']));

    user_module_invoke('insert', $array, $user, $category);

    // Build and save the serialized data field now.    $data = array();
    foreach ($array as $key => $value) {
      if ((substr($key, 0, 4) !== 'auth') && ($key != 'roles') && (!in_array($key, $user_fields)) && ($value !== NULL)) {
        $data[$key] = $value;
      }
    }
    db_query("UPDATE {users} SET data = '%s' WHERE uid = %d", serialize($data), $user->uid);

    // Save user roles (delete just to be safe).    if (isset($array['roles']) && is_array($array['roles'])) {
      db_query('DELETE FROM {users_roles} WHERE uid = %d', $array['uid']);
      foreach (array_keys($array['roles']) as $rid) {
        if (!in_array($rid, array(DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID))) {
          db_query('INSERT INTO {users_roles} (uid, rid) VALUES (%d, %d)', $array['uid'], $rid);
        }
      }
    }

    // Build the finished user object.    $user = user_load(array('uid' => $array['uid']));
  }

  // Save distributed authentication mappings.  $authmaps = array();
  foreach ($array as $key => $value) {
    if (substr($key, 0, 4) == 'auth') {
      $authmaps[$key] = $value;
    }
  }
  if (sizeof($authmaps) > 0) {
    user_set_authmaps($user, $authmaps);
  }

  return $user;
}
?>
 

No comments:

Post a Comment

Source base installation of php, mysql and apache in ubuntu/ linux

Compile and Install a LAMP(Linux/Apache/MySQL/PHP) Server from Source In the last post, I described the method to install a LAMP ser...