20

How can I pass arguments to drupal_get_form() in Drupal 7?

function new_menu_callback() {
  $vars = some_example_function(); // returns: array(1 => 'one', 2 => 'two');
  $output = $vars[2];
  $output .= drupal_render(drupal_get_form('new_form'));
}

function new_form($form, &$form_state) {
  // How can I access $vars[1] from new_menu_callback() here?
}
1
  • 4
    There are a lot of examples for this. Run a grep for drupal_get_form from drupal root directory.
    – Sivaji
    Commented Sep 10, 2011 at 7:37

3 Answers 3

35

Just add $vars as second argument.

drupal_get_form('new_form', $vars);

and...

function new_form($form, &$form_state, $vars) {
// ...

Quote from drupal_get_form()

... Any additional arguments are passed on to the functions called by drupal_get_form(), including the unique form constructor function. For example, the node_edit form requires that a node object is passed in here when it is called. These are available to implementations of hook_form_alter() and hook_form_FORM_ID_alter() as the array $form_state['build_info']['args'].

3

The additional arguments you pass to drupal_get_form() are available in $form_state['build_info']['args'], but you can't have function calls in your page arguments. I'd suggest the following approach:

function mymodule_menu() {
    $items = array();
    $items['mymodule/example'] = array(
      'page callback' => 'drupal_get_form',
      'page arguments' => array('mymodule_form'),
    );
    return $items;
}


function mymodule_form($form, &$form_state) {
  // this function now uses dev/user friendly named keys
  $vars = mymodule_example_function();
  $form = array();

  $form['heading'] = array(
    '#markup' => check_plain($vars['heading']),
  );

  // use other arguments here

  return $form;
}

The rest of what you need is in the Form API reference

1
1

I had a similar issue and it was solved with a mix of @kalabro's answer and my own way to deal with it.

So basically I have a static landingpage where I use tokens. In the hook_tokens I call the register form via $form = drupal_get_form('user_register_form', 'register-test');.

And finally in the hook_form_alter I check the if the String is "register-test". This is done via $form_state['build_info']['args'][0]. Here the function:

function hook_form_user_register_form_alter(&$form, &$form_state, $form_id) {
...
if ($form_state['build_info']['args'][0] == 'register-test') {
    // manipulate the form as usual
    $form['...
  }
...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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