Jump to content

Contact Form tutorial


giannisok

Recommended Posts

Simple Contact Form
Using Google Recaptcha & Valitron validation library

1.png

2.png

3.png

I just finished creating a simple Contact-Form for a client's website so i thought it would be really helpfull to share it with the community.

The contact form uses:

The contact-form is located inside a contact-page, so the bare minimum you need in order to setup your own is:

  1. contact.php (template file used by your contact-page)
  2.  _contact-controller.php (file used as a controller for your contact-form functionality like send email, validate fields etc)
  3. 2 extra lines inside your composer.json file


So, let's start:

First you need to update your composer.json file adding 2 lines inside the require object:

"vlucas/valitron": "^1.2",
"google/recaptcha": "~1.1"

Here is a sample composer.json file:

{
  "name": "processwire/processwire",
  "type": "library",
  "description": "ProcessWire CMS/CMF",
  "keywords": [ "cms","cmf", "content management system" ],
  "homepage": "https://processwire.com",
  "authors": [
    {
      "name": "Ryan Cramer",
      "email": "ryan@processwire.com",
      "homepage": "https://processwire.com",
      "role": "Developer"
    }
  ],
  "require": {
    "php": ">=5.3.8",
    "ext-gd": "*",
    "vlucas/valitron": "^1.2",
    "google/recaptcha": "~1.1"
  },
  "autoload": {
    "files": [ "wire/core/ProcessWire.php" ]
  },
  "minimum-stability": "dev"
}

open console and navigate to processwire root folder (where composer.json file is)
on this step i assume you have already setup composer for your project, otherwise google it :)
run the following command:

composer update

this will create a vendor folder (if it does not already exist) and download valitron and google recaptcha libraries.

Then open your contact-page template file(usually named contact.php inside your templates directory) and add the following:
* Note: The form below uses bootstrap 3.0.0 css, so if you are using something else you need to make the appropriate changes.

<?php namespace ProcessWire;
include('_contact-controller.php')
?>
<div class="container">
	<div class="row">
		<div class=" col-md-4">
            <h2>Contact Form</h2>

            <?php if($session->flashMessage):?>
            <div class="alert <?=!$session->sent && (!$v->validate() || !$resp->isSuccess()) ? 'alert-danger' : 'alert-success'?>" role="alert">
              <?php echo $session->flashMessage;?>
            </div>
            <?php endif;?>

            <form id="contact-form" method="post">
                <div class="form-group <?=$v->errors('name') ? 'has-error' : ''?>">
                    <label for="name">Name</label>
                    <input class="form-control" name="name" id="name" type="text" value="<?=$sanitizer->text($input->post->name)?>">
                </div>
                <div class="form-group <?=$v->errors('email') ? 'has-error' : ''?>">
                    <label for="email">Email</label>
                    <input class="form-control" name="email" id="email" type="text" value="<?=$sanitizer->text($input->post->email)?>">
                </div>
                <div class="form-group <?=$v->errors('message') ? 'has-error' : ''?>">
                    <label for="message">Message</label>
                    <textarea class="form-control" name="message" id="message"><?=$sanitizer->text($input->post->message)?></textarea>
                </div>
                <div class="form-group">

                    <!-- Google Recaptcha code START -->
                    <div class="g-recaptcha" data-sitekey="<?=$googleSiteKey?>"></div>
                    <script type="text/javascript"
                            src="https://www.google.com/recaptcha/api.js">
                    </script>
                    <!-- Google Recaptcha code END -->

                </div>
                <button type="submit" class="btn btn-primary">SEND</button>
            </form>
      	</div>
    </div>
</div>
<?php
    //here we remove the flash-message because it is already shown above the form.
    $session->remove('flashMessage');
    //reset 'sent' variable for future submit
	$session->sent = false;
?>


Next create a file inside you templates directory with name: _contact-controller.php:
and set the required variables($googleSiteKey, $contactFormRecipient, $contactPageID)

<?php
namespace ProcessWire;

/**
*    here we include Valitron & Google recaptcha libraries
*    make sure the path is correct in your template
*/
include(dirname(__FILE__) . "/../../vendor/vlucas/valitron/src/Valitron/Validator.php");
include(dirname(__FILE__) . '/../../vendor/google/recaptcha/src/ReCaptcha/ReCaptcha.php');

/**
*    here we add the form field values to Valitron
*/
$v = new \Valitron\Validator(array(
        'name' => $sanitizer->text($input->post->name),
        'email' => $sanitizer->email($input->post->email),
        'message' => $sanitizer->text($input->post->message),
    )
);

/**
*    validation rules set for each form field
*    For more details on Valitron/Validator usage visit: 
*    https://github.com/vlucas/valitron
*/
$v->rule('required', ['name', 'email', 'message']);
$v->rule('lengthMin', 'name', 5);
$v->rule('email', 'email');

/**
*    set Google recaptcha site-key & secret-key
*    create a new key from: https://www.google.com/recaptcha/admin
*/
$googleSiteKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$googleSecretKey = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY';

/**
*    set the email of the contact form recipient(usually the website owner)
*/
$contactFormRecipient = 'your@company.com';

/**
*    set the id of contact-page in order to redirect there when the form is sent
*/
$contactPageID = '1045';

//here we check whether the 'name' field exists inside post variables (which means the form is posted)
if ($input->post->name) {

    //if fields validation passes
    if ($v->validate()) {

        $reCaptcha = new \ReCaptcha\ReCaptcha($googleSecretKey);
        $resp = $reCaptcha->verify($input->post->{'g-recaptcha-response'}, $_SERVER["REMOTE_ADDR"]);

        //if google-recaptcha validation passes
        if ($resp->isSuccess()) {
        
            //This is the HTML message
            $message = '
                <html>
                    <head>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <title>Contact Form | ' . $input->post->name . '</title>
                    </head>
                    <body>
                        <p>' . $input->post->message . '</p>
                    </body>
                </html>';

            //here we send the form to $contactFormRecipient
            wireMail($contactFormRecipient, $input->post->email, "Contact Form | " . $input->post->name, $message);
            
            //here we set a flash-message to notify the user that the form was successfully sent
            $session->flashMessage = 'Thank you for your message! We will get in touch with you shortly.';
            
            //save in session that the form is sent
			$session->sent = true;

            //finally redirect user to contact-page
            $session->redirect($pages->get($contactPageID)->url);
        } else {
            //self explain
            $session->flashMessage = 'Error while validating you are not a robot!';
        }
    }
}
?>

Thats all!
You now have a simple contact-form working with captcha and field validation!
I would be more than happy to help anyone having problems on the setup.
 

Edited by giannisok
add images
  • Like 17
Link to comment
Share on other sites

11 hours ago, giannisok said:

You now have a simple contact-form working with captcha and field validation!
I would be more than happy to help anyone having problems on the setup.

"Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies."

That's the way I like it :) Thanks for the detailed instructions. I will probably use it in one of my projects in the near future.

Edited by szabesz
spelling
  • Like 3
Link to comment
Share on other sites

And here is the ALL-IN-ONE-FILE-WITHOUT-COMMENTS version...just put this in your contact.php template file (don't forget about composer update though):

<?php
namespace ProcessWire;
include(dirname(__FILE__) . "/../../vendor/vlucas/valitron/src/Valitron/Validator.php");
include(dirname(__FILE__) . '/../../vendor/google/recaptcha/src/ReCaptcha/ReCaptcha.php');

$v = new \Valitron\Validator(array(
        'name' => $sanitizer->text($input->post->name),
        'email' => $sanitizer->email($input->post->email),
        'message' => $sanitizer->text($input->post->message),
    )
);

$v->rule('required', ['name', 'email', 'message']);
$v->rule('lengthMin', 'name', 5);
$v->rule('email', 'email');

$googleSiteKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$googleSecretKey = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY';
$contactFormRecipient = 'your@company.com';
$contactPageID = '1045';

if ($input->post->name) {
    if ($v->validate()) {
        $reCaptcha = new \ReCaptcha\ReCaptcha($googleSecretKey);
        $resp = $reCaptcha->verify($input->post->{'g-recaptcha-response'}, $_SERVER["REMOTE_ADDR"]);

        if ($resp->isSuccess()) {
            $message = '
                <html>
                    <head>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                        <title>Contact Form | ' . $input->post->name . '</title>
                    </head>
                    <body>
                        <p>' . $input->post->message . '</p>
                    </body>
                </html>';

            wireMail($contactFormRecipient, $input->post->email, "Contact Form | " . $input->post->name, $message);
            $session->flashMessage = 'Thank you for your message! We will get in touch with you shortly.';
			$session->sent = true;
            $session->redirect($pages->get($contactPageID)->url);
        } else {
            $session->flashMessage = 'Error while validating you are not a robot!';
        }
    }
}
?>
<div class="container">
	<div class="row">
		<div class=" col-md-4">
            <h2>Contact Form</h2>

            <?php if($session->flashMessage):?>
            <div class="alert <?=!$session->sent && (!$v->validate() || !$resp->isSuccess()) ? 'alert-danger' : 'alert-success'?>" role="alert">
              <?php echo $session->flashMessage;?>
            </div>
            <?php endif;?>

            <form id="contact-form" method="post">
                <div class="form-group <?=$v->errors('name') ? 'has-error' : ''?>">
                    <label for="name">Name</label>
                    <input class="form-control" name="name" id="name" type="text" value="<?=$sanitizer->text($input->post->name)?>">
                </div>
                <div class="form-group <?=$v->errors('email') ? 'has-error' : ''?>">
                    <label for="email">Email</label>
                    <input class="form-control" name="email" id="email" type="text" value="<?=$sanitizer->text($input->post->email)?>">
                </div>
                <div class="form-group <?=$v->errors('message') ? 'has-error' : ''?>">
                    <label for="message">Message</label>
                    <textarea class="form-control" name="message" id="message"><?=$sanitizer->text($input->post->message)?></textarea>
                </div>
                <div class="form-group">
                    <!-- Google Recaptcha code START -->
                    <div class="g-recaptcha" data-sitekey="<?=$googleSiteKey?>"></div>
                    <script type="text/javascript"
                            src="https://www.google.com/recaptcha/api.js">
                    </script>
                    <!-- Google Recaptcha code END -->
                </div>
                <button type="submit" class="btn btn-primary">SEND</button>
            </form>
      </div>
  </div>
</div>
<?php
	$session->remove('flashMessage');
	$session->sent = false;
?>
Edited by giannisok
fixed error
  • Like 3
Link to comment
Share on other sites

  • 3 months later...

Hello Giannisok,

at the moment i try to built my first processwire website. It's fine, but now i have problems to built a simple bootstrap form.

You have made a very interesting possibility, but is it possible to make your form without using composer in a simple way?

Many thanks

Lena

 

Link to comment
Share on other sites

Yes it is... :)

Instead of using composer just download the 2 libraries:

unzip them inside a folder

...and replace the lines:

include(dirname(__FILE__) . "/../../vendor/vlucas/valitron/src/Valitron/Validator.php");
include(dirname(__FILE__) . '/../../vendor/google/recaptcha/src/ReCaptcha/ReCaptcha.php');

with:

include(dirname(__FILE__) . "yourfolder/vlucas/valitron/src/Valitron/Validator.php");
include(dirname(__FILE__) . 'yourfolder/google/recaptcha/src/ReCaptcha/ReCaptcha.php');

Hope it helps!

Actually composer doesn't do any magic...it just downloads the libraries inside the vendor folder but you can always do it manually if you want.

  • Like 3
Link to comment
Share on other sites

Replace include with require:

require(dirname(__FILE__) . "yourfolder/vlucas/valitron/src/Valitron/Validator.php");
require(dirname(__FILE__) . 'yourfolder/google/recaptcha/src/ReCaptcha/ReCaptcha.php');

This way if the paths are not correct you will get an error...

Link to comment
Share on other sites

Thank you,

I changed my  code to require, it doesn' work. So I try it again with include. But I got the same error.

Fehler: Class 'Valitron\Validator' not found (Zeile 35 in /mnt/web116/d3/92/57789292/htdocs/processwire/site/templates/crs-contact2.php)

include(dirname(__FILE__) . 'Valitron/Validator.php');
include(dirname(__FILE__) . 'recaptcha/src/ReCaptcha/ReCaptcha.php');

Code 35:

$v = new \Valitron\Validator(array(
        'name' => $sanitizer->text($input->post->name),
        'email' => $sanitizer->email($input->post->email),
        'message' => $sanitizer->text($input->post->message),
    )
);

I tried several links to the directory, but every link output the same error. 

Have you another idea?

Thank you

Lena

Link to comment
Share on other sites

  • 1 month later...

@giannisok thanks for sharing this, is awesome for a simple form where I don't need to save the user data anywhere!

Got it all working with recaptcha/validation, however, when I receive the email, it's still as plain text:

// received email
<html>
    <head>
        <meta http-equiv="Content-Type: text/html" content="text/html; charset=utf-8" />
        <title>Contact Form | Sam</title>
    </head>
    <body>
        <p>test message</p>
    </body>
</html>

Any ideas why this is? The content type is set so I thought it would show as formatted html. Thanks for any info.

 

  • Like 1
Link to comment
Share on other sites

  • 4 weeks later...

I had to modify the code a little because HTML formatting wasn't happening when I received the emails. Mine is as follows:

<?php

    require(dirname(__FILE__) . "/../../vendor/vlucas/valitron/src/Valitron/Validator.php");
    require(dirname(__FILE__) . '/../../vendor/google/recaptcha/src/ReCaptcha/ReCaptcha.php');

    $v = new \Valitron\Validator(array(
        'name' => $sanitizer->text($input->post->name),
        'email' => $sanitizer->email($input->post->email),
        'message' => $sanitizer->text($input->post->message),
        )
    );

$v->rule('required', ['name', 'email', 'message']);
$v->rule('lengthMin', 'name', 3);
$v->rule('email', 'email');

$googleSiteKey = 'xxxxxxxxxxx';
$googleSecretKey = 'xxxxxxxxxxx';
$contactFormRecipient = 'my_email';
$contactPageID = '1022';

if ($input->post->name) {
    if ($v->validate()) {
        $reCaptcha = new \ReCaptcha\ReCaptcha($googleSecretKey);
        $resp = $reCaptcha->verify($input->post->{'g-recaptcha-response'}, $_SERVER["REMOTE_ADDR"]);

        if ($resp->isSuccess()) {

            $name = $input->post->name;
            $email = $input->post->email;
            $message = $input->post->message;

            $message = "

                <html>
                    <body>
                        <p><b>From:</b></p>
                        <p>{$name}</p>
                        <p><b>Email:</b></p>
                        <p>{$email}</p>
                        <p><b>Message:</b></p>
                        <p>{$message}</p>
                    </body>
                </html>";


            $mail = wireMail();

            $mail->to($contactFormRecipient)
              ->from($email)
              ->subject('Contact form submission')
              ->bodyHTML($message)
              ->send();

            $session->flashMessage = '<h2>Thanks for the message. I will get in touch with you shortly.</h2>';
            $session->sent = true;
            $session->redirect($pages->get($contactPageID)->url);
        } else {
            $session->flashMessage = 'Error while validating you are not a robot!';
        }
    }
}
?>


<div class="body-row">
    <div class="wrapper">

        <?php if($session->flashMessage):?>
        <div class="alert <?=!$session->sent && (!$v->validate() || !$resp->isSuccess()) ? 'alert-danger' : 'alert-success'?>" role="alert">
          <?php echo $session->flashMessage;?>
        </div>
        <?php endif;?>

        <form id="contact-form" method="post">
            <div class="<?=$v->errors('name') ? 'has-error' : ''?>">
                <label for="name">Name</label>
                <input class="form-control" name="name" id="name" type="text" value="<?=$sanitizer->text($input->post->name)?>">
            </div>
            <div class="<?=$v->errors('email') ? 'has-error' : ''?>">
                <label for="email">Email</label>
                <input class="form-control" name="email" id="email" type="text" value="<?=$sanitizer->text($input->post->email)?>">
            </div>
            <div class="<?=$v->errors('message') ? 'has-error' : ''?>">
                <label for="message">Message</label>
                <textarea class="form-control" name="message" id="message"><?=$sanitizer->text($input->post->message)?></textarea>
            </div>
            <div>
                <!-- Google Recaptcha code START -->
                <div class="g-recaptcha" data-sitekey="<?=$googleSiteKey?>"></div>
                <script type="text/javascript"
                        src="https://www.google.com/recaptcha/api.js">
                </script>
                <!-- Google Recaptcha code END -->
            </div>

            <div class="centered">
                <button type="submit">SEND MESSAGE</button>
            </div>
        </form>

    </div>
</div>


<?php
    $session->remove('flashMessage');
    $session->sent = false;
?>

Works now with proper formatting.

  • Like 2
Link to comment
Share on other sites

need some help,

I followed the guide except one, adapted to uikit design, i have latest development pw edition , generated google keys,

But my mail form doesnt respond , nor show validation errors, doesnt matter if i chose or not google captch or if i just skip the fields

tracy debuger doesnt show any errors

page just update leaving all filds as they were.

 

is it a problem of local website development or i need to install a kind of mail module?

is it possible to debug it somehow?

<?php namespace ProcessWire;
include('_contact-controller.php')
?>



<div pw-append='grid' class='uk-width-1-3@m uk-flex-first@m uk-text-center uk-text-left@m'>
	<div class="uk-container">
		
            <h3>Contact Form</h3>

            <?php if($session->flashMessage):?>
            <div class="alert <?=!$session->sent && (!$v->validate() || !$resp->isSuccess()) ? 'uk-form-danger' : 'uk-form-success'?>" role="alert">
              <?php echo $session->flashMessage;?>
            </div>
            <?php endif;?>

            <form id="contact-form" method="post">
                <div class="uk-margin uk-inline <?=$v->errors('name') ? 'has-error' : ''?>">
                <span class="uk-form-icon" uk-icon="icon: user"></span>
                    <input class="uk-input" placeholder="" name="name" id="name" type="text" value="<?=$sanitizer->text($input->post->name)?>">
                </div>
                <div class="uk-margin uk-inline <?=$v->errors('email') ? 'has-error' : ''?>">
                   <span class="uk-form-icon" uk-icon="icon: user"></span>
                 
                    <input class="uk-input" placeholder="" name="email" id="email" type="text" value="<?=$sanitizer->text($input->post->email)?>">
                </div>
                <div class="uk-margin uk-inline <?=$v->errors('message') ? 'has-error' : ''?>">
                  <span class="uk-form-icon" uk-icon="icon: pencil"></span>
                 
                    <textarea class="uk-textarea" placeholder="" name="message" id="message"><?=$sanitizer->text($input->post->message)?></textarea>
                </div>
                <div class="form-group">

                    <!-- Google Recaptcha code START -->
                    <div class="g-recaptcha" data-sitekey="<?=$googleSiteKey?>"></div>
                    <script type="text/javascript"
                            src="https://www.google.com/recaptcha/api.js">
                            
                    </script>
                    <!-- Google Recaptcha code END -->

                </div>
                
                    <button class="uk-button uk-button-default" type="submit">Submit</button>
            </form>
      	
    </div>
</div>
<?php
    //here we remove the flash-message because it is already shown above the form.
    $session->remove('flashMessage');
    //reset 'sent' variable for future submit
	$session->sent = false;
?>

 

Link to comment
Share on other sites

@danielsl I noticed this so I looked at the code more closely. I modified it to this, where it checks if the form has been sent, then validates, if the fields are ok, it checks whether recaptcha has been done.

<?php

    require(dirname(__FILE__) . "/../../vendor/vlucas/valitron/src/Valitron/Validator.php");
    require(dirname(__FILE__) . '/../../vendor/google/recaptcha/src/ReCaptcha/ReCaptcha.php');

    $googleSiteKey = 'xxxxxx';
    $googleSecretKey = 'xxxxxx';
    $contactFormRecipient = 'my_email';
    $contactPageID = '1022';

    $v = new \Valitron\Validator(array(
        'name' => $sanitizer->text($input->post->name),
        'email' => $sanitizer->email($input->post->email),
        'message' => $sanitizer->text($input->post->message)
        )
    );

    $v->rule('required', ['name', 'email', 'message']);
    $v->rule('email', 'email');


if ($input->post->sendMe) {
    if ($v->validate()) {
        $reCaptcha = new \ReCaptcha\ReCaptcha($googleSecretKey);
        $resp = $reCaptcha->verify($input->post->{'g-recaptcha-response'}, $_SERVER["REMOTE_ADDR"]);

        if ($resp->isSuccess()) {

            $name = $input->post->name;
            $email = $input->post->email;
            $message = $input->post->message;

            $message = "

                <html>
                    <body>
                        <p><b>From:</b></p>
                        <p>{$name}</p>
                        <p><b>Email:</b></p>
                        <p>{$email}</p>
                        <p><b>Message:</b></p>
                        <p>{$message}</p>
                    </body>
                </html>";


            $mail = wireMail();

            $mail->to($contactFormRecipient)
              ->from($email)
              ->subject('Contact form submission')
              ->bodyHTML($message)
              ->send();

            $session->flashMessage = '<h2>Thanks for the message. I will get in touch with you shortly.</h2>';
            $session->sent = true;
            $session->redirect($pages->get($contactPageID)->url);
        }
        else {
            $session->flashMessage = '<h2>Recaptcha must be complete.</h2>';
        }
    }
    else {
        $session->flashMessage = '<h2>Please fill out the fields correctly.</h2>';
    }
}
?>


<div class="body-row">
    <div class="wrapper">

        <?php if($session->flashMessage):?>
        <div class="alert <?=!$session->sent && (!$v->validate() || !$resp->isSuccess()) ? 'alert-danger' : 'alert-success'?>" role="alert">
          <?php echo $session->flashMessage;?>
        </div>
        <?php endif;?>

        <form id="contact-form" method="post">
            <div class="<?=$v->errors('name') ? 'has-error' : ''?>">
                <label for="name">Name (required)</label>
                <input class="form-control" name="name" id="name" type="text" value="<?=$sanitizer->text($input->post->name)?>">
            </div>
            <div class="<?=$v->errors('email') ? 'has-error' : ''?>">
                <label for="email">Email (required)</label>
                <input class="form-control" name="email" id="email" type="text" value="<?=$sanitizer->text($input->post->email)?>">
            </div>
            <div class="<?=$v->errors('message') ? 'has-error' : ''?>">
                <label for="message">Message (required)</label>
                <textarea class="form-control" name="message" id="message"><?=$sanitizer->text($input->post->message)?></textarea>
            </div>
            <div>
                <!-- Google Recaptcha code START -->
                <div class="g-recaptcha" data-sitekey="<?=$googleSiteKey?>"></div>
                <script type="text/javascript"
                        src="https://www.google.com/recaptcha/api.js">
                </script>
                <!-- Google Recaptcha code END -->
            </div>

            <div class="centered">
                <button type="submit" name="sendMe" value="1">SEND MESSAGE</button>
            </div>
        </form>

    </div>
</div>


<?php
    $session->remove('flashMessage');
    $session->sent = false;
?>

Maybe not the best solution but it seems to work. Maybe some other members can help clean up my logic. Anyway, hope this helps.

Screenshot 2017-03-21 19.32.11.png

Screenshot 2017-03-21 19.34.01.png

Screenshot 2017-03-21 19.48.27.png

  • Like 1
Link to comment
Share on other sites

I am sending the NEW version of Simple Contact Form:)
This new version uses module MarkupGoogleRecaptcha in order to render the captcha.

If you have downloaded Valitron validator through composer then add the following line to your _head.php:

include(dirname(__FILE__) . "/../../vendor/autoload.php");

or include the old-way on the top of "partials/contact/_controller.php": 

require(dirname(__FILE__) . "/../../vendor/vlucas/valitron/src/Valitron/Validator.php");


There are 3 files currently:

  • contact.php (template)
  • partials/contact/_controller.php
  • partials/contact/_email.php

First file contact.php:

<?php namespace ProcessWire;
include('partials/contact/_controller.php');
?>

<h2><?php echo __('Contact Form') ?></h2>

<?php if($session->flashMessage):?>
<div class="alert <?php echo $session->sent ? 'alert-success' : 'alert-danger'?>" role="alert">
	<?php echo $session->flashMessage;?>
</div>
<?php endif;?>

<form id="contact-form" action="<?php echo $page->url;?>" method="post">
	<div class="form-group <?php echo $v->errors('name') ? 'has-error' : ''?>">
		<div class="input-group">
			<span class="input-group-addon"><i class="fa fa-user"></i></span>
			<input required class="input-lg form-control" name="name" id="name" type="text" value="<?php echo $name?>" placeholder="<?php echo __('Name') ?>">
		</div>
	</div>
	<div class="form-group <?php echo $v->errors('email') ? 'has-error' : ''?>">
		<div class="input-group">
			<span class="input-group-addon"><i class="fa fa-envelope"></i></span>
			<input required class="input-lg form-control" name="email" id="email" type="email" value="<?php echo $email?>" placeholder="<?php echo __('Email') ?>">
		</div>
	</div>
	<div class="form-group <?php echo $v->errors('phone') ? 'has-error' : ''?>">
		<div class="input-group">
			<span class="input-group-addon"><i class="fa fa-phone"></i></span>
			<input class="input-lg form-control" name="phone" id="phone" type="tel" value="<?php echo $phone?>" placeholder="<?php echo __('Phone') ?>">
		</div>
		<div class="field-notice" rel="phone"></div>
	</div>
	<div class="form-group <?php echo $v->errors('message') ? 'has-error' : ''?>">
		<div class="input-group">
			<span class="input-group-addon"><i class="fa fa fa-quote-left"></i></span>
			<textarea rows="7" class="input-lg form-control" placeholder="<?php echo __('Message') ?>" name="message" id="message"><?php echo $message?></textarea>
		</div>
	</div>
	<div class="form-group">
		<?php echo $captcha->render()?>
	</div>
	<button id="contact_send" class="btn btn-default" type="submit"><i class="fa fa-paper-plane" aria-hidden="true"></i> <?php echo __('SEND') ?></button>
</form>

<?php
	$session->remove('flashMessage');
	$session->sent = false;

	echo $captcha->getScript();
?>

Then file partials/contact/_controller.php:

<?php
namespace ProcessWire;

use Valitron\Validator;

$captcha = $modules->get("MarkupGoogleRecaptcha");

$name = $sanitizer->text($input->post->name);
$email = $sanitizer->email($input->post->email);
$phone = $sanitizer->text($input->post->phone);
$message = $sanitizer->text($input->post->message);

$v = new Validator([
	'name' => $name,
	'email' => $email,
	'message' => $message,
]);

$v->rule('required', ['name', 'email', 'message']);
$v->rule('email', 'email');

$contactFormRecipient = 'your@company.com';

if ($input->post->name) {
	if ($v->validate()) {
		if ($captcha->verifyResponse() === true) {
			$subject = 'Contact Form';
			$messageHTML = include_once('partials/contact/_email.php');
			$mail = wireMail()
				->to($contactFormRecipient)
			    ->header('Reply-To', $email)
				->subject($subject)
				->bodyHTML($messageHTML);

			if ($mail->send()) {
				$session->flashMessage = __('Thank you for your message! We will get back to you.');
				$session->sent = true;
				$session->redirect($page->url);
			} else {
				$session->flashMessage = __('Mail not sent. Error occured.');
			}

		} else {
			$session->flashMessage = __('Recaptcha Validation Error');
		}
	} else {
		$session->flashMessage = __('Please correct the errors and try again.');
	}
}
?>

And finally partials/contact/_email.php:

<?php ob_start();?>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title><?php echo $subject; ?></title>
</head>
<body>
	<h1>New message from <i><?php echo $name; ?></i></h1>

	<p><?php echo $message; ?></p>

	<hr>

	<h3>Contact Info:</h3>
	<p><strong>Name:</strong> <?php echo $name; ?></p>
	<?php if(!empty($phone)):?>
	<p><strong>Phone:</strong> <?php echo $phone; ?></p>
	<?php endif;?>
	<p><strong>Email:</strong> <a href="mailto:<?php echo $email; ?>"><?php echo $email; ?></a></p>

</body>
</html>
<?php return ob_get_clean();?>

Hope you like it! ;):)

  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...