2

I'm writing a simple module to handle newsletter subscriptions and I want to create a form which is based on information passed in as a url argument.

Example path: /subscribe/verify/eiurhgiergierugskdfadsf

I'd like to create a form for /subscribe/verify which takes "eiurhgiergierugskdfadsf" as a parameter so that I can lookup the user by that hash value and then populate the form with their subscriber id and other information.

I can't seem to figure out how to get url arguments available in my form function though.

$items['subscribe/verify'] = array(
    'title' => 'Verify Email',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('subscribe_terms_form_verify'),
    'access arguments' => array('access content'),
);



function subscribe_terms_form_verify($unique_id) {
   ...
}

How do I safely get access to the url parameter in my form callback?

4

You need to introduce the argument as a 'wildcard', and pass it through to your function in the page arguments like so:

$items['subscribe/verify/%'] = array(
  'title' => 'Verify Email',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('subscribe_terms_form_verify', 2),
  'access arguments' => array('access content'),
);

The hook_menu() docs are worth read, they explain wildcards in good detail.

Your form function will have this signature:

function subscribe_terms_form_verify($form, &$form_state, $unique_id) {

}

$form and $form_state are provided as parameters to your form through drupal_get_form(), so the 3rd argument will contain the information passed from the URL.

4
  • Well said Clive! Nice answer as always :)
    – AKS
    Jan 13 '13 at 20:25
  • I tell you.. I have -tried- to read the wildcard docs about hook_menu(), but they are essentially TOO robust for a n00b. Until I'm able to learn the simple situations, it's hard to really understand what it is describing about the complex situations. Jan 13 '13 at 21:25
  • Thank you for this, it worked! The other examples I had found on SO all referenced 1 extra method parameter and therefore only included 1 in the page arguments array which wouldn't work for me... this worked like a charm. Jan 13 '13 at 21:26
  • Menu wildcards are just one of those things, once you know it you know it but until then it can be confusing. The number that you pass to the page arguments is based on the URL string itself. It breaks down by splitting the URL by the '/' character, then counting from zero until you hit the % character. So for the URL subscribe/% the index would be 1, for subscribe/verify/% it's 2, for subscribe/verify/something/% it's 3 and so on
    – Clive
    Jan 13 '13 at 22:37

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.