2

I need one button at the end of one content type view form. This button should redirect the user to another page.

I have something like the following code:

function mymodule_node_view($node, $view_mode, $langcode) {

    if ($node->type == 'my_type') {
            $form = drupal_get_form('redirect_button_form');
            $node->content['redirect_button'] = $form;
            //$node->nid is the data I need in the submit function
    }
 }

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Redirect button text'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    $path = 'mypath';
    $options = ****I need the nid here;
    drupal_goto($path,$options );
}

How can I pass the nid from the hook_node_view to the submit function?

3

See the code with comments inside:

function mymodule_node_view($node, $view_mode, $langcode) {

if ($node->type == 'YOUR_NODE_TYPE') {
  //adding the nid to the drupal_get_form()
  $form = drupal_get_form('redirect_button_form', $node->nid);
  $node->content['redirect_button'] = $form;
 }
}

//see the 3th param ($nid)
function redirect_button_form($form, &$form_submit, $nid) {
    //adding a hiddin field with the nid
    $form['hidden-item'] = array(
    '#type' => 'hidden',
    '#value' => $nid,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('New Item'),
    );
    return $form;
}

function redirect_button_form_submit($form, &$form_state) {
    $path = 'node/';
    //here your nid
    $options = $form_state['values']['hidden-item'];
    $path .= $options . '/edit';
    drupal_goto($path);

}
3

You don't need to use form here. Just use l() with the button name and the link path.

function mymodule_node_view($node, $view_mode, $langcode) {

if ($node->type == 'my_type') {
   $node->content['redirect_button'] = array(
     '#markup' => l('Redirect button', 'yourpath/' . $node->nid);
   );
    }
}
  • I test the code but don't works for me. – Adrian Cid Almaguer Jan 18 '16 at 17:13
  • I edited my answer. Please check now. – Manikandan Jan 19 '16 at 5:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.