Upload CSV File in Admin Controller - Custom module - php

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 !
Update :
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' => 'file',
'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);
}
}

There is no file type name csvfile , you need to use filed type file and then hadel the csv file after upload, check file extension then process the data.

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']);
}
}

Related

Cannot insert data barcode with $id_barcode on codeigniter

I tried to create a barcode using zend_barcode library , when I try to run perfectly but when I try to do a project there is a problem , I try to create a barcode based on $id_barcode I input when I insert does not work .
This my Controllers
function insert() {
$barcode = $this->input->post('id_barcode');
$imageResource = Zend_Barcode::factory('code128', 'image', array('text'=>$barcode), array())->draw();
$imageName = $barcode.'.jpg';
$imagePath = './result/';
if (!is_dir($imagePath)) {
mkdir ($imagePath, 777, TRUE);
}
$createbarcode = imagejpeg($imageResource, $imagePath.$imageName);
$this->product_m->insert_produk($createbarcode);
redirect('admin/product');
}
this my Models
function insert_produk($createbarcode){
$data = array(
'id_barcode' => $this->input->post('id_barcode'),
'reseller_produk'=> $this->input->post('reseller_produk'),
'nama_produk' => $this->input->post('nama_produk'),
'jenis_produk' => $this->input->post('jenis_produk'),
'harga_produk' => $this->input->post('harga_produk'),
'stock_produk' => $this->input->post('stock_produk'),
'date' => $this->input->post('date'),
'image' => $createbarcode);
$this->db->insert('tb_produk', $data);
}

How to migrate entity from XML to Drupal 7 using migrate module

I have created a class using migrate module but I am unable to migrate entities. my class codes are below please check it and tell me whats the problem with it??
<?php
class ItemOrderXMLMigration extends XMLMigration {
public function __construct() {
parent::__construct(MigrateGroup::getInstance('OrderFeed'));
$this->description = t('Migrate entity from XML file');
//$this->softDependencies = array('WineFileCopy');
$fields = array(
'Number' => t('Number'),
'Date' => t('Date'),
'SubTotal' => t('Sub Total'),
'Discount' => t('Discount'),
'ShippingCharges' => t('Shipping Charges'),
'ShippingChargesDiscount' => t('Shipping Charges Discount'),
'NumItems' => t('NumItems'),
'VATPercentage' => t('VAT Percentage'),
'CurrencyCode' => t('Currency Code'),
'PaymentTypeDesc' => t('Payment Type Desc'),
'OrderState' => t('Order State'),
);
$this->map = new MigrateSQLMap($this->machineName,
array(
'Number' => array(
'type' => 'varchar',
'length' => 225,
'not null' => TRUE,
)
),
MigrateDestinationEntityAPI::getKeySchema('entity_example_basic','first_example_bundle')
);
$xml_folder = DRUPAL_ROOT . '/' . drupal_get_path('module', 'products_import') . '/xml/';
$items_url = $xml_folder . 'OrderFeed.xml';
$item_xpath = '/Orders/Item'; // relative to document
$item_ID_xpath = 'Number'; // relative to item_xpath and gets assembled
// into full path /producers/producer/sourceid
$items_class = new MigrateItemsXML($items_url, $item_xpath, $item_ID_xpath);
$this->source = new MigrateSourceMultiItems($items_class, $fields);
$this->destination = new MigrateDestinationEntityAPI('entity_example_basic','first_example_bundle');
$this->addFieldMapping('field_number', 'Number')
->xpath('Number');
$this->addFieldMapping('field_subtotal', 'SubTotal')
->xpath('SubTotal');
$this->addFieldMapping('field_discount', 'Discount')
->xpath('Discount');
//$this->addUnmigratedDestinations(array('weight'));
}
}
?>
When I import it I got the save error message for all entities: Creating default object from empty value File /var/www/mig/migration/sites/all/modules/migrate_extras/entity_api.inc, line 227
Try the latest or updated migrate module https://www.drupal.org/project/migrate. I think you were using old one which were having some issues to migrate entities.
Why don't you try with a feed importer (Feeds module) using XPath parser module?. It's really easy, and you can use both an uploaded file or a source URL.

How to show the file upload name for jQuery Multiple File Upload Plugin

How to show the file upload name for jQuery Multiple File Upload Plugin v1.48?
After the users have uploaded the file, is there a way to show the file that they have uploaded under the profile?
1.if ( isset($_FILES['tb-documents']) ) {
$documents = $_FILES['tb-documents'];
foreach ( $documents['name'] as $key => $value ) {
if ( $documents['name'][$key]) {
$document = array(
'name' => $documents['name'][$key],
'type' => $documents['type'][$key],
'tmp_name' => $documents['tmp_name'][$key],
'error' => $documents['error'][$key],
'size' => $documents['size'][$key]
);
$status = wp_handle_upload($document, array('test_form' => false));
if( !isset($status['error']) ) {
$uploads = wp_upload_dir();
add_user_meta($user->ID, 'tb-documents', $uploads['url'].'/'.basename($status['file']));
}
}
}
}
The upload is working well on the user profile. However, I want to pull out the file name that they have uploaded and display all the uploaded file names to them.
Which variable should I use?
1.I tried this, $content .= '.$documents['name']'; but it doesn't work. It shows syntax error.
You have to combine results from this $documents['name'][$key] and show it to user.
For example:
if (isset($_FILES['tb-documents'])) {
$uploadedFiles = array();
$documents = $_FILES['tb-documents'];
foreach ($documents['name'] as $key => $value) {
if ($documents['name'][$key]) {
$document = array(
'name' => $documents['name'][$key],
'type' => $documents['type'][$key],
'tmp_name' => $documents['tmp_name'][$key],
'error' => $documents['error'][$key],
'size' => $documents['size'][$key]
);
$status = wp_handle_upload($document, array('test_form' => false));
if (!isset($status['error'])) {
$uploads = wp_upload_dir();
add_user_meta($user->ID, 'tb-documents', $uploads['url'] . '/' . basename($status['file']));
$uploadedFiles[] = $documents['name'][$key];
}
}
}
var_dump(implode(", ", $uploadedFiles));
}
If you want to show the uploaded files to the uploader, you can handle it easily in JQuery using the fileuploaddone callback provided by jQuery uploader
$('#fileupload')
.bind('fileuploaddone', function (e, data) {
console.log( data['result']['files'][0]['name'] );
console.log( data['result']['files'][0]['url'] );
});
If you have multiple files, you need to loop over data['result']['files'] array.

Creating jstree from ftp directory structure

I need to use jstree to display the directory structure of a ftp account's homedir.
I somehow got stuck at retrieving the full directory structure (and create a json object, xml file, html code, whatever). It is most likely something easy that is just slipping my mind, but anyway, here's what i tried so far:
function draw_tree($path)
{
global $con;
$list = ftp_nlist($con,$path);
$dirs = array(); $files = array();
foreach($list as $file)
{
if(ftp_is_dir($file))
{
$dir[] = array(
'attr' => array('data-path' => $path . '/' . $file,
'data' => $file,
'state' => 'closed',
'children' => // ??? some recursive function should
// probably go here
);
}
else {
$files[] = array(
'attr' => array('data-path' => $file)
);
}
}
return array_merge($dirs,$files);
}

In drupal 6, How to process uloaded file in more than one steps?

I am writing custom module in drupal.
Aim is to :
1. Upload a csv file
2. Display its content in a tabular layout.
3. On confirmation, save it in database.
Problem I am facing:
I am unable to upload any file. I am not getting any thing in $_FILES, even if I upload or not. >> SOLVED
How do I split the process ? Suppose I succeed in uploading file [with your help indeed ;) ], and I save the file, suppose in drupal6/uploaded_data directory. How do I redirect to next page where I can read from file and show tabular data for confirmation.
Codes :)
menu hooks and all
function productsadmin_menu() {
$items['admin/settings/product-administration'] = array(
'title' => 'Product Administration',
'description' => 'Upload products data',
'page callback' => 'productsadmin_form',
'access arguments' => array('access content'),
'type' => MENU_NORMAL_ITEM,
);
return $items;
}
function productsadmin_form() {
return drupal_get_form('productsadmin_my_form');
}
This function is passed to drupal_get_form()
function productsadmin_my_form() {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['csv'] = array(
'#type' => 'file',
'#title' => 'Product Catalog',
'#description' => 'Product catalog in specified csv format',
'#required' => FALSE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
Validation (The part which is not working is commented)
function productsadmin_my_form_validate($form, &$form_state) {
if($form_state['values']['csv'] == "") {
form_set_error('csv', t('Please input product catalog csv data'));
}
/* // Check if file is uploaded (Not working)
if ($_FILES['files']['name']['csv'] == '') {
form_set_error('csv', t('Please upload product catalog' . $rahul_vals));
}
*/
}
Submit action
function productsadmin_my_form_submit($form, &$form_state) {
/*
1. Move File to uploaded_dir
2. Change the header so that it is redirected to new page
*/
}
you shouldn't use $_FILES in drupal,use drupal api
I made this example for you to explain how to work with cvs
/**
* Form function
*/
function _form_cvs_import($form_state) {
$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['container'] = array(
'#type' => 'fieldset',
'#title' => t('CVS UPLOAD') ,
);
$form['container']['cvs_file'] = array(
'#type' => 'file' ,
'#title' => t('CVS FILE') ,
'#description' => t('insert your cvs file here') ,
) ;
$form['container']['submit'] = array(
'#type' => 'submit' ,
'#value' => t('SEND') ,
) ;
return $form ;
}
/**
* form validate
*/
function _form_cvs_import_validate($form, $form_state) {
$validators = array(
'file_validate_extensions' => array('cvs'),
);
if(!file_save_upload('cvs_file', $validators)) { // the file is not submitted
form_set_error('cvs_file', 'Please select the cvs file') ;
}else{ // the file is submitted another validation for extension
$file = file_save_upload('cvs_file', $validators, file_directory_path()) ;
if($file->filemime != 'application/octet-stream' ) {
form_set_error('cvs_file', 'Extensions Allowed : cvs') ;
}
}
}
/**
* form submit
*/
function _form_cvs_import_submit($form, $form_state) {
$file = file_save_upload('cvs_file', $validators, file_directory_path()) ; // this is the cvs file in the tmp directory
$file_handler = fopen($file->filepath, 'r') ; // open this cvs file
$line_num = 0 ;
$fields = array() ;
while(!feof($file_handler)) {
$line_num++ ;
$line = fgets($file_handler) ; // this is the line/row
$line_array = explode(",", $line); // array of row fields
$field_num = 0 ;
foreach($line_array as $field) {
$field_num++ ;
$fields[$line_num][$field_num] = str_replace('"', '', $field ); // E.g you can access second row and third field by $fields[2][3]
}
}
fclose($file_handler);
unlink($file->filepath);
}

Categories