Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Submitted Post values in Drupal 7

I'm having problems accessing the posted values after a form submission with Drupal 7.

Say I have a simple form with one text field and a submit button.

function sample_form($form, &$form_state){
  $form['sample']['name'] = array(
  '#description' => 'Name',
  '#value' => 'Name',
  '#type' => 'textfield',
  );
 $form['sample']['sample_submit'] = array(
   '#type' => 'submit',
   '#value' => 'SUBMIT',
   '#submit' => array('sample_form_submit')
 );
}

and then my submit handler, which is meant to display the value the user entered in the textfield.

function sample_form_submit($form, &$form_state){
  drupal_set_message($form_state['values']['name']);
}

However, the message always contains the default value for the textfield, in this case 'name'. If I enter "Mike" and hit submit, the message displays "name" (the default value).

How can I get at the submitted values? I know I can access with

$form_state['input']['name']

but my understanding is that the above gives me the raw, unsanitized $_POST data.

I need the user entered value, how can I get this? I'm really unclear about the process of getting user submitted data using the drupal forms API.

Thanks for any help!

like image 450
John Avatar asked Aug 28 '26 02:08

John


1 Answers

It's because you're using #value instead of #default_value for the text field. Using the former will always overwrite the value provided by the user. You just need to change your code to this:

function sample_form($form, &$form_state){
  $form['sample']['name'] = array(
    '#description' => 'Name',
    '#default_value' => 'Name', // <-- Change made here
    '#type' => 'textfield',
  );

  $form['sample']['sample_submit'] = array(
    '#type' => 'submit',
    '#value' => 'SUBMIT',
    '#submit' => array('sample_form_submit')
  );
}

This is only true for elements that actually take in an inputted value. For example, #value is still the correct key to use for hidden inputs, submit buttons etc. Select lists, checkboxes, etc. will also need to use #default_value or you'll never get the user submitted data.

Check out the Drupal FAPI for reference in case you haven't seen it.

like image 109
Clive Avatar answered Aug 29 '26 15:08

Clive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!