Jump to content

[PS 1.7]- [HOW TO] - Upload CSV File in Admin Controller - Custom module


Recommended Posts

Hi guys,

Ā 

I'm trying to create an Admin Controller with a csv file uploader to process it like an array.

Ā 

I can't find an efficient way to do it, I tried to use $this-> fields_form, but nothing is showing up.

Then I did a tpl file with an input file, called in initContent, but I don't know how to retrieve my file in the controller.

I need to create multiple object of different classes that I made, thanks to the csv file.

Ā 

Does somebody have some documentation that could help me, I've already search through prestashop dev doc, stack overflow, ect but I've didn't see anything that could help me (maybe I didn't search the good way ?)

Ā 

Waiting for your help guys !

Edited by jmauclair (see edit history)
Link to comment
Share on other sites

Update :

Ā 

Just found a way to upload my file, but it's upload as .tmp and can't be processed as a csv file, how can I convert a tmp file to a csv ?

Ā 

Here is my code :

Ā 

	public function __construct()
	{
		parent::__construct();
		// Base
		$this->bootstrap = true; // use Bootstrap CSS
		$this->fields_options = array(
			'general' => array(
				'title' => $this->l('Upload DB'),
				'fields' => array(
					'DB_BULB_DATA' => array(
						'title' => $this->l('Upload DB'),
						'type' => 'csvFile',
						'name' => 'DB_BULB_DATA'
					),
				),
				'submit' => array('title' => $this->trans('Save', array(), 'Admin.Actions')),
			),
		);
		if(isset($_FILES['DB_BULB_DATA'])){
			$headers = fgetcsv(fopen($_FILES['DB_BULB_DATA']['tmp_name'], "r+"));
			print_r($headers);
		}
	}

Ā 

Link to comment
Share on other sites

@jmauclair

Ā 

I am not sure how you find the file type csvFile. i think the file type will be file and. using that you can handel the csv file after uploadĀ 

public function renderCsvUploadForm()
	{
		$fields_form = array(
			'form' => array(
				'legend' => array(
					'title' => $this->l('Settings'),
					'icon' => 'icon-cogs'
				),
				'input' => array(
					array(
						'type' => 'file',
						'label' => $this->l('Upload DB'),
						'name' => 'DB_BULB_DATA',
						'desc' => $this->l('Upload an CSV File'),
						
					),

				),
				'submit' => array(
					'title' => $this->l('Save')
				)
			),
		);

		$helper = new HelperForm();
		$helper->show_toolbar = false;
		$helper->table = $this->table;
		$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->module = $this;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$helper->identifier = $this->identifier;
		$helper->submit_action = 'submitCsvUploadConf';
		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->tpl_vars = array(
			'uri' => $this->getPathUri(),
			'fields_value' => $this->getConfigFieldsValues(),
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id
		);

		return $helper->generateForm(array($fields_form));
	}

After post back the data handel to import

	public function postProcess()

	{
	
		if (Tools::isSubmit('submitCsvUploadConf'))
		
		{
		
			$handle = fopen($_FILES['filename']['tmp_name'], "r");
			
			$headers = fgetcsv($handle, 1000, ",");
			
			while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
			
				{
				
					$data[0];
					
					$data[1];
				
				}
			
			fclose($handle);

		}
		
	}

Ā 

Hope it solve your issues

Ā 

Thank you

Link to comment
Share on other sites

5 hours ago, SmartDataSoft said:

@jmauclair

Ā 

I am not sure how you find the file type csvFile. i think the file type will be file and. using that you can handel the csv file after uploadĀ 

public function renderCsvUploadForm()
	{
		$fields_form = array(
			'form' => array(
				'legend' => array(
					'title' => $this->l('Settings'),
					'icon' => 'icon-cogs'
				),
				'input' => array(
					array(
						'type' => 'file',
						'label' => $this->l('Upload DB'),
						'name' => 'DB_BULB_DATA',
						'desc' => $this->l('Upload an CSV File'),
						
					),

				),
				'submit' => array(
					'title' => $this->l('Save')
				)
			),
		);

		$helper = new HelperForm();
		$helper->show_toolbar = false;
		$helper->table = $this->table;
		$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->module = $this;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$helper->identifier = $this->identifier;
		$helper->submit_action = 'submitCsvUploadConf';
		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->tpl_vars = array(
			'uri' => $this->getPathUri(),
			'fields_value' => $this->getConfigFieldsValues(),
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id
		);

		return $helper->generateForm(array($fields_form));
	}

After post back the data handel to import

	public function postProcess()

	{
	
		if (Tools::isSubmit('submitCsvUploadConf'))
		
		{
		
			$handle = fopen($_FILES['filename']['tmp_name'], "r");
			
			$headers = fgetcsv($handle, 1000, ",");
			
			while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
			
				{
				
					$data[0];
					
					$data[1];
				
				}
			
			fclose($handle);

		}
		
	}

Ā 

Hope it solve your issues

Ā 

Thank you

Thanks for the help but the functionsĀ 

getPathUri(),
getConfigFieldsValues(),

InĀ 

		$helper = new HelperForm();
		$helper->show_toolbar = false;
		$helper->table = $this->table;
		$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
		$helper->default_form_language = $lang->id;
		$helper->module = $this;
		$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
		$helper->identifier = $this->identifier;
		$helper->submit_action = 'submitCsvUploadConf';
		$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name;
		$helper->token = Tools::getAdminTokenLite('AdminModules');
		$helper->tpl_vars = array(
			//'uri' => $this->getPathUri(),
			//'fields_value' => $this->getConfigFieldsValues(),
			'languages' => $this->context->controller->getLanguages(),
			'id_language' => $this->context->language->id
		);

Are not set in my controller, where can I find them ?

Link to comment
Share on other sites

Just now, SmartDataSoft said:

Hello, I just put a sample for you. You can follow this module as guide.

https://github.com/PrestaShop/blockbanner/blob/master/blockbanner.php

As their is no value need to pass in form field. You can remove getConfigFieldsValues()

Ā 

If you are developer I think you understand next steps what to do.

Ā 

Thank you

Thanks for the link, I'll check that

Link to comment
Share on other sites

9 minutes ago, SmartDataSoft said:

Hello, I just put a sample for you. You can follow this module as guide.

https://github.com/PrestaShop/blockbanner/blob/master/blockbanner.php

As their is no value need to pass in form field. You can remove getConfigFieldsValues()

Ā 

If you are developer I think you understand next steps what to do.

Ā 

Thank you

I don't really understand why my controller isn't displaying any form,

Ā 

I'm calling renderCsvUploadForm in getContent like :Ā 

return $this->renderCsvUploadForm();

It doesn't work, so I try in construct, it doesn't work too, then in initContent, and nothing display too.

Ā 

I don't really understand what I do wrong, it seems that there only fields_options that show up

Link to comment
Share on other sites

Hello, are you creating a module and inserting the code or you are trying to insert in admin controller. If possible you can. Post your module full code or file.Ā 

Then I can recheck the code and told you.

Ā 

Module you need to extend from moduleAdmin controller

Ā 

Thank you

Link to comment
Share on other sites

Just now, SmartDataSoft said:

Hello, are you creating a module and inserting the code or you are trying to insert in admin controller. If possible you can. Post your module full code or file.Ā 

Then I can recheck the code and told you.

Ā 

Module you need to extend from moduleAdmin controller

Ā 

Thank you

Hi, I'm trying to insert it in a controller, as I said later :

Ā 

class Admin<modulename>UploadBulbDatabaseController extends ModuleAdminController

Ā 

Link to comment
Share on other sites

Just find out how to do it, I feel dummy šŸ˜…

I just needed to save my tmp file as a csv to be able to use it then.

Ā 

Here is the fullĀ code :

<?php


class Admin<YourModuleName>Upload<YourThings>DatabaseController extends ModuleAdminController
{
	public function __construct()
	{
		parent::__construct();
		// Base
		$this->bootstrap = true; // use Bootstrap CSS
		$this->name = "Admin<YourModuleName>Upload<YourThings>Database";
		$this->fields_options = array(
			'general' => array(
				'title' => $this->l('Upload DB'),
				'fields' => array(
					'DB_<YourThings>_DATA' => array(
						'title' => $this->l('Upload DB'),
						'type' => 'file',
						'name' => 'DB_<YourThings>_DATA'
					),
				),
				'submit' => array('title' => $this->l('Save')),
			),
		);
	}

	public function initContent()
	{
		parent::initContent();
		unset($_FILES);
	}

	public function postProcess()

	{
		$fileName = '<YourThings>Db.csv';
		if (!file_exists(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName)) {
			if (isset($_FILES['DB_<YourThings>_DATA'])) {
				$tmpPath = $_FILES['DB_<YourThings>_DATA']["tmp_name"];
				move_uploaded_file($tmpPath, _PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName);
				$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
				$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
				$keys = array_shift($Db);
				foreach ($Db as $i => $row) {
					$Db[$i] = array_combine($keys, $row);
				}
				print_r($Db);
			}
		} else {
			$uploadCsv = file(_PS_MODULE_DIR_ . '<YourModuleName>/upload/' . $fileName, FILE_SKIP_EMPTY_LINES);
			$Db = array_map("str_getcsv", $uploadCsv, array_fill(0, count($uploadCsv), ';'));
			$keys = array_shift($Db);
			foreach ($Db as $i => $row) {
				$Db[$i] = array_combine($keys, $row);
			}
			print_r($Db);
		}
		unset($_FILES['DB_<YourThings>_DATA']);
	}
}

Ā 

Ā 

Feel free to us it or give amelioration, I'm now searching a way to display my CSV as field List šŸ˜‰

Link to comment
Share on other sites

  • jmauclair changed the title to [PS 1.7]- [HOW TO] - Upload CSV File in Admin Controller - Custom module
59 minutes ago, SmartDataSoft said:

Hello, You can check this controller code. It is Prestashop 1.6 contoller native it has simple features .Ā 

https://github.com/PrestaShop/PrestaShop-1.6/blob/master/controllers/admin/AdminAttachmentsController.php

Ā 

you need to handelĀ  Ā postProcess()Ā  for that.

I think now you are able to solve the things

Thank you

Thank you for your help !

Ā 

I've add some conditionnal to verify if the file exist and some line to unset the $_FILES and everything is working like a charm now !

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...