How to access form data in hook_form_validate() in drupal 7
Asked Answered
G

1

6

I have a form implemented from hook_form called simplequiz_form() I want to access its data after submit below is the code I have written but I can't seem to access its data once its submitted. What am I doing wrong ?

function simplequiz_form_validate($form, &$form_state) {
// here  is where we will validate the data and save  it in the db.
$thid = db_insert('simplequiz')
->fields(array(

'questions' => &$form_state['question'],
**I can't seem to access the value of a field questions** 

))
->execute();

 return $thid;
 }

Below is my implementation of hook_form()

function simplequiz_form($form, &$form_submit)
{ 

$form['question'] = array(
'#title' => t('Please input your question'),
'#type' => 'text_format',
'#required' => FALSE,
'#description' => t('Here is where you can enter your questions'),    
);

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

}

if I use $form_state['values']['question']

I get the below error:

PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1: INSERT INTO {simplequiz} (questions) VALUES (:db_insert_placeholder_0_value, :db_insert_placeholder_0_format); Array ( [:db_insert_placeholder_0_value] => [:db_insert_placeholder_0_format] => filtered_html ) in simplequiz_form_submit() (line 245 of /home/vishal/Dropbox/sites/dev/sites/all/modules/simplequiz/simplequiz.module).

it worked using $form_state['values']['question']['value']

Gabbert answered 24/11, 2011 at 6:16 Comment(0)
P
9

It's best practice to use hook_form_validate, just for validation purposes, anything other than validation should be done in hook_form_submit.

Either way they both function almost the same way.

All the form data is stored in $form_state['values'], so to access $form['questions'] values, just use $form_state['values']['questions'].

Pushbike answered 24/11, 2011 at 7:23 Comment(2)
it worked I had to change it a bit though $form_state['values']['question']['value']Gabbert
Just a remark: there is no hook_form_validate(). This is known as a "form validate handler".Onega

© 2022 - 2024 — McMap. All rights reserved.