Formhandler subject dynamic field - typo3

I have problem with the TYPO3 extension "Formhandler". I installed the extension, added captcha and everything is working.
This is the HTML template:
<!-- ###TEMPLATE_FORM1### begin -->
<form action="###REL_URL###" name="projektform" id="projektform" method="post" class="formhandler">
<br />
<div id="sender_name">
<label for="sender_name"><span style="color:red;">*</span>Name:</label>
<br />
<input type="text" name="formhandler[sender_name]" id="sender_name"
value="###value_sender_name###" />
###error_sender_name###
</div>
<br />
<div id="sender_email">
<label for="sender_email"><span style="color:red;">*</span>Email:</label>
<br />
<input type="text" name="formhandler[sender_email]" id="sender_email"
value="###value_sender_email###" />
###error_sender_email###
</div>
<br />
<div id="sender_message">
<label for="message"><span style="color:red;">*</span>Message:</label>
<br />
<textarea name="formhandler[message]" id="message">###value_message###</textarea>
###error_message###
</div>
<br />
<!--###CAPTCHA_INSERT### this subpart is removed if CAPTCHA is not enabled! -->
<div id="captcha">
<label for="freecapfield"><span style="color:red;">*</span>###SR_FREECAP_NOTICE###</label>
<br />
###SR_FREECAP_CANT_READ###
<br />
<div class="cap-img">
###SR_FREECAP_IMAGE###
</div>
<br />
<input type="text" id="freecapfield" name="formhandler[freecapfield]" title="###SR_FREECAP_NOTICE###" value="">
<br />
###error_freecapfield###
</div>
<!--###CAPTCHA_INSERT###-->
<br />
<input type="submit" value="Submit" ###submit_nextStep### />
</form>
<!-- ###TEMPLATE_FORM1### end -->
<!-- ###TEMPLATE_SUBMITTEDOK### begin -->
<p>The following message has been sent:</p>
<p>###value_message###</p>
<!-- ###TEMPLATE_SUBMITTEDOK### end -->
<!-- ###TEMPLATE_EMAIL_ADMIN_PLAIN### begin -->
The following contact form has been sent to you:
Sender: ###value_sender_name### ###value_sender_email###
Text:
###value_message###
<!-- ###TEMPLATE_EMAIL_ADMIN_PLAIN### end -->
This is the typo script:
<INCLUDE_TYPOSCRIPT: source="FILE:fileadmin/contactform/1-contactform.ts">
plugin.Tx_Formhandler.settings {
debug = 1
templateFile = fileadmin/contactform/1-contactform.html
formValuesPrefix = formhandler
finishers {
1 {
class = Tx_Formhandler_Finisher_Mail
}
2 {
class = Tx_Formhandler_Finisher_SubmittedOK
config.returns = 1
}
}
# Rules for the validation
validators.1.class = Validator_Default
validators.1.disabled = 0
validators.1.config.fieldConf {
message.errorCheck.1 = required
message.errorCheck.2 = minLength
message.errorCheck.2.value = 5
sender_name.errorCheck.1 = required
sender_email.errorCheck.1 = required
sender_email.errorCheck.2 = email
freecapfield.errorCheck.1 = srFreecap
}
# Layout if the error message
singleErrorTemplate {
totalWrap = |
singleWrap = <span style="color: red;">|</span>
}
}
So what I have is Name, Email, Message and a captcha fields, working perfectly.
But then I wanted to add a "subject" field in the form, so that when someone sends an email from the online contact form, he would be able to set a subject of that email.
I added an additional input field:
<div id="subject">
<label for="subject">Subject:</label>
<br />
<input type="text" name="formhandler[subject]" id="subject" value="###value_subject###"/>
</div>
After adding the input in the HTML template, I entered the value "SUBJECT". The result was that I was able to see the value in the formhandler debugger:
The current GET/POST params are:
sender_name NAME
sender_email EMAIL#MAIL.COM
subject SUBJECT
message MESSAGE
freecapfield kdlxp
step-2-next 1
submitted 1
randomID 5fab4cc19017c5c48dafb6a05ed7687b
removeFile
removeFileField
submitField
Then all I needed to do was to "assign" that value to the "admin subject" field. I did a lot of researching and I was able to find the following code:
plugin.Tx_Formhandler.settings.predef.myformname {
finishers {
1.class = Tx_Formhandler_Finisher_Mail
1.config {
limitMailsToUser = 5
admin {
subject = TEXT
subject.data = GPvar:formhandler|title
}
}
}
}
So I put the code in my typo script, substituting "myformname" with the name of my form "projektform" and title with the name of my input field "subject", but when I send an email, there is no subject.
I did a lot of searching, tried a lot of examples, but the result was the same. Could you please point me to the right direction?

The use of GPvar is deprecated, use GP instead:
subject.data = GP:formhandler|subject
More information can be found in this howto: How to access Formhandler values in TypoScript

The Link has slightly chanced to http://www.typo3-formhandler.com/en/blog/howtos/how-to-access-formhandler-values/

Or you could use the mechanism that is meant to do that for you:
In your template you specified the fieldname by name="formhandler[subject]".
This means your value will be stored under the key "subject".
Most, if not all, finishers are able to deal with this key/value pairs just like this:
plugin.Tx_Formhandler.settings {
finishers {
1 {
class = Tx_Formhandler_Finisher_Mail
config.admin.subject = subject
}
}
}
Also another reason why your code might not work is that you did not specify your form to use a predef and configured most of it outside a predef. But the config for the subject that you found uses predef. Just changing the predef name is not enough do associate the config with your form. It has to be on the same level as your other config. This might just work as well:
plugin.Tx_Formhandler.settings {
finishers {
1.class = Tx_Formhandler_Finisher_Mail
1.config {
limitMailsToUser = 5
admin {
subject = TEXT
subject.data = GP:formhandler|subject
}
}
}
}
Sidenote:
Even though it is okay not to use predef (because you have no need for multiple different forms) it is not recommended, you should consider changing your config to using predefs.

Assuming that your form really is based on a predef form with the key "projektform":
plugin.Tx_Formhandler.settings.predef.projektform {
finishers {
1.class = Tx_Formhandler_Finisher_Mail
1.config {
limitMailsToUser = 5
admin {
subject = TEXT
subject.data = GP:formhandler|subject
subject.sanitize = 1
}
}
}
}
If you access GET/POST parameters using a cObject like "TEXT", you should always add "sanitize=1". Formhandler hooks into stdWrap and adds the submitted form data to the GET/POST array.
The better way to do it is the way #denvercoder suggested using just the name of the input field:
plugin.Tx_Formhandler.settings.predef.projektform {
finishers {
1.class = Tx_Formhandler_Finisher_Mail
1.config {
limitMailsToUser = 5
admin {
subject = subject
}
}
}
}

Related

doGet fails when same commands are called as a subfunction within it

Trying to learn Google Web Apps, I'm having the hardest time in 4 years of studying Google services. At this point, with help from other people, I have assembled a Web App form which successfully processes a few questions and accepts the submission of a file, sending the file to a folder on my Google Drive, appending the form answers to a Google Sheet, and sending me an email alerting me to the form submission. I think I understand how it works, but in trying to make the simplest of changes to it, it stopped working and gave me an error message I don't what to do with.
The form requires the user to upload an image of their COVID vaccination card. Since some people have more than one card, the form allows the user to upload more than file. This screen shot shows what the form displays upon successful submission.
The form fields and their answers remain in place, and below them appears the message "Uploaded successfully! You may upload another." What I want to have happen, besides a message like this appearing, is for all form fields and their answers disappear except for the Vacc Card/Choose File and Submit buttons.
So, I am trying to follow the instructions in this video from the highly popular YouTube Channel Learn Google Sheets & Excel Spreadsheets: Create Views (Pages) in Web App - Google Apps Script Web App Tutorial - Part 7
In this video, we see how to make the submission of a Web App form add to the current URL the string "?v=form" or "?v=whatever" and have the DoGet(e) function offer a different HTML file depending on whether the URL contains "&v" and if does, what follows that.
However, in following THE VERY FIRST STEP in the instructions, the App stopped working. All I did was cut what was inside the function doGet(e), place it inside a new function loadForm(), and put inside the doGet a calling of that function:
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
}
This one change caused the App to fail, returning nothing but a screen reading "The script completed but did not return anything."
My code:
/*
* Original doGet function; works fine. */
// function doGet(e){
// return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
// .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
// }
/** Step that caused this to fail: */
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} // else {HtmlService.createHtmlOutput('<h1>Hello<h1>')} // This would have been the next step, and the step after that making a second HTML file.
// Commenting out this step did NOT help.
}
function loadForm(){
return HtmlService.createTemplateFromFile('index').evaluate().addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
} /** There you have it. All that follows is part of what works. */
function uploadFiles(formObject) {
var folderID = "1nvhxUoj9uRlE0KpBNjW3cosIuuRpAQly"; // Massage / VaccinationCards
try {
var folder = DriveApp.getFolderById(folderID);
var fileUrl = "";
//Upload file if exists
if (formObject.myFile.length > 0) {
var name = formObject.name;
var namePref = formObject.namePref;
var pronouns = formObject.pronouns;
var ready = formObject.ready;
var email = formObject.email;
var phone = formObject.phone;
var callTimes = formObject.callTimes;
var questions = formObject.questions;
var blob = formObject.myFile;
var file = folder.createFile(blob);
fileUrl = file.getUrl();
} else {
fileUrl = null;
}
SpreadsheetApp.openById("1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50").getSheetByName("cards")
.appendRow([name, namePref, pronouns, ready, email, phone, callTimes, questions, fileUrl, new Date()]);
GmailApp.sendEmail('atiqzabinski#gmail.com', 'New Vax Card Uploaded!', 'Hey sweetie, smells like business! https://docs.google.com/spreadsheets/d/1S6RCLu8SKl0u8cVrEKd-3B71w5A-lvz0ikw_LPzgH50/edit', {name: 'Vacc Card Robot'});
return fileUrl;
} catch (error) {
return error.message;
}
}
My HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body style = "background:none transparent;">
<!-- <link href="/tpm-styles.css" rel="stylesheet" type="text/css"> -->
<link href="https://transformphillymassage.com/tpm-styles.css" rel="stylesheet" type="text/css">
<link href="https://transformphillymassage.com/formstyles.css" rel="stylesheet" type="text/css">
<form id="myForm" onsubmit="handleFormSubmit(this)">
<p>
<label for="FormControlFile">Legal Name:</label>
<input name="name" class="form-control-file" type="text" size="35" required/>
<br>
<label for="FormControlFile">Preferred Name:</label>
<input name="namePref" class="form-control-file" type="text" size="30">
<br> <label for="FormControlFile">Pronouns:</label>
<input name="pronouns" class="form-control-file" type="text" size = "35">
</p>
<p>
<label for="FormControlFile">Choose One:</label>
<!-- <select id = "id_ready" name = "ready" class="form-control-file" required/> -->
<!-- <select id = "id_ready" name = "ready" required/> -->
<select name = "ready" class="form-control-file" required/>
<option value = "I'm ready to book!">I'm ready to book!</option>
<option value = "I have questions.">I have questions.</option>
</select>
</p>
<p>
<label for="FormControlFile">email:</label>
<input name="email" class="form-control-file" type="text" size = "40" required/>
<br>
<label for="FormControlFile">Phone Number:</label>
<input name="phone" class="form-control-file" type="text" size = "28" />
<br>
<label for="FormControlFile">Best Times To Call:</label><br>
<input name="callTimes" class="form-control-file" type="text" size="50"/>
</p>
<p>
<label for="FormControlFile">Vacc Card:</label>
<input name="myFile" class="form-control-file" type="file" required/>
</p>
<p>
<label for="FormControlFile">Questions / Comments:</label><br>
<textarea name ="questions" class="form-control-file" cols="45" rows="4"></textarea>
<br>
<button type="submit"><span class="charm spanlavender">Submit</span></button>
</p>
</form>
<div id="urlOutput"></div>
<script>
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject){
google.script.run.withSuccessHandler(updateUrl).withFailureHandler(onFailure).uploadFiles(formObject);
}
function updateUrl(url) {
var div = document.getElementById('urlOutput');
if(isValidURL(url)){
div.innerHTML = '<div class="alert alert-success" role="alert">Uploaded successfully!<br>You may upload another.</div>';
// document.getElementById("myForm").reset();
} else {
//Show warning message if file is not uploaded or provided
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ url +'!</div>';
}
}
function onFailure(error) {
var div = document.getElementById('urlOutput');
div.innerHTML = '<div class="alert alert-danger" role="alert">'+ error.message +'!</div>';
}
function isValidURL(string) {
var res = string.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
return (res !== null);
}
</script>
</body>
</html>
return is missing on the else part of your if-else statement
Replace your doGet function by
function doGet(e) {
if (e.parameters.v == 'form') {
return loadForm()
} else {
return HtmlService.createHtmlOutput('<h1>Hello<h1>')
}
}
Below are a couple of function that could be used to debug your doGet function by using the Google Apps Script editor.
/**
* Test case 1: v parameter equal to 'form'
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
e.parameter.v = 'form';
doGet(e);
}
/**
* Test case 2: No v parameter
*
*/
function test_1_doGet(){
const e = {
parameter: {}
};
doGet(e);
}
Related
Google App Script how to load different pages using HTML Service?
How can I test a trigger function in GAS?
getting parameters from a url returns 'parameter is undefined"
How to get a URL string parameter passed to Google Apps Script doGet(e)
Serve separate HTML pages Google apps script not working
doGet(e) parameter undefined

angular 2, validate form if at least one input is typed

I'm quite new to Angular, and I've already searched the web, without finding a correct solution for my situation.
I have a dynamic form created by a *ngFor. I need to disabled the submit button if the inputs are all empty and show the alert div; but I need to enable the submit if at least one of those forms contains something different from ''.
Here is my html code
<form class="form-inline" #form="ngForm">
<div class="form-group" *ngFor="let meta of state.metaById; let i = index" style="margin: 5px">
<label>{{meta.nome}}</label>
<input type="text" class="form-control" #nome (blur)="inputInArray(nome.value, i);">
</div>
<button type="button" class="btn btn-primary" (click)="getCustomUnitaDocumentaliRow(this.param)" [disabled]="fieldNotCompiled">invia</button>
</form>
<div class="alert-notification" [hidden]="!fieldNotCompiled">
<div class="alert alert-danger">
<strong>Va compilato almeno un campo.</strong>
</div>
</div>
and here is my Typescript code
inputInArray(nome: string, indice) {
if (this.state.controlloMetaId = true) {
this.state.metadatoForm[indice] = nome;
}
// this.fieldNotCompiled = false;
for (const i in this.state.metaById) {
console.log(this.state.metadatoForm);
if (isUndefined(this.state.metadatoForm[i]) || this.state.metadatoForm[i] === '') {
this.fieldNotCompiled = true && this.fieldNotCompiled;
} else {
this.fieldNotCompiled = false && this.fieldNotCompiled;
}
console.log(this.fieldNotCompiled);
}
With this code I can check the first time a user type something in one input, but it fails if it empty one of them (or all of them)
Thanks for your time
UPDATE
Check if any input got a change that is different from empty or space, just by doing:
<input ... #nome (input)="fieldNotCompiled = !nome.value.trim()" ....>
DEMO
You can set a listener to the form changes:
#ViewChild('form') myForm: NgForm;
....
ngOnInit() {
this.myForm.valueChanges.subscribe((value: any) => {
console.log("One of the inputs has changed");
});
}

A Simple Grails form. I'm at a loss

I will preface this by saying my background is Graphic Design (been doing JavaScript for a few years).Ok, I've been looking and looking for a simple tutorial on how to create a basic form with a a controller, that sends the form info in the body of an email.
This is what I have in my GSP:
<g:form name="batchform" url="[action:'forminfo', controller:'onboardingform'] />
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${params.apparea01}' />
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${params.deptname02}' />
<input type="submit" value="Submit Form" id="FormButton" >
<g:form>
And the controller is where I get confused:
package .com
import util.Environment
import MailTools
import MetricsLogger
class OnboardingformController {
String apparea01,
String deptname02
static constraints = {
apparea01 blank: false, nullable: false
deptname02 blank: false, nullable: false
}
def index() {
render (view:'onboardingform.gsp')
}
sendMail {
to 'me#email.com'
cc params.mail
subject 'I am the form test in the subjectline'
body 'i am the body of the form. I should have vars here that display the user input from form fields'
}
}
I do not currently have a DOMAIN set up since there is no DB attached to this site. I just need to shove those Field Inputs into the Email body. I realize this maybe a very basic operation that escapes me (my background is Fine Arts, not Computer Science).
The MailTools is configured already to a default mailbox. The form needs to be send to another email address.
The MetricsLogger captures user info upon landing on the page.
Thanks in advance. This knowledge will open my eyes in my quest to be an Artist / Programmer :)
Ok, I came up with this controller in
grails-app/controllers/test/OnboardingformController.groovy:
package test
class OnboardingformController {
def index() {
render( view: 'onboardingForm.gsp' )
}
def formSubmission( String apparea01, String deptname02, String email ) {
println "Send Mail from $email to me#email.com with apparea01=$apparea01 and deptname02=$deptname02"
/*
// Commented out for now so I don't have to set up mail ;-)
sendMail {
to 'me#email.com'
cc params.mail
subject 'I am the form test in the subjectline'
body 'i am the body of the form. I should have vars here that display the user input from form fields'
}
*/
redirect( action:'index' )
}
}
And this GSP grails-app/onboardingform/onboardingform.gsp:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Onboarding</title>
</head>
<body>
<g:form action="formSubmission">
<p>
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${params.apparea01}' />
</p>
<p>
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${params.deptname02}' />
</p>
<p>
<label>Email</label>
<g:textField name="email" type="text" placeholder="Place Holder Text Field 3" value='${params.email}' />
</p>
<p>
<input type="submit" value="Submit Form" id="FormButton" >
</p>
</g:form>
</body>
</html>
Which when the form is filled in, should print out the values you entered (to the console) and redirect to the form. Let me know if anything doesn't make sense :-)
If you need validation (without a domain object), you can use a Command Object. This changes the controller to:
package test
class OnboardingformController {
def index() {
render( view: 'onboardingForm.gsp' )
}
def formSubmission( SubmissionCommandObject cmd ) {
if( !cmd.validate() ) {
render( view: 'onboardingForm.gsp', model:[ data: cmd ] )
return
}
else {
println "Send Mail from $cmd.email to me#email.com with apparea01=$cmd.apparea01 and deptname02=$cmd.deptname02"
}
redirect( action:'index' )
}
}
class SubmissionCommandObject {
String apparea01
String deptname02
String email
static constraints = {
apparea01 blank: false, nullable: false
deptname02 blank: false, nullable: false
email blank: false, email: true
}
}
And the view to:
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main"/>
<title>Onboarding</title>
</head>
<body>
<g:hasErrors bean="${data}">
<g:renderErrors bean="${data}" as="list" />
</g:hasErrors>
<g:form action="formSubmission">
<fieldset>
<p class="prop ${hasErrors(bean:data, field:'apparea01', 'errors')}">
<label>Application Group or Area</label>
<g:textField name="apparea01" type="text" placeholder="Place Holder Text Field 1" value='${data?.apparea01}' />
</p>
<p class="prop ${hasErrors(bean:data, field:'deptname02', 'errors')}">
<label>Department Name</label>
<g:textField name="deptname02" type="text" placeholder="Place Holder Text Field 2" value='${data?.deptname02}' />
</p>
<p class="prop ${hasErrors(bean:data, field:'email', 'errors')}">
<label>Email</label>
<g:textField name="email" type="text" placeholder="Place Holder Text Field 3" value='${data?.email}' />
</p>
<p>
<input type="submit" value="Submit Form" id="FormButton" >
</p>
</fieldset>
</g:form>
</body>
</html>
Obviously, this could be prettier, but will suffice for this quick example

Contact form with file attachment?

I have a contact form which is a template for pages on wordpress that I use if I need a contact form. All works fine but I want to add the capability of adding a file attachment so when the user fills in their name etc they can upload a photo and that photo will be sent to be me as an attachment.
I have a perfect working contact form and I only want to add that functionality to it. All my current code does all this it sends the name of the person their email address and their message to my email, all I'm missing is the attachment feature. I've been looking at alot of contact forms with this feature but to integrate that feature to my sendmail.php seems very hard as the coding style is completely different. Here is a demo of this in action. demo
This is my php file that has the form in it.
<?php get_header(); ?>
<script type="text/javascript">
$(document).ready(function(){
$('#contact').ajaxForm(function(data) {
if (data==1){
$('#success').fadeIn("slow");
$('#bademail').fadeOut("slow");
$('#badserver').fadeOut("slow");
$('#contact').resetForm();
}
else if (data==2){
$('#badserver').fadeIn("slow");
}
else if (data==3)
{
$('#bademail').fadeIn("slow");
}
});
});
</script>
<!-- begin colLeft -->
<div id="colLeft">
<!-- Begin .postBox -->
<div class="postBox">
<div class="postBoxTop"></div>
<div class="postBoxMid">
<div class="postBoxMidInner first clearfix">
<h1>Contact Us</h1>
<p><?php echo get_option('alltuts_contact_text')?></p>
<p id="success" class="successmsg" style="display:none;">Your email has been sent! Thank you!</p>
<p id="bademail" class="errormsg" style="display:none;">Please enter your name, a message and a valid email address.</p>
<p id="badserver" class="errormsg" style="display:none;">Your email failed. Try again later.</p>
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"></textarea><br />
<input type="submit" id="submitinput" name="submit" class="submit" value="SEND MESSAGE"/>
<input type="hidden" id="receiver" name="receiver" value="<?php echo strhex(get_option('alltuts_contact_email'))?>"/>
</form>
</div>
</div>
<div class="postBoxBottom"></div>
</div>
<!-- End .postBox -->
</div>
<!-- end colleft -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
and here is the file that handles the sending of the mail.
<?php
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(mail($to, $subject, $message, $headers))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
Thanks!
You can read this simple tutorial to know what needs to be done to add file upload support to your current form:
http://www.tizag.com/phpT/fileupload.php
Hope it helps!
EDITED
After the upload process, you can do like this:
if (file_exists($_FILES['uploaded']['tmp_name'])) {
$mail->AddAttachment($_FILES['uploaded']['tmp_name'], $_FILES['uploaded']['name']);
}
What this does is to add an attachment to your email by calling the AddAttachment from PHPMailer, and using the file just uploaded from the TMP folder of your server... so no actual storage of the file is necessary.
You can use
http://wordpress.org/plugins/contact-form-7/
It has a option for Upload field as well as all validations, really easy to use.
You just need to enter shortcode and you can use the contact form anywhere you want.

grails controllers render errors multiple domain classes

I have this controller which performs me a multiple domain databinding class, and it is working as i want. But i would like some help about the error messages. Is it possible to display error messages from multiple domain classes? If so, how should be the code both is the view and in the controller?
class CarroMovel {
String move
String rodas
String espelhos
Carro carro
static hasMany = [carros: Carro]
static belongsTo = Carro
static constraints = {
move(nullable:false, blank:false)
}
static mapping = {
version false
}
}
class Carro {
String name
String marca
String matricula
static constraints = {
name(nullable:false, blank:false)
}
static mapping = {
version false
}
}
def save3 = {
def carroInstance = new Carro( )
def carroMovelInstance = new CarroMovel( )
carroInstance.name = params.carro.name
carroInstance.marca = params.carro.marca
carroInstance.matricula = params.carro.matricula
carroMovelInstance.move = params.carroMovel.move
carroMovelInstance.rodas = params.carroMovel.rodas
carroMovelInstance.espelhos = params.carroMovel.espelhos
carroInstance.save(failOnError: true)
carroMovelInstance.carro = carroInstance
carroMovelInstance.save(failOnError: true)
}
<g:form controller="carro" action="save3">
<h1>Add New Carro Record</h1>
<p>Basic Information</p>
<label>Name
<span class="small">Add your name</span>
</label>
<input type="text" name="carro.name" value="${carroInstance?.name}" /><br>
<label>Marca
<span class="small">Add your name</span>
</label>
<input type="text" name="carro.marca" value="${carroInstance?.marca}" /><br
<label>Matricula
<span class="small">Add your name</span>
</label>
<input type="text" name="carro.matricula" value="${carroInstance?.matricula}" /><br>
<label>Move
<span class="small">Add your name</span>
</label>
<input type="text" name="carroMovel.move" value="${carroMovelInstance?.move}" /><br>
<label>Rodas
<span class="small">Add your name</span>
</label>
<input type="text" name="carroMovel.rodas" value="${carroMovelInstance?.rodas}" /><br>
<label>Espelho
<span class="small">Add your name</span>
</label>
<input type="text" name="carroMovel.espelhos" value="${carroMovelInstance?.espelho}" /><br>
<g:submitButton name="save" value="Save" id="addConference"/>
<div class="spacer"></div>
</g:form>
<g:hasErrors bean="${carroInstance}">
<div class="errors">
<g:renderErrors bean="${carroInstance}" as="list" />
</div>
</g:hasErrors>
Grails Validation Errors Primer
The errors for a domain object are stored in an errors property that is added to the object after it is validated. This property is an implementation of the Spring Errors interface.
You can get the errors either by calling the methods of this interface directly, e.g. to display the errors for the move field of a Carro instance:
List<FieldError> moveErrors = carroMovelInstance.errors?.getFieldErrors('move')
To get the error messages for each error, you'll need a referrence to the messageSource bean created by Grails. You could get the message for each of the above errors with:
List<String> errorMessages = moveErrors.collect {error ->
messageSource.getMessage(error, Locale.default)
}
Alternatively, Grails provides the eachError and renderErrors tags that simplify displaying errors and their corresponding messages in a GSP.
Specific Problems With Your Code
In your controller code, an exception will be thrown whenever save fails due to validation errors, so the view has no opportunity to display the errors. To fix this, change the controller so that it returns the domain objects (along with their errors) when saving fails
def save3 = {
def carroInstance = new Carro( )
def carroMovelInstance = new CarroMovel( )
carroInstance.name = params.carro.name
carroInstance.marca = params.carro.marca
carroInstance.matricula = params.carro.matricula
carroMovelInstance.move = params.carroMovel.move
carroMovelInstance.rodas = params.carroMovel.rodas
carroMovelInstance.espelhos = params.carroMovel.espelhos
// I'm assuming in the code below that the view that displays the form is 'create.gsp'
if (!carroInstance.save()) {
render view: 'create', model : [carro: carroInstance, carroMovel: carroMovelInstance]
return
}
carroMovelInstance.carro = carroInstance
if (!carroMovelInstance.save()) {
render view: 'create', model : [carro: carroInstance, carroMovel: carroMovelInstance]
}
}
The GSP also needs to be changed to display these errors using either the Errors API directly or one of the Grails tags (see above)