5

I have a custom module with form and I want to pass the values from form_state into email. This is my code.

//The form page callback
function mymodule_page($form, &$form_state) {
    $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter name here'),
    );
    $form['surname'] = array(
        '#type' => 'textfield',
        '#title' => t('Enter surname here'),
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#submit' => array('mymodule_submit'),
    );

    return $form;
}

function mymodule_submit($form, &$form_state) {
    $name = $form_state['values']['name']; 
    drupal_mail('mymodule', 'mymodule_mail', 'myemail', language_default(), array($name));
    dpm($form_state);
}

/**
 * Implements hook_mail().
 */
function custom_test_mail($key, &$message, $params) {
    switch($key) {
        case 'mymodule_mail':

        $message['subject'] = t('Hello');
        $message['body'][] = t('This is a body text');

        break;
    }
}

I'm receiving the email with the subject and body, but without the value from $form['name'].

How can I pass the values from form fields?

6

You're already passing $name as a parameter, but you're not actually inserting it into the body so it won't show up in the email.

It's best to use a keyed array so you can easily refer to parameters by name, something like this:

$params = array('name' => $name);
drupal_mail('mymodule', 'mymodule_mail', 'myemail', language_default(), $params);

...

$message['body'][] = t('This is a body text');
$message['body'][] = t('Name: @name', array('@name' => $params['name']));
  • Thank you, Clive. It's working great. I wish I could add 10 points :) – user2519032 Feb 18 '14 at 21:55

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.