Allowing E-Mail to be optional in form?

Hey everyone,

I’m currently tinkering with contact form as described in Cookbook, it works almost everything as expected.

The contact form is a booking form for online apointments, the form generates a unique video conference link and password for user and client. The data is being shown in confirmation page and sent via mail.

Sometimes our clients don’t want to share e-mail, they only need to have conference link (that is OK for us too, some clients don’t want to enter the mail because of privacy reasons).

Now here is my question, how should I modify the controller to allow e-mail to be optional? Probably something in ‘to’ line should be changed? Currently, it looks like this:

            $kirby->email([
                'template' => 'text-client',
                'from'     => 'no-reply@topsecretclientmail.dot.com',
                'to'       => $data['email'],
                'subject'  => 'Online-Beratung beim XXXXX - Ihre Anfrage für ' . $page->date()->toDate('%d %B %Y'),
                'data'     => [
                    'date'              => $page->date()->toDate('%d %B %Y'),
                    'timeframe'         => $page->timeframe(),
                    'name'              => get('name'),
                    'vorname'           => get('vorname'),
                    'company'           => get('company'),
                    'sbausweis'         => get('sbausweis'),
                    'arbeitssituation'  => get('arbeitssituation'),
                    'beratungsform'     => get('beratungsform'),
                    'beratungdgs'       => get('beratungdgs'),
                    'email'             => get('email'),
                    'message'           => get('message'),
                    'panelurl'          => $page->panel()->url(),
                    'randomizer'        => md5(str::slug($data['name'] . $akt_microtime))
                ]
            ]);

In this current state, the contact form outputs error when mail is not entered and expect the user to enter mail.

If you don’t want to require the email field, then make it optional in the form. Has nothing to do with the code you are showing, because that is about sending an email.

The email is required in the rules

  $rules = [
            'name'  => ['required', 'minLength' => 3],
            'email' => ['required', 'email'],
            'text'  => ['required', 'minLength' => 3, 'maxLength' => 3000],
        ];

So you would have to remove the required attribute.

That looks as if you wanted to send something to the mail address you get from the form. But of course, you cannot send anything if you have no email address.

When removing the Mail from required, I still get this error:

And for second part of your message, I’d love to send the mail if a mail is entered :slight_smile:

The you need to make the email sending conditional depending on the value of the email field.