<p>You could move the logic to overwrite the recipient email out of the config and into a hook. This ensures that the element query is only executed later in the lifecycle, which avoids the warning you're seeing in the logs. It also avoids inefficiently running the query during every request.</p>
<p>First, set a reasonable default recipient e-mail – in your case <code>support@website.co.uk</code> – in the <code>config/contact-form.php</code> so the settings validate (otherwise, the submission will be cancelled before any event is fired). Then use the <a href="https://github.com/craftcms/contact-form#the-beforesend-event" rel="nofollow noreferrer"><code>beforeSend</code> event</a> to modify the recipient emails right before the e-mail is sent:</p>
<pre class="lang-php prettyprint-override"><code>use craft\contactform\events\SendEvent;
use craft\contactform\Mailer;
use yii\base\Event;

// ...

Event::on(Mailer::class, Mailer::EVENT_BEFORE_SEND, function(SendEvent $event) {
    // your custom logic to find the correct recipient goes here
    $recipient = '…';

    // this must be an array of strings
    $event-&gt;toMails = [$recipient];
});
</code></pre>
<p>You can put this code in a <a href="https://craftcms.com/docs/4.x/extend/module-guide.html" rel="nofollow noreferrer">custom module</a>.</p>

CC BY-SA 4.0
2022-10-21T17:23:58.907Z
Thanks for that. I've created a module following the documents, but must have something wrong as it's not working. The email form submits fine and the email comes through, but it went to the default address in the config file, not overridden by the one from the entry. You can see my code in this gist [link](https://gist.github.com/paul-frost/7f471c1402761b17f263a4d94483a2b4)
Paul Frost
CC BY-SA 4.0
2022-10-22T13:07:47.853Z
I've now updated the code in the gist after a lot or trial and error. But I'm getting "Setting unknown property: craft\contactform\events\SendEvent::toEmail" when I send a message. [link to gist](https://gist.github.com/paul-frost/7f471c1402761b17f263a4d94483a2b4)
Paul Frost
CC BY-SA 4.0
2022-10-24T07:28:30.240Z
@PaulFrost Ah my bad, looks like `SendEvent::toEmails` (also note the `s` at the end) _only_ allows an array of strings, not a single string. I've corrected the example code in my answer, setting `$event->toMails = [$recipient]` should work!
MoritzLost
CC BY-SA 4.0
2022-10-24T11:13:36.173Z
Brilliant, it's working now. Thanks.
Paul Frost
CC BY-SA 4.0
2022-10-21T13:06:56.567Z
2022-10-24T07:28:05.587Z
2022-10-24T07:28:05.587Z
MoritzLost
<p>I'm getting that warning in my log since updating to Craft4.
I've traced it to a problem with my config/contact-form.php.
This is a modified version of the suggested code for <a href="https://github.com/craftcms/contact-form#dynamically-adding-email-recipients" rel="nofollow noreferrer">Dynamically adding email recipients</a>.
With help from the SE community I came up with this as a way to use the <a href="https://craftcms.stackexchange.com/questions/23238/how-to-encrypt-or-hide-variable-dynamic-email-address-in-contact-form">contact form but not reveal any email addresses</a> in the public html code.
Instead of using the email address in the submission it sends the 'contactKey' data field. Then in the config file it does an element query to get all the contacts section entries and then matches up the 'contactKey' field with the 'contactEmail' field and then passes that to $toEmail.</p>
<p>It still works, but I'm concerned that it may cause other issues and ideally should be fixed. But I lack the programming skills to work out what needs to change to prevent the query happening before Craft is initialised. There is a <a href="https://github.com/craftcms/cms/issues/11033" rel="nofollow noreferrer">GitHub thread about this issue here</a>.</p>
<p>Here is my cofig/contact-form.php code:</p>
<pre><code>&lt;?php
$request = Craft::$app-&gt;request;
if (!$request-&gt;getIsConsoleRequest()) {
    $toEmailId = $request-&gt;getBodyParam('toEmail');

$criteria = \craft\elements\Entry::find()
    -&gt;section('contacts')
    -&gt;all();

$allAddresses = [];
foreach($criteria as $entry){
    $allAddresses[$entry-&gt;contactKey] = $entry-&gt;contactEmail;
}
$toEmail = (array_key_exists($toEmailId, $allAddresses))? $allAddresses[$toEmailId] : null;
return [
    'toEmail' =&gt; ($toEmail ?: 'support@website.co.uk'),
    'prependSubject'      =&gt; 'Website:',
    'prependSender'       =&gt; '',
    'allowAttachments'    =&gt; false,
    'successFlashMessage' =&gt; 'Thanks for your message'
];
}
</code></pre>
<p>The public web page contact form has this in it:</p>
<pre><code>&lt;form method=&quot;post&quot; action=&quot;&quot; accept-charset=&quot;UTF-8&quot;&gt;
        {{ csrfInput() }}
        {{ actionInput('contact-form/send') }}
        &lt;input type=&quot;hidden&quot; name=&quot;toEmail&quot; value=&quot;{{ entry.contactKey }}&quot;&gt;
</code></pre>

<plugin-contactform><craft4>
Element query executed before Craft is fully initialized
# Element query executed before Craft is fully initialized

(Asked by: username_0 on 2022-10-21)

I'm getting that warning in my log since updating to Craft4.
I've traced it to a problem with my config/contact-form.php.
This is a modified version of the suggested code for Dynamically adding email recipients.
With help from the SE community I came up with this as a way to use the contact form but not reveal any email addresses in the public html code.
Instead of using the email address in the submission it sends the 'contactKey' data field. Then in the config file it does an element query to get all the contacts section entries and then matches up the 'contactKey' field with the 'contactEmail' field and then passes that to $toEmail.
It still works, but I'm concerned that it may cause other issues and ideally should be fixed. But I lack the programming skills to work out what needs to change to prevent the query happening before Craft is initialised. There is a GitHub thread about this issue here.
Here is my cofig/contact-form.php code:
request;
if (!$request->getIsConsoleRequest()) {
    $toEmailId = $request->getBodyParam('toEmail');

$criteria = \craft\elements\Entry::find()
    ->section('contacts')
    ->all();

$allAddresses = [];
foreach($criteria as $entry){
    $allAddresses[$entry->contactKey] = $entry->contactEmail;
}
$toEmail = (array_key_exists($toEmailId, $allAddresses))? $allAddresses[$toEmailId] : null;
return [
    'toEmail' => ($toEmail ?: 'support@website.co.uk'),
    'prependSubject'      => 'Website:',
    'prependSender'       => '',
    'allowAttachments'    => false,
    'successFlashMessage' => 'Thanks for your message'
];
}

The public web page contact form has this in it:

        {{ csrfInput() }}
        {{ actionInput('contact-form/send') }}

**Tags:** plugin-contactform, craft4


---

## 1 answers

### Answer by username_1 on 2022-10-21. Score: 1 | Accepted answer

You could move the logic to overwrite the recipient email out of the config and into a hook. This ensures that the element query is only executed later in the lifecycle, which avoids the warning you're seeing in the logs. It also avoids inefficiently running the query during every request.
First, set a reasonable default recipient e-mail – in your case support@website.co.uk – in the config/contact-form.php so the settings validate (otherwise, the submission will be cancelled before any event is fired). Then use the beforeSend event to modify the recipient emails right before the e-mail is sent:
use craft\contactform\events\SendEvent;
use craft\contactform\Mailer;
use yii\base\Event;

// ...

Event::on(Mailer::class, Mailer::EVENT_BEFORE_SEND, function(SendEvent $event) {
    // your custom logic to find the correct recipient goes here
    $recipient = '…';

    // this must be an array of strings
    $event->toMails = [$recipient];
});

You can put this code in a custom module.

> **Comments:**
> **username_0**: Thanks for that. I've created a module following the documents, but must have something wrong as it's not working. The email form submits fine and the email comes through, but it went to the default address in the config file, not overridden by the one from the entry. You can see my code in this gist [link](https://gist.github.com/paul-frost/7f471c1402761b17f263a4d94483a2b4)  
> **username_0**: I've now updated the code in the gist after a lot or trial and error. But I'm getting "Setting unknown property: craft\contactform\events\SendEvent::toEmail" when I send a message. [link to gist](https://gist.github.com/paul-frost/7f471c1402761b17f263a4d94483a2b4)  
> **username_1**: @PaulFrost Ah my bad, looks like `SendEvent::toEmails` (also note the `s` at the end) _only_ allows an array of strings, not a single string. I've corrected the example code in my answer, setting `$event->toMails = [$recipient]` should work!  
> **username_0**: Brilliant, it's working now. Thanks.  

---

