Drupal form submission - drupal

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).

Related

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 ""

Drupal 7, how to dynamically populate a field based on the summation of two other fields?

I have two fields
$form["field_num_males"]
$form["field_num_females"]
I need to dynamically populate the field $form["field_gender_total"] with the summation of them, before the submission (AJAX).
How can this be done with Drupal 7?
Thanks!
Yes it can be done with Ajax. The following code will automatic update the total when the text field is updated:
function gender_total_menu()
{
$items = array();
$items['test'] = array(
'title' => Gender total,
'page callback' => 'drupal_get_form',
'page arguments' => array('gender_total_form'),
'access callback' => array(TRUE),
'type' => MENU_CALLBACK,
);
return $items;
}
function gender_total_form($form, &$form_state)
{
$total = 0;
if (array_key_exists('values', $form_state) &&
array_key_exists('field_num_males', $form_state['values']) &&
array_key_exists('field_num_females', $form_state['values'])
) {
$total = $form_state['values']['field_num_males'] + $form_state['values']['field_num_females'];
}
$form = array();
$form["field_num_males"] = array(
'#type' => 'textfield',
'#title' => t("Number of males"),
'#default_value' => 0,
'#ajax' => array(
'callback' => 'ajax_update_callback',
'wrapper' => 'wrapper',
),
);
$form["field_num_females"] = array(
'#type' => 'textfield',
'#title' => t("Number of females"),
'#default_value' => 0,
'#ajax' => array(
'callback' => 'ajax_update_callback',
'wrapper' => 'wrapper',
),
);
$form['total'] = array(
'#markup' => '<p> Total: ' . $total . '</p>',
'#prefix' => '<div id="wrapper">',
'#suffix' => '</div>',
);
return $form;
}
function ajax_update_callback($form, $form_state)
{
return $form['total'];
}
Try the Computed Field module
Computed Field is a very powerful CCK field module that lets you add a
custom "computed fields" to your content types. These computed fields
are populated with values that you define via PHP code. You may draw
on anything available to Drupal, including other fields...

drupal 7. how to refactor a form array

I am creating a wizard from the Drupal example file and would like to refactor the segments of code that are repeated when setting up items like options and radios.
I have already tried a simple function passing "ordinary" and "preferential" but can't find a way to make it work.
Can someone give me an idea of the best way to do this?
unfactored code is as below:
function services_wizard_share_capital_classes($form, &$form_state) {
$form['share_classes']['type_of_class'] = array(
'#type' => 'select',
'#title' => t('What type of share will this class be?'),
'#options' => array(
1 => t('Ordinary'),
2 => t('Preferential'),
),
);
$form['ordinary']['share_type'] = array(
'#type' => 'item',
'#description' => t("You chose Ordinary Shares"),
'#states' => array(
'visible' => array(
':input[name="type_of_class"]' => array('value' => '1'),
),
),
);
$form['preferential']['share_type'] = array(
'#type' => 'item',
'#description' => t("You chose Preferential Shares"),
'#states' => array(
'visible' => array(
':input[name="type_of_class"]' => array('value' => '2'),
),
),
);
return $form;
}
I'm not sure about this being the best way but it's certainly a way to refactor your code:
function _services_wizard_share_capital_classes_add_el(&$form, $name, $description, $index) {
$form[$name]['share_type'] = array(
'#type' => 'item',
'#description' => t($description),
'#states' => array(
'visible' => array(
':input[name="type_of_class"]' => array('value' => "$index"),
),
)
);
}
function services_wizard_share_capital_classes($form, &$form_state) {
// Other code
_services_wizard_share_capital_classes_add_el($form, 'ordinary', 'You chose Ordinary Shares', 1);
_services_wizard_share_capital_classes_add_el($form, 'preferential', 'You chose Preferential Shares', 2);
// etc...
}

drupal form to calculate date

I need a function to be able to retrieve the selected date from a date_popup in drupal form this is my form and the code that i've tried,Im doing a form for pregnancy calculator and im new in drupal i need to know how to implement the date calculation in my form.As testing i written a function to read value selected but it's giving me the 1970-01-01 date
<?php
/*
*Implementing hook_menu
*/
function Pregnancy_menu() {
$items['form/Pregnancy'] = array(
'title' => 'Pregnancy Calculator',
'page callback' => 'drupal_get_form',
'page arguments' => array('Pregnancy_form'),
'access callback' => TRUE,
);
return $items;
}
function Pregnancy_form($form_type) {
$form['Pregnancy_Period'] = array(
'#type' => 'date_popup',
'#title' => 'Date of your last menstrual period',
'#date_format' => 'Y-m-d',
'#date_text_parts' => array('year'),
'#date_increment' => 30,
'#date_year_range' => '-1:0',
'#default_value' => date(Y) . date(M) . date(D),
);
$form['Calculate_Forward'] = array(
'#type' => 'submit',
'#value' => t('Calculate Forward'),
);
$form['Reset_form'] = array(
'#type' => 'submit',
'#value' => t('Reset this Form'),
);
$form['Conception_result'] = array(
'#type' => 'textfield',
'#title' => t('Conception Occurred:(about two weeks after last menstrual period)'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
);
$form['First_trimester_Ends'] = array(
'#type' => 'textfield',
'#title' => t('First Trimester Ends :(12 weeks)'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
);
$form['Second_trimester_Ends'] = array(
'#type' => 'textfield',
'#title' => t('Second Trimester Ends :(27 weeks)'),
'#prefix' => '<div style="float:left;">',
'#suffix' => '</div>',
);
$form['Due_Date'] = array(
'#type' => 'date_popup',
'#title' => 'Estimated Due Date (40 weeks)',
'#date_format' => 'Y-m-d',
'#date_text_parts' => array('year'),
'#description' => t('Plus or Minus 2 weeks'),
'#date_increment' => 30,
'#date_year_range' => '+1:+1',
'#default_value' => date(Y) . date(M) . date(D),
);
$form['Calculate_Backward'] = array(
'#type' => 'submit',
'#value' => t('Calculate Backward'),
);
return $form;
}
function Pregnancy_form_submit($form, &$form_state) {
//what should I write here to get the value of the selected date and to add on it a specific time.For testing im using:
$selected_time= $_POST[''Pregnancy_Period'];
$output=$selected_time;
drupal_set_message($output);//but it's showing 1970-01-01
}
You don't want to access $_POST variables directly when using Drupal's form API, instead use the $form_state variable, specifically the values key.
In your submit function, $form_state['values']['Due_Date'] will contain the value inputted in the text box, $form_state['values']['Second_trimester_Ends'] will contain the input for that field, and so on.
To get the individual date parts you can use:
list($year, $month, $day) = explode('-', $form_state['values']['Due_Date']);
To add an amount of time to that value use a combination of strtotime and mktime:
// Prepare a timestamp based on the received date at 00:00:00 hours
$date = mktime(0, 0, 0, $month, $day, $year);
$new_date = strtotime('+2 hours', $date);
$new_date_formatted = date('Y-m-d', $new_date);
There are lots of options for the strtotime function, just have a look a the documentation page linked above.
Hope that helps

Drupal - add form element on successful submission

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

Resources