drupal 7. how to refactor a form array - drupal

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

Related

How to clear selected values from multiple select field

I have a form with a multiple select field where a user can select several values in it
$form['export_type_section']['export_type'] = array(
'#title' => t('Export types'),
'#type' => 'select',
'#multiple' => TRUE,
'#size' => 10,
'#options' => $options,
'#ajax' => array(
'event' => 'change',
'callback' => 'test_export_form_export_type_ajax_callback',
),
);
I have another field in the form
$form['document_type'] = array(
'#type' => 'select',
'#options' => array(0 => t('All Types'), 1 => t('Test1'), 2 => t('Test2'), 3 => t('Test3')),
'#title' => 'Document Types',
'#default' => 0,
'#ajax' => array(
'event' => 'change',
'callback' => 'test_export_form_document_type_ajax_callback',
),
);
I am trying to figure out how to reset the export_type field when the document_type is changed. I would like to clear the selected values so that the user can reselect what is needed whenever the document_type changes. I tried several formats in the test_export_form_document_type_ajax_callback but none worked.
Anybody knows how to do it?

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.

How do I add an onchange handler to a dropdown list in Drupal?

How can I add an onchange handler to a dropdown list in Drupal? The dropdown list is added using hook_form(). I have to perform a function depending on the onchange function.
Is there a way to do this?
You can add a form like this:
hook_form()
{
$form1["dropdown"] = array(
'#type' => 'select',
'#title' => t('Preview the page with themes available'),
'#options' => $ptions,
'#default_value' => 'defalut_value',
'#attributes' => array('onchange' => "form.submit('dropdown')"),
);
//Submit button:
$form1['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit '),
'#attributes' => array('style' => 'display: none;'),
);
Now you can add submit functionality using hook_submit().
Here is the simple example using '#ajax' property
$form['select'] = array(
'#type' => 'select',
'#title' => 'Option #1',
'#options' => $option,
'#ajax' => array(
// Call function that rebuilt other field
'callback' => 'ajax_load_field',
'method' => 'replace',
// div to be get replace by function output
'wrapper' => 'chart',
'effect' => 'fade'
),
);
If you generate another form field by using this drop down.
Then use AHAH for that.
$form['my_form_submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
'#weight' => 1,
'#submit' => array('my_form_submit'),//none JS version
'#ahah' => array(
'event' => 'click',
'path' => 'mymodule/js', //Your ajax function path
'wrapper' => 'myform-wrapper',
'method' => 'replace',
'effect' => 'fade',
'progress' => array(
'type' => 'bar',
'message' => t('Loading...')
)
),
While I am sure that Nicholas is way past this issue by now, this may help some who are searching for a solution.
I'm using D7 and getting the single quotes around dropdown encoded to ' I suppose by >check_plain. >How do I avoid that? – Nicholas Tolley Cottrell Jun 2 at 16:03
I just found the "Drupal" way of doing this.
Step 1, set a variable to contain dropdown by using drupal_add_js:
drupal_add_js(array('mymodule' => array('varname' => 'dropdown')), 'setting');
Step 2, add the attributes line as
'#attributes' => array('onchange' => "form.submit(Drupal.settings.mymodule.varname)"),

AJAX in Drupal Forms?

How would you go about constructing a step by step form that uses AJAX through Drupal to pull the next form step?
For example,
Step 1:
I like Baseball
I don't like Baseball.
When that person clicks on either Like or Don't Like, I want to use AJAX to recognize and pull the next part of the form, remove/hide the first section since its not needed, and present the next section.
Example:
Step 1:
I like Baseball
*click
(fade out)
Step 2:
My favorite team is __________
The player I like most is __________
What is the best way to do this through Drupal Form API? I know how to build the forms and modules, but I have never used AJAX yet. I know a few things exist out there that are supposed to help, but I wanted to know if anyone here has done it and how they approached it.
You may want to give a look at the AHAH helper module.
usually i am create full form with fieldsets, then control them manually by jquery.
i assume there lot of ready to go modules in drupal, some of these:
http://drupal.org/project/conditional_fields / http://drupal.org/project/multistep
also: http://www.google.ru/search?q=drupal+multistep+ajax+form
If you don't want to write any code, and don't need the entered data to be drupal nodes, I suggest using the webform module. It has a pretty simple UI for building forms, and allows you do do multipage forms with conditional fields. You can then export the results as CSV, email them, etc.
I have made to solutions for this problem in drupal 7. First one I solve it with Ajax as was requested(if someone want I can convert this to drupal6), however it should be better to solve this using attribute #states. So also made a solution in the bottom using states.
How to solve this using Ajax:
function ajax_in_drupal_form($form, &$form_state)
{
$baseball = array(
'like' => t('I like Baseball'),
'unlike' => t('I don\'t like Baseball')
);
$form['step'] = array(
'#prefix' => '<div id="baseball-wrapper">',
'#suffix' => '</div>',
);
if ($form_state['values']['baseball'] == 'like') {
$form['step']['team'] = array(
'#type' => 'textfield',
'#title' => t('My favorite team is'),
);
$form['step']['player'] = array(
'#type' => 'textfield',
'#title' => t('The player I like most is'),
);
}
else if ($form_state['values']['baseball'] == 'unlike') {
$form['step']['other'] = array(
'#type' => 'textfield',
'#title' => t('What do you like'),
);
}
else {
$form['step']['baseball'] = array(
'#type' => 'radios',
'#options' => $baseball,
'#title' => t('Select your option'),
'#ajax' => array(
'callback' => 'ajax_update_step_callback',
'wrapper' => 'baseball-wrapper',
),
);
}
return $form;
}
function ajax_update_step_callback($form, $form_state) {
return $form['step'];
}
Here is the solution using #states(The preferred way of solving it):
function states_in_drupal_form($form, &$form_state)
{
$baseball = array(
'like' => t('I like Baseball'),
'unlike' => t('I don\'t like Baseball')
);
// step 1
$form['step']['baseball'] = array(
'#type' => 'radios',
'#options' => $baseball,
'#title' => t('Select your option'),
'#states' => array(
'invisible' => array(':input[name="baseball"]' => array('checked' => TRUE),
),
)
);
// step 2 like baseball
$form['step']['team'] = array(
'#type' => 'textfield',
'#title' => t('My favorite team is'),
'#states' => array(
'visible' => array(':input[name="baseball"]' => array('checked' => TRUE)),
'visible' => array(':input[name="baseball"]' => array('value' => 'like')),
)
);
$form['step']['player'] = array(
'#type' => 'textfield',
'#title' => t('The player I like most is'),
'#states' => array(
'visible' => array(':input[name="baseball"]' => array('checked' => TRUE)),
'visible' => array(':input[name="baseball"]' => array('value' => 'like')),
)
);
// step 2 I don't like baseball
$form['step']['other'] = array(
'#type' => 'textfield',
'#title' => t('What do you like'),
'#states' => array(
'visible' => array(':input[name="baseball"]' => array('checked' => TRUE)),
'visible' => array(':input[name="baseball"]' => array('value' => 'unlike')),
)
);
return $form;
}

Resources