I'm missing a column in my exchangeArray. It is the column with the filename, here a snippet of my controller add action:
if ($form->isValid()) {
$data = $form->getData();
// Upload path
$location = "public/files/";
// A bit validation of uploaded file
$allowedExtension = array('xls', 'xlsx');
$extension = explode('.', $data['DCL_Path']['name']);
$extension = end($extension);
$import['DCL_Path']=$data['DCL_Path']['name'];
//$fileName = time() . '.' . $extension;
$fileName = $data['DCL_Path']['name'];
// Check if everything is OK!
//echo $fileName;
if (0 === $data['DCL_Path']['error'] && in_array($extension, $allowedExtension)) {
move_uploaded_file($data['DCL_Path']['tmp_name'], $location . $fileName);
} else {
echo 'Something went wrong!';
}
//$namen = explode(",", $import ); //Konvertierung des Strings in ein Array
//echo "<pre>"; var_dump($namen); echo "</pre>"; //Formartierte Ausgabe des Arrays
$this->table->saveImport($import);
Everything will be saved, but DCL_path is missing.
Here my exchangearray also:
public function exchangeArray(array $data)
{
$this->DCLID= !empty($data['DCLID']) ? $data['DCLID'] : null;
$this->UnitID= !empty($data['UnitID']) ? $data['UnitID'] : null;
$this->DCL_Path= !empty($data['DCL_Path']) ? $data['DCL_Path'] : null;
$this->Importdate= !empty($data['Importdate']) ? $data['Importdate'] : null;
$this->Importuser= !empty($data['Importuser']) ? $data['Importuser'] : null;
$this->Importok= !empty($data['Importok']) ? $data['Importok'] : null;
$this->DCL_Type= !empty($data['DCL_Type']) ? $data['DCL_Type'] : null;
$this->Changed_per_User= !empty($data['Changed_per_User']) ? $data['Changed_per_User'] : null;
$this->Description_Changes= !empty($data['Description_Changes']) ? $data['Description_Changes'] : null;
}
I added this statement: $import['DCL_Path']=$data['DCL_Path']['name']; to force it, but it didn't help. So my question would be how to add data in datafields of my exchangeArray.
EDIT1: Here is the start off my addAction.
$import = new Import(); //Neue Instanz von Import
$form->setInputFilter($import->getInputFilter()); //Filter an Form binden
$form->setData($request->getPost()); //Daten abholen
//echo $form->isValid();
if (! $form->isValid()) {
return ['form' => $form]; //Wenn die Daten nicht valide sind
// return $this->redirect()->toRoute('import'); //Routing
// Zend_Debug::dump("nicht valide");
//echo "nicht valide";
}
else{ //aus Tableadapter
$import->exchangeArray($form->getData());
// echo "valide";
//echo $import["DCL_Path"];
// Merge data thus
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
$form->setData($data);
I also find another solution which is working, I post it additional perhaps it might help somebody else. Of course I still would prefer the way via exchangeArray.
$this->table->saveImport($import); //Daten speichern
$letzter = $this->table->getlastImport($fileName);
echo ($letzter->DCLID);
$this->table->updateoneRow($letzter->DCLID, 'DCL_Path', $fileName);
Related
create custom form with email file jpg attached successfully sent to server. but the problem is, there's no email attached when receive email. try looking for all this forum no result. still get no email attached on receiving email. here's my code on indexcontroller.
upload server controlling
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'confirm' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['confirm'] );
$newFilename = $uploader->getUploadedFileName();
} catch (Exception $e) {
$error = true;
}
}
code to call email file attached
$attachmentFilePath = Mage::getBaseDir('media'). DS . 'confirm' . DS . $fileName;
if(file_exists($attachmentFilePath)){
$fileContents = file_get_contents($attachmentFilePath);
$attachment = $mail->getMail()->createAttachment($fileContents);
$attachment->filename = $fileName;
}
hope someone can help my problem thanks
Try this code
//upload code
$fileName = '';
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != '') {
try {
$fileName = $_FILES['attachment']['name'];
$fileExt = strtolower(substr(strrchr($fileName, ".") ,1));
$fileNamewoe = rtrim($fileName, $fileExt);
$fileName = preg_replace('/\s+', '', $fileNamewoe) . time() . '.' . $fileExt;
$uploader = new Varien_File_Uploader('attachment');
$uploader->setAllowedExtensions(array('doc', 'docx','pdf', 'jpg'));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'confirm' . DS ;
if(!is_dir($path)){
mkdir($path, 0777, true);
}
$uploader->save($path, $_FILES['attachment']['confirm'] );
$newFilename = $uploader->getUploadedFileName();
$mailTemplate = Mage::getModel('core/email_template');
$mailTemplate->setSenderName('Sender Name');
$mailTemplate->setSenderEmail('sender#sender.email');
$mailTemplate->setTemplateSubject('Subject Title');
$mailTemplate->setTemplateText('Body Text');
// add attachment
$mailTemplate->getMail()->createAttachment(
file_get_contents($path.$newFilename), //location of file
Zend_Mime::TYPE_OCTETSTREAM,
Zend_Mime::DISPOSITION_ATTACHMENT,
Zend_Mime::ENCODING_BASE64,
basename( $newFilename )
);
$mailTemplate->send('toemail#email.com','subject','set message');
} catch (Exception $e) {
$error = true;
}
}
The cookbook explanation code works very well with the NewAction() controller but how to edit a form who have a file with this technic ?
this edit controller always erase file even if it does not exist. thats a problem when I just want to edit text but not the file itself...
public function editAction(Request $request, Model $model)
{
$deleteForm = $this->createDeleteForm($model);
$editForm = $this->createForm(ModelType::class, $model);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$file = $model->getPicture();
$fileName = substr(md5(uniqid()), 0, 10) . '.' . $file->guessExtension();
$uploadDir = $this->container->getParameter('kernel.root_dir') . '/../web/' . Model::UPLOAD_DIR;
$file->move($uploadDir, $fileName);
$model->setPicture($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($model);
$em->flush();
return $this->redirectToRoute('my_route', array('id' => $model->getId()));
}
I've got an "addForm" and a "editForm". After I have added a document file in the addForm, it will be saved in my db. If I want to edit this form, I have to upload this document again. The old document will be deleted. I would like to make a function to check whether the document is already uploaded or not, so I do not have to upload it every time I want to edit an item. I just do not know where to start. A little help will be great.
my add/editform:
$pdf = new Zend_Form_Element_File('document');
$pdf->setLabel('Nieuwe PDF')
->addValidator('extension', true, array('docx',
'docx','pdf','txt'))
->addValidator('Count', false, 1)
->addValidator('Size', false, 10240000)
->setDestination( PUBLIC_PATH . '/../data/invoicespdf/')
->setRequired(false);
Try using this in the controller...modify it to fit your needs :
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ('administrator' == $user->role) {
$oldFileName = $form->getElement('oldfilename')->getValue(); //the hidden field
$data = $form->getValues();
$model->populate($data);
if (file_exists('uploads/cv/' . $oldFileName)) {
$form->getElement('cv')->setIgnore(true); //this is my Form File Element - the file exists, I don't need to store the filename
} else { // if you want you can unlink $oldFileName
$upload = new Zend_File_Transfer_Adapter_Http();
$info = $upload->getFileInfo('cv');
$upload->setDestination("uploads/cv/");
if (file_exists('uploads/cv/' . $info['cv']['name'])) {
$newFileName = time() . rand(0, 100000) . "-" . $info['cv']['name']; // I need to avoid overwriting file
} else {
$newFileName = $info['cv']['name'];
$upload->addFilter('Rename', $newFileName);
}
try {
$upload->receive();
} catch (Zend_File_Transfer_Exception $e) {
$e->getMessage();
}
}
$model->save();
return $this->_helper->redirector('list');
} else {
//some error message
$this->_helper->redirector('list');
}
} else { //form not valid
$this->view->form = $form;
}
} else {
$model->find($id);
$data = array();
$data = $model->toArray();
$data['oldfilename'] = $model->get_cv(); //the filename stored in db
$form->getElement('cv')->setRequired(false);
$form->populate($data);
$this->view->form = $form;
}
I have a website form, which works flawlessly. Except on IE 10 where it won't work at all, although strangely enough if I enable the compatibility mode, it works 90% fine.
With it on, it will submit the form and then give me an error saying there was an error (which is an internal message about the image which has not been uploaded - although the rest of the form gets uploaded).
*So, without compatibility mode on, it won't work (it will submit blank entry results without actually proceeding to the next screen).
As for with compatibility mode, it will not upload the user's image*
I assume the problem is with the process form.
<?php
include('config.php');
ini_set('error_reporting', E_ALL);
ini_set('display_errors', '1');
require_once('db.php');
$db = new db();
$cats = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['cats'])) {
$cats = implode(",", $_POST['cats']);
}
$categories = $_POST['categories'];
$str = $categories . ": " . $cats;
//echo $str;
}
$data = array();
$data[] = !empty($_POST['company']) ? $_POST['company'] : '';
$data[] = !empty($_POST['phone']) ? $_POST['phone'] : '';
$data[] = !empty($_POST['website']) ? $_POST['website'] : '';
$data[] = !empty($_POST['messagefr']) ? $_POST['messagefr'] : '';
$data[] = !empty($_POST['messageen']) ? $_POST['messageen'] : '';
$data[] = !empty($str) ? $str : '';
$data[] = !empty($_POST['profession']) ? $_POST['profession'] : '';
$data[] = !empty($_POST['manufacturiers_stand']) ? $_POST['manufacturiers_stand'] : '';
$data[] = !empty($_POST['percent_quebec']) ? $_POST['percent_quebec'] : '';
$data[] = !empty($_POST['percent_canada']) ? $_POST['percent_canada'] : '';
$data[] = !empty($_POST['percent_usa']) ? $_POST['percent_usa'] : '';
$data[] = !empty($_POST['percent_autre']) ? $_POST['percent_autre'] : '';
$data[] = !empty($_POST['bt_export']) ? $_POST['bt_export'] : '';
$data[] = !empty($_POST['bt_exporte_souhaite']) ? $_POST['bt_exporte_souhaite'] : '';
$data[] = !empty($_POST['bt_prod_verts']) ? $_POST['bt_prod_verts'] : '';
$data[] = !empty($_POST['bt_new_prod']) ? $_POST['bt_new_prod'] : '';
$data[] = !empty($_POST['name']) ? $_POST['name'] : '';
$data[] = !empty($_POST['email']) ? $_POST['email'] : '';
$data[] = !empty($_POST['resource_phone']) ? $_POST['resource_phone'] : '';
$data[] = !empty($_POST['personne_ressource']) ? $_POST['personne_ressource'] : '';
$data[] = !empty($_POST['backup_name']) ? $_POST['backup_name'] : '';
$data[] = !empty($_POST['backup_email']) ? $_POST['backup_email'] : '';
$data[] = !empty($_POST['backup_phone']) ? $_POST['backup_phone'] : '';
$result = $db->query("INSERT INTO form_corpo_test (compagnie,
telephone,
site_web,
texte_fr,
texte_en,
categories,
profil_exposant,
stands_du_manufacturier,
pourcentage_quebec,
pourcentage_canada,
pourcentage_usa,
pourcentage_autre,
exporte,
exporte_souhaite,
produits_vert,
nouveau_produits,
nom,
courriel,
telephone_ressource,
personne_ressource_c_toi,
autre_personne_ressource,
autre_courriel,
autre_telephone)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", $data);
if (!$result) {
echo 'Veuillez nous contactez si vous voyez ce message';
}
$pic = ($_FILES['photo']['name']);
$pic = (mysql_real_escape_string($_FILES['photo']['name']));
$dirPath = $_POST['company'];
$dirExists = is_dir($dirPath);
if (#!dirExists)
$dirExists = mkdir($dirPath, 0755);
#$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo '<br/>' . 'Le dossier ' . $dirPath . " a été créer" . '<br/>';
} else {
echo '<br/>' . "Le dossier " . $dirPath . " n'a PAS été créer car il existe déja" . '<br/>';
}
$folder_name = $dirPath;
$folder = $folder_name . '/';
$folder = $folder . basename($_FILES['photo']['name']);
if ($_FILES["photo"]["size"] >= 10485760) {
echo "F2";
die();
}
if (move_uploaded_file($_FILES['photo']['tmp_name'], $folder)) {
echo '<br/>' . "Le fichier " . basename($_FILES['photo']['name']) . " a été téléchargé" . '<br/>' . '<br/>' . "Et nous avons bien recu votre formulaire!" . '<br/>';
} else {
echo '<br/>' . "Désolé, mais il y a eu une erreur." . '<br/>';
}
?>
Upon the request of posting my form here (it was too long by 2,000 characters), so I posted it on a fiddle:
http://jsfiddle.net/NdRJV/
EDIT:
As Zeeba suggested, I forced the IE to read another browser:
I used
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
But, to read more on the topic, anyone else in need of this can visit:
What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
try adding this to you meta tags
<meta http-equiv="X-UA-Compatible" content="IE=edge" >
So, I am using Zend to handle my image uploads. This script works well, but I was wondering if there is a way to resize the image that is being uploaded no matter what the current size is. I've seen 2 similar posts, but their code was entirely different, thus would be difficult to translate into mine from theirs. If possible, I would really like to not have to use extensions, but I will if I have to. Any ideas?
if (isset($_POST['upload'])) {
require_once('scripter/lib.php');
//try {
$destination = 'C:\----';
$uploader = new Zend_File_Transfer_Adapter_Http();
$uploader->setDestination($destination);
$filename = $uploader->getFileName(NULL, FALSE);
$uploader->addValidator('Size', FALSE, '10000kB');
$uploader->addValidator('ImageSize', FALSE, array('minheight' => 100, 'minwidth' => 100));
//$pic = $filename;
if (!$uploader->isValid() || $errors) {
$messages = $uploader->getMessages();
} else {
//$pic = $filename;
$no_spaces = str_replace(' ', '_', $filename, $renamed);
$uploader->addValidator('Extension', FALSE, 'gif, png, jpg');
$recognized = FALSE;
if ($uploader->isValid()) {
$recognized = TRUE;
} else {
$mime = $uploader->getMimeType();
$acceptable = array('jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif');
$key = array_search($mime, $acceptable);
if (!$key) {
$messages[] = 'Unrecognized image type';
} else {
$no_spaces = "$no_spaces.$key";
$recognized = TRUE;
$renamed = TRUE;
}
}
$uploader->clearValidators();
if ($recognized) {
$existing = scandir($destination);
if (in_array($no_spaces, $existing)) {
$dot = strrpos($no_spaces, '.');
$base = substr($no_spaces, 0, $dot);
$extension = substr($no_spaces, $dot);
$i = 1;
do {
$no_spaces = $base . '_' . $i++ . $extension;
} while (in_array($no_spaces, $existing));
$renamed = TRUE;
}
$uploader->addFilter('Rename', array('target' => $no_spaces));
$success = $uploader->receive();
if (!$success) {
$messages = $uploader->getMessages();
} else {
//$pic = $no_spaces;
$uploaded = "$filename uploaded successfully";
$pic = $filename;
if ($renamed) {
$pic = "imgs/upld/" . $no_spaces;
$uploaded .= " and renamed $no_spaces";
//$pic = $no_spaces;
//$pic = $uploader->getFileName(NULL, FALSE);
} else {$pic = "imgs/upld/" . $filename;;}
$messages[] = "$uploaded";
//$pic = $no_spaces;
}
Zend Framework does not ship with a component for handling images.
Good News! PHP has several components that are really good at dealing with all kinds of image issues.
GD (one of those great PHP extensions) is currently shipped as a core extension for PHP, perhaps you will find it useful.
Maybe this will help: http://phpcodeforbeginner.blogspot.com/2013/04/resize-image-or-crop-image-using-gd.html
(not really trying to be too snarky ;)