Drupal 6 Multistep Forms: form_state values empty on submit - php

I'm having trouble getting the values from a multistep form to insert into the database. All I'm getting is empty values for each field.
Here's the code:
function multistep_profile_menu() {
$items['multistep_profile'] = array(
'title' => t('Multistep Profile'),
'page callback' => 'drupal_get_form',
'page arguments' => array('multistep_profile'),
'type' => MENU_NORMAL_ITEM,
'access arguments' => array('access content'),
);
return $items;
}
function multistep_profile(&$form_state) {
// $form_state['storage']['step'] keeps track of what page we're on.
if (!isset($form_state['storage']['step'])) {
$form_state['storage']['step'] = 1;
}
//stores form data and carries it between steps
$default_value = '';
if (isset($form_state['storage']['values'][$form_state['storage']['step']])) {
$default_value = $form_state['storage']['values'][$form_state['storage']['step']];
}
switch ($form_state['storage']['step']) {
// Step 1 of Form
case 1:
$form['step_one'] = array(
'#title' => t('Step 1'),
'#type' => 'fieldset',
'#description' => t('Just getting started.'),
);
// Full Name
$form['step_one']['full_name'] = array(
'#title' => t('Full Name'),
'#type' => 'textfield',
'#description' => t('Please enter your name.'),
'#required' => TRUE,
'#default_value' => isset($default_value['full_name']) ? $default_value['full_name'] : '',
);
// College/University/Organization
$form['step_one']['college'] = array(
'#type' => 'textfield',
'#title' => t('College/University/Organization'),
'#default_value' => isset($default_value['college']) ? $default_value['college'] : '',
);
// Academic Disciplines
$form['step_one']['academic'] = array(
'#type' => 'textfield',
'#title' => t('Academic Disciplines'),
'#default_value' => isset($default_value['academic']) ? $default_value['academic'] : '',
);
break;
// Step 2 of Form
case 2:
$form['step_two'] = array(
'#title' => t('Step 2'),
'#type' => 'fieldset',
'#description' => t('Almost done.'),
);
// Job Title
$form['step_two']['job_title'] = array(
'#title' => t('Job Title'),
'#type' => 'textfield',
'#description' => t('Please enter your job title.'),
'#default_value' => isset($default_value['job_title']) ? $default_value['job_title'] : '',
);
// Department
$form['step_two']['department'] = array(
'#type' => 'textfield',
'#title' => t('Department'),
'#default_value' => isset($default_value['department']) ? $default_value['department'] : '',
);
break;
// Step 3 of Form
case 3:
$form['step_three'] = array(
'#title' => t('Step 3'),
'#type' => 'fieldset',
'#description' => t('Almost done, part 3.')
);
// Q1
$form['step_three']['q1'] = array(
'#title' => t('Why do you want to develop a globally networked course?'),
'#type' => 'textarea',
'#description' => t(''),
);
break;
//Confirmation
case 4:
$form['thanks'] = array(
'#value' => '<p>'. t('Your Profile is complete.') .'</p>',
);
break;
}
//programmatically display buttons
if ($form_state['storage']['step'] > 1) {
$form['previous'] = array(
'#type' => 'submit',
'#value' => t('<< Previous'),
);
}
if ($form_state['storage']['step'] != 4) {
$form['next'] = array(
'#type' => 'submit',
'#value' => t('Continue >>'),
);
}
else {
$form['finish'] = array(
'#type' => 'submit',
'#value' => t('Finish'),
);
}
return $form;
}
function multistep_profile_submit($form, &$form_state) {
//Save the values for the current step into the storage array.
$form_state['storage']['values'][$form_state['storage']['step']] = $form_state['values'];
//Check the button that was clicked and change the step.
if ($form_state['clicked_button']['#id'] == 'edit-previous') {
$form_state['storage']['step']--;
}
elseif ($form_state['clicked_button']['#id'] == 'edit-next') {
$form_state['storage']['step']++;
}
elseif ($form_state['clicked_button']['#id'] == 'edit-finish') {
//You should store the values from the form in the database here.
dpm($form_state);
// INSERT into DB
$full_name = $form_state['values']['full_name'];
$college = $form_state['values']['college'];
$academic = $form_state['values']['academic'];
$job_title = $form_state['values']['job_title'];
$department = $form_state['values']['department'];
$q1 = $form_state['values']['q1'];
db_query("INSERT INTO {multistep_profile} (full_name, college, academic, job_title, department, q1, created) VALUES
('%s', '%s', '%s', '%s', '%s', '%s', %d)", $full_name, $college, $academic, $job_title, $department, $q1, time());
drupal_set_message(t('Your profile has been saved.'));
unset($form_state['storage']);
//Go to this page after completing the form.
//$form_state['redirect'] = 'node';
}
}
The only value that makes it into the DB is the 'created' date timestamp.
I ran a DPM to check if the values are being carried over between form steps, and they are, I just can't figure out how to get them to insert into the database. Any help?

Looking at your submit function, you (correctly) store the values collected on the different steps under $form_state['storage']['values'][<step_number>]. This matches with the DPM output you posted, i.e. the values show up under $form_state['storage']['values'][1]..., $form_state['storage']['values'][2]..., etc.
But in your final submit processing, you try to access them under $form_state['values'][...], just as if this was a single step form. As your last step does not post any values, you will not find anything there.
So looks like you'd just need to change your final value collection logic to grab the values from the storage (sub)arrays where you have placed them before :)
E.g.:
$full_name = $form_state['values']['full_name'];
would need to be
$full_name = $form_state['storage']['values'][1]['full_name'];
and so on for the other values.

Related

Drupal 7: how do I save module settings?

I am trying to create some settings for a module and am following the guide on Drupal.org. I am also comparing my work to existing modules.
The config menu appears in the correct place with the correct fields but when I hit save no input is saved. (I have run cache clear and registry rebuild.)
Would anyone know what I am doing wrong here? I cannot see how my stuff differs.
On my .admin.inc file I have set the form as such:
function contact_page_settings() {
$form = array();
$config = contact_page_default_settings();
$form['#tree'] = TRUE;
$form['contact_page_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Top Section'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'top-title' => array(
'#type' => 'textfield',
'#title' => t('Top title'),
'#default_value' => !empty($config['top-title']) ? $config['top-title'] : '',
),
'top-left' => array(
'#type' => 'text_format',
'#title' => t('Top left'),
'#default_value' => !empty($config['top-left']) ? $config['top-left'] : '',
),
'top-right' => array(
'#type' => 'text_format',
'#title' => t('Top right'),
'#default_value' => !empty($config['top-right']) ? $config['top-right'] : '',
),
);
return system_settings_form($form);
}
On my .module file I have:
function contact_page_menu() {
$items = array();
$items['admin/settings/contact-page'] = array(
'title' => 'Contact Page content',
'page callback' => 'drupal_get_form',
'access arguments' => array('administer site configuration'),
'page arguments' => array('contact_page_settings'),
'type' => MENU_NORMAL_ITEM,
'file' => '/admin/contact_page.admin.inc',
);
return $items;
}
function contact_page_default_settings() {
$defaults = array(
'top-tile' => 'Top title',
'top-left' => 'Top left',
'top-right' => 'Top right',
);
$config = variable_get('contact_page_settings', array());
return array_merge($defaults, $config);
}
OK, so I found out the values were saving - just they were not appearing in my text areas when I reloaded the config page.
The problem was that I was using text_format fields which save data as an array. I needed to get the value property of that array as my default value.
So, I just added ['value'] to the default_value ternary expression:
'#default_value' => !empty($config['top-right']['value']) ? $config['top-right']['value'] : '',

How to update the fields using custom form in drupal7

I am having three fields: First name, Last name and Year of birth. In code I am easily inserting into database when I press submit button, so I want to update these fields when I want to click on Edit button. Please anyone help me to code this update to put the inserted data in a database or please post code.
<?php
function my_module_menu() {
$items = array();
$items['my_module/form'] = array(
'title' => 'My form',
'page callback' => 'drupal_get_form',
'page arguments' => array('my_module_my_form'),
'access arguments' => array('access content'),
'description' => 'My form',
'type' => MENU_CALLBACK,
);
$items['my_module/edit'] = array(
'title' => t('Edit Name'),
'page callback' => 'drupal_get_form',
'page arguments' => array('my_module_edit'),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
);
return $items;
}
function my_module_my_form($form_state) {
$form['first_name'] = array(
'#type' => 'textfield',
'#title' => t('First name'),
'#required' => TRUE, // Added
);
$form['last_name'] = array(
'#type' => 'textfield',
'#title' => t('Last name'),
'#required' => TRUE, // Added
);
$form['year_of_birth'] = array(
'#type' => 'textfield',
'#title' => ('Year of birth'),
'#description' => 'Format is "YYYY"',
);
// Adds a simple submit button that refreshes the form and clears its contents -- this is the default behavior for forms.
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
function my_module_edit($form, &$form_submit){
$form['Edit'] = array(
'#type' => 'Edit',
'#value' => 'Edit',
);
return $form;
}
function my_module_my_form_submit($form, &$form_state){
$firstName = $form_state['values']['fname'];
$lastName=$form_state['value']['lname'];
$yearofbirth = $form_state['values']['yearOfbirth'];
$query ="INSERT INTO `slideshow`.`mymoduledb`(`first_name`,`last_name`,`year_of_birth`) VALUES ('{$firstName}','{$lastName}','{$yearofbirth}')";
//$result=db_query($query);
if ($success = db_query($query)) {
// Tell the user that the employee has been saved.
drupal_set_message(t(' has been saved.'));
}else{ // If there's an error, $success will evaluate to FALSE, and the following code will execute.
drupal_set_message(t('There was an error saving your data. Please try again.'));
}
}
}
Inorder to edit form field you can reuse the form and set the default value field '#default_value'
storing the form submitted data fetched from database using the respective uniques ids.Refer the link for sample code.
https://www.drupal.org/node/2069383

custom url to display content from database in custom form in drupal 7

I created custom form in drupal 7 and data is saved in a table called "person" in database when i am trying to retrieve data in custom url data is displaying but when loading the form page "page not found" message is displaying not getting that form, if the code for retrieve data in custom url is commented then i get form page.
this is the code which i used:
<?php
/**
* #file
* Provides a custom form, data are saved in database and can retrieve data in table format in custom url.
*/
//Implementation of hook_menu()
function form_test_menu() {
$items['formtest'] = array(
'title' => 'Form Test',
'page callback' => 'drupal_get_form',
'page arguments' => array('form_test_form'),
'access callback' => TRUE,
);
$items = array();
$items['results'] = array( // change to the url you want
'title' => 'results',
'type' => MENU_CALLBACK,
'page callback' => 'results',
'access arguments' => array('access content'),
);
return $items;
}
//function to describe field in the form
function form_test_form($form,&$form_submit) {
$form['name'] = array(
'#title' => t('name'),
'#type' => 'textfield',
'#size' => 20,
'#maxlength' => 20,
'#required' => TRUE,
'#default_value' => 'Enter Your Name',//make this field required
);
$form['address']['email'] = array(
'#type' => 'textfield',
'#title' => t('E-mail'),
'#required' => TRUE,
'#maxlength' => 255,
);
$form['price'] = array(
'#type' => 'textfield', //you can find a list of available types in the form api
'#title' => 'What is Your Price?',
'#size' => 10,
'#maxlength' => 10,
'#required' => TRUE, //make this field required
);
$form['attending'] = array(
'#type' => 'radios',
'#title' => t('Will you be attending?'),
'#options' => array(
'1' => t('Yes'),
'0' => t('No'),
),
'#required' => TRUE,
'#default_value' => isset($attending) ? $attending : NULL,
);
$form['submit'] = array(
'#value' => 'Submit',
'#type' => 'submit',
);
return $form;
}
//validation code for integer
function form_test_form_validate($form, &$form_state) {
if (!($form_state['values']['price'] > 0)){
form_set_error('price', t('Price must be a positive number.'));
}
}
//inserting data into database
drupal_write_record('person', $data);
function form_test_form_submit($form, &$form_state) {
$id = db_insert('person')
->fields(array(
'name' => $form_state['values']['name'],
'email' => $form_state['values']['email'],
'price' => $form_state['values']['price'],
'attending' => $form_state['values']['attending'],
// 'ios' => $form_state['values']['ios'],
))
->execute();
drupal_set_message(t('data saved successfully.'));
}
//Retrieving data from database
function results() {
print "CUSTOM TABLE CONTENT";
print "<br /> ";
print "<br /> ";
$query = db_select('person', 'u');
$query->fields('u', array('name')); //mention the field that you want to display
$query->fields('u', array('email'));
$query->fields('u', array('price'));
$query->fields('u', array('attending'));
$result = $query->execute();
while($record = $result->fetchAssoc()) { //while loop mention how the data want to display
echo "<li>";
print_r($record['name']);
print " ";
print_r($record['email']);
print " ";
print_r($record['price']);
print " ";
print_r($record['attending']);
echo "</li>";
}
}
$items = array();
this code should be come under the main function
function form_test_menu() {
the code should be like this
function form_test_menu() {
$items = array();
no other modification it will work.

Custom module form problems

I am struggling in my attempts to programmatically display a form to display in my node-page view area. I have the following code in my "simplemodule".
function simplemodule_newcomer_form($form_state){
$form = array();
$form['simplemodule_newcomer']['name'] = array(
'#type' => 'textfield',
'#title' => t('name'),
'#description' => t(''),
'#weight' => -1,
);
$form['simplemodule_newcomer']['email'] = array(
'#title' => t('email'),
'#type' => 'textfield',
'#description' => t(''),
'#weight' => 0,
);
$form['simplemodule_newcomer']['phone'] = array(
'#title' => t('telephone No.'),
'#type' => 'textfield',
'#description' => t(''),
'#weight' => 0,
);
$form['submit_button'] = array(
'#type' => 'submit',
'#value' => 'enter',
);
return $form;
}
function simplemodule_newcomer_form_submit($form_id, &$form_state){
//dealing with submitted data
}
This code works but only from a defined link in my administration menu.
What I want to do is get the form to display and submit on a specific node in view mode. So it creates the effect that there is a form to fill when visiting the node.
You can implement hook_nodeapi() and attach your form using drupal_get_form():
function simplemodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($node->nid == $the_nid && $op == 'view') {
$node->content['my_additional_field'] = array(
'#value' => drupal_get_form('simplemodule_newcomer_form'),
'#weight' => 10,
);
}
}
You can use the #weight key to specify where in relation to the other content on the page your form will appear. Also you'll need to clear Drupal's caches when you implement this hook to make sure it's picked up.
Surely you can use
hook_form_alter(&$form, &$form_state, $form_id) and
hook_nodeapi(&$node, $op, $teaser = NULL, $page = NULL)
http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_form_alter/7
http://drupal.org/node/1011692

Drupal custom form remembering textfield data

I am setting up a configuration page for a new module and I am having trouble getting my textfield to remember data I previously entered.
I am setting #default_value by calling variable_get but the value never gets reset in the textfield. It is however correctly stored as a variable and visible on the variable editor page.
Below is a code fragment:
$form = array();
$form['username'] = array(
'#type' => 'textfield',
'#title' => t('Username'),
'#default_value' => variable_get('username', '' ),
'#description' => t('supply the username'),
'#maxlength' => 30,
'#required' => TRUE,
'#weight' => -1,
);
return system_settings_form($form);
How can I fix this?
Updated code
The submit function is as follows:
function mymodule_settings_submit($form, &$form_state){
drupal_set_message('form submit responding : ' . $form_state['values']['username'] );
variable_set( 'username', $form_state['values']['username'] );
}
Updated code #2
The full code:
function my_module_init(){
}
function my_module_menu(){
$items = array();
$items['admin/settings/helper'] = array(
'title' => 'helper',
'page callback' => 'drupal_get_form',
'page arguments' => array('helper_setup'),
'access arguments' => array('access administration pages'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function helper_setup(){
$node_types = node_get_types('names');
$form = array();
$form['username'] = array(
'#type' => 'textfield',
'#title' => t('Username'),
'#default_value' => variable_get('username', '' ),
'#description' => t('supply the username'),
'#maxlength' => 30,
'#required' => TRUE,
'#weight' => -1,
);
$form['#submit'][] = 'my_module_settings_submit';
return system_settings_form($form);
}
function my_module_validate($form, &$form_state){
die('validation area responding!');
}
function my_module_settings_submit($form, &$form_state){
drupal_set_message('form submit responding : ' . $form_state['values']['username'] );
variable_set( 'username', $form_state['values']['username'] );
}
in your form submit function you should insert variable_set('variableName' , 'value') variables is not inserted automatically..
UPDATE:
$form['username'] = array(
'#type' => 'textfield',
'#title' => t('Username'),
'#default_value' => variable_get('username', '' ),
'#description' => t('supply the username'),
'#maxlength' => 30,
'#required' => TRUE,
'#weight' => -1,
);
$form['#submit'][] = '_myform_submit_function' ;
return system_settings_form($form);
now lets build your submit function
function _myform_submit_function($form,&$form_state ) {
variable_set('username', $form_state['values']['username']) ;
drupal_set_message('form submit responding : ' . $form_state['values']['username'] );
}
now clear the cache and tell me if its working or not

Categories