views:

39

answers:

1

Hello Everyone,

I am creating a form where i have to populate "X" form elements (text-fields to be specific) based on values in the database (X number of elements, properties of each element etc). Is there a way to do this using the Drupal Form API or should i start from somewhere else. I tried using a for() loop in the form generating function but this doesn't work. Please post you suggestions and any related links.

+1  A: 

sure you can, just put the #default_value with the value coming from the DB.

$form['text'] = array(
  '#type' => 'textfield',
  '#default_value' => $db->val,
);

EDIT say you have a questionnaire object ($questionnaire) that contains a param named "question_list" where you have stored all your questions; what you can do is run a foreach on the list like:

$form['questionnaire'] = array('#type'=>'fieldset','#title'=>$questionnaire->title,);

foreach($questionnaire->question_list as $id=>$question_obj){
 $form['questionnaire']['question_'.$id]=array(
 '#type'=>'textfield',
 '#title'=>$question->question,
 '#default_value'=>$form_state['values']['question_'.$id],
 );

}

At the end you will have an associative array where each question is identified by 'question_'.$id

I hope this is what you're looking for. :)

Bladedu
Thanks for the answer, but what i am looking for is to create a certain "number" of form elements, where the number is pulled from the database. Say I have a questionnaire, where the questions are stored in a DB, now the page needs to generate a text field for each of these questions( #number of questions, #question attributes are in DB). Can we do this using the Form API?
Mahesh Marisetti
Edited my answer hopefully I fully understood your question now :)
Bladedu
Thank you for you answer. I realized that i left out "$" in my code, the for loop works now. Newbie Lesson learned: Look in your code before you leap to SF.
Mahesh Marisetti