How to Upload files on Different page of PrestaShop - Top Programming Questions and Answers
Posted On: Sep 14, 2018
Categories: Shopping Carts & Platforms
PrestaShop is most simple shopping cart that suits for small sized businesses. If you are looking to open a new shop, PrestaShop should be at your first option. The reason is that it is fully open source and one can modify it according to this own choice.
The topic that we selected today for questions answers session is basically an advance functionality of PrestaShop and that is File upload option at different pages of PrestaShop. Being a merchant, sometimes you need to get some files from customers in the form of PDF, excel, video, MP3, JPEG or any of the other file format. It is not better to have third party clouding servers to get files.
Why not get it done through your own shop server?
Similarly, sometimes you need to send a file to your customers, it can be done through PrestaShop itself and therefore cutting the need of external services.
The today’s post targets the same thing. While using this feature, people gets some errors or bugs and they look for a solution for them. We have tried today to give every possible solution of such issues. So given here Top Programming Questions and Answers about File Upload Option in PrestaShop;
Question No. 1
Hi, I want to disable the upload option at the contact form so that no one can send me the files through this option?
Answer: You can deactivate this option from the back office. Go to customers>Customer Services. Where you can make the option on or off as per your choice.
Question No. 2
Hi, I want to create an input field on the customer registration form. Through this fields, visitors have to upload a file containing the proof that he has right to access the store. I want to check this proof and then allow his registration. How it is possible?
Answer: You need to modify the registration form. You can access the registration form through ./themes/YOUR-THEME/authentication.tpl. Right after the birth day field around line 130, you have to add this;
<divclass="form-group">
<labelfor="fileUpload">{l s='Select file'} *
<inputtype="hidden"name="MAX_FILE_SIZE"value="2000000"/>
<inputtype="file"class="required form-control"id="fileUpload"name="fileUpload"/>
You can add the filed in customer class and Controllers(AdminCustomersController.php, AuthController.php, Customer.php).
First of all, name a field ‘fileupload’ through which you are declaring and creating the field. Let's run this statement on SQL to create the field in the customer table to store the filename.
ALTERTABLE`ps_customer`ADD`fileUpload` VARCHAR(100)NOTNULL;
In ./classes/Customer.php around line ~30 we'll find the declared variables. Add the new one like this:
classCustomerCoreextendsObjectModel
{
public $id;
public $fileUpload;
public $id_shop;
...
then in line ~192 add the new field like this:
'date_add'=> array('type'=>self::TYPE_DATE,'validate'=>'isDate','copy_post'=>false),
'date_upd'=> array('type'=>self::TYPE_DATE,'validate'=>'isDate','copy_post'=>false),
'fileUpload'=> array('type'=>self::TYPE_STRING,'validate'=>'isGenericName'),
),
Now, inside ./controllers/front/AuthController.php around line ~379 we prepare the information:
// Preparing customer
$customer =newCustomer();
$lastnameAddress =Tools::getValue('lastname');
$firstnameAddress =Tools::getValue('firstname');
$_POST['lastname']=Tools::getValue('customer_lastname', $lastnameAddress);
$_POST['firstname']=Tools::getValue('customer_firstname', $firstnameAddress);
// Add this line
$fileUpload =Tools::getValue('fileUpload');
around line ~423 you will find the birthday validation, so you have to make the validation field.
$customer->firstname =Tools::ucwords($customer->firstname);
$customer->birthday =(empty($_POST['years'])?'':(int)Tools::getValue('years').'-'.(int)Tools::getValue('months').'-'.(int)Tools::getValue('days'));
if(!Validate::isBirthDate($customer->birthday))
$this->errors[]=Tools::displayError('Invalid date of birth.');
// Add this code...
//$customer->fileUpload = 'N/A';
// If you want the uploader as OPTIONAL, remove the comment of the line above.
$file = $_FILES['fileUpload'];
$allowed = array('txt','rtf','doc','docx','pdf','png','jpeg','gif','jpg');
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
if( file_exists($file['tmp_name'])&& in_array($extension, $allowed))
{
$filename = uniqid()."-".basename($file['name']);
$filename = str_replace(' ','-', $filename);
$filename = strtolower($filename);
$filename = filter_var($filename, FILTER_SANITIZE_STRING);
$file['name']= $filename;
$uploader =newUploaderCore();
$uploader->upload($file);
$customer->fileUpload = $filename;
}
The same way, in the line ~552, leaving it like this:
$customer->birthday =(empty($_POST['years'])?'':(int)Tools::getValue('years').'-'.(int)Tools::getValue('months').'-'.(int)Tools::getValue('days'));
if(!Validate::isBirthDate($customer->birthday))
$this->errors[]=Tools::displayError('Invalid date of birth');
// Add this code...
//$customer->fileUpload = 'N/A';
// If you want the uploader as OPTIONAL, remove the comment of the line above.
$file = $_FILES['fileUpload'];
$allowed = array('txt','rtf','doc','docx','pdf','png','jpeg','gif','jpg');
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
if( file_exists($file['tmp_name'])&& in_array($extension, $allowed))
{
$filename = uniqid()."-".basename($file['name']);
$filename = str_replace(' ','-', $filename);
$filename = strtolower($filename);
$filename = filter_var($filename, FILTER_SANITIZE_STRING);
$file['name']= $filename;
$uploader =newUploaderCore();
$uploader->upload($file);
$customer->fileUpload = $filename;
}
This way the files will be uploaded in the ./upload/ folder, if you want to specify another subfolder just insert the path in $uploader->upload('my-path/'.$_FILES['fileUpload']);
To add the input fields in the registration form open ./themes/YOUR-THEME/authentication.tpl around ~182 and ~509 right after the birthday fields.
<divclass="form-group">
<labelfor="fileUpload">{l s='Select file'} *
<inputtype="hidden"name="MAX_FILE_SIZE"value="2000000"/>
<inputtype="file"class="required form-control"id="fileUpload"name="fileUpload"/>
Don't forget to configure the form to send multimedia information on every tags like the following code: (depends on theme)
<formmethod="post"id="create-account_form" ... enctype="multipart/form-data">
To show the filename in the client list open ./controllers/admin/AdminCustomersController.php around line ~159 and add:
'connect'=> array(
'title'=> $this->l('Last visit'),
'type'=>'datetime',
'search'=>false,
'havingFilter'=>true
),
'fileUpload'=> array(
'title'=> $this->l('Uploaded File'),
'type'=>'text',
'search'=>true,
'havingFilter'=>true
)
));
In the same file, around ~821:
// Connections
'connections'=> $connections,
// Uploaded File
'fileUpload'=> $fileUpload,
// Referrers
'referrers'=> $referrers,
'show_toolbar'=>true
Clean the cache after updating the files. If you want to show the files inside the Customer View you need to modify ./admin/themes/default/template/controllers/customers/helpers/view/view.tpl.put this code right after the $customer->birthday validation at lines ~550 and ~420 to run the uploader in AuthController.php
if(isset($_FILES['fileUpload']['name'])&&!empty($_FILES['fileUpload']['name'])&&!empty($_FILES['fileUpload']['tmp_name']))
{
$extension = array('.txt','.rtf','.doc','.docx','.pdf','.png','.jpeg','.gif','.jpg');
$filename = uniqid().basename($_FILES['fileUpload']['name']);
$filename = str_replace(' ','-', $filename);
$filename = strtolower($filename);
$filename = filter_var($filename, FILTER_SANITIZE_STRING);
$_FILES['fileUpload']['name']= $filename;
$uploader =newUploaderCore();
$uploader->upload($_FILES['fileUpload']);
$customer->fileUpload = $filename;
}
Question No. 3: Hi, I want that the order information will be printed on a single page and I should have option to select which part should appear on print page and which material not. By default, it prints on 3 pages which is a bit useless.
Answer: Go to override.css in /admin/themes/default/css/override.css from where you can change the print style as needed.
@media print {
p {text-indent: 10%}
}
You need to adjest with css action "display:none" with Paypal tab and other tab.
Question No. 4
I am using PrestaShop 1.6 and I want make use of import.csv. We have imported the images and text and set the upload file option to 1. Now guide me to how to upload and attach a PDF file as a data sheet with products.
Answer: So in the AdminImportController.php, add those two lines in the fields list for products import (case $this->entities[$this->l('Products')])
'delete_existing_attachments'=> array('label'=> $this->l('Delete existing attachments (0 = No, 1 = Yes)')),
'attachment'=> array('label'=> $this->l('attachment')),
Then at the end of the function productImport(), after those lines:
else{
StockAvailable::setQuantity((int)$product->id,0,(int)$product->quantity,(int)$this->context->shop->id);
}
};
add this:
// Attachment files import
//delete existing attachments if "delete_existing_attachments" is set to 1
if(isset($product->delete_existing_attachments))
if((bool)$product->delete_existing_attachments)
$product->deleteAttachments();
$attachments = get_object_vars($product);
if(isset($attachments['attachment'])&&!empty($attachments['attachment']))
foreach(explode($this->multiple_value_separator, $attachments['attachment'])as $single_attachment)
{
$tab_attachment = explode('|', $single_attachment);
$attachment_filename = isset($tab_attachment[0])? $tab_attachment[0]:'';
$attachment_name = isset($tab_attachment[1])? trim($tab_attachment[1]): $attachment_filename ;
$attachment_description = isset($tab_attachment[2])? trim($tab_attachment[2]):'';
if(!empty($attachment_filename))
{
$id_attachment =(int)Attachment::addAttachmentImport($attachment_filename, $attachment_name, $attachment_description);
Attachment::addAttchmentProductImport($product->id, $id_attachment);
Product::updateCacheAttachment($product->id);
}
}
In the attachment class file (classes/Attachment.php) add at the end those two functions:
publicstaticfunction addAttachmentImport($filename, $name, $description)
{
$attachment =newAttachment();
$languages =Language::getLanguages();
foreach($languages as $language)
$attachment->name[$language['id_lang']]= strval($name);
$attachment->description[$language['id_lang']]= $description;
$attachment->file = sha1($filename);
$attachment->file_name = $filename;
$path_file = _PS_DOWNLOAD_DIR_.$filename;
$attachment->file_size = filesize($path_file);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$attachment->mime = finfo_file($finfo, $path_file);
$attachment->addAttachment();
return(int)$attachment->id;
}
publicstaticfunction addAttchmentProductImport($id_product, $id_attachment)
{
returnDb::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'product_attachment` (`id_attachment`, `id_product`)
VALUES ('.(int)$id_attachment.', '.(int)$id_product.')
');
}
delete the cache file: /cache/class_index.php You must put your files in the /Download folder. In your cvs file, the "attachment" column could contain this:
myfile1.doc|Name of my file Or if you want to attach several files to one product:
myfile1.doc|Name of my file%myfile2.pdf| Name of my file
Question No. 5
Is there a way to bound the visitors to upload a company document on registration page. While searching on internet, I found such uploading modules there which allows uploading on order, product and cart page but how to do it on registration?
Answer: Sadly, there is already available module for this purpose. So you need to do a core modification or writing your own module. However, if you are not code expert, contact some module development company.
Note: These questions are answered by top community developers and do not reflect FME Modules.