How to get and send radio and select data from a form to an email?

Hey there,

maybe it’s more a question about php in general than Kirby, but I have no idea how I get and send data from my radio and select option of the contact form to my email.

I only found this on the www. “https://kirby-uniform.readthedocs.io/en/latest/examples/extended/” and think it should go into the right direction?

The “input type= text fields” are working fine and I receive the written data in my e-mail. Thank you for the cookbooks on your homepage! Without I wouldn’t have known where to start ( I’m a noob in php and stuff like java…).

HELP :wink:

Here comes my troublemaker-code that is wrong right now:
From my snippet I’ve used in the article.php (name: contacttagesfahrten.php)

<div class="field">
    <label for="zustieg">
        <h6>Zustieg<abbr title="required">*</abbr></h6>
  </label>
<p>
    <input type="Radio" name="zustieg" value="eins" required> Zustieg 1</input> 
    <input type="Radio" name="zustieg" value="zwei" required> Zustieg 2</input>   
    <input type="Radio" name="zustieg" value="drei" required> Zustieg 3</input>  
    <?= isset($alert['zustieg']) ? '<span class="alert error">' . html($alert['zustieg']) . '</span>' : '' ?>
  </p>
</div><hr />
						
<div class="field">
	<label for="reisebuero">
		<h6>Reisebüro<abbr title="required">*</abbr></h6>
	</label>							
		<select name="reisebuero" size="" required>
			<option value="">Ihr Reisebüro</option>
				<optgroup label="Bad Schandau" class="reisebuerostadt">
					<option value="1">Reisebüro Adresse 1</option>
				</optgroup>
				<optgroup label="Boxdorf" class="reisebuerostadt">
					<option value="2">Reisebüro Adresse 2</option>
				</optgroup>
				<optgroup label="Coswig" class="reisebuerostadt">
					<option value="3">Reisebüro Adresse 3</option>
				</optgroup>
<?= isset($alert['reisebuero']) ? '<span class="alert error">' . html($alert['reisebuero']) . '</span>' : '' ?>
                  </select>
</div>

My controller:
article.php

<?php
return function($kirby, $pages, $page) {
	
  // get all subpages
  $subpages = $page->children()->listed();

  // pass $articles and $pagination to the template

$alert = null;

	if($page->reisetermin()->isempty()) {
	     if($kirby->request()->is('POST') && get('submit')) {

    // check the honeypot
    if(empty(get('website')) === false) {
        go($page->url());
        exit;
    }


    $data = [
			'reise'  => get('reise'),
			'termin'  => get('termin'),
			'personenanzahl'  => get('personenanzahl'),
			'personen'  => get('personen'),
			'zustieg'  => get('zustieg'. 'checked'),
			'reisebuero'  => get('reisebuero'),
                    'name'  => get('name'),
			'strasse'  => get('strasse'),
			'plzort'  => get('plzort'),
			'telefon'  => get('telefon'),
                    'email' => get('email'),
                    'text'  => get('text'),
			'dsgvo'  => get('dsgvo'),
			'formblatt'  => get('formblatt')
    ];

    $rules = [
			'reise'  => ['min' => 3],
			'termin'  => ['min' => 3],
			'personenanzahl'  => ['required', 'min' => 1],
			'personen'  => ['required', 'min' => 3, 'max' => 3000], 
			'zustieg'  => ['checked'],
			'reisebuero'  => ['checked'],
                    'name'  => ['required', 'min' => 3],
			'strasse'  => ['required', 'min' => 3],
			'plzort'  => ['required', 'min' => 5],
			'telefon'  => ['required', 'min' => 3],
                    'email' => ['required', 'email'],
			'formblatt'  => ['required',],
			'dsgvo'  => ['required',]
    ];

    $messages = [
			'reise'  => 'Bitte geben Sie den Namen der Reise ein',
			'termin'  => 'Bitte geben Sie das Reisedatum ein',
			'personenanzahl'  => 'Bitte geben Sie die Personenanzahl ein',
			'personen'  => 'Bitte geben Sie die Personen an',
			'zustieg'  => 'Bitte wählen Sie eine Option aus',
			'reisebuero'  => 'Bitte wählen Sie ein Reisebüro aus',
                    'name'  => 'Bitte geben Sie Ihren vollen Namen ein',
                    'email' => 'Bitte geben Sie eine gültige E-Mail-Adresse ein',
			'strasse' => 'Bitte geben Sie Ihre Straße ein',
			'plzort' => 'Bitte geben Sie Ihre PLZ ein',
			'telefon' => 'Bitte geben Sie Ihre Telefonnummer an'	
    ];

    // some of the data is invalid
    if($invalid = invalid($data, $rules, $messages)) {
        $alert = $invalid;

        // the data is fine, let's send the email
    } else {
        try {
            $kirby->email([
                'template' => 'emailtagesfahrten',
                'from'     => esc($kirby->site()->email()),
                'replyTo'  => $data['email'],
                'to'       => esc($kirby->site()->email()),
                'subject'  => esc($data['name']) . ' hat Ihnen eine Buchungsanfrage für eine Tagesfahrt gesendet',
                'data'     => [
						'reise'   => esc($data['reise']),
						'termin'   => esc($data['termin']),
						'personenanzahl'   => esc($data['personenanzahl']),
						'personen'   => esc($data['personen']),
						'zustieg'   => esc($data['zustieg']),
						'reisebuero'   => esc($data['reisebuero']),
						'text'   => esc($data['text']),
						'strasse'   => esc($data['strasse']),
						'plzort'   => esc($data['plzort']),
						'telefon'   => esc($data['telefon']),
						'email'   => esc($data['email']),
                    'sender' => esc($data['name'])
                ]
            ]);

        } catch (Exception $error) {
            $alert['error'] = "Die Nachricht konnte nicht gesendet werden";
        }

        // no exception occured, let's send a success message
        if (empty($alert) === true) {
            $success = 'Ihre Nachricht wurde gesendet. Vielen Dank, wir melden uns schnellstmöglich bei Ihnen zurück';
            $data = [];
        }
    }
} }

return [
    'alert'   => $alert,
    'data'    => $data ?? false,
    'success' => $success ?? false
];
	

};

So may anybody give me a hint/ example, how I have to write “if that value is selected send me this text and if the second value is selected send me this text, please…”? Is it possible to solve it just in the controller and template.php and the email.php? Or do I have to do other stuff somewhere else?

Thank you!
Best regards,
Isabelle

Data:

 $data = [
    'zustieg'  => get('zustieg'),
    'reisebuero'  => get('reisebuero'),
];

Rules

$rules = [
    'zustieg'  => ['in' => [['eins', 'zwei', 'drei']]],
    'reisebuero'  => ['in' => [['1','2','3']]],
];

Form radio:

<p>
   <?php $value = $data['zustieg']?? '' ?>
    <input type="radio" name="zustieg" value="eins" <?php e($value=='eins', 'checked')?>> Zustieg 1</input> 
    <input type="radio" name="zustieg" value="zwei" <?php e($value=='zwei', 'checked')?>> Zustieg 2</input>   
    <input type="radio" name="zustieg" value="drei"> <?php e($value=='drei', 'checked')?>  Zustieg 3</input>  
    <?= isset($alert['zustieg']) ? '<span class="alert error">' . html($alert['zustieg']) . '</span>' : '' ?>
  </p>

Form select:

<div class="field">
	<label for="reisebuero">
    <h6>Reisebüro<abbr title="required">*</abbr></h6>
    <?php $value = $data['reisebuero']?? '' ?>
	</label>							
		<select name="reisebuero" size="" required>
			<option value="">Ihr Reisebüro</option>
				<optgroup label="Bad Schandau" class="reisebuerostadt">
					<option value="1" <?php e($value=='1', ' selected')?>>Reisebüro Adresse 1</option>
				</optgroup>
				<optgroup label="Boxdorf" class="reisebuerostadt">
					<option value="2" <?php e($value=='2', ' selected')?>>Reisebüro Adresse 2</option>
				</optgroup>
				<optgroup label="Coswig" class="reisebuerostadt">
					<option value="3" <?php e($value=='3', ' selected')?>>Reisebüro Adresse 3</option>
				</optgroup>
<?= isset($alert['reisebuero']) ? '<span class="alert error">' . html($alert['reisebuero']) . '</span>' : '' ?>
    </select>
</div>
2 Likes

Hi Texnixe,

thank you for the very fast answer! :relaxed: I tried it for the radio field, but it’s not working. Is there something I’m missing or is there another solution to solve the problem? I can send the mail but the data for the radio field is still missing. :thinking:

Form radio:

<div class="field">
    <label for="zustieg">
        <h6>Zustieg<abbr title="required">*</abbr></h6>
    </label>
    <?php $value = $data['zustieg'] ?? '' ?>
    <input type="Radio" name="zustieg" value="eins" <?php e($value=='eins', 'checked')?> required> Zustieg 1</input> 
    <input type="Radio" name="zustieg" value="zwei" <?php e($value=='zwei', 'checked')?> required> Zustieg 2</input>   
    <input type="Radio" name="zustieg" value="drei" <?php e($value=='drei', 'checked')?> required> Zustieg 3</input>  
     <?= isset($alert['zustieg']) ? '<span class="alert error">' . html($alert['zustieg']) . '</span>' : '' ?>
</div>

Data and rules copied like you’ve written.

In my email.html.php

Hallo,

    <p><?php $zustieg ?></p>

        <p>Mit freundlichen Grüßen</p>
        <p><?= $sender ?></p>

_____________
Edit

I’ve tried it with the select field now and it’s also not working. I can send the form but in the e-mail-text the value is not showing. Maybe something like on the bottom of this page

https://stackoverflow.com/questions/9365853/getting-the-text-of-radio-button-instead-of-values

could work? :thinking:

This won’t do anything. You’ld need to echo it or something. I suppose this will be an array, so you’ll have to loop over your array items.

1 Like

Oh, yeah :see_no_evil::see_no_evil::see_no_evil: !!!
It’s working now.

Thank you very much, I thought I as a noob will not be able to solve this, but thanks to both of you!
Learning something new every day :relaxed:

Have a nice start into the new week!:v:

2 Likes

Glad you got it working :+1:

1 Like

Thank you! You too.

1 Like

Hi @texnixe,

Very helpful piece of code for my situation as well, thank you.

What I’m struggling with is generating the options in the select field from a set of subpages. What I’m looking to do is exactly what OP needed, except my options are fetched from a set of published subpages, replacing the numerical values in your example with the slug of the subpage. Any chance you could take a look?

<?php $value = $data['group']?? '' ?>
<select name="group" size="" required>
    <option value="" disabled selected>Select group</option>
    <?php foreach (page('groups')->children()->listed() as $group): ?>
        <option value="<?= $group->title() ?>" <?php e($value=='<?= $group->title()->slug() ?>', ' selected')?>>
        <?= $group->title() ?>
    </option>
    <?php endforeach ?>
        <?= isset($alert['group']) ? '<span class="alert error">' . html($alert['group']) . '</span>' : '' ?>
</select>

Thank you so much!

This line has some issues.

If you set the value to the group’s title and then compare it to something else (i.e. `$group->title()->slug()), then this will always return false.

Secondly, putting this code ‘<?= $group->title()->slug() ?>’ in quotes and within PHP tags, doesn’t make sense, either.

So, imho it should be

<option value="<?= $group->slug() ?>" <?php e($value === $group->slug(), 'selected')?>>

Or $group->title()->slug() depending on what you want to do, but then in both cases.

sorry for the stupid question - i don’t check it …
what is the correct code to get the selected option in the email? :see_no_evil:
in this example
<?= $zustieg ?>
doesn`t work … how can i loop through the different values?

I have the same problem. Anyone can help? How can i loop the values?

Could you be more specific, please? Which values do you want to loop through? A radio or select field only gives you a single value, not an array.

Hey thanks for ur fast reply. I have a select field and in the email html template <?= $optiontitle ?>. But when i submit then nothing happens.

I think it helps if you post both your form and your form handling code, so that we can see where your error is. As such, I don’t know what $optiontitle is supposed to be.

In this recipe, you can also see how to fetch data from a form, and pass it on to the email template: Email contact form | Kirby CMS

Form:

<select id="anliegen" class="form-select" required>
                  <option value="" selected>Ihr Anliegen</option>
                  <option value="verkaufen">Ich möchte verkaufen</option>
                  <option value="kaufen">Ich möchte kaufen</option>
                  <option value="bewerten">Ich möchte bewerten lassen</option>
                  <option value="termin">Ich möchte einen Termin vereinbaren</option>
                  <option value="sonstiges">Sonstige Anfrage</option>
                </select>

Controller:

$data = [
            'vorname'  => get('vorname'),
            'nachname'  => get('nachname'),
            'email' => get('email'),
            'telefon' => get('telefon'),
            'anliegen' => get('anliegen'),
            'nachricht'  => get('nachricht')
        ];
$rules = [
            'vorname'  => ['required', 'minLength' => 3],
            'nachname'  => ['required', 'minLength' => 3],
            'email' => ['required', 'email'],
            'telefon'  => ['required', 'minLength' => 3],
            'anliegen'  => ['in' => [['verkaufen','kaufen','bewerten', 'termin', 'sonstiges']]],
            'nachricht'  => ['required', 'minLength' => 3, 'maxLength' => 3000],
        ];
$kirby->email([
                    'template' => 'email',
                    'from'     => 'yourcontactform@yourcompany.com',
                    'replyTo'  => $data['email'],
                    'to'       => 'email@email.de',
                    'subject'  => esc($data['vorname']) . ' sent you a message from your contact form',
                    'data'     => [
                        'vorname' => esc($data['vorname']),
                        'nachname'   => esc($data['nachname']),
                        'email'   => esc($data['email']),
                        'anliegen'   => esc($data['anliegen']),
                        'telefon' => esc($data['telefon']),
                        'nachricht'   => esc($data['nachricht']),
                    ]
                ]);

email.html.php

<?= $vorname ?>
<?= $nachname ?>
<?= $telefon ?>
<?= $anliegen?>
<?= $nachricht ?>

Every field whose value you want to be passed when the form is submitted, needs a name attribute, and our select field doesn’t have one.

On a side note, the select field is also missing the code to keep the selected value after form submission in case the form does not validate.

ah perfect. yea the missing name attribute was the issue. Now it works perfect. Thanks