[Tut] HTML Contact Form Template to Email with Custom Fields - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html) +--- Thread: [Tut] HTML Contact Form Template to Email with Custom Fields (/thread-99108.html) |
[Tut] HTML Contact Form Template to Email with Custom Fields - xSicKxBot - 03-31-2022 HTML Contact Form Template to Email with Custom Fields <div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/03/html-contact-form-template-to-email-with-custom-fields.jpg" width="550" height="480" title="" alt="" /></div><div><div class="modified-on" readability="7.1111111111111"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on January 5th, 2022.</div> <p>Why do we need a contact form on a website? It is to enable (prospective) customers to connect with you.</p> <p>Elon Musk says, “…maximize the area under the curve of customer happiness…”.</p> <p>So, increasing the possibilities of reading the customer’s mind will drive us forward to attain the goal. The contact form interface is one of the tools to know our customers.</p> <p>Let’s design a <a href="https://phppot.com/php/responsive-two-column-html-contact-form-with-php-mailing-support/">simple and useful contact form</a> component for your website. The below sections explain how to create a contact form from the scratch.</p> <h2>Uses of a contact form in a website</h2> <p>There are a few more advantages of having a contact form interface.</p> <ol> <li>It helps have conversions by knowing the requirement of the customers.</li> <li>It helps to know the scope of improvements.</li> <li>It helps to collect the end users’ ideas and opinions relevant to the business model.</li> </ol> <h2>About this example</h2> <p>This example code is for designing an HTML contact form with the following features.</p> <ol> <li><a href="https://phppot.com/php/php-contact-form-with-custom-fields/">Contact form with custom fields</a>.</li> <li>Add/Delete custom fields dynamically via jQuery.</li> <li><a href="https://phppot.com/php/sendmail-in-php-using-mail-smtp-with-phpmailer/">Send an email</a> with the posted form data.</li> <li>Storing the form data into the database.</li> </ol> <h2>Application configuration</h2> <p>This HTML contact form backend code allows both send an email and the store-to-database action. But, The store-to-database feature is optional and disabled initially.</p> <p>This configuration file has the flag to enable or disable the store-to-database feature.</p> <p>By default, the <em>ENABLE_DATABASE</em> flag is set to false. Make it true to show the “store-to-database” control in the UI.</p> <p class="code-heading">config.php</p> <pre class="prettyprint"><code class="language-php"> <?php const ENABLE_DATABASE = false; ?> </code></pre> <h2>HTML contact form landing page code</h2> <p>This <a href="https://phppot.com/php/php-contact-form-with-add-more-file-attachment-option/">HTML code is to display a contact form</a> on a landing page. The <em>index.php</em> file includes the following to make an HTML contact form dynamic.</p> <ul> <li>It contains the form HTML.</li> <li>It includes the application configuration file.</li> <li>It requires the form action PHP file to process data submitted by the user.</li> <li>It includes the form validation javascript and required jQuery dependency.</li> </ul> <p>By connecting all the contact form example components, this file lets the HTML contact form be interactive.</p> <p>It shows two controls to <em>save to the database</em> or to <em>send an email</em>. By default the <em>save to the database</em> control will be hidden. It is configurable to display this option.</p> <p class="code-heading">index.php</p> <pre class="prettyprint"><code class="language-html"> <?php require_once __DIR__ . '/contact-form-action.php';?> <?php require_once __DIR__ . '/config.php';?> <!DOCTYPE html> <html> <head> <link href="style.css" rel="stylesheet" type="text/css" /> <title>HTML Contact Form with Add More Custom Fields</title> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <script type="text/javascript" src="js/contact.js"> </script> </head> <body> <h1>HTML Contact Form with with Add More Custom Fields</h1> <div class="form-container"> <form name="mailForm" id="mailForm" method="post" action="" enctype="multipart/form-data" onsubmit="return validate()"> <div class="input-row"> <label style="padding-top: 20px;">Name</label> <span id="userName-info" class="info"></span><br /> <input type="text" class="input-field" name="userName" id="userName" /> </div> <div class="input-row"> <label>Subject</label> <span id="subject-info" class="info"></span><br /> <input type="text" class="input-field" name="subject" id="subject" /> </div> <div class="input-row"> <label>Message</label> <span id="userMessage-info" class="info"></span><br /> <textarea name="userMessage" id="userMessage" class="input-field" id="userMessage" cols="60" rows="6"></textarea> </div> <div class="input-row"> <div class="custom-field-name"> <input type="text" class="custom-field" name="Fieldname[]" id="Fieldname" placeholder="Fieldname" /> </div> <div class="custom-field-value"> <input type="text" class="custom-field" name="Fieldvalue[]" id="Fieldvalue" placeholder="Fieldvalue" /> </div> <div class="col"> <div class="custom-field-col"> <div onClick="addMore();" class="plus-button" title="Add More"> <img src="./images/icon-add.svg" alt="Add More"> </div> <div onClick="remove();" class="minus-button" title="Remove"> <img src="./images/icon-remove.svg" alt="Remove"> </div> </div> </div> </div> <div class="col"> <input type="submit" name="send" id="send" class="btn-submit" value="Send email" /> <div class="col"> <?php if(ENABLE_DATABASE == true){?> <input type="submit" name="savetodatabase" class=btn-submit id="savetodatabase" value="Save database" /> <?php }?> </div> <div id="pageloader"> <img id="loading-image" src="./images/loader.gif" /> </div> </div> <div id="statusMessage"> <?php if (! empty($message)) { ?> <p class='<?php echo $type; ?>Message'><?php echo $message; ?></p> <?php } ?> </div> </form> </div> </body> </html> </code></pre> <h2>Contact form validation script using jQuery</h2> <p><a href="https://phppot.com/jquery/jquery-form-validation-with-tooltip/">Form validation</a> can be done either on the server-side or client-side. But, validation on the client-side with Javascript is very usual. And it is quite easy and seamless also.</p> <p>So, I created a jQuery-based validation script to validate the HTML contact form. It requires all fields to be mandatory except the custom fields.</p> <p>The contact form custom fields are optional. But, in PHP, it checks the custom field name and value not to be empty. This <a href="https://phppot.com/php/php-form-validation/">server-side validation</a> will be done before preparing the contact-form action parameter.</p> <h3>Other JavaScript handlers</h3> <p>This <em>contact.js</em> file does not only include the validation handler. But also, defines handlers to add, delete custom field rows in the UI.</p> <p>It allows anyone row of custom field inputs to be in the HTML contact form. It is coded in the <em>showHideControls()</em> function of the below file.</p> <p class="code-heading">contact.js</p> <pre class="prettyprint"><code class="language-JavaScript"> function validate() { var valid = true; $(".info").html(""); var userName = document.forms["mailForm"]["userName"].value; var subject = document.forms["mailForm"]["subject"].value; var userMessage = document.forms["mailForm"]["userMessage"].value; if (userName == "") { $("#userName-info").html("(required)"); $("#userName").css('background-color', '#FFFFDF'); valid = false; } if (subject == "") { $("#subject-info").html("(required)"); $("#subject").css('background-color', '#FFFFDF'); valid = false; } if (userMessage == "") { $("#userMessage-info").html("(required)"); $("#userMessage").css('background-color', '#FFFFDF'); valid = false; } handleLoader(valid); return valid; } function handleLoader(valid) { if (valid == true) { if ($("#savetodatabase")) { $("#savetodatabase").hide();// hide submit } $("#send").hide(); $("#loading-image").show();// show loader } } function addMore() { $(".input-row:last").clone().insertAfter(".input-row:last"); $(".input-row:last").find("input").val(""); showHideControls(); } function remove() { $(".input-row:last").remove(".input-row:last"); $(".plus-button:last").show(); $(".minus-button:last").hide(); $(".input-row:last").find("input").val(""); } function showHideControls() { $(".plus-button").hide(); $(".minus-button").show(); $(".minus-button:last").hide(); $(".plus-button:last").show(); } </code></pre> <h2>PHP contact form action to send email or store to Database</h2> <p>Generally, the contact form action will send an <a href="https://phppot.com/php/send-email-with-multiple-attachments-using-php/">email with the body of posted form data</a>. This example gives additional support to store the posted message and the details in the database.</p> <p>This will be suitable when the HTML contact form is used to collect the following.</p> <ul> <li>Users’ feedback</li> <li>Support request</li> <li>Project inquiry</li> <li>Comments</li> </ul> <p>This PHP code handles the form submission by checking the posted action index. It uses the PHP mail() function to send the HTML contact form email. If you want to send an <a href="https://phppot.com/php/send-email-in-php-using-gmail-smtp/">email via SMTP using the PHPMailer library</a>, the link has the code for it.</p> <p>Refer <a href="https://www.php.net/manual/en/function.mail.php" target="_blank" rel="noopener">PHP.net manual</a> to know more about this mail() function.</p> <p>If the user clicks the ‘Save to database’ button, it connects the Database via the DataSource class. It triggers insert action by sending the form data in the query parameters.</p> <p class="code-heading">contact-form-action.php</p> <pre class="prettyprint"><code class="language-php"> <?php namespace Phppot; use Phppot\DataSource; require_once __DIR__ . '/DataSource.php'; require_once __DIR__ . '/index.php'; if (! empty($_POST["savetodatabase"])) { $conn = new DataSource(); $query = "INSERT INTO tbl_contact_mail(userName,subject,userMessage)VALUES(?,?,?)"; $paramType = 'sss'; $paramValue = array( $_POST["userName"], $_POST["subject"], $_POST["userMessage"] ); $id = $conn->insert($query, $paramType, $paramValue); if (! empty($_POST["Fieldname"])) { $customFieldLength = count($_POST["Fieldname"]); for ($i = 0; $i < $customFieldLength; $i ++) { if (! empty($_POST["Fieldname"][$i]) && $_POST["Fieldvalue"][$i]) { $query = "INSERT INTO tbl_custom_field(fieldName,fieldValue,contact_id)VALUES(?,?,?)"; $paramType = 'ssi'; $paramValue = array( $_POST["Fieldname"][$i], $_POST["Fieldvalue"][$i], $id ); $conn->insert($query, $paramType, $paramValue); } } } if ($query==true) { $message = "Data Saved"; $type = "success"; } else { $message = "Problem in data"; $type = "error"; } } elseif (! empty($_POST["send"])) { if (isset($_POST["userName"])) { $userName = $_POST["userName"]; } if (isset($_POST["subject"])) { $subject = $_POST["subject"]; } if (isset($_POST["userMessage"])) { $message = $_POST["userMessage"]; } $htmlBody = '<div>' . $message . '</div>'; $htmlBody .= '<br>'; $htmlBody .= '<div style=font-weight:bold;>More details:' . '</div>'; for ($i = 0; $i < count($_POST["Fieldname"]); $i ++) { if (isset($_POST["Fieldname"][$i]) && (isset($_POST["Fieldvalue"][$i]))) { $fieldname = $_POST["Fieldname"][$i]; $fieldvalue = $_POST["Fieldvalue"][$i]; $htmlBody .= '<div>' . $fieldname . '<div style=display:inline-block;margin-left:10px;>' . $fieldvalue . '</div>'; } } $htmlBody .= '<br><br><br>'; $htmlBody .= '<div>Thank You...!' . '</div>'; // Run loop $recipient="[email protected]"; if (mail($recipient, $subject, $htmlBody)) { $message = "Mail sent successfully"; $type = "success"; } else { $message = "Problem in sending email"; $type = "error"; } } ?> </code></pre> <h2>Database script</h2> <p>This .sql file contains the create a statement and required indices of the tbl_contact table.</p> <p><a href="https://phppot.com/php/how-to-import-sql-into-a-database-using-php/">Import this SQL</a> after setting up this example code in your PHP environment.</p> <p>Note: This is only required if you need the “Store to database” option.</p> <p class="code-heading">database.sql</p> <pre class="prettyprint"><code class="language-sql"> -- -------------------------------------------------------- -- -- Table structure for table `tbl_contact` -- CREATE TABLE `tbl_contact` ( `id` int(11) NOT NULL, `userName` varchar(255) NOT NULL, `subject` varchar(255) NOT NULL, `userMessage` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `tbl_custom_field` -- CREATE TABLE `tbl_custom_field` ( `id` int(11) NOT NULL, `contact_id` int(11) NOT NULL, `fieldName` varchar(11) NOT NULL, `fieldValue` varchar(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Indexes for dumped tables -- -- -- Indexes for table `tbl_contact` -- ALTER TABLE `tbl_contact` ADD PRIMARY KEY (`id`); -- -- Indexes for table `tbl_custom_field` -- ALTER TABLE `tbl_custom_field` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_contact` -- ALTER TABLE `tbl_contact` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `tbl_custom_field` -- ALTER TABLE `tbl_custom_field` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; </code></pre> <p><img loading="lazy" class="alignnone size-large wp-image-15958" src="https://phppot.com/wp-content/uploads/2021/11/html-contact-form-custom-field-550x480.jpg" alt="html contact form custom field" width="550" height="480" srcset="https://phppot.com/wp-content/uploads/2021/11/html-contact-form-custom-field-550x480.jpg 550w, https://phppot.com/wp-content/uploads/2021/11/html-contact-form-custom-field-300x262.jpg 300w, https://phppot.com/wp-content/uploads/2021/11/html-contact-form-custom-field.jpg 619w" sizes="(max-width: 550px) 100vw, 550px"></p> <h2>Conclusion</h2> <p>I hope this article gives you a useful contact form component for your website. It will be helpful to have a good idea to create a form like this on your own.</p> <p>Custom field integration with contact forms a rare and tricky requirement. Share your thoughts in the comments section to continue posting useful codes.</p> <p><a class="download" href="https://phppot.com/downloads/html-contact-form-custom-field.zip">Download</a></p> <p> <!-- #comments --> </p> <div class="related-articles"> <h2>Popular Articles</h2> </p></div> <p> <a href="https://phppot.com/php/html-contact-form-template-to-email-with-custom-fields/#top" class="top">↑ Back to Top</a> </p> </div> https://www.sickgaming.net/blog/2022/01/05/html-contact-form-template-to-email-with-custom-fields/ |