drupal form_execute for repopulation - drupal

I need a working example of how to repopulate form fields with the help of drupal_execute($form_id,$form_state). I can repopulate by altering the default_values as follows:
function sample_myform($form_state){
$form['field']['name'] = array(
'#type' => 'textfield',
'#title'=> 'Name: ',
'#maxlength'=> 127,
'#default_value'=> $form_state['values']['name'],
);
$form['field']['button1'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
function sample_myform_form_alter(&$form,$form_state,$form_id){
if($form_id=='sample_myform'){
$id = db_result(db_query("select max(id) from test2"));
$name = db_result(db_query("select name from test2 where id ='$id'"));
$form['field']['name']['#default_value'] = "$name";
drupal_set_message(t('Name: '.$name." id: ".$id));
}
}
However, i want to use drupal_execute for repopulation. Any suggestions?

drupal_execute calls drupal_prepare_form which calls hook_form_alter, so you should be fine. On the other hand, you could pass your values in $form_state['values'] like this:
$form_state['values']['name'] =
db_result(db_query("select name from test2 where id ='$id'"));
drupal_execute('sample_myform', $form_state);
However, if #tree is true for the element, the first line should read
$form_state['values']['field']['name'] =
db_result(db_query("select name from test2 where id ='$id'"));

Related

Problems with Forms => Variables are not accepted in the form

Not sure where the problem is in the following form used in a template file in Drupal7. Help is highly appreciated. The problems are the following:
1. The variables $title and $surname are not passed over to the form's default value.
=> Error Message: Notice: Undefined variable: title in form_user_information()
=> Error Message: Notice: Undefined variable: surname in form_user_information()
2. There's a Warning: strpos() expects parameter 1 to be string, array given in drupal_strip_dangerous_protocols()
Thanks in advance.
<?php
//Load User data:
global $user;
$uid = $user->uid;
$account = user_load($uid);
//Get User data:
$title = 'Mrs.';
print $title . '<br><br>'; //Result: Value is printed and not empty!
$surname = check_plain($account->field_vorname['und']['0']['value']);
//$surname = 'Tom';
print $surname . '<br><br>'; //Result: Both values are printed and are not empty!
function form_user_information($form, &$form_state) {
//Form
$form['#action'][] = request_uri();
$form['#id'][] = 'form_user_information';
$form['#validate'][] = 'form_user_information_validators';
$form['#submit'][] = 'form_user_information_submit';
$form['#prefix'] = '<div id="form_user_information">';
$form['#suffix'] = '</div>';
//Select-Field: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#select
$form['Title'] = array(
'#type' => 'select',
'#title' => t('Title'),
'#options' => array(
'Frau' => t('Mr.'),
'Herr' => t('Mrs.'),
),
'#default_value' => $title,
);
$form['surname'] = array(
'#type' => 'textfield',
'#maxlength' => 50,
'#size' => 40,
'#required' => TRUE,
'#title' => t('Surname'),
//'#attributes' => array('placeholder' => $surname),
'#default_value' => $surname,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array('#type' => 'submit', '#value' => 'Confirm data');
return $form;
}
//print form
$form = drupal_get_form('form_user_information');
print drupal_render($form);
//Form Validation:
function form_user_information_validators($form, &$form_state) {
if ($form_state['values']['surname'] == '') {
form_set_error('surname', t('Please enter your surname.'));
}
}
//Form Submit:
function form_user_information_submit($form, &$form_state) {
//...
}
//get form information
echo "<pre>".print_r($form,true)."</pre>";
?>
1) Set the global variables $title and $surname with global scope:
//Get User data:
$global $title = ...
$global $surname = ...
Otherwise set all these variables (including $user) inside the function form_user_information which is the best practice.
I would also suggest not use $title as variable name because it may cause problems with already defined $title of the $page variable. Instead use something like $user_title.
2) Which line does this come from?
Guess this issue can be closed. See the 2 comments. Thanks Theodoros for your help.

Drupal 6 : Not populating select list from db_query()

I have made a custom form in a module where I have used a select list & I am trying to populate that with the name of OG name.
I wrote a function for db_query() & that is giving me exact out put but I am not able to populate that in from select.
Function for db_query():-
function taskform_project_select(){
$options=array();
$project_query = "SELECT node.title FROM {node}, {og} WHERE node.nid = og.nid";
$project_details = db_query($project_query);
while($project_title = db_fetch_object($project_details)){
$options = $project_title->title;
dpm($options);
}
return $options;
}
Code in Form:-
$options = taskform_project_select();
$form['edproject'] = array(
'#type' => 'select',
'#title' => t('Project'),
'#options' => $options,
'#description' => t('Choose a project'),
'#prefix' => '<td>',
'#suffix' => '</td>',
);
Thanks :)
Correct syntax is:
$options[] = $project_title->title;
..with square brackets.
$options[$project_title->title] = $project_title->title;
provides a meaningful key value to the result. You could also retrieve the nid and use that as the key.

Drupal 6: Checkboxes table not rendering properly

I'm working on a Drupal 6 module which I want to generate a table with checkboxes in each row from data I have saved in a database. The table is being generated fine, but the checkboxes are not rendering in the table but are instead having their node id's put below the table. See the screenshot below:
"21" is the node id of "Test Question 01", and "19" is the node id of "Test Question 02".
The code I'm using (yes, it is all in a theme function which isn't ideal. I'm planning on moving stuff around once the checkboxes problem is resolved):
function theme_qt_assignment_questions_table($form) {
// Get the questions from the database
$db_results = db_query('SELECT {qt_questions}.nid, title, lesson, unit FROM node INNER JOIN {qt_questions} on {node}.nid = {qt_questions}.nid WHERE lesson = %d AND unit = %d',
$form['#lesson'], $form['#unit']);
// Define the headers for the table
$headers = array(
theme('table_select_header_cell'),
array('data' => t('Title'), 'field' => 'title'/*, 'sort' => 'asc'*/),
array('data' => t('Lesson'), 'field' => 'lesson'),
array('data' => t('Unit'), 'field' => 'unit'),
);
while($row = db_fetch_object($db_results)) {
$checkboxes[$row->nid] = '';
$form['nid'][$row->nid] = array(
'#value' => $row->nid
);
$form['title'][$row->nid] = array(
'#value' => $row->title
);
$form['lesson'][$row->nid] = array(
'#value' => $row->lesson
);
$form['unit'][$row->nid] = array(
'#value' => $row->unit
);
}
$form['checkboxes'] = array(
'#type' => 'checkboxes',
'#options' => $checkboxes,
);
// Add the questions to the table
if(!empty($form['checkboxes']['#options'])) {
foreach(element_children($form['nid']) as $nid) {
$questions[] = array(
drupal_render($form['checkboxes'][$nid]),
drupal_render($form['title'][$nid]),
drupal_render($form['lesson'][$nid]),
drupal_render($form['unit'][$nid]),
);
}
} else {
// If no query results, show as such in the table
$questions[] = array(array('data' => '<div class="error">No questions available for selected lesson and unit.</div>', 'colspan' => 4));
}
// Render the table and return the result
$output = theme('table', $headers, $questions);
$output .= drupal_render($form);
return $output;
}
Turns out my attempt at simplification of the problem was, in fact, the problem. Namely, doing everything in hook_theme isn't correct. Rather, I defined a function that pulls the info from database and creates the checkboxes array and call it in hook_form as such:
$form['questions_wrapper']['questions'] = _qt_get_questions_table($node->lesson, $node->unit);
At the end of this function (_qt_get_questions_table()), I specify the theme function which put everything into the table as such:
$form['#theme'] = 'qt_assignment_questions_table';
I'm still very new to Drupal so this explanation may not be the best to someone having the same problem, but hopefully it will help.

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

With custom module, display result ,

function searchsong_block($op='list',$delta=0){
$block = array();
switch($op){
case "list":
$block[0][info] = t('Search song');
return $block;
case "view":
$block['subject']='THIS IS SONG SEARCH MODULE';
$block['content']=drupal_get_form('custom1_default_form');
return $block;
}
}
function custom1_default_form () {
$form = array();
$form['txt_name'] =
array('#type' => 'textfield',
'#title' => t('Please enter your name'),
'#default_value' => variable_get('webservice_user_url',''),
'#maxlength' => '40',
'#size' => '20',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save Details'),
);
return $form;
}
function custom1_default_form_validate (&$form, &$form_state) {
if(($form_state['values']['txt_name']) == '') {
form_set_error('user_webservice', t('Enter a name'));
}
}
function custom1_default_form_submit ($form_id, $form_values) {
$GET_TXT_VAL = $_POST['txt_name'];
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'song', $GET_TXT_VAL);
$output='';
while ($row = db_fetch_object($result)) {
// drupal_set_message($row->title);----IF I ENABLE THIS LINE THEN MY SEARCH RESULT DISPLAYING IN THE GREEN BLOCK, YES I KNOW THIS FUNCTION SOMETHING LIKE ECHO JUST FOR TESTING PURPOSE WE SHOULD USE
$output .=$row->title;
}
$block['content'] = $output;
}
How to print my output ,
Above module does not display anything , even error also,
i thing i should use theme('itemlist') somthing , but i am not sure how to use this , and where i should use this ,
So what i want is , i want to display my search result , in the content region ,
Please find my question picture view below..
Validate and submit are not for outputting data.
You should show your results in custom1_default_form:
Add in submit $_SESSION['search_text'] or use multistep "storage" (learn drupal form api for this).
But let's look how to work via sessions:
Add in custom1_default_form:
// Here is your form code, so form will appear on the top
// ...
if (isset($_SESSION['search_text'])) {
//add here your code from submit that output searching result
$form['result'] = array(
'#type' => 'item',
'#value' => $output,
);
unset($_SESSION['search_text']); // don't forget clear session
}
Your submit function should be like this:
function custom1_default_form_submit($form, &$form_state) {
$_SESSION['search_text'] = $form_state['values']['txt_name'];
// this will store text field into session, then reload page,
// so you drupal_get_form will see entered values.
}
This is all.
Tips:
if(($form_state['values']['txt_name']) == '') {
form_set_error('user_webservice', t('Enter a name'));
}
This code is not needed, if you do:
$form['txt_name'] = array(
... // other properties
'#required' => true,
);
Read please about form api here: http://api.drupal.org
Other way to use block, just call function that output result and form via drupal_get_form, so:
...
$block['content']='custom1_default_result';
...
function custom1_default_result () {
$output .= drupal_get_form('custom1_default_form');
...
$output .= //search result if session filled/
}

Resources