4

I'm using the following code to add a cancel button on every form I have for add / edit of every content type. The target should be the destination adress in the url

In some content types it is working and some not:

$link = l(t('Annuleren'), drupal_get_destination());

      // add the actual button to the form
      $form['actions']['cancel'] = array(
        '#type'   => 'submit',
        '#value' => "Annuleren",
        '#access' => TRUE,
        '#weight' => 55,
        '#submit' => $link,
        '#limit_validation_errors' => array(),
        );

      dpm ($form);    

It has something todo with #value. If I replace it to #markup like below example then it is working but I do not get a label in the button.

  '#markup' => "Annuleren",

How to solve this?

6

In your code above, you're using wrong value for #submit. #submit accepts an array of submit callback function names, check e.g. here.

You can either add a link in form, which will take user to destination and style the link to look like a button. Check example below:

function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'markup',
    '#markup' => '<div class="form-cancel-button-wrapper">' . l(t("Cancel"), 'URL', array('attributes' => array('class' => array('form-cancel-button')))) . '</div>',
  );

  return $form;
}

OR you can create a normal submit button and add a custom submit handler which will take user to destination. Check example below:

function _custom_form() {
  $form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value' => "Cancel",
    '#weight' => 55,
    '#submit' => array('_custom_form_cancel')
    '#limit_validation_errors' => array(),
  );

  return $form;
}

function _custom_form_cancel($form, &$form_state) {
  drupal_goto('URL');
}

Note: When you define a custom form element, you don't need to give #access property specifically, it is TRUE by default.

  • You'd better use $form_state['redirect'] = 'redirect-to-this-path'; to the submit handler instead of drupal_goto. Read this post for details. – mchar Nov 14 '16 at 9:59
  • @mchar, yes, we can use $form_state['redirect'] as well, but since its a cancel button, we can use drupal_goto() as well because there is nothing which will be stopped from executing after user clicks on cancel. – Yogesh Nov 14 '16 at 10:17
  • Totally agree! but what if you want to hook to that redirect from another module later on? – mchar Nov 14 '16 at 10:39

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.