It's working now!
Thank you very much Can and LostKobrakai!!!
I splited the form in two steps. That was easier for me. And i did not save the form to pages.
The files are stored on the server and our workflow system can get it.
Maybe it is not the best but for now it's working. I did a little start over.
This is now my site. On the first step i only validate the email field.
<!-- include head start -->
<?php include('./_head_pluploadtest.php'); ?>
<!-- include head end -->
<!-- include header start -->
<?php include('./_header.php'); ?>
<!-- include header end -->
<div id="basic-site-text" class="row content-box">
<div class="large-12 columns"></div>
<div class="medium-9 columns content-box-column-left">
<?php
/**
* ### Example front-end form template with file upload and fields ###
*
* - with files (images) upload to page field
* - adds new page on the fly and adds uploaded images
* - prevents CRSF attacks, this also prevents double post by refresh page after submit
* - has required fields with error messages inline
* - sanitizing and saving values to a page
* - jquery example with disabled submit button on form submit
*
* Edit add or remove form markup below and configure this section according to what you need.
*
*/
// ------------------------------ FORM Configuration ---------------------------------------
// --- Some default variables ---
$success_message = "<div id='form-success-message' class='text-center'><i class='fi-check'></i><br><h4>Danke, Ihre Daten wurden übermittelt.</h4></div>";
// --- All form fields as nested array ---
// using html form field name => template field nam, from the page you're going to create
$form_fields = array(
'email' => array('type' => 'email', 'value' => '', 'required' => true)
);
// --- Page creation settings ---
$template = "service-upload-files"; // the template used to create the page
$parent = $pages->get("/service/pluploadtest/");
$page_fields = array('email');
// $page_fields = define the fields (except file) you want to save value to a page
// this is for the form process to populate page fields.
// Your page template must have the same field names existent
// ------------------------------ FORM Processing ---------------------------------------
include("./form-plupload-test.php");
?>
<!-- ========================= FORM HTML markup ================================== -->
<?php
/**
* Some vars used on the form markup for error and population of fields
*
* $errors[fieldname]; to get errors
* $form_fields[fieldname]['value'];
*
* Some helper function to get error markup
* echo showError(string);
*
* Prevent CSRF attacks by adding hidden field with name and value
* you an get by using $session->CSRF
* $session->CSRF->getTokenName();
* $session->CSRF->getTokenValue();
*
* $errors['csrf']; used to check for CSRF error
*
*/
?>
<?php if(!$success) : ?>
<?php if(!empty($errors)) echo showError("Die Form enthält Fehler!"); ?>
<?php if(!empty($errors['csrf'])) echo showError($errors['csrf']); ?>
<form name="myform" class="myform" id="fileUploadForm" method="post" action="./" enctype="multipart/form-data">
<input type="hidden" name="<?php echo $session->CSRF->getTokenName(); ?>" value="<?php echo $session->CSRF->getTokenValue(); ?>"/>
<div class=" <?php if(isset($errors['email'])) echo "error";?>">
<label for="email">Ihre E-Mail Adresse: * </label>
<input type="text" name="email" id="email" placeholder='max.mustermann@email.de' value="<?php
// zeigt die E-Mail Adresse des Users wenn eingeloggt.
if($user->isLoggedin()) {
if (empty($_POST["email"]))
echo $user->email;
}
echo $sanitizer->entities($form_fields['email']['value']); ?>"/>
<?php if(isset($errors['email'])) echo showError($errors['email']); ?>
</div>
<?php
// if user is logged in... show some content specifically for logged-in users
if ($user->isLoggedin()) {
echo "<div class='callout secondary'>";
echo $page->service_email_info_logged_in;
echo "</div>";
}
else {
echo "<div class='callout secondary'>";
echo $page->service_email_info_logged_out;
echo "</div>";
}
?>
<div>
<!--<div id="fileList"></div><br><br>-->
<input type="hidden" name="action" id="action" value="send"/>
<input data-toggle="loadingModal" type="submit" name="submit" id="submit" value="nächster Schritt" class="button service_button float-right"/>
</div>
<!-- Fehlermeldung plupload
<pre id="console"></pre>-->
</form>
<div class="full reveal" id="loadingModal" data-reveal>
<div>
<img src="<?php echo $config->urls->templates?>images/loading_circle.gif" alt="Intropsective Cage"><br>
</div>
</div>
<?php else: ?>
<!-- <p><?php echo $success_message; ?></p>
<form id="fileUploadForm" method="post" action="./" enctype="multipart/form-data">
<div id="dropArea">
<input class="dragDropFileUploadField" type="file" name="file[]" accept="jpg,jpeg,png,gif,mpg,mpeg,mp4,avi,wmv,mov,zip" multiple>
<button type="submit" name="action" value="submit">Upload</button>
</div>
</form>
<div id="fileList"></div>-->
<form method="post" action="./" enctype="multipart/form-data">
<div id="uploader">
<p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
</div>
<input type="submit" name="submit" id="submit" value="Absenden" class="button service_button"/>
</form>
<!-- <?php echo $_POST['email']; ?> -->
<!-- übergibt die E-Mail Adresse an die nächste Seite -->
<?php $session->newemail = $_POST['email']; ?>
<?php endif; ?>
</div><!-- Ende Container -->
<div class="medium-3 columns content-box-column-right">
</div>
</div>
<!-- include footer start -->
<?php include('./_foot.php'); ?>
<!-- include footer end -->
<!-- include footer start -->
<?php include('./_foot_service_pluploadtest.php'); ?>
<!-- include footer end -->
On the second site i used pluploader with queue widget
When i now add some files...
the get uploaded if i hit the submit button
And my xml files get generated with the email adress inside
Form validation:
<?php
// ------------------------------ FORM Processing ---------------------------------------
$errors = null;
$success = false;
// helper function to format form errors
function showError($e){
return "<div class='alert callout'><p class='error'>$e</p></div>";
}
// dump some variables
// var_dump($_FILES,$_POST,$_SESSION);
/**
* Cast and save field values in array $form_fields
* this is also done even form not submited to make populating the form later easier.
*
* Also used for pupulating page when form was valid
*/
$required_fields = array();
foreach($form_fields as $key => $f){
if($f['type'] == 'email'){
$form_fields[$key]['value'] = $sanitizer->email($input->post->$key);
}
// store required fields in array
if($f['required']) $required_fields[] = $key;
}
/**
* form was submitted, start processing the form
*/
if($input->post->action == 'send'){
// validate CSRF token first to check if it's a valid request
if(!$session->CSRF->hasValidToken()){
$errors['csrf'] = "Die Formulardaten wurden nicht richtig ausgefüllt. Bitte versuchen Sie es erneut.";
}
/**
* Ceck for required fields and make sure they have a value
*/
foreach($required_fields as $req){
// reqired text fields
} if($form_fields[$req]['type'] == 'email'){
if(!strlen($form_fields[$req]['value'])){
$errors[$req] = "Bitte geben Sie Ihre E-Mail Adresse an.";
}
}
/*
* if no required errors found yet continue file upload form processing
*
if(empty($errors)) {
// create the new page to add field values and uploaded images
$uploadpage = new Page();
$uploadpage->template = $template;
$uploadpage->parent = $parent;
// add title/name and make it unique with time and uniqid
$uploadpage->title = date("d-m-Y H:i:s") . " - " . uniqid();
// populate page fields with values using $page_fields array
foreach($page_fields as $pf){
if($templates->get($template)->hasField($pf)){
$uploadpage->$pf = $form_fields[$pf]['value'];
} else {
throw new WireException("Template '$template' has no field: $pf");
}
}
// RC: for safety, only add user uploaded files to an unpublished page, for later approval
// RC: also ensure that using v2.3+, and $config->pagefileSecure=true; in your /site/config.php
$uploadpage->addStatus(Page::statusUnpublished);
$uploadpage->save(); */
// $success_message .= "<p>Page created: <a href='$uploadpage->url'>$uploadpage->title</a></p>";
$success = true;
// reset the token so no double posts happen
// also prevent submit button to from double clicking is a good pratice
$session->CSRF->resetToken();
/*
}*/}
the upload handler for plupload:
<?php
// --- WireUpload settings ---
$upload_path = $config->paths->assets . "files/service_upload_files/pluploadtest/"; // tmp upload folder
$file_extensions = array('jpg', 'jpeg', 'gif', 'png', 'tif', 'tiff');
$max_files = 0;
$max_upload_size = 1*14336*14336; // make sure PHP's upload and post max size is also set to a reasonable size 1*102400 = 100 MB
$overwrite = false;
$newemail = $session->newemail;
// RC: create temp path if it isn't there already
if(!is_dir($upload_path)) {
if(!wireMkdir($upload_path)) throw new WireException("No upload path!");
}
// setup new wire upload
$u = new WireUpload('file');
$u->setMaxFiles($max_files);
$u->setMaxFileSize($max_upload_size);
$u->setOverwrite($overwrite);
$u->setDestinationPath($upload_path);
$u->setValidExtensions($file_extensions);
// start the upload of the files
$files = $u->execute();
// create XML files for switch
// remove extension from files
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $files);
foreach($withoutExt as $withoutExt_string) {
$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;
$root = $doc->createElement('phpemail');
$root = $doc->appendChild($root);
$email = $doc->createElement('email');
$email = $root->appendChild($email);
$text = $doc->createTextNode($newemail);
$text = $email->appendChild($text);
$doc->save($upload_path . $withoutExt_string . ".xml");
}
?>
And the plupload config in my footer:
<!-- jQuery first, then foundation JS. -->
<script src="<?php echo $config->urls->templates?>scripts/vendor/jquery.min.js"></script>
<script src="<?php echo $config->urls->templates?>scripts/vendor/what-input.min.js"></script>
<script src="<?php echo $config->urls->templates?>scripts/foundation.min.js"></script>
<script src="<?php echo $config->urls->templates?>scripts/app.js"></script>
<script src="<?php echo $config->urls->templates?>scripts/onchange_dropdown_service.js"></script>
<script src="<?php echo $config->urls->templates?>scripts/email_service_validation.js"></script>
<script src="<?php echo $config->urls->templates?>scripts/plupload.full.min.js"></script>
<script src="<?php echo $config->urls->templates?>scripts/jquery.plupload.queue.js"></script>
<script src="<?php echo $config->urls->templates?>langs/de.js"></script>
<script type="text/javascript">
$(function() {
// Setup html5 version
$("#uploader").pluploadQueue({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url : 'uploadplupload/',
//chunk_size: '1mb',
unique_names: false,
rename : true,
dragdrop: true,
filters : {
// Maximum file size
max_file_size : '200mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,jpeg,gif,png,tif,tiff"}
]
},
// max file restriction with errors
init : {
FilesAdded: function(up, files) {
var max_files = 3;
plupload.each(files, function(file) {
if (up.files.length > max_files) {
alert('Sie dürfen bei einem Durchgang nur ' + max_files + ' Dateien hochladen.');
up.removeFile(file);
}
});
if (up.files.length >= max_files) {
$('#pickfiles').hide('slow');
}
},
FilesRemoved: function(up, files) {
if (up.files.length < max_files) {
$('#pickfiles').fadeIn('slow');
}
}
},
// Resize images on clientside if we can
//resize : {width : 320, height : 240, quality : 90},
flash_swf_url : '../../js/Moxie.swf',
silverlight_xap_url : '../../js/Moxie.xap'
});
// start file upload ob drop
//var uploader = $("#uploader").pluploadQueue();
//uploader.bind('FilesAdded', function(up, files) {
//uploader.start();
//});
// Client side form validation
// uploads the files in queue and submits the form
$("form").submit(function(e) {
var uploader = $("#uploader").pluploadQueue();
// Validate number of uploaded files
if (uploader.total.uploaded == 0) {
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind("StateChanged", function() {
if (uploader.total.uploaded == uploader.files.length)
$("form").submit();
});
uploader.start();
} else
alert("Sie müssen mindestens eine Datei auswählen.");
e.preventDefault();
}
});
});
</script>
<noscript><p><img src="//piwik-gbd.de/piwik.php?idsite=5" style="border:0;" alt="" /></p></noscript>
<!-- End Piwik Code -->
</body>
</html>
I will made a step by step tutorial. This becomes too big. Maybe i can improve something.
But for now it works! :)
Hello dragan,
thanks for your answer. It sound silly, but sometimes all i need is little help. You are right.
I removed the extension and did a foreach on that array. This works for me:
// create XML files for switch
// remove extension from files
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $files);
foreach($withoutExt as $withoutExt_string) {
$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;
$root = $doc->createElement('phpemail');
$root = $doc->appendChild($root);
$email = $doc->createElement('email');
$email = $root->appendChild($email);
$text = $doc->createTextNode(($form_fields ["email"]["value"]));
$text = $email->appendChild($text);
$doc->save($upload_path . $withoutExt_string . ".xml");
}
To get the email value i used var_dump to go trough the array.
$text = $doc->createTextNode(($form_fields ["email"]["value"]));