Contact Form - SendMessage

8 posts by 3 authors in: Forums > CMS Builder: Plugins & Add-ons
Last Post: June 26, 2020   (RSS)

By petrogus - May 10, 2020 - edited: May 10, 2020

Hi CMS Builder

I have created a form with Form Generator with the following fields, which work perfect (all Records are stored to CMS Builder)
'name', 'surname', 'phone', 'email', 'message' and 'agree' (checkbox)

but I want to send these information to administrator with email as well.

While I search to forum I understand that I need to use email template with custom placeholder (as look bellow)

Visitor Name : #visitor.name#
Visitor Email: #visitor.email#
Visitor Phone : #visitor.phone#
Visitor Message : #visitor.message#
Visitor Accept Terms : #visitor.agree#

From Email Templates, I tried to send these data using "Export Templates as PHP or SendMessage() PHP with no luck.

Below I have attach the code which I am using. Could you help me ?

All relevant Code is under

/********** Send Message **********/

<?php header('Content-type: text/html; charset=utf-8'); ?>
<?php
  // load viewer library
  $libraryPath = 'xxxxxx/lib/viewer_functions.php';
  $dirsToCheck = ['','../','../../','../../../','../../../../']; 
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }
  
  // FORM SETTINGS
  $FORM_TABLE          = "contact_form";
  $FORM_ALLOW_ADD      = true;  // allow creating new records
  $FORM_ALLOW_EDIT     = false; // allow editing existing records,  link to page with ?num=123 to specify record num
  $FORM_REQUIRE_LOGIN  = false; // require users to be logged in to use form
  $FORM_RECORD_NUM     = intval(@$_REQUEST['num']);   // specify record number to edit in url like this: ?num=123
  $FORM_UPLOAD_FIELDS  = []; 
  $FORM_PRESAVETEMPID  = @$_REQUEST['preSaveTempId'] ? $_REQUEST['preSaveTempId'] : uniqid('x'); // for future use - uploads
  $_IS_ADD_FORM        = !$FORM_RECORD_NUM;
  $_IS_EDIT_FORM       = $FORM_RECORD_NUM;

  // ERROR/SECURITY CHECK
  $formRecord     = $FORM_RECORD_NUM ? mysql_get($FORM_TABLE, $FORM_RECORD_NUM) : [];
  $userOwnsRecord = @$formRecord['createdByUserNum'] && $formRecord['createdByUserNum'] == @$CURRENT_USER['num'];
  if      (!function_exists('fg_util_isPluginEnabled')) { die("You must activate the Form Generator plugin before you can access this page."); }
  else if ($FORM_REQUIRE_LOGIN && !@$CURRENT_USER)      { die("You must login to use this form!"); }
  else if ($_IS_ADD_FORM && !$FORM_ALLOW_ADD)           { die("Add record - access not permitted!"); }
  else if ($_IS_EDIT_FORM) {
    if      (!$FORM_ALLOW_EDIT)                         { die("Modify record - access not permitted!"); }  
    else if (!$formRecord)                              { die("Modify record - record doesn't exist!"); }  
    else if ($FORM_REQUIRE_LOGIN && !$userOwnsRecord)   { die("Modify record - you can only edit records you've created!"); }
  }
  
  // PROCESS FORM - Update this PHP code block if you need to change the error checking or error/alert messages
  $errorsAndAlerts = '';
  if (@$_REQUEST['_save']) {

    ### CREATE DATE-FIELDS
    
    
    ### ERROR CHECKING
    list($table, $num) = [$FORM_TABLE, $FORM_RECORD_NUM]; // assign shorter convenience variables
    if (@$_REQUEST['name'] == '')   { $errorsAndAlerts .= "'Name' is required.<br />\n"; }
    if (@$_REQUEST['email'] == '')  { $errorsAndAlerts .= "'email' is required.<br />\n"; }
    if (!@$_REQUEST['agree'])     { $errorsAndAlerts .= "'Agree' is required.<br />\n"; } // uncomment to make checkbox required


    ### INSERT NEW RECORD
    if (!$errorsAndAlerts) {
      $colsToValues = array(
        'createdDate='     => "NOW()",
        'createdByUserNum' => (int) @$CURRENT_USER['num'],
        'updatedDate='     => "NOW()",
        'updatedByUserNum' => (int) @$CURRENT_USER['num'],
        'dragSortOrder'    => time(),
        'name'             => @$_REQUEST['name'],
        'surname'          => @$_REQUEST['surname'],
        'phone'            => @$_REQUEST['phone'],
        'email'            => @$_REQUEST['email'],
        'message'          => @$_REQUEST['message'],
        'agree'            => @$_REQUEST['agree'],
      );

      // insert or update record (and adopt uploads [for future use])
      $recordNum = fg_util_insertOrUpdateRecord($FORM_TABLE, $FORM_RECORD_NUM, $colsToValues);
      adoptUploads($FORM_TABLE, $FORM_PRESAVETEMPID, $recordNum);
      removeExpiredUploads(); // erase old expired uploads


      // on success
      $_REQUEST        = []; // clear form fields
      $errorsAndAlerts = "Thank you! The form has been submitted successfully.<br />\n";
      $success         = true;		  
    }
  }
  
 
  // Load Record (for edit forms)
  if ($_IS_EDIT_FORM) {
    $FORM_RECORD = mysql_get($FORM_TABLE, (int) $FORM_RECORD_NUM);
    $_REQUEST     = fg_util_prePopulateRequest($FORM_RECORD);
  }

  // set page title
  $formTitle = "Contact Form";
	
  if ($FORM_ALLOW_ADD && $FORM_ALLOW_EDIT) { // if form supports add and edit, show which action is taking place
    if ($_IS_ADD_FORM)   { $formTitle .= " - Add record"; } 
    if ($_IS_EDIT_FORM)  { $formTitle .= " - Modify record"; } 
  }


/********** Send Message **********/

	$email    = isset( $_REQUEST['email'] ) ? $_REQUEST['email'] : '';
	$fullname = isset( $_REQUEST['name'] ) ? $_REQUEST['name']." ".$_REQUEST['surname'] : '';
	$phone    = isset( $_REQUEST['phone'] ) ? $_REQUEST['phone'] : '';
	$message  = isset( $_REQUEST['message'] ) ? $_REQUEST['message'] : '';
	if(@$_POST['agree'] == "1") { $agree = "Yes!"; } else { $agree = "No?"; }
	
	

if (!$errorsAndAlerts) {
  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id'        => 'TEST-MAIL-ME',
    'addHeaderAndFooter' => false,
    'placeholders'       => array(
      'visitor.name'      => $fullname,
      'visitor.email'     => $email,
      'visitor.phone'     => $phone,
      'visitor.message'   => $message,
      'visitor.agree'     => $agree,
    ),
  ));

    //Get the subject to use in the title tag.
    $htmlTitle  = htmlencode($emailHeaders['subject']);
    //Custom Header
    $header = <<<__HTML__
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>$htmlTitle</title>
</head>

<body>

__HTML__;

  //Generate the footer
  $footer = <<<__HTML__
</body>
</html>
__HTML__;
  
  //Add teh footer and header to the email headers.
  $emailHeaders['html'] = $header . $emailHeaders['html'] . $footer;

  //Send the email
  $mailErrors = sendMessage($emailHeaders);
  if ($mailErrors) { die("Mail Error: $mailErrors"); }
 
  }
  /******** End of Sent Message *******/
  
?> 
PetroGus

By petrogus - May 12, 2020 - edited: May 12, 2020

Thank you Greg for your response,

I wasn't clear enough with my previews post. At the first time script send mails in the way that email template was structured
but the placeholders was empty. Finally we find the correct sequence to work.

I copy the way it work to me below (partial copy)

.
.
.
.

    ### INSERT NEW RECORD
    if (!$errorsAndAlerts) {
      $colsToValues = array(
        'createdDate='     => "NOW()",
        'createdByUserNum' => (int) @$CURRENT_USER['num'],
        'updatedDate='     => "NOW()",
        'updatedByUserNum' => (int) @$CURRENT_USER['num'],
        'dragSortOrder'    => time(),
        'name'             => @$_REQUEST['name'],
        'surname'          => @$_REQUEST['surname'],
        'phone'            => @$_REQUEST['phone'],
        'email'            => @$_REQUEST['email'],
        'message'          => @$_REQUEST['message'],
        'agree'            => @$_REQUEST['agree'],
      );

      // insert or update record (and adopt uploads [for future use])
      $recordNum = fg_util_insertOrUpdateRecord($FORM_TABLE, $FORM_RECORD_NUM, $colsToValues);
      adoptUploads($FORM_TABLE, $FORM_PRESAVETEMPID, $recordNum);
      removeExpiredUploads(); // erase old expired uploads
	  
		$email    = isset( $_REQUEST['email'] ) ? $_REQUEST['email'] : '';
		$fullname = isset( $_REQUEST['name'] ) ? $_REQUEST['name']." ".$_REQUEST['surname'] : '';
		$phone    = isset( $_REQUEST['phone'] ) ? $_REQUEST['phone'] : '';
		$message  = isset( $_REQUEST['message'] ) ? $_REQUEST['message'] : '';
		if(@$_POST['agree'] == "1") { $agree = "Yes!"; } else { $agree = "No?"; }


	  $emailHeaders = emailTemplate_loadFromDB(array(
		'template_id'        => 'TEST-MAIL-ME',
		'addHeaderAndFooter' => false,
		'placeholders'       => array(
		  'visitor.name'      => $fullname,
		  'visitor.email'     => $email,
		  'visitor.phone'     => $phone,
		  'visitor.message'   => $message,
		  'visitor.agree'     => $agree,
		),
	  ));

    //Get the subject to use in the title tag.
    $htmlTitle  = htmlencode($emailHeaders['subject']);
    //Custom Header
    $header = <<<__HTML__
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>$htmlTitle</title>
</head>

<body>

<style type="text/css">p { margin-bottom: 1em; color:#000; }</style>

__HTML__;
// ***NOTE*** style tag is for Yahoo Mail which otherwise drops paragraph spacing - http://www.email-standards.org/blog/entry/yahoo-drops-paragraph-spacing/
// ... having a defined <title></title> helps get by spam filters

  //Generate the footer
  $footer = <<<__HTML__
</body>
</html>
__HTML__;
  
  //Add teh footer and header to the email headers.
  $emailHeaders['html'] = $header . $emailHeaders['html'] . $footer;

  //Send the email
  $mailErrors = sendMessage($emailHeaders);
  if ($mailErrors) { die("Mail Error: $mailErrors"); }

      // on success
      $_REQUEST        = []; // clear form fields
      $errorsAndAlerts = "Thank you! The form has been submitted successfully.<br />\n";
      $success         = true;		  
    }
  }
 

.
.
.
.

Thank you for your support !!!

Could you help me in case I would like to send email with values from checkboxes (multi value)

PetroGus

By gregThomas - May 12, 2020

Hey petrogus,

Good to hear the issue is resolved.

When sending the values from a set of multi-select checkbox fields, the simplest solution is to send the values as a comma-separated string using the implode function.

For example, if you had a set of multi-select checkboxes like this:

<input name="cities[]" value="London" />
<input name="cities[]" value="New York" />
<input name="cities[]" value="Tokyo" />

You could add the values as a placeholder to your email using the following method:

  $cities = "";
  if( !empty($_REQUEST['cities']) && is_array($_REQUEST['cities']) ) {
    $cities = implode(", ", $_REQUEST['cities']);
  }

  $placeholders = [
    'visitor.name'      => $fullname,
    'visitor.email'     => $email,
    'visitor.phone'     => $phone,
    'visitor.message'   => $message,
    'visitor.agree'     => $agree,
    'visitor.cities'    => $cities
  ];

This is just sample code, so you'll probably need to make a few changes to get it working with your codebase, but hopefully, it will point you in the right direction.

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com

By petrogus - May 12, 2020

Great !! Many Thanks Greg

PetroGus

By AlanAlonso - June 22, 2020

I made some changes to the code and worked perfectly to me, but now I need to send two emails at the same time with diferent templates, can you please help me.

if (!$errorsAndAlerts) {
  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id'        => 'TEST-MAIL-ME',
    'addHeaderAndFooter' => false,
    'placeholders'       => array(
      'visitor.name'      => $fullname,
      'visitor.email'     => $email,
      'visitor.phone'     => $phone,
      'visitor.message'   => $message,
      'visitor.agree'     => $agree,
    ),
  ));

By gregThomas - June 23, 2020

Hey AlanAlonso, 

You can call the emailTemplate_loadFromDB and sendMessage functions for each email that you need to send. For example, if you have two templates called TEST-MAIL-ME and TEST-MAIL-ME-2, you could send both using the following code:

if (!$errorsAndAlerts) {
  
  //Create the placeholders that will be used in both emails
  $placeholders = [
    'visitor.name'      => $fullname,
    'visitor.email'     => $email,
    'visitor.phone'     => $phone,
    'visitor.message'   => $message,
    'visitor.agree'     => $agree,
  ];

  //Send the first email
  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id'        => 'TEST-MAIL-ME',
    'addHeaderAndFooter' => false,
    'placeholders'       => $placeholders,
  ));
  $mailErrors = sendMessage($emailHeaders);


  //Send the second
  $emailHeaders = emailTemplate_loadFromDB(array(
    'template_id'        => 'TEST-MAIL-ME-2',
    'addHeaderAndFooter' => false,
    'placeholders'       => $placeholders,
  ));
  $mailErrors = sendMessage($emailHeaders);

This just example code, so you'll have to make a few changes to get it working (for example; updating the email template ID's), but it should point you in the right direction.

Cheers,

Greg Thomas







PHP Programmer - interactivetools.com

By AlanAlonso - June 26, 2020

Thank you Greg, I will try to update form generator to include  this.