Drupal FAPI form calls callback twice - drupal

First post on stack overflow... so go easy on me!
There doesn't seem to be a suitable solution to the Drupal FAPI multiple callback issue for simple form submissions.
THE PROBLEM: My form, when submitted, adds two entries to the respective database table. Given that there is only one call to add it to the database, I feel it's safe to assume that the query is run twice (hence the dual entries).
The following code may help to provide a basis for a solution. Oh, it's Drupal 7 too, so documentation is still very much D6 centric.
function mymodule_sidebar_form_add_submit(&$form, &$form_state) {
$form_values = $form_state['values'];
$se_title = check_plain(trim($form_values['title']));
$se_link = url(trim($form_values['link']));
$se_content = check_plain(trim($form_values['content']));
$se_image = isset($form_values['image']) ? $form_values['image'] : '';
// The multi-line part below is actually a single line the real code
$query = sprintf("INSERT INTO sidebar_element(title, image_url, content)
VALUES ('%s', '%s', '%s');", $se_title, $se_image, $se_content);
db_query($query);
drupal_set_message(t('Sidebar Element has been added successfully.'));
}
... and my form function contains a submit button:
$form['submit'] = array(
'#value' => t('Add Sidebar'),
'#type' => 'submit',
'#title' => t('Add Sidebar'),
'#submit' => array('mymodule_sidebar_form_add_submit'),
);
I guess the questions I need answered are:
Why is there a double callback in the first place?
Is there a way to identify the first callback?
Thanks in advance to all.

$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save')
);
$form['#submit'] = array('my_form_submit');
And replace
// The multi-line part below is actually a single line the real code
$query = sprintf("INSERT INTO sidebar_element(title, image_url, content)
VALUES ('%s', '%s', '%s');", $se_title, $se_image, $se_content);
db_query($query);
with
// The multi-line part below is actually a single line the real code
$query = "INSERT INTO {sidebar_element} (title, image_url, content)
VALUES ('%s', '%s', '%s')";
db_query($query, $se_title, $se_image, $se_content);

For Drupal 7
// Add the buttons.
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#access' => my_func(),
'#value' => t('Save'),
'#weight' => 100,
'#submit' => array('my_form_submit'),
);
As example read node_form() code

To find out where the second call is coming from, the easiest way is to install devel.module and use ddebug_backtrace() in your submit callback. You might need to disable the HTTP redirecto to see it, too (exit()).
But more importantly, use the API, Luke!
<?php
db_insert('sidebar_element')
->fields(array(
'title' => $se_title,
'image_url' => $se_image,
'content' => $se_content,
))
->execute():
?>
This is how your insert query should look like, what you are doing is insecure!
And for SELECT, use db_query() with named placeholders:
<?php
$result = db_query('SELECT * FROM {sidebar_element} WHERE title = :title', array(':title' => $something));
?>

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'];
}

How to add a custom event item in Buddypress Activity Stream?

Does anybody know the basic steps on how to add a custom event item to the Buddypress activity stream? I've got a custom post type of "activity" that my members can click on in the post and it records in a database table that that user has "completed" that activity. More or less like a "to do" list. I'm trying to figure out how I can integrate this with the buddypress activity stream so when a user clicks the button, it inserts something like, "John Doe has completed Permalinked Post Title Here." I've looked through the Buddypress codex & have Googled quite a bit, but I can't seem to find any good tutorials on this. If anybody can point me in the right direction or give me a simple plain English step by step I would appreciate it. Please know that I'm not looking for any code written, just a general idea of the steps involved in making this happen.
For anyone who is searching, this is what I wrote in my php file that was called in the ajax request for the button that "completes" the activity...
// Begin Code for Custom Activity Stream
global $wp, $wp_query;
$this_activity_object = get_post( $activity_post_id_complete );
$title = $this_activity_object->post_title;
$activity_content = $title;
$this_user_profile_url = bp_core_get_user_domain($wp_user_id);
$action_String = "#" . bp_core_get_username($wp_user_id)." just completed a custom activity!";
global $bp;
bp_activity_add( array(
'user_id' => $wp_user_id,
'item_id' => $activity_db_id_complete,
'action' => $action_String,
'content' => $activity_content,
'component' => 'activity',
'primary_link' => '' . $title . '',
'type' => 'custom_activity_update',
'hide_sitewide' => false
));
You can use bp_activity_add(). For example, you'd do it like this:
// record an activity item to the activity table
bp_activity_add( array(
'id' => $id
'user_id' => $user_id,
'item_id' => $item_id,
'action' => $action,
'content' => $content,
'component' => $component,
'primary_link' => $link,
'type' => $type,
'secondary_item_id' => $secondary_item_id,
'recorded_time' => $time,
'hide_sitewide' => false,
'is_spam' => $spam
));
Ref explaining what the parameters mean:
http://codex.buddypress.org/developer/function-examples/bp_activity_add/

Create content in Drupal based on options in a drop down

I am working on a Drupal site that needs to have a 'careers' page. I have a list of twenty or so jobs, and 30 or so locations where these jobs may be available.
What I am looking to do is make it so, when a job becomes available, all that needs to be done is the user selects the job title and the location where it is available and it will create the posting with the job description and other info I have along with the info for that location.
Another hurtle I am running into is making it so I can have multiple instances... ex. If the same job is available at two or more locations.
I have been trying to wrap my mind around how I am going to make this work and am coming up blank. If anyone has an idea to point me in the right direction, it would be appreciated.
Sounds like a pretty common use case; if it was me I'd approach it like this:
Create a 'Job' content type
Add a new 'Location' Vocabulary
Add a term reference field on the 'Job' content type to the 'Location' vocabulary, with unlimited values (or the maximum no. of locations you want to allow per job).
Create a custom form for your admins, something like:
function MYMODULE_add_job_form($form, &$form_state) {
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#maxlength' => 255,
'#required' => TRUE
);
// Load the vocabulary (the machine name might be different).
$vocabulary = taxonomy_vocabulary_machine_name_load('location');
// Get the terms
$terms = taxonomy_get_tree($vocabulary->vid);
// Extract the top level terms for the select options
$options = array();
foreach ($terms as $term) {
$options[$term->tid] = $term->name;
}
$form['locations'] = array(
'#type' => 'select',
'#title' => t('Locations'),
'#options' => $options,
'#multiple' => TRUE,
'#required' => TRUE
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Add job')
);
return $form;
}
Create a custom submit handler for the form to add the new node programatically:
function MYMODULE_add_job_form_submit($form, &$form_state) {
$location_tids = array_filter($form_state['values']['locations']);
$node = new stdClass;
$node->type = 'job';
$node->language = LANGUAGE_NONE;
node_object_prepare($node);
$node->title = $form_state['values']['title'];
$node->field_location_term_ref[LANGUAGE_NONE] = array();
foreach ($location_tids as $tid) {
$node->field_location_term_ref[LANGUAGE_NONE][] = array(
'tid' => $tid
);
}
node_save($node);
$form_state['redirect'] = "node/$node->nid";
}
You'll need to add a page callback for that form obviously, and there'll likely be some small changes you'll need to make (names of fields etc), but it should give you a good starting point. You'll also need to load the location taxonomy terms at some point to extract the description info you mentioned...you can use taxonomy_term_load() to do that.

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.

How to override default values of form on submit event

I have a form which has textfields with default values specified. On submit event, I want these default values to be changed with the new set of values that I am passing. I am using form_set_value($element, $value, $form_state) for this. However it is not updating. Any ideas? My code is
function sample_myform($form_state){
$form['field']['name'] = array(
'#type' => 'textfield',
'#title'=> 'Name: ',
'#maxlength'=> 127,
'#default_value' => param1,
);
$form['field']['placeholder'] = array(
'#type'=> 'value',
'#value' => array(),
);
$form['field']['button1'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
function sample_myform_validate($form,&$form_state){
$name2 = $form_state['values']['name'];
form_set_value($form['field']['placeholder'], $name2, $form_state); */
form_set_value($form['field']['name'],'God',$form_state);
$form_state['rebuild'] = true;
}
One thing for sure, $form['field']['placeholder'] will never, ever change since you set #value. Once #value is set, Form API moves on. Be careful though with setting just #default_value on a #type value as that can be tampered with. You can do something like $form_state['placeholder'] = $name2; in validate and use that in the form builder function.
What you try to do with name works in Drupal 7 but I suspect you are in Drupal 6. The validate function overwrites $form_state['values'] just fine but that's not persisted for the form rebuild. Once again, save into $form_state as you need.

Resources