开发者

Drupal form_submit and default_value

I have a simple form:

function mymodule_test_form(&$form_state, $nid) {
  form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Click me!',
  );
  $form['mymodule_status'] = array(
    '#type' => 'select',
    '#attributes' => array('class' => 'myclass'),
    '#default_value' => variable_get('mymodule_status', 0),
    '#options' => ar开发者_Python百科ray('one', 'two', 'three', 'four', 'five'),
  );
  return $form;
}

function mymodule_test_form_submit($form, &$form_state) {
  global $user;
  db_query("INSERT INTO {mymodule} (nid, uid, number, created) VALUES (%d, %d, %d, " . time() . ")", $nid, $user->uid, $status);
}

And in my node-contenttype.tpl.php file I print drupal_get_form('mymodule_test_form', $node->nid). BTW, is it the right way to print the drupal_get_form in the template? I tried adding the drupal_get_form to the hook_nodeapi view state, but nothing outputs, so I just ended up printing it in the template.

Another thing is the default value, I'm not sure how to use that. The variable_get always is 0. Do I need to create a custom query of my own and set that as my default value? I thought the default_value is automatically retrieved by drupal or something...

Hope I can get some help. Thanks.

Edit: Found out the node id is under: $form['#parameters'][2]


You use variable_get for accessing a value previously set with variable_set. So, variable_get isn't returning anything because there isn't a previously-set variable with the name mymodule_status. See http://api.drupal.org/api/function/variable_get/6.

I'm not sure, but it seems like you want the default value to be the status previously set by the user if that user has already set it. You'll need to do a query for that case.



function mymodule_test_form(&$form_state, $nid) {
  global $user;
  form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Click me!',
  );

  $query = "SELECT number FROM {mymodule} WHERE nid = %d AND uid = %d";
  $result = db_query($query, $nid, $user->uid);

  if ($result) $status = db_result($result);
  if ($status) $default_value = $status;
  else $default_value = 0;

  $form['mymodule_status'] = array(
    '#type' => 'select',
    '#attributes' => array('class' => 'myclass'),
    '#default_value' => $default_value,
    '#options' => array('one', 'two', 'three', 'four', 'five'),
  );
  return $form;
}

Also in your submit function, you need to reference $form_state['values']['mymodule_status'] instead of $status.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜