Search code examples
phpemailcraftcms

Craft - Dynamically adding email recipients error


Currently working on dynamically adding email recipients into my Craft Contact Form. My current setup follows the instructions on the contact form github exactly.

In my form I've added the following line:

<input type="hidden" name="toEmail" value="{{ '[email protected]'|hash }}" />

In config/contact-form.php I've added the following:

<?php

$config = [];
$request = Craft::$app->request;

if (
    !$request->getIsConsoleRequest() &&
    ($toEmail = $request->getValidatedBodyParam('toEmail')) !== null
) {
    $config['toEmail'] = $toEmail;
}

return $config;

The error which I'm getting is:

HTTP 400 - Request contained an invalid body param

The toEmail field is getting to the contact-form.php it just seems to fail on validation? Whenever I change the name of the input field to whatever name="toEmailxxx" it just sends it correctly to the email set in the CMS settings.

How can I resolve this issue?


Solution

  • I think here is what you are looking for:

    Then from your craft/config/contact-form.php config file, you’ll need to add a bit of logic:

    <?php
    namespace Craft;
    
    $toEmail = craft()->request->getPost('toEmail');
    $toEmail = craft()->security->validateData($toEmail);
    
    return array(
        'toEmail' => ($toEmail ?: null),
        //.....