Drupal AJAX button on user profile

2019-08-08 15:26发布

问题:

I've been trying to add AJAX buttons for a while. I am able to do it on forms, like this:

function hook_form_alter(&$form, &$form_state, $form_id) {
$form['suspend'] = array(
            '#type' => 'button',
            '#name' => 'foo',
            '#value' => t('bar'),
            '#ajax'  => array('callback' => '_foo_bar'),
        );

return $form;
}

working fine. However I cannot get it to work on user profiles or non-forms, like this:

function hook_user_view_alter(&$build) {
$build['suspend'] = array(
            '#type' => 'button',
            '#name' => 'foo',
            '#value' => t('bar'),
            '#ajax'  => array('callback' => '_foo_bar'),
        );

return $build;
}

Are there simple ways of doing this? I use blocks & views on this site and would rather not have to install Panels if possible (:

Thanks!

回答1:

If it's not inside a form, wrap it into a form:

function example_suspend_form($form, &$form_state) {
  $form['suspend'] = array(
    '#type' => 'button',
    '#name' => 'foo',
    '#value' => t('bar'),
    '#ajax'  => array('callback' => '_foo_bar'),
  );

  return $form;
}

function example_user_view_alter(&$build) {
  $build['example_suspend_form'] = drupal_get_form('example_suspend_form');
}