Drupal - add form element on successful submission - drupal

In a Drupal custom module, I want to make $form['link_wrapper'] conditional on a successful submission of the form but this is not a very successful way of doing this. Can anyone suggest better approach.
function my_function_my_form($form_state){
//echo "-" . $form_state['post']['op'] ."-";
//die();
global $base_root;
$form = array();
$form ['query_type'] =array (
'#type' => 'radios',
'#title' => t('Select from available Queries'),
'#options' => array(
"e_commerce_orders" => t("Query1"),
"new_orders" => t("Query2"),
"cancelled_orders" => t("Query3")),
'#required' => TRUE,
);
// only show link when submitted
if($form_state['post']['op'] == 'Submit')
{
$form['link_wrapper'] = array(
'#prefix' => '<div>',
'#value' => l("Click to View file"),
'#suffix' => '</div><br><br>',
);
}
// add submit button
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'));
return $form;
}

Have you tried setting your condition in the validate hook?
Something like:
function my_function_my_form_validate($form_state){
//some condition is true
$form_state['something'] = TRUE;
}
http://api.drupal.org/api/function/hook_validate/6
This is rough. I can't remember the args for hook_validate

Related

Drupal form submission

I have created a form in drupal. I don't know how to handle the submission. I want to do some selection from database with the values i get from form. Here is my code to create form
function q_search_form() {
$form['qsearch']['category'] = array(
'#type' => 'select',
'#options' => array(0 => 'Any', 1 => 'Automotive', 2 => 'Real Estate'),
'#attributes' => array('class' => 'drop-box'),
'#prefix' => '<table width="470"><tr><td width="170">Select Category</td><td width="300">',
'#suffix' => '</td></tr>'
);
$form['qsearch']['city'] = array(
'#type' => 'select',
'#options' => array(0 => 'Any', 1 => 'Calicut', 2 => 'Kochi'),
'#attributes' => array('class' => 'drop-box'),
'#prefix' => '<tr><td width="170">City</td><td width="300">',
'#suffix' => '</td></tr>'
);
$form['qsearch']['property'] = array(
'#type' => 'select',
'#options' => array(0 => 'Any', 1 => 'House', 2 => 'Land'),
'#attributes' => array('class' => 'drop-box'),
'#prefix' => '<tr><td width="170">Property</td><td width="300">',
'#suffix' => '</td></tr>'
);
$form['qsearch']['wanto'] = array(
'#type' => 'select',
'#options' => array(0 => 'Any', 1 => 'Sell', 2 => 'Buy'),
'#attributes' => array('class' => 'drop-box'),
'#prefix' => '<tr><td width="170">Want to</td><td width="300">',
'#suffix' => '</td></tr>'
);
$form['qsearch']['submit'] = array(
'#type' => 'submit',
'#value' => t('Search'),
'#attributes' => array('id' => 'Search', 'class' => 'srch-button'),
'#prefix' => '<tr><td><a class="adv-srch" href="#">Advance Search</a></td><td>',
'#suffix' => '</td></tr></table>'
);
return $form;
}
You can write following submit function,
function q_search_form_submit($form, &$form_state) {
// To get selected values from form
$values = $form_state['values'];
// do print_r($values); exit; to check the values
}
This is pretty simple. You just have to implement the form_submit function. From the function above, I assume the name of your module to be q_search. So, here is what the submit function would look like:
function q_search_form_submit($form, &$form_state) {
// you can get the values submitted by the users using
// `$form_state['values']`, and use the database functions
// to implement your logic.
}
If you also want to validate the user inputs before the actual submit, you should add a validation function which would look like:
function q_search_form_validate($form, &$form_state) {
// validate here
}
You can use form_set_error, in the validate function if the validation fails.
You can do pretty much anything you want in the form_submit function.
function q_search_form_submit($form, &$form_state) {
$category = $form_state['values']['category'];
$city = $form_state['values']['city'];
//etc..
//use these values to query your database tables
$query = db_select($category, 'c');
//narrow results to those only in the selected city:
$query->join($city, 'cy', 'c.city = cy.cid');
//narrow results further with more ->join statements
$results = $query
->fields('c', array(fields you want from the categories table))
//fields from other tables...
->execute();
//do whatever with the $results (print on a different page, print in a table, etc).

Drupal 7 form state undefined index

I create a form like this in .module file:
function form_registration_form($form, &$form_state) {
$form['registration']['email'] = array(
'#title' => t('EMAIL ADDRESS'),
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 44,
'#maxlength' => '80',
'#rules' => array(
'email',
'length[10, 50]',
)
);
$form['registration']['password'] = array(
'#title' => t('PASSWORD'),
'#type' => 'password',
'#required' => TRUE,
'#size' => 44,
'#maxlength' => '80',
);
$form['registration']['submit'] = array(
'#value' => 'SIGN IN',
'#type' => 'submit',
'#submit' => array('form_registration_handler')
);
return $form;
}
function form_registration_handler($form, &$form_state){
$email = $form_state['registration']['email'];
drupal_set_message($email);
}
However drupal always say that "Undefined index: registration in form_registration_form_submit()". I really dont know what I am doing wrong here. Any suggestions will be very useful for me. Thank you very much.
You can always enable the Devel module and dsm($form) the submit function. For instance:
function form_registration_handler($form, &$form_state){
dsm($form);
dsm($form_state);
}
By DSMing, you can easily find the value you want to use in your submit function.
Add this lines to head of your form_registration_form function:
$form = array();
$form['registration'] = array();
The notice appear becuse $form['registration'] is not declared as a void array.

Drupal 7 Custom Field Widget not saving user input

I'm building a custom field module to work with our streaming video provider. As part of this, I need to grab a video based on a selected category from the provider's API. The field will need to store a number of pieces - the selected category, the selected video, and some additional details (such as a caption) yet to be added.
I can get this form to appear on the node edit page (after attaching the field to a content type), but it doesn't appear to be saving the user's input. Here's the form in place on the edit node screen: Field on node editing screen. Workflow for the user is they select a category, which populates the list of videos to select. When they select a video, they're shown a preview in $element['teacherstv']['teacherstv_video_details']. This is working right up to the point where the user saves the form. At that point, the selected values are lost.
I've looked through the Field API and Forms API docs for D7, but can't see any clear instructions for how to set up this kind of field widget and have it save user input.
Here's the code for hook_field_widget_form()
function teacherstv_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
// $value = $isset($items[$delta['teacherstv']) ? $items[$delta]['teacherstv'] : '';
$widget['#delta'] = $delta;
//lets get an array of our categories from core
$coreapi = new coreapi();
$APIsettings = variable_get('teacherstv_API_settings');
$coreapi->apiuser = $APIsettings['username'];
$coreapi->apipwd = $APIsettings['password'];
$coreapi->apiurl = $APIsettings['api_url'];
$coreapi->sortcriteria = "alpha";
//$categoriesavailable = $coreapi->get_categories();
$categories = coreapi_get_categories();
$defaults = $field['settings'];
$settings = $instance['settings'];
$category = !is_null($form_state['values'][$field['field_name']]['und'][$delta]['teacherstv']['teacherstv_category']) ? $form_state['values'][$field['field_name']]['und'][$delta]['teacherstv']['teacherstv_category'] : $defaults['teacherstv']['defaultcategory'];
switch ($instance['widget']['type']) {
case 'teacherstv':
$element['teacherstv'] = array(
'#tree' => TRUE,
'#type' => 'fieldset',
'#title' => t('TeachersTV Video'),
'#description' => '<p>' . t('Select a video from the TeachersTV service to embed.') . '</p>',
'#delta' => $delta,
);
$element['teacherstv']['teacherstv_category'] = array(
'#type' => 'select',
'#field_parents' => 'teacherstv',
'#title' => t('Video Categories'),
'#options' => $categories,
'#description' => t('Select a video category for a list of videos'),
'#default_value' => !is_null($settings['teacherstv_category']) ? array($settings['teacherstv_category']) : array($category),
'#ajax' => array(
'callback' => 'teacherstv_ajax_videolist',
'wrapper' => 'teacherstv-videolist-' . $delta . '-div',
'method' => 'replace',
),
'#delta' => $delta,
);
$videos = coreapi_list_videos($category);
$videos[0] = "--Please select a video--";
asort($videos);
$element['teacherstv']['teacherstv_video'] = array(
'#type' => 'select',
'#title' => t('Select a video'),
'#field_parents' => 'teacherstv',
'#prefix' => '<div id="teacherstv-videolist-' . $delta . '-div">',
'#suffix' => '</div>',
'#options' => array(0 => 'Video 1'),
'#default_value' =>
isset($form_state['values'][$field['field_name']]['und'][$delta]['teacherstv']['teacherstv_video']) ? $form_state['values'][$field['field_name']]['und'][$delta]['teacherstv']['teacherstv_video'] : NULL,
'#description' => t('Select a video.'),
'#options' => $videos,
'#ajax' => array(
'callback' => 'teacherstv_ajax_videoselect',
'wrapper' => 'teacherstv-videodetails-' . $delta . '-div',
),
'#delta' => $delta,
);
$video_keys = array_keys($videos);
$selected_video = isset($form_state['values'][$field['field_name']]['und'][$delta]['teacherstv_category']) ? $form_state['values'][$field['field_name']]['und'][$delta]['teacherstv_category'] : NULL;
$element['teacherstv']['teacherstv_video_details'] = array(
'#type' => 'markup',
'#field_parents' => 'teacherstv',
'#title' => t('Video details'),
'#prefix' => '<div id="teacherstv-videodetails-' . $delta . '-div">',
'#suffix' => '</div>',
'#description' => t('Details about the video.'),
'#markup' => teacherstv_ajax_render_video($selected_video),
'#delta' => $delta,
);
break;
}
return $element;
}
Its probably the AJAX callback , in your AJAX callback, use
$form_state['rebuild'] = TRUE;
or assign the ajax value to a new element to have it in the $form_state array..
use devel and dpm($form_state). I bet your value is ""

Why is the drupal 6 status message not showing what fields are required when I first submit the form

When I submit the form without filling in one of the required fields( or any combination of required fields) there is no status message presented to let me know I have missed the required fields.
The second time I submit the form the status message shows me what fields are required.
The status message seems to be one step behind the form submission.
If after the first submit I change what fields are filled in and I submit again then the status message that should have show the previous time will show now.
When the form is filled in correctly it submits as normal.
The form is displayed using drupal_get_form( 'otherWaysToRequest' );
This is called in a template file in the theme.
Does anyone know why the status message is one step behind?
This is a sample of the code being used
function otherWaysToRequest(&$form_state)
{
global $base_url;
$pathToTheme = path_to_theme();
$form['top-check'] = array(
'#type' => 'fieldset',
'#attributes' => array('class' => 'checkboxes'),
);
$form['top-check']['gift'] = array(
'#title' => t('Included a gift'),
'#type' => 'checkbox',
'#suffix' => '<br />',
'#required' => false,
);
$form['top-check']['contact'] = array(
'#title' => t('I would like to speak to you'),
'#type' => 'checkbox',
'#suffix' => '<br />',
'#required' => false,
);
$form['name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#required' => true,
);
$form['email'] = array(
'#title' => t('Email Address'),
'#type' => 'textfield',
'#required' => true,
);
$form['bottom-check'] = array(
'#type' => 'fieldset',
'#attributes' => array('class' => 'checkboxes'),
'#description' => t('<p class="Items">If you have ...:</p><p class="Items">I have included .....</p>')
);
$form['bottom-check']['share'] = array(
'#title' => t('A Share'),
'#type' => 'checkbox',
'#suffix' => '<br />',
'#required' => FALSE,
);
$form['submit'] = array(
'#type' => 'image_button',
'#src' => $pathToTheme.'/image.gif',
'#value' => t('Submit Form'),
);
}
function otherWaysToRequest_validate($form, &$form_state)
{
$mail_reg_ex = '/[-a-zA-Z0-9._]+[#]{1}[-a-zA-Z0-9.]+[.]{1}[a-zA-Z]{2,4}/';
if(!preg_match($mail_reg_ex, $form_state['values']['email']))
{
form_set_error('email', t('Invalid email address.'));
}
if( 0 == $form_state['values']['gift'] & 0 == $form_state['values']['contact'] )
{
form_set_error('gift', t('You must choose one of the first two options on the form'));
}
}
function otherWaysToRequest_submit($form, &$form_state)
{
//mail details
}
It's because by the time you're calling drupal_get_form in your template file the messages have already been committed for the current page; your validation messages will therefore show up the next time messages are displayed to the screen which is on the next page load.
You should build up the form in a custom module rather than the theme to get around this. The easiest way would be to create a block which you can assign to a region (using either hook_block in Drupal 6 or a combination of hook_block_info() and hook_block_view in Drupal 7).

My Form Submit Function Is Not Working

I'm developing a custom module for Drupal 6, that creates a simple form. My problem is that the submit function is not being called/processed!!! Here's my code:
function listgroups_menu(){
$items['user/%/groups-settings'] = array(
'title' => 'Groups Settings',
'page callback' => 'listgroups_groups_list',
'page arguments' => array(1),
'access callback' => TRUE,
'type' => MENU_LOCAL_TASK,
);
return $items;
}
function listgroups_groups_list ($uid){
/*
* Couple lines here to access the DB & get the user's $groups.
*/
variable_set('listgroups_database_result', $groups );
$output = drupal_get_form('listgroups_settiongs_form');
return $output;
}
/**
* Form Builder
*/
function listgroups_settiongs_form(){
$groups = variable_get('database_result', array());
//Building the form
$form['display_option'] = array(
'#type' => 'checkbox',
'#title' => t('Show my group.'),
);
$form['groups_selection'] = array(
'#type' => 'radios',
'#title' => 'Please select your group',
'#options' => $groups,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return system_settings_form($form);
}
/**
* Submition
*/
function listgroups_settiongs_form_submit($form, &$form_state){
echo "<pre>I'm heeeeeeeeeeeeeeeeeeeeeerr!!!</pre>";
drupal_set_message('Your settings have been saved! YES!!!');
}
Now, the form rendering & the data retrival of the Db is just perfect. It's when I click the submit button, I get nothing at all!! Only the page refreshes & the messages doesn't appear!!
Any idea why?!!!!
use
return $form;
instead of
return system_settings_form($form);
and also
function xyz_form_submit($form, &$form_state){
//echo "<pre>I'm heeeeeeeeeeeeeeeeeeeeeerr!!!</pre>";
drupal_set_message('<pre>I\'m heeeeeeeeeeeeeeeeeeeeeerr!!!</pre>Your settings have been saved! YES!!!');
}
the problem was if you use system_setting_form then it start behaving as a system setting page that is generally used to store some information in database. So making it normal form you need to return only $form.
Include a submit handler and then assign it a function
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#submit' => array('my_module_function_submit'),
);
my_module_function_submit($form, $form_state){
.
.
.
.
.
}
Refer this link https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#submit_property

Resources