Drupal 7 : Getting the values from radio buttons form api - drupal

So this is my form :
$active = array(0 => t('Poster'), 1 => t('Postcard'), 2=>t('Post it'));
$form['radioimage']['active'] = array(
'#type' => 'radios',
'#default_value' => isset($node->active) ? $node->active : 1,
'#options' => $active,
);
I want to know which radio button was selected. I am trying to access the data but I don't know what its called I can't even use devel for some reason.
I tried below but they all failed
$form_state['values']['radioimage']['active'][0]
$form_state['values']['radioimage']['active']

Drupal flattens the values in the $form_state array by default so
$form['radioimage']['active']
will actually come out in
$form_state['values']['active']
If you want to explicitly keep your naming hierarchy then you should set the #tree key on the parent element:
$form['radioimage'] = array(
'#type' => 'container',
'#tree' => TRUE
);
In that case the value will be in
$form_state['values']['radioimage']['active']

Related

Drupal Ajax Forms

I have a form in Drupal that calls an external database in Netezza. Retrieve this data from Netezza lasts about 10 seconds. Then, based on that information I have to build a select control to let the user choose from a list of categories. When the user chooses a category I do another expensive call to Netezza to retrieve more information.
The problem is that for the second interaction (when the user chose a category) the form is reprocessed and therefore doing 2 expensive calls to Netezza, not one as anyone would expect or desire.
Do you know a workaround for this situation? Is there a way to do an ajax call using the Drupal Ajax Framework without rebuilding the entire form?
Thanks.
PD: Reading documentation about the Ajax Framework I guess a solution could be using another path specifiying #ajax['path'], but havenĀ“t fully tested that behavior and will be thankful if you share your experience.
PD2: I would prefer a workaround based on the Drupal Ajax Framework, not in a caching mechanism.
I'd highly recommend you to have a look into Drupal Examples, specially the module called ajax_example.
this is a fast sample code, might not be running, but just to give you the idea
function expensive_form($form, &$form_state) {
$form['category'] = array(
'#title' => t('Cateogry'),
'#type' => 'select',
'#options' => first_expensive_operation(),
'#ajax' => array(
'callback' => 'choose_category_callback',
'wrapper' => 'ajax-div',
// 'method' defaults to replaceWith, but valid values also include
// append, prepend, before and after.
// 'method' => 'replaceWith',
// 'effect' defaults to none. Other valid values are 'fade' and 'slide'.
'effect' => 'slide',
// 'speed' defaults to 'slow'. You can also use 'fast'
// or a number of milliseconds for the animation to last.
// 'speed' => 'slow',
),
);
$form['ajax_fieldset'] = array(
'#title' => t("Ajax Fields"),
// The prefix/suffix provide the div that we're replacing, named by
// #ajax['wrapper'] above.
'#prefix' => '<div id="ajax-div">',
'#suffix' => '</div>',
'#type' => 'fieldset',
'#description' => t('This is where we get automatically updated something'),
);
// this will only be executed on the second run of the form
// when the category is set.
if (isset($form_state['values']['category'])) {
$form['ajax_fieldset']['something'] = array(
'#title' => t('Somethings'),
'#type' => 'select',
'#options' => second_expensive_operation($form_state['values']['category']),
);
}
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
/**
* Callback element needs only select the portion of the form to be updated.
* Since #ajax['callback'] return can be HTML or a renderable
* array, we can just return a piece of the form.
*/
function choose_category_callback($form, $form_state) {
return $form['ajax_fieldset'];
}

Only partial theming of custom form

I've constructed a custom module to create a form. Now I'm stuck on the theming. I already have a CSS stylesheet for the form, since my company is part of the government and they have a preset branding. So I wanted to change the HTML used by the default form theme functions of Drupal thus implementing the correct style.
But only the form-tag of the form gets rendered. The fieldset and elements are not rendered. When the theme functions are removed the default theming kicks in and the form renders normally (but of course without the requested theming).
What I have tried so far:
Added a hook_theme function to add theme functions
function publicatieaanvraagformulier_theme() {
return array(
'publicatieaanvraagformulier_form' => array(
'arguments' => array("element" => NULL)
),
'publicatieaanvraagformulier_fieldset' => array(
'arguments' => array("element" => NULL)
),
'publicatieaanvraagformulier_form_element' => array(
'arguments' => array(
"element" => NULL,
"value" => NULL
)
)
);
}
Added ['#theme'] to the form-element, fieldset-element and the form-elements
$form['#theme'] = "publicatieaanvraagformulier_form";
$form['groep'] = array(
'#title' => t("Please fill in your details"),
'#type' => "fieldset",
'#theme' => "publicatieaanvraagformulier_fieldset"
);
$form['groep']['organisatie'] = array(
'#title' => t("Organization"),
'#type' => "textfield",
'#attributes' => array("class" => "text"),
'#theme' => "publicatieaanvraagformulier_form_element"
);
Added the actual theme function based on the default ones in form.inc
function theme_publicatieaanvraagformulier_form($element) {
function theme_publicatieaanvraagformulier_fieldset($element)
function theme_publicatieaanvraagformulier_form_element($element, $value)
I haven't included the code of these functions because even with the default themefunctions code, they don't work. Therefor I assume they are not the source of the problem.
The form is called
//Get the form
$form = drupal_get_form('publicatieaanvraagformulier');
//Add messages
$errors = form_get_errors();
if (!empty($errors)) {
$output .= theme("status_messages","error");
}
//Show form
$output .= $form;
return $output;
I haven't found similar 'complicated' examples of theming a form, but have pieced together the former from books and online searches.
Hopefully someone has an answer to this problem (point out the mistake I made).
Greetings
Jeroen

cannot get checkboxes value using drupal form api

i have form in drupal which uploads images and has got few checkboxes in it.
Here is the form:
$form['checklist_fieldset'] = array(
'#type' => 'fieldset',
'#title' => t('Check List'),
'#collapsible' => FALSE,
'#collapsed' => FALSE,
);
$form['checklist_fieldset']['heating'] = array(
'#type' => 'checkboxes',
'#title' => t('Heating options'),
'#options' => array(
'0' => t('Yes'),
'1' => t('No')
),
'#description' => t('Heating details.')
);
and here is my submit function where i am processing image upload and grabbing the checkboxes value as well. I am getting the success message and image is getting uploaded but not getting the value of check boxes.
function property_add_view_submit($form,&$form_state){
$validators = array();
if($file = file_save_upload('p_file1',$validators,file_direcotry_path)){
$heating = array_keys($form_state['values']['heating']);
drupal_set_message(t('Property Saved! '.$heating));
dpm( $form_state['values']['heating']);
}
When you use #options on a FAPI element the value passed to the $form_state is the array key, so you don't need to use array_keys().
I'm not sure why you're using checkboxes for a yes/no, usually one would use a simple checkbox element. However if that's really what you want to do:
Your #options can't contain on option with 0 as the array key, it will be automatically filtered out and you'll never know if that option has been checked.
You should use $heating_options_chosen = array_filter($form_state['values']['heating'] to get the selected checkbox options.
I honestly think your code should look like this though:
$form['checklist_fieldset']['heating'] = array(
'#type' => 'checkbox',
'#title' => t('Heating options'),
'#options' => array(
'1' => t('Yes'),
'0' => t('No')
),
'#description' => t('Heating details.')
);
$heating_checked = $form_state['values']['heating'] == 1;
If I have checkbox Friends and options are like
[ ] abc
[ ] def
[ ] ghi
[ ] jkl
And I want to know which options user have marked, then use below function.
if ($form_state->getValue('friends') != NULL) {
foreach ($form_state->getValue('friends') as $key => $value) {
if ($value != 0) {
$friends = $friends . ", " . $key;
$friends = substr_replace($friends, "", 0, 1);
}
}
}
If user has chosen abc and ghi then you will get 1,3 as result in $friends
If you wanted to know the value then use $friends = $friends.", ".$value;
it worked for me..hope it will help you as well :)

How to access form data in hook_form_validate() in drupal 7

I have a form implemented from hook_form called simplequiz_form() I want to access its data after submit below is the code I have written but I can't seem to access its data once its submitted. What am I doing wrong ?
function simplequiz_form_validate($form, &$form_state) {
// here is where we will validate the data and save it in the db.
$thid = db_insert('simplequiz')
->fields(array(
'questions' => &$form_state['question'],
**I can't seem to access the value of a field questions**
))
->execute();
return $thid;
}
Below is my implementation of hook_form()
function simplequiz_form($form, &$form_submit)
{
$form['question'] = array(
'#title' => t('Please input your question'),
'#type' => 'text_format',
'#required' => FALSE,
'#description' => t('Here is where you can enter your questions'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
if I use $form_state['values']['question']
I get the below error:
PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count at row 1: INSERT INTO {simplequiz} (questions) VALUES (:db_insert_placeholder_0_value, :db_insert_placeholder_0_format); Array ( [:db_insert_placeholder_0_value] => [:db_insert_placeholder_0_format] => filtered_html ) in simplequiz_form_submit() (line 245 of /home/vishal/Dropbox/sites/dev/sites/all/modules/simplequiz/simplequiz.module).
it worked using $form_state['values']['question']['value']
It's best practice to use hook_form_validate, just for validation purposes, anything other than validation should be done in hook_form_submit.
Either way they both function almost the same way.
All the form data is stored in $form_state['values'], so to access $form['questions'] values, just use $form_state['values']['questions'].

Drupal filter_form form input

This drupal form snippet will give me a textarea with user able to change filter to full html/wysiwyg mode.
My Questions: How can I default to to full html mode?
function MY_MODULE_admin() {
$form = array();
$form['format'] = filter_form($form->format);
// MY_MODULE - ** Image 1 **
$form['MY_MODULE_image_1'] = array(
'#type' => 'textarea',
'#title' => t('Image 1'),
'#default_value' => variable_get('setup_image_1', 'image_1.jpg'),
'#description' => "Current value =" .variable_get('setup_image_1', 'image_1.jpg'),
'#required' => TRUE,
);
This did the trick.
$form = array();
$form['carousel_setup_image_1']['accepted_text_1'] = array(
'#type' => 'textarea',
'#title' => t('Image 1 - Carousel '),
'#default_value' => variable_get('carousel_setup_image_1', 'carousel_image_1.jpg'),
'#description' => "Current value =" .variable_get('carousel_setup_image_1', 'carousel_image_1.jpg'),
);
$form['carousel_setup_image_1']['format'] = filter_form(2, NULL, array('accepted_text_1_format'));
Well there are two ways.
One, you can set that role's default format to Full HTML under Input Formats.
Two, you can say $form['format']['#default_value'] = 2 (I think Full HTML is 2). This will preselect Full HTML.
however, I am not sure why $edit['carousel_setup_image_1']['accepted_text_1']) does not contain entered value.
function carousel_setup_block($op = 'list', $delta = 0, $edit = array())
{
switch($op)
{
// case save (save configuration values)
case 'save':
variable_set('carousel_setup_image_1',
$edit['carousel_setup_image_1']['accepted_text_1']);
break;
}
}
For Drupal 7: The best way to handle (or leverage) the Drupal text filter system is to use not 'textarea', but the 'text_format' field type, like this, which will render a textarea with the filter select below:
$form['holycrap'] = array(
'#type' => 'text_format',
'#format' => NULL, // <- Let Drupal handle the default, based upon user role
'#title' => t('The HTML for the Holy Crap block above the Main Menu.'),
'#default_value' => variable_get('caplogin_holycrap', _caplogin_holycrap_default_html()),
);
return $form;

Resources