I am trying to let a contact form (Contact Form 7) on a WordPress site create new contacts in my CRM program (solve360). To make it easier, I also activated a plugin (Forms: 3rd Party Integration) in which I defined a submission url and field mapping. Part of it works, but I am missing something simple here...
When pressing the send button, the data is sent to an email address (success) and to solve360 (not yet successfully). I actually receive a message that a new contact was created in solve360, however all the fields are empty. So I am guessing the problem is that the form fields are not properly transferred to the solve360 fields. However, I am using this template from solve360:
// REQUIRED Edit with the email address you login to Solve360 with
define('USER', '****************');
// REQUIRED Edit with token, Solve360 menu > My Account > API Reference > API Token
define('TOKEN', '*****************');
// Get request data
$requestData = array();
parse_str($_SERVER['QUERY_STRING'], $requestData);
// Configure service gateway object
require 'Solve360Service.php';
$solve360Service = new Solve360Service(USER, TOKEN);
//
// Preparing the contact data
//
$contactFields = array('firstname','lastname','businessemail','businessphonedirect','name','homeaddress','cus tom10641628','custom11746174','custom13346238');
$contactData = array();
// adding not empty fields
foreach ($contactFields as $solve360FieldName => $requestFieldName) {
if ($requestData[$requestFieldName]) {
$contactData[$solve360FieldName] = $requestData[$requestFieldName];
}
}
//
// Saving the contact
//
// If there was business email provided:
// check if the contact already exists by searching for a matching email address.
// if a match is found update the existing contact, otherwise create a new one.
//
if ($contactData['businessemail']) {
$contacts = $solve360Service->searchContacts(array(
'filtermode' => 'byemail',
'filtervalue' => $contactData['businessemail'],
));
}
if (isset($contacts) && (integer)$contacts->count > 0) {
$contactId = (integer)current($contacts->children())->id;
$contactName = (string)current($contacts->children())->name;
$contact = $solve360Service->editContact($contactId, $contactData);
} else {
$contact = $solve360Service->addContact($contactData);
$contactName = (string)$contact->item->name;
$contactId = (integer)$contact->item->id;
}
if (isset($contact->errors)) {
// Email the error
mail(
USER,
'Error while adding contact to Solve360',
'Error: ' . $contact->errors->asXml()
);
die ('System error');
} else {
// Email the result
mail(
USER,
'Contact posted to Solve360',
'Contact "' . $contactName . '" https://secure.solve360.com/contact/' . $contactId . ' was posted to Solve360'
);
}
In their example, they use a contact form with method="get" instead of method="post", however in the user interface of Contact Form 7, I believe the method is fixed to "post". Could this be the problem?
Or is there a different issue? Note that an empty contact is created at the moment. I can provide field mapping details and Forms 3rd party integration does allow hooks, if that helps in anyway.
Any help would be really appreciated! Thanks.
I discovered that the action method (POST) of the 3rd party plugin was not matching the expected action method (GET) of the Solve360 script. Therefore, I had to remove the following from the script:
// Get request data
$requestData = array();
parse_str($_SERVER['QUERY_STRING'], $requestData);
and change the following piece of code from
// adding not empty fields
foreach ($contactFields as $solve360FieldName => $requestFieldName) {
if ($requestData[$requestFieldName]) {
$contactData[$solve360FieldName] = $requestData[$requestFieldName];
}
}
to
// adding not empty fields
foreach ($contactFields as $solve360FieldName => $requestFieldName) {
if ($_POST[$requestFieldName]) {
$contactData[$solve360FieldName] = $_POST[$requestFieldName];
}
}
Hope this will help someone who is connecting Contact Form 7 to their Solve360 database.
Related
I am working on a MemberMouse subscription Wordpress website. I want to get data of the user into the php file via API to a Mailchimp mailing list.
I wrote the following script, that should be called under the condition that once the script is loaded it sends the following php sript:
<?php
require_once 'MCAPI.class.php';
$apikey='Your-API-Key'; // Enter your API key
$api = new MCAPI($apikey);
$retval = $api->lists();
$listid='List-Id'; // Enter list Id here
$uname = $_GET["username"]; // Enter subscriber last name
$email = $_GET["email"]; // Enter subscriber email address
$merge_vars = array('FNAME' => $uname);
if($api->listSubscribe($listid, $email,$merge_vars) === true) {
echo 'success';
}
?>
However, it always gives me an error and can not read the user data.
Here is the Membermouse Wordpress Hooks: http://support.membermouse.com/support/solutions/articles/9000020294-membermouse-wordpress-hooks#member-data
And here if using PHP interface: https://membermouse.uservoice.com/knowledgebase/articles/319071-using-the-php-interface
The MCAPI.class.php is another php that reads data for Mailchimp. It is simply the MailChimp API PHP Class, which I integrated it into my project.
By the way, manually adding the member via the script above is no problem:
<?php
require_once 'MCAPI.class.php';
$apikey='Your-API-Key'; // Enter your API key
$api = new MCAPI($apikey);
$retval = $api->lists();
$listid='List-Id'; // Enter list Id here
$email='Subscriber-email-address'; // Enter subscriber email address
$name='Subscriber-first-name'; // Enter subscriber first name
// By default this sends a confirmation email - you will not see new members
// until the link contained in it is clicked!
$merge_vars = array('FNAME' => $name);
if($api->listSubscribe($listid, $email,$merge_vars) === true) {
echo 'success';
}
?>
Context
I'm trying to delay sending the autoresponder (mail2) in contact form 7 for 8hours after the submission of the initial form. I'm thinking something like this:
add_action("wpcf7_before_send_mail", "wpcf7_do_something_else"); function wpcf7_do_something_else($cf7) {
// get the contact form object
$wpcf = WPCF7_ContactForm::get_current();
// if you wanna check the ID of the Form $wpcf->id
if (/*Perform check here*/) {
// If you want to skip mailing the data, you can do it...
$wpcf->skip_mail = true;
}
return $wpcf; }
Problem
Not sure what filter/hooks to use.
I've searched the forums and have seen many similar issues but none that seem to address my concern. I believe this is different because:
Form validation is not being used at this point
The form method does not seem to be related (just 1 post action)
The routes are not wrapped in web middleware
Here's what the application is supposed to be doing:
A user (with or without Authentication) views a public page with form (display_event)
The user selects a specific ticket for ordering and is directed to a 2nd form (register_step1)
The user then fills out demographic info for as many tickets as are being ordered
The processing step, if the email address used is of a valid user (in DB) should return to the form in step 2 & 3, populate the fields and flash a message. Otherwise it would perform the save() actions required. (register_step2)
The relevant routes from web.php are here:
Route::get('/events/{event}', 'EventController#show')->name('display_event');
Route::post('/register/{event}', 'RegistrationController#showRegForm')->name('register_step1');
Route::post('/register/{event}/create', 'RegistrationController#store')->name('register_step2');
The relevant portions of the RegistrationController.php are here:
public function showRegForm (Request $request, $id) {
// Registering for an event from /event/{id}
$ticket = Ticket::find(request()->input('ticketID'));
$quantity = request()->input('quantity');
$discount_code = request()->input('discount_code');
$event = Event::find($ticket->eventID);
return view('v1.public_pages.register', compact('ticket', 'event', 'quantity', 'discount_code'));
}
And:
public function store (Request $request) {
$event = Event::find(request()->input('eventID'));
if(Auth::check()) {
$this->currentPerson = Person::find(auth()->user()->id);
}
// set up a bunch of easy-reference variables from request()->input()
$email = Email::where('emailADDR', $checkEmail)->first();
if(!Auth::check() && $email === null) {
// Not logged in and email is not in database; must create
$person = new Person;
// add person demographics from form
} elseif(!Auth::check() && $email !== null) {
// Not logged in and email is in the database;
// Should force a login -- return to form with input saved.
flash("You have an account that we've created for you.
Please attempt to login and we'll send you a password to your email address.", 'warning');
return back()->withInput();
} elseif(Auth::check() && ($email->personID == $this->currentPerson->personID)) {
// the email entered belongs to the person logged in; ergo in DB
$person = $this->currentPerson;
// add person demographics from form
} elseif(Auth::check() && ($email->personID != $this->currentPerson->personID)) {
// someone logged in is registering for someone else in the DB
$person = Person::find($email->personID);
// add person demographics from form
} else {
// someone logged in is registering for someone else NOT in the DB
$person = new Person;
// add person demographics from form
}
// do more stuff...
$reg = new Registration; (set up a registration record)
}
I took the advice indicated in #apokryfos's comment and changed the form parsing-then-display script from a POST to a get.
redirect()->back() is, apparently, always a method=get and that was the cause of the MethodNotAllowedHttpException. In my ~2 weeks using Laravel, I hadn't yet come across that fact.
I've posted this question twice in the last two days and I have really run dry of solutions. I'm creating a very simple comment box that when filled out sends the comment in an email to my company's safety department. I have been receiving this 5.5.4 Invalid Domain Error for the last couple days.
It's SMTP and TLS. The port and server name is correct. The server allows for anonymous emails, and does not validate. I'm using the Swiftmailer library so I shouldn't need to script a ELHO/HELO. The only property of the email that's not defined/hard coded is the body of the message. This is the code for my controller (index.php).
// Initialize Swiftmailer Library
require_once("./swiftmailer/lib/swift_required.php");
// Class that contains the information of the email that will be sent (from, to, etc.)
require_once("./classes/EmailParts.php");
// The class that "breaks" the data sent with the HTML form to a more "usable" format.
require_once("./classes/ContactForm.php");
// =====================
// Main Configuration
// =====================
define("EMAIL_SUBJECT", "Safety Concerns");
define("EMAIL_TO", "safetydepartment#company.com");
define("EMAIL_FROM", "safetydepartment#company.com");
// SMTP Configuration
define("SMTP_SERVER", 'exchange.company.local');
define("SMTP_PORT", 25);
function main($contactForm) {
// Checks if something was sent to the contact form, if not, do nothing
if (!$contactForm->isDataSent()) {
return;
}
// Validates the contact form and checks for errors
$contactForm->validate();
$errors = array();
// If the contact form is not valid:
if (!$contactForm->isValid()) {
// gets the error in the array $errors
$errors = $contactForm->getErrors();
} else {
// If the contact form is valid:
try {
// send the email created with the contact form
$result = sendEmail($contactForm);
// after the email is sent, redirect and "die".
// We redirect to prevent refreshing the page which would resend the form
header("Location: ./success.php");
die();
} catch (Exception $e) {
// an error occured while sending the email.
// Log the error and add an error message to display to the user.
error_log('An error happened while sending email contact form: ' . $e->getMessage());
$errors['oops'] = 'Ooops! an error occured while sending your email! Please try again later!';
}
}
return $errors;
}
// Sends the email based on the information contained in the contact form
function sendEmail($contactForm) {
// Email part will create the email information needed to send an email based on
// what was inserted inside the contact form
$emailParts = new EmailParts($contactForm);
// This is the part where we initialize Swiftmailer with
// all the info initialized by the EmailParts class
$emailMessage = Swift_Message::newInstance()
->setSubject($emailParts->getSubject())
->setFrom($emailParts->getFrom())
->setTo($emailParts->getTo())
->setBody($emailParts->getBodyMessage());
// Another Swiftmailer configuration..
$transport = Swift_SmtpTransport::newInstance(SMTP_SERVER, SMTP_PORT, 'tls');
$mailer = Swift_Mailer::newInstance($transport);
$result = $mailer->send($emailMessage);
return $result;
}
// Initialize the ContactForm with the information of the form and the possible uploaded file.
$contactForm = new ContactForm($_POST, $_FILES);
// Call the "main" method. It will return a list of errors.
$errors = main($contactForm);
// Call the "contactForm" view to display the HTML contact form.
require_once("./views/contactForm.php");
I've posted the entirety of my code at Dropbox. There's not much, but I think the problem must lie in the Index.
I have a common ‘Contact Form’ in my project which is called in most of pages like index, about us etc. this page accept user inputs and sent an email to admin, then return back to the page, from which it is called
Code for contact form is
class Form_Contactus extends Zend_Form
{
public function init()
{
$this->setMethod('post');
$this->setAction('contactus/index');
$frontController = Zend_Controller_Front::getInstance();
$pageName = $this->createElement('hidden','pageName');
$pageName->setValue( $frontController->getRequest()->getControllerName() );
$FullName = $this->createElement('text','FullName');
$FullName->setLabel('Full Name')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$Email = $this->createElement('text','Email');
$Email->setLabel('Email')
->setRequired(true)
->addFilter('StringTrim')
->addValidator('EmailAddress')
->addValidator('NotEmpty');
$Message = $this->createElement('textarea','Message');
$Message->setLabel('Message')
->setAttribs( array('rows' => 3, 'cols' => 20 ))
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator('NotEmpty');
$submit = $this->createElement('submit','submit');
$submit->setLabel('Submit')
->setIgnore(true);
$this->addElements(array( $pageName,
$FullName,
$Email,
$Message,
$submit, )
);
}
}
Please note that, the line $this->setAction('contactus/index');. My idea is, if I fill this form (note it is a common form) from index page, it pass through 'contactus controller’ index action. Sent a mail from there and return back to index page. If the page is filled from about us page, it return back to about us page.
It is included in the different pages like index, about etc by code
$conForm = new Form_Contactus();
echo $conForm;
And the controller code looks like as
class ContactusController extends Zend_Controller_Action
{
protected $_redirector = null;
public function init()
{
$registry = Zend_Registry::getInstance();
$this->msgObj = $registry['MessageHandler'];
}
public function indexAction()
{
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$form = new Form_Contactus();
if ($this->_request->isPost()) {
$formData = $this->_request->getPost();
if ($form->isValid($formData)) {
$pageName = $formData['pageName'];
$FullName = $formData['FullName'];
$Email = $formData['Email'];
$Message = $formData['Message'];
if( strlen(trim( $FullName) ) ){
$mailBody .= "Name:\r\n\t".$FullName ."\r\n\r\n";
$mailBody .= "Email:\r\n\t".$Email ."\r\n\r\n";
$mailBody .= "Message:\r\n\t".$Message ."\r\n\r\n";
$mail = new Zend_Mail();
$transport = new Zend_Mail_Transport_Smtp('localhost');
Zend_Mail::setDefaultTransport($transport);
$mail->setSubject('Contact Enquiry.');
$mail->setFrom($Email, $FullName);
$mail->addTo(CONTACT_ADMIN_EMAIL, CONTACT_ADMIN_NAME);
$mail->setBodyText($mailBody);
if( $mail->send() ){
$this->msgObj->addMessage('Thank you!');
$this->msgObj->addMessage('Your message has been received and will be reviewed within 72 hours.');
}
else{
$this->msgObj->addError('Unable to sent mail! Please try later.');
}
}
}
else {
$this->msgObj->addError('Please correct the following:!');
$form->populate($formData);
$pageName = 'index';
}
}
$this->view->form = $form;
$this->_helper->redirector('index', $pageName);
}
}
everything works fine and mail is gone if I fill this form except that the form is not validated. For example the mail may sent without ‘FullName’, which is a required field
another problem is unable to display messages like ‘'Thank you’ .
this may because of $this->_helper->redirector method I used. The form is redirected and hence lost the values. If I use $this->_helper->forwarded or $this_forward() it also doesn’t work.
Any one can please suggest a method for me to dipsply validation message and other messages properly? Sorry for my poor English and thanks in advance
If the form doesn't validate (and send the contact information), then don't redirect. Simply move your redirect into your "if valid" block.
You can still add a field to store the page to return to once the form is completed successfully. You probably need to go about populating it a different way though, otherwise the contact page will be used as the "go to" page when the form is created in the contactus/index action (ie. when the form doesn't validate the first time)
Also, is there a reason you're not using Zend_Mail to actually send the mail? Since you're using the Zend Framework anyway?
Yes, the problem may be is because of my approach was wrong. I used one controller/page. For eg IndexController for index page, Aboutus Controller for about us page etc. the contactus is a small form that included in all these pages and thus the problem. Anyone can please suggest a better method?