Help with ajax callback and drupal_process_form - ajax

I have a form that is added through the nodeapi displayed only on view mode. Users can select an item from a select menu and their choice will automatically get saved to the database with a hook_menu callback on change. If the user has javascript disabled, it'll submit normally with the form api. This is all working fine, but now for security reasons I want to submit the ajax version via the form api too. My form_name_submit is simple like:
function mymodule_test_form_submit($form, &$form_state) {
global $user;
db_query("INSERT INTO {mymodule} (nid, uid, status, created) VALUES (%d, %d, %d, " . time() . ")", $form['#parameters'][2], $user->uid, $form_state['values']['mymodule_status']);
}
My ajax:
$('.mysubmit').css('display', 'none');
$('.myclass').change(function() {
$.ajax({
type: 'POST',
url: Drupal.settings.basePath + 'mymodule/set/' + $nid + '/' + $('.myclass').val(),
dataType: 'json',
data: { 'ajax' : true, 'form_build_id' : $('#mymodule-form input[name=form_build_id]').val() }
});
});
And my callback function:
function mymodule_set($nid, $status) {
$form_build_id = $_POST['form_build_id'];
$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form['#post'] = $_POST;
$form['#redirect'] = FALSE;
$form['#programmed'] = FALSE;
$form_state['post'] = $_POST;
drupal_process_form($form_id, $form, $form_state);
}
Originally my callback function was about the same as my submit function, but now I'm trying to use the submit function with ajax as well. Is this the right way to use drupal_process_form? The form is grabbed from the cache, it get's validated and submitted if no errors? I'm using some code from this tutorial to apply to my situation: http://drupal.org/node/331941 There doesn't seem to be any examples of what I'm trying to do. I also have $form['#cache'] = TRUE; in my form function.
How does drupal_process_form compare the submitted values with the original form to check for integrity? Am I supposed to add my values to the form_state since the form state will be empty with ajax. Been stuck on this for a few days, hopefully someone has experience with this.
Thanks.

I had to do somenthing similar to you in the past and read the same tutorial you posted, unfortunately there isn't much information avalaible about this and it was headache for me to make it work. I don't remember well the details but I was taking a look to the code I wrote and here are a couple of suggestions that may work for you:
Do not submit the form using your own jQuery code, instead use the new "#ahah" property of form elements that can be used for calling your callback in the onchange of the select http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/6#ahah
IF you are doing this in a node form, adding the #ahah property in a form alter may not work, I remember having seen an issue about this that wasn't solved at that moment. if this is the case, use this code for attaching the ahah binding, you'll not need "efect", "method" or "progress" since you just want to submit the form, not to change anything about it:
function YOURMODULE_form_alter(&$form, $form_state, $form_id) {
if ('YOURCONTENTTYPE_node_form' == $form_id) {
//the only way I could make it work for exisiting fields is adding the binding "manually"
$ahah_binding = array(
'url' => url('YOURCALLBACKPATH'),
'event' => 'change',
'wrapper' => 'FIELD-wrapper',
'selector' => '#FIELD',
'effect' => 'fade',
'method' => 'replace',
'progress' => array('type' => 'throbber'),
);
drupal_add_js('misc/jquery.form.js');
drupal_add_js('misc/ahah.js');
drupal_add_js(array('ahah' => array('FIELDd' => $ahah_binding)), 'setting');
//force the form to be cached
$form['#cache'] = TRUE;
}
}
Here is my callback function, note that it has some modifications from the tutorial you posted:
function YOURMODULE_js() {
// The form is generated in an include file which we need to include manually.
include_once 'modules/node/node.pages.inc';
// We're starting in step #3, preparing for #4.
//I have to add the 'rebuild' element, if not an empty node was created
$form_state = array('storage' => NULL, 'submitted' => FALSE, 'rebuild' => TRUE);
$form_build_id = $_POST['form_build_id'];
// Step #4.
$form = form_get_cache($form_build_id, $form_state);
// Preparing for #5.
$args = $form['#parameters'];
$form_id = array_shift($args);
$form_state['post'] = $form['#post'] = $_POST;
$form['#programmed'] = $form['#redirect'] = FALSE;
// if you want to do any modification to the form values, this is the place
// Step #5.
drupal_process_form($form_id, $form, $form_state);
// Step #6 and #7 and #8.
$form = drupal_rebuild_form($form_id, $form_state, $args, $form_build_id);
// Final rendering callback.
drupal_json(array('status' => TRUE, 'data' => $output));
}
As I said before there are details that I have forgot but maybe this will help you.
Good Luck.

Related

Frontend custom post submission results in wp_insert_post() undefined

I've been struggling for a few days with this issue and I really hope you can help me out.
I've created a plugin, which is located in:
'/wp-content/plugins/my-cool-plugin'.
My plugin allows users to post a custom post type via a form on a public page, basically anyone should be able to post something.
Using jQuery, I listen to when my frontend form is submitted and using Ajax I pass the data from the form to a php file to process it into a post.
This file is located at:
'/wp-content/plugins/my-cool-plugin/inc/processor.php'.
Below is the content of my processor file:
$var1= $_POST['some'];
$var2= $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish',
'mcp_1' => $var1,
'mcp_2' => $var2
);
$post_id = wp_insert_post( $new_post, $wp_error );
if ($wp_error == 'false'){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
When I test my form, it results in the following error:
Call to undefined function wp_insert_post() on line ... which is the following line:
$post_id = wp_insert_post( $new_post, $wp_error );
Do I need to include something since I'm not in the WordPress 'scope' anymore?
Or is there another (much better) way for inserting custom posts from a front end form?
Why are you running the file out of wordpress scope? That is not the best practive. Instead you could run it in wordpress scope and user wordpress native ajax.
add_action('wp_ajax_yourplugin_create_post', 'yourplugin_create_post');
add_action('wp_ajax_nopriv_yourplugin_create_post', 'yourplugin_create_post');
function yourplugin_create_post() {
// your code here
}
Then you would need your ajax url to be passed from php to js:
function your_plugin_ajaxurl() {
?>
<script type="text/javascript">
var yourPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
}
add_action('wp_head','your_plugin_ajaxurl');
Then you can use your ajax request but you would need to indicate action:yourplugin_create_post and url = yourPluginAjaxUrl
Try adding
require(dirname(__FILE__) . '/wp-load.php');
It took me some time to process Nick's answer, but I finally got it to work! Like Nick said, I dropped using the process file because is was out of the scope of WordPress. I moved my post creation from my proces file to a new function in the plugin init file (my-cool-plugin.php), as Nick suggested. This resulted in the following new function:
add_action('wp_ajax_coolplugin_create_post', 'coolplugin_create_post');
add_action('wp_ajax_nopriv_coolplugin_create_post', 'coolplugin_create_post');
function coolplugin_create_post() {
$var1 = $_POST['some'];
$var2 = $_POST['data'];
$new_post = array(
'post_type' => 'my_custom_post',
'post_status' => 'publish'
'post_title' => 'Some title'
);
$post_id = wp_insert_post( $new_post, $wp_error );
// check if there is a post id and use it to add custom meta
if ($post_id) {
update_post_meta($post_id, 'mcp_1', $var1);
update_post_meta($post_id, 'mcp_2', $var2);
}
if ($wp_error == false){
$post_url = get_permalink( $post_id );
echo $post_url;
}else {
// some sort of error
}
}
I also had to change the way I inserted my custom values into the newly created post, because the wp_insert_post() function only accepts default post parameters (see the wp_insert_post documentation for these parameters).
Next to my insert/create post function I also had to make some adjustments to my javascript file, which retrieves the filled in data from my form. Therefore (as Nick suggested) I needed to pass my Ajax URL from PHP to JS by adding the following function to my-cool-plugin.php like this:
function your_plugin_ajaxurl() { ?>
<script type="text/javascript">
var coolPluginAjaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }
add_action('wp_head','your_plugin_ajaxurl');
By adding the coolPluginAjaxUrl variable to the head I'm able to use the URL in my javascript to post the data to when my form is submitted, like this:
$( '#form' ).on( 'submit', function(e) {
var request;
e.preventDefault();
var val_one = $( '#val-one' ).val();
var val_two = $( '#val-two' ).val();
var formData = {
action: 'coolplugin_create_post',
some: val_one,
data: val_two,
};
request = $.ajax({
type: 'POST',
url: coolPluginAjaxUrl,
data: formData,
});
});
The formData holds the coolplugin_create_post action defined in PHP and the request is posted to the coolPluginAjaxUrl URL, defined in the head.
Thanks Nick for pointing me into the right direction and I hope that my solution will also help others. Please note that I've stripped my code of several security measures for others to easily understand how the code works.

Drupal ajax form, partial render

Good day.
I created custom form in my module and defined submit button like this:
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#ajax' => array(
'callback' => 'fmg_addbanner_ajax_callback',
'method' => 'replace',
'wrapper' => 'banner_add_wrapper'
)
);
Then outputted my form like this:
$form = drupal_get_form('fmg_banner_add_form', $region_id);
print render($form);
But ajax requests don't work. I think because of there are no needed drupal js files. How can I solve this problem? Thanks.
The normal case will be to have #ajax attached to a common input, like checkbox, text box etc.
The behavior is that when user change the input value, it'll fire your callback through ajax and send entire form over, and then you can process this form behind the scene and adjust certain things before sending the form back and change the element to the wrapper you defined.
One of the question that I had for partial form rendering is when I need to do some ajax call or inject partial form element to certain area of the page while keeping the integrity of the form rendering. (I don't know exactly what form build did, i guess i don't want to know)
Since form rendering uses the renderable array, if you just want to extract certain element, you could just do
$form = drupal_get_form('application_form');
$body = render($form['body']);
The following is a real example that i took a form and split into header, footer and the rest of form elements.
// get a form for updating application info.
$form = drupal_get_form('pgh_awards_review_application_form', $app);
$elements = array();
$form_render = render($form);
$elements = array(
'qualify' => render($form['qualify']),
'threshold_met' => render($form['threshold_met']),
'submit' => render($form['submit']),
);
if (preg_match('/<form.+div>/', $form_render, $matches)) {
$elements['header'] = $matches[0];
}
if (preg_match('/<input type="hidden".+form>/s', $form_render, $matches)) {
$elements['footer'] = $matches[0];
}
$vars['form'] = $elements;
It's definitely not pretty approach, it just serves the needs at the moment.

Update area outside of CGridView via Ajax

I'm working with CGridview and updating the grid after an Ajax call. However before I get into the grid I have a a small title and a count $model->itemCount identifying how many records there are. How would I additionally try to update this piece of information along with the grid. Would it be a separate JS call?
Appreciate any help
This is my current code for the grid
'click'=>"function(){
$.fn.yiiGridView.update('item-grid', {
type:'POST',
url:$(this).attr('href'),
success:function(message) {
$('#Ajax-Flash').html(message).fadeIn().animate({opacity: 1.0}, 3000).fadeOut('slow');
$.fn.yiiGridView.update('item-grid');
}
})
return false;
}",
Not sure is this what yoy want but you can use beforeAjaxUpdate() in CgridView as shown below
<?php
$this->widget('zii.widgets.grid.CGridView', array('id'=>'insurance_grid',
'beforeAjaxUpdate'=>"function(id, data){
//Your code to update the title and count
}",
'dataProvider'=>$model->search(),
//'filter'=>$model,
'summaryText' => '', // 1st way
'template' => '{items}{pager}', // 2nd way
'selectableRows' => 2,
'selectionChanged' => "
function(id){
}",
'columns'=>array(array('id'=>'selectedCompanies',
'class'=>'CCheckBoxColumn',
array('name'=>'Agency Name',
'type'=>'raw',
'value'=>'$data->agencyname',
),
),
));
?>

Drupal Form API : display the same form again with AJAX, but with different values, on submit

this is my first post on Stackoverflow, after reading perhaps hundreds of thoughtful questions and no less useful answers.
My point is, today, I never found an (even dirty) way to do what I intend to do, and never managed to find an answer, although it seems quite improbable that no one ever had the same request and/or problem.
Which is, by the way...
Calling the same form again with AJAX, but with different values than those previously entered by the user
The idea
I've got a Drupal Form (a normal form built with Drupal Form API) with textfields and an AJAX-ified submit button. This form is displayed through an AJAX call and is itself AJAX-ified, so.
When I click on 'Submit', I want to do some stuff like looking in the database, updating some values, etc, based on what the user entered in the form. And then, I want to ajax-display the same form again, but with different values than those entered by the user in the first instance of the form.
Everything goes fine with doing whatever I want during the processing, but whatever I do, no matter what, I face the same problem again and again :
The problem
When the new instance of the form is displayed, it is displayed with the previous values (those entered by the user). I never was able to display other values than those previously here in the form when "Submit" was clicked in the previous instance of the form.
Simple example
What I'm actually trying to do is quite complex, with several ajax_commands and a bit of processing, but here is a simpler example that faces exactly the same problem :
function ajax_first_callback_to_my_form($type = 'ajax') {
// here the first instance of the form is ajax-called. No problem with that.
$mail = 'example#mail.com';
$first_message = 'Please enter an email address...';
$commands = array();
$commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($mail, $first_message));
$page = array('#type' => 'ajax', '#commands' => $commands);
return($page);
}
function display_my_form($mail, $message) {
// the function used to display the form.
// it can be called by the first ajax callback (the previous function in this example)
// or by the ajax callback triggered by clicking 'submit' on the form itself.
$form = drupal_get_form('my_form', $mail, $message);
$display = '<div id="my_ajax_wrapper">';
$display .= render($form);
$display .= '</div>';
return $display;
}
function my_form($form, &$form_state, $mail, $message) {
// the form constructor
$form = array (
'email' => array (
'#type' => 'textfield',
'#default_value' => $mail,
'#suffix' => '<div id="my_message">'.$message.'</div>',
),
'submit' => array (
'#type' => 'submit',
'#ajax' => array (
'callback' => 'my_ajax_callback', ),
),
);
}
function my_ajax_callback($form, &$form_state) {
// triggered by clicking 'submit' in the form
$mail = $form_state['values']['email'];
if ($mail == 'correct_mail#gmail.com') {
$new_mail = 'different_mail#gmail.com';
$new_message = 'You entered a correct email and here is your new one';
} else {
$new_mail = $mail;
$new_message = 'You entered an incorrect mail, please correct it';
}
$commands = array();
$commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($new_mail, $new_message));
$page = array('#type' => 'ajax', '#commands' => $commands);
return($page);
}
function my_form_submit($form, &form_state) {
// my_form submit handler
$form_state['rebuild'] = true; // appears necessary, otherwise won't work at all
}
Okay, it was quite a long piece of code but it seemed useful to fully understand my question.
Processing stuff happens correctly...
All the stuff I want to do in my_form_submit or in my_ajax_callback is properly done. If I check the variables in display_my_form() they are correctly updated.
... but the new instance of the form doesn't take it into account
But whatever I can try, the next time the form is displayed with AJAX, the email field will be 'example#mail.com' as its default value (or any different mail entered by the user), and the message div will be filled with 'Please enter an email address...'.
I tried MANY ways of doing this differently, putting the after-submit processing in the ajax callback, in the my_form_submit function, using $_SESSION variables instead of passing them through the different functions, using the database... None of this works.
What to do ?
Quite annoying. This is not the first time I encountered this problem. Last time I could find a workaround, simply by giving up this idea of re-displaying the same form through AJAX, but now I really would appreciate being able to do this.
Could the problem be related to $form_state['rebuild'] ?
By the way, I'm curious about it : have you encountered this problem before ? Is it something simple which I'm missing out ? If it's a bug, could this bug be Drupal-related, or AJAX-related... ?
Any help or ideas will be truly appreciated. Thank you for your time.
I came up with a solution to this one :
If you are to display the same form again with AJAX, for instance with this function (called by your AJAX callback), no matter what you'll do, it will display the same values again and again :
// It doesn't work :
function display_my_form($mail, $message) {
$form = drupal_get_form('my_form', $mail, $message);
$display = '<div id="my_ajax_wrapper">';
$display .= render($form);
$display .= '</div>';
return $display;
}
If you want to change the fields values when refreshing the form, you have to update the form manually, after having called it again, by adding this kind of line :
// It works :
function display_my_form($mail, $message) {
$form = drupal_get_form('my_form', $mail, $message); // $variables are simply ignored if the form is already displayed. Rebuilding it won't change a thing.
$form['email']['#default_value'] = $mail; // update a part of the form
$form['email']['#suffix'] = $message; // update another part of the form
$display = '<div id="my_ajax_wrapper">';
$display .= render($form);
$display .= '</div>';
return $display; // sends $display to our AJAX callback, and everything's fine now
}
Contrary to easy belief one (such as... me) can first have about it, the form doesn't take into account the variables it's being sent with drupal_get_form, when already constructed and recalled by AJAX.
It's just not enough to update the variables, and do drupal_get_form again. You have to do drupal_get_form, and afterwards manually update the parts of the form you want updated.
Hope this will help someone.
Well I am quite confident about your issue if this is the case:
$commands[] = ajax_command_replace('#my_ajax_wrapper', display_my_form($new_mail, $new_message));
The problem is not anything else its just the id you are passing.You need a class and not the id "#my_ajax_wrapper", because id might get changed but class won't in this case.
Try with this you should get the result as you want.
Note: to make it work, one needs to add this in form_submit handler:
function my_form_submit($form, &$form_state)
{
$form_state['rebuild'] = true;
}

Drupal Webform Validation (webform_form_alter)

I'm doing some webform validation using webform_form_alter. I'm using webform_form_alter because I switch certain content on a "select" field.
In my webform-form-317.tpl.php I defined new fieldsets I set my fields into this new fieldset and unset the original from the webform.
$form['submitted']['ContactInfo'] = array(
'#type' => 'fieldset',
'#prefix' => '<div id="ContactInfo">',
'#suffix' => '</div>',
'#weight' => -10,
'#title' => 'Contact Information'
);
$form['submitted']['ContactInfo']['phone_home'] = $form['submitted']['phone_home'];
unset($form['submitted']['phone_home']);
in my webform_form_alter I have the following code:
switch ($form_id)
{
case 'webform_client_form_317':
{
$form['#validate'][] = 'validate_form';
}
}
My Validate_form function looks like:
function validate_form($form_id, $form_values)
{
if ($form_values['submitted_tree']['ContactInfo']['phone_home'] == "")
{
form_set_error('phone_error', t('Please enter a home phone number.'));
}
}
The issue is that the $form_values['submitted_tree']['ContactInfo']['phone_home'] comes back as nothing even is the user has inputted something into the textfield.
Any suggestions on what i'm doing wrong?
As a second question in case somebody also the answers, how do I modify the of these textfields to set the class for "form-text required error" so they show up in red with the rest of the mandatory fields.
Thanks
I hope you don't write this code in the webform module, but have made your a custom module for it.
In the first case, your function should be
function validate_form($form, &$form_state) {
if ($form_state['values']['submitted_tree']['ContactInfo']['phone_home'] == "") {
form_set_error('phone_home', t('Please enter a home phone number.'));
}
}
If you are talking about the error class, Drupal add it to all fields that has an error set like is done on the above code. You need to pass in the name of the form field as first param to the form_set_error function.

Resources