简体   繁体   中英

Drupal 7 & PHP - display content if $form is any Content Type

I need help creating an if statement that will print out a cancel button only in forms for nodes. Without an if statement the cancel button prints out on all forms, including site search forms. I tried using a '$form_id !=' but adding every form ID where I don't want the cancel button to be doesn't seem very intuitive. Any help would be much appreciated.

<?php

/**
* Implements hook_form_alter().
*/
function cancel_button_form_alter(&$form, &$form_state, $form_id) {
  // Here is where I'm having trouble. What variable can 
  // I put that targets ANY content type?
  if ($form_id != 'search_block_form') {
    // Add a cancel button.
    $form['actions']['cancel'] = array(
      '#type' => 'submit',
      '#value' => t('Cancel'),
      '#access' => TRUE,
      '#weight' => 15,
      '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
      '#limit_validation_errors' => array(),
    );
  }
}

/**
* Custom cancel button callback.
*/
function cancel_button_form_cancel($form, &$form_state) {
$url = $_GET['destination'] ? $_GET['destination'] : '';
drupal_goto($url);
}

If you are in a node/content, the $form variable will have a node object. But if the form is not for/from node then it won't have the node object. You can check like this:

if(isset($form['#node'])) {
    // Your code goes here
}

Actually, I have a bit confusion about $form['#node'] (:P). You can get it by debugging the $form or $form_state variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM