how to use drupal_write_record. my db does not update when the form submits

advertisements

Im using drupal and im trying to create my own form in a block.

Ive wrote a module which creates a block with a submit button.

When the form is submitted im trying to write the values to my db.

im using this code

function my_module_my_form_submit($form, &$form_state) {
    block_example_insert_credits($credits_record);
}

function block_example_insert_credits() {
  global $user;
  $credits_record = array(
    'nid' => $node->nid,
    'uid' => $user->uid,
    'credits' => $form_state['values']['bids'],
  );
  drupal_write_record('example_table', $credits_record, 'nid');
}

the form submits and validates, and the table and columns exist in my db. When I submit the form nothing gets sent to database, why isnt my code correct?


There are a few things not quite right:

  1. You're not passing any parameters to block_example_insert_credits()
  2. You have no reference to $credits_record in my_module_my_form_submit() so nothing would be passed to the insert function anyway.
  3. You're trying to access $form_state from a function in which it doesn't exist
  4. You don't have a reference to the node object anywhere so you can't use it. $node isn't a globally available variable, if you want a node object it will have to come from a value save in your form or from the menu_get_object() function (if the block is being displayed on a node page).

Try this code and see if you have any luck:

function my_module_my_form_submit($form, &$form_state) {
  block_example_insert_credits($form_state);
}

function block_example_insert_credits($form_state) {
  global $user;
  $node = menu_get_object();
  $credits_record = array(
    'nid' => $node->nid,
    'uid' => $user->uid,
    'credits' => $form_state['values']['bids'],
  );
  drupal_write_record('example_table', $credits_record, 'nid');
}

Hope that helps.