1

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="{{ 'me@example.com'|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?

Pimmesz
  • 335
  • 2
  • 8
  • 29

1 Answers1

1

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),
    //.....
halfer
  • 19,824
  • 17
  • 99
  • 186
Priyanka
  • 287
  • 1
  • 11
  • Thank you for your reply! When I use this setup it seems to not know where to get craft from? Error I get is: Call to undefined function Craft\craft() – Pimmesz Nov 22 '19 at 08:44
  • 1
    I guess you are using Craft 3. craft() is gone in Craft 3; instead you will be accessing Craft::$app-> for most things. I'd suggest generating your Craft 3 plugin scaffolding at pluginfactory.io, and if you leave code comments on, it'll give you some hints on how to do stuff like this. This article might also be helpful to you: So You Wanna Make a Craft 3 Plugin? – Priyanka Nov 22 '19 at 08:48
  • The strange thing is that I don't seem to get any bodyParams in my contact-form.php. I guess if I do the following, which is definitively defined in my form, it should print out the values of that bodyParam? It just prints NULL var_dump($request->getBodyParam('fromName')); – Pimmesz Nov 22 '19 at 09:00
  • Wouldn't it be easier, and perhaps safer, to set it within a beforeSend? – Pimmesz Nov 22 '19 at 09:03
  • I'm an idiot!!! Got it to work! I didn't do the hashing of the email correctly. Thank you for your reply!!! – Pimmesz Nov 22 '19 at 09:33
  • Cool ! It happens some time ..ha ha – Priyanka Nov 22 '19 at 10:14