In my custom module I would like to add the comments functionality. I've tried a couple of things but didn't workout so far.
// render comments form
$output .= theme('my_module_front_page');
$comment = new stdClass;
$comment->nid = $node_good_practice->nid;
$output .= render(drupal_get_form('comment_form', $comment));
return $output;
The code above puts the comments form to my node page.
But when I fill in the comment form and submit, it redirects me to this page: comment/reply/node id
and then i have to fill in my comment all over again and the comment isn't saved.
I would like to submit and stay on the same page instead of the redirect. And the comment must be saved after submitting.
Right now, the comment form appears on my node page (custom module template). I enter a comment and click on "Save."
I am sent to /comment/reply/<node_id>
, but all the comment fields are empty. The comment isn't saved either.
What I would like to happen is:
Adding Redirect
$form['#redirect'] = "/success-stories/".$node_good_practice->good_practice_name."/".$node_good_practice->nid;
It did not change anything.
Changing action
$form['#action'] = "/success-stories/".$node_good_practice->good_practice_name."/".$node_good_practice->nid;
It redirects me to node/node_id/#comment-17
Use drupal_build_form()
$info->nid = $node_good_practice->nid;
$comment['build_info']['args'][0] = $info;
$comment['redirect'] = "http://www.google.nl";
$output .= render(drupal_build_form('comment_form', $comment));
The form is being displayed, but it does not redirect; it is sent to comment/reply/node_id
.
Since you are using a custom module, you could alter the comment_form using the form_alter hook for your specific cases. You can set the form to only use your modules submit function. Then in your custom submit function, you submit the comment to the comment module for saving (calling the comment_form_submit function), and then do the redirect back to the node yourself.
Something along the lines of this:
<?php
function mymodule_form_alter(&$form,&$form_state,$form_id){
if ($form_id == 'comment_form' && isset($form['#node']) && ($form['#node']->type == 'mynodetype')){
$form['#submit'] = array('mymodule_comment_form_submit');
}
}
function mymodule_comment_form_submit($form,&$form_state){
module_load_include('module','comment');
comment_form_submit($form,$form_state);
$url = drupal_get_path_alias('node/'.$form['#node']->nid);
header('Location: '.$url, TRUE);
drupal_exit($url);
}
In your template file, still build the comment form the way you are:
$info->nid = $node_good_practice->nid;
$comment['build_info']['args'][0] = $info;
$output .= render(drupal_build_form('comment_form', $comment));
This solution may seem a bit hacky, but it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With