Drupal Form API: Create Form Elements based on the database values (Dynamic Form Creation)
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 开发者_Python百科for() loop in the form generating function but this doesn't work. Please post you suggestions and any related links.
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. :)
精彩评论