Jump to content

Profields Table CSV Importer / Exporter


adrian

Recommended Posts

This module adds CSV import and export functionality to Profields Table fields on both the admin and front-end.

http://modules.processwire.com/modules/table-csv-import-export/
https://github.com/adrianbj/TableCsvImportExport
 
Access to the admin import/export for non-superusers is controlled by two automatically created permissions:

table-csv-import and table-csv-export

Another permission (table-csv-import-overwrite) allows you to control access to the overwrite option when importing.
 
The overwrite option is also controlled at the field level. Go to the table field's Input tab and check the new "Allow overwrite option" if you want this enabled at all for the specific field.

Please consider limiting import overwrite option to trusted roles as you could do a lot of damage very quickly with the overwrite option :)

 
post-985-0-54092400-1412974677_thumb.png

post-985-0-17382500-1413051422_thumb.png

 
Front-end export of a table field to CSV can be achieved with the exportCsv() method:

// export as CSV if csv_export=1 is in url
if($input->get->csv_export==1){
   $modules->get('ProcessTableCsvExport'); // load module
   // delimiter, enclosure, file extension, multiple fields separator, names in first row
   $page->fields->tablefield->exportCsv('tab', '"', 'tsv', '|', true); 
}
// display content of template with link to same page with appended csv_export=1
else{
   include("./head.inc");

   echo $page->tablefield->render(); //render table - not necessary for export - just displaying the table
   echo "<a href='./?csv_export=1'>Export Table as CSV</a>"; //link to initiate export

   include("./foot.inc");
}

 
Front-end import can be achieved with the importCsv() method:

$modules->get('TableCsvImportExport'); // load module
// data, delimiter, enclosure, convert decimals, ignore first row, multiple fields separator, append or overwrite
$page->fields->tablefield->importCsv($csvData, ';', '"', true, false, '|', 'append');

Please let me know if you have any problems, or suggestions for improvements.

Enjoy!

  • Like 21
  • Thanks 1
Link to comment
Share on other sites

I was confused by that which is why I hadn't commented yet - I was trying to let it sink in to see if I could get what you meant :)

I should probably do a little more cleaning of the CSV for trailing commas, extra spaces, and the like - it's on my list.

Link to comment
Share on other sites

Small update committed for finer control over the overwrite option when importing.

The new table-csv-import-overwrite permission allows you to control access to the overwrite option when importing. If a user doesn't have this permission, they won't have the option to choose overwrite.
 
The overwrite option is also controlled at the field level. Go to the table field's Input tab and check the new "Allow overwrite option" if you want this enabled at all for the specific field. So if overwrite is not enabled for each particular table field, it doesn't matter what permission the user has, no-one will have access to it.
 
post-985-0-15034700-1413051579_thumb.png
  • Like 2
Link to comment
Share on other sites

  • 2 months later...
  • 1 month later...

Awesome module Adrian thanks for sharing. I am getting some strange behavior though. I have two different table field types assigned to one template. When I try uploading a csv I get the following error message. "That is not an allowed file extension for a CSV import. Try again with a .csv, .tsv, or .txt file". My file is indeed a csv.

I have tried both tab and comma separated columns.  If "ignore first row" is checked, it will not import anything. If it is unchecked, it will import only one row. 

Also, if I paste the csv data it imports it fine into the desired columns and table, but also imports the data into the other table field assigned to that template. The two table field types have different names and a different amounts of columns. Any suggestions or tips is appreciated. I will be glad to pm you the csv I am using if you so wish. Thanks in advance.

Link to comment
Share on other sites

Hi Adrain, 

I removed one table field from the template and that is when I was able to get it to import the one row after I unchecked "ignore first row" however, I still received the same error message, but it did import the one row. It sound like something is wrong with my csv but I cant see where.  I think there may be a separate issue with it importing into both field types. I am sending you the csv file now. Thanks for taking the time to look at it.

Link to comment
Share on other sites

Thanks @RJay - I think I have managed to fix all those issues - I hadn't tested with multiple Table fields on the one page. Please check the latest version and let me know how it goes for you.

PS There was nothing wrong with your CSV file.

Link to comment
Share on other sites

Hi Adrian, 

Thanks for such a quick response time. Premium service there :). After applying your updates, I was able to paste the csv data in and it was applied to the proper table, ignoring the other.

However, when trying to import the csv file I still get the message "Session: That is not an allowed file extension for a CSV import. Try again with a .csv, .tsv, or .txt file"

I tried this on both local and development servers just in case it was a permission issue. I then tried removing one of the tables, once I did that, I still received the message, but it did import the first row of the csv file. I am going to try maybe a text file and then just redoing the fields and go from there. I'll let you know what my results are.

*Update

Uploading a txt file works perfectly. Not sure why it does not like the csv files.

Link to comment
Share on other sites

However, when trying to import the csv file I still get the message "Session: That is not an allowed file extension for a CSV import. Try again with a .csv, .tsv, or .txt file"

I am thinking it must be my mimetype checks. Can you please try replacing:

if(($csv_file_extension == 'csv' || $csv_file_extension == 'txt' || $csv_file_extension == 'tsv') &&
    ($csv_type == 'text/plain' || $csv_type == 'text/tab-separated-values' || $csv_type == 'text/csv')){
    $this->session->{$fieldName . '_csv_data'} = file_get_contents($_FILES[$csv_filename]["tmp_name"]);
}
 

with:

if($csv_file_extension == 'csv' || $csv_file_extension == 'txt' || $csv_file_extension == 'tsv'){
    $this->session->{$fieldName . '_csv_data'} = file_get_contents($_FILES[$csv_filename]["tmp_name"]);
}

and see if that allows the csv upload to work.

  • Like 1
Link to comment
Share on other sites

Great to hear. I have committed another update that removes those checks - they really aren't very useful anyways as they can be manipulated in the browser and aren't always provided (hence the errors you were getting).

Can you please confirm that all the other multiple Table field and issues with only one row importing are also now solved?

Thanks for your help in getting this all fixed.

Link to comment
Share on other sites

Importing and exporting both appear to be working perfectly. Thank you for providing such a great module and excellent support for it. It still amazes me how helpful the staff, moderators and other forum members are around here.

  • Like 1
Link to comment
Share on other sites

  • 1 month later...

Hi Adrian,

This is a jolly helpful module, thanks for developing it.

I ran into a problem when using it on a page where the table field is contained within a repeater on the page's template.

The set up is as follows:

The page template has the following fields:
  • Title
  • Programmes
Programmes is a repeater field containing two fields:
  • Year
  • Programme
The Year field is an integer field
The Programme field is the table field
 
The error occurs on page save and is reported as follows:
 
Notice: Trying to get property of non-object in [my_path_to]/site/modules/TableCsvImportExport/TableCsvImportExport.module on line 263

Warning: Invalid argument supplied for foreach() in [my_path_to]/site/modules/TableCsvImportExport/TableCsvImportExport.module on line 263

Fatal error: Call to a member function makeBlankItem() on a non-object in [my_path_to]/site/modules/TableCsvImportExport/TableCsvImportExport.module on line 277
Error: Call to a member function makeBlankItem() on a non-object (line 277 of [my_path_to]/site/modules/TableCsvImportExport/TableCsvImportExport.module) 
This error message was shown because site is in debug mode ($config->debug = true; in /site/config.php). Error has been logged.

By reworking the template to include only Title and Programme fields (i.e. a single table, no repeater) the problem goes away.

I can work with that but wondered, since one of the posts above deals with a similar/related use case, if you can help at all.

Many thanks,

Nic

Link to comment
Share on other sites

@sgt.blikey - I am glad you like it. I have put together a fix for supporting repeaters - please let me know if it works for you as expected. If anyone sees any issues with normal Table fields (not in repeaters), with this new version, please let me know!

Even though I just added support for repeaters, I want to make sure you have you read this thread: https://processwire.com/talk/topic/8832-error-in-complex-form/ - it is in the Profields support board, but I am assuming you have access. In particular read the post by Ryan where he says that Tables in Repeaters are not officially supported, although he does say that if they were working and now aren't, he'd consider investigating. 

Mostly just wanted to warn you that maybe you will run into other issues with this approach.

Have you considered switching to PageTables or even simple child pages and putting your Table field in those?

Link to comment
Share on other sites

@adrian

I (don't) think I had seen the thread you linked to. I guess table fields in repeaters is adding a layer of complexity that need not be there and it would be sensible to follow the PageTables/child pages route.

I'll have a go with your updated module and let you know how that goes but will probably implement as PageTables/child pages.

Many thanks for acting so promptly.

Nic

(oops, hadn't actually seen that thread!)

  • Like 1
Link to comment
Share on other sites

  • 2 weeks later...
  • 2 months later...

Hi everyone,

I have just added support for single and multiple page-reference fields and multiple options - requires PW 2.6.4 and Table 7-beta that Ryan released last week.

  • Export converts page IDs to the title of the page.
  • Import looks up the titles and populates the table with the IDs of the matching pages.

Please let me know if you have any problems with this new version.

  • Like 1
Link to comment
Share on other sites

A few more tweaks - you can now specify the separator when importing and exporting tables with the new multi-value fields. Also a couple of bug fixes and a speed improvement when importing.

  • Like 1
Link to comment
Share on other sites

  • 10 months later...

Hi Adrian,

I think there's a problem when using your module with any other code or modules that use fgets() or file() - such as Horst's WireQueueTextfile module (and possibly others.) I've just spent a couple of hours tracking this down over IRC with a client.

The init() routine of your module sets PHPs auto_detect_line_endings flag to true - which can have un-intended consequences on other code run after your module initialises. In my client's case, they are using WireQueue with the textfile storage and it was throwing up errors, with your module installed, while unserialising a line pulled from the queue file using fgets() at the end of the getItem() method that pulls an item from the Wire Queue.

Commenting out the following in TableCsvImportExport.module;

ini_set('auto_detect_line_endings', true);

fixed things for us.

I understand the attraction of making the exported/imported files cross-platform compatible, but I think your module has other options open rather than changing the PHP setting during the init() routine. Perhaps, at the start of the import routine, you could read the initial state of that flag, then ini_set() it to true while you do the import and finally restore it to the initial setting on exit from your routine?

Thanks for your great modules and for considering this request!

  • Like 2
Link to comment
Share on other sites

Hi Steve - sorry you had to waste a couple of hours troubleshooting that, but thanks for the detailed analysis of the problem and the solution.

The latest version should take care of it - please let me know if there are any continued problems.

Thanks again!

  • Like 4
Link to comment
Share on other sites

  • 4 weeks later...

Hello ! 

I have a strange problem when importing .csv file. The error is:

32×PHP Notice: Array to string conversion in .../TableCsvImportExport/TableCsvImportExport.module:360
16×PHP Notice: Indirect modification of overloaded property TableRow::$Array has no effect in .../TableCsvImportExport/TableCsvImportExport.module:360

The content of csv file  :

00003;07-05-2016;14:37:57;0;3;5106;18;58;31;102;1;0;237;7;31;3;16;1;0;0;0

 
Can you help me ? 
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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      This module lets you add some custom menu items to the main admin menu, and you can set the dropdown links dynamically in a hook if needed.
      Sidenote: the module config uses some repeatable/sortable rows for the child link settings, similar to the ProFields Table interface. The data gets saved as JSON in a hidden textarea field. Might be interesting to other module developers?
      Custom Admin Menus
      Adds up to three custom menu items with optional dropdowns to the main admin menu.
      The menu items can link to admin pages, front-end pages, or pages on external websites.
      The links can be set to open in a new browser tab, and child links in the dropdown can be given an icon.
      Requires ProcessWire v3.0.178 or newer.
      Screenshots
      Example of menu items

      Module config for the menus

      Link list shown when parent menu item is not given a URL

      Advanced
      Setting child menu items dynamically
      If needed you can set the child menu items dynamically using a hook.
      Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $colours = $event->wire()->pages->findRaw('template=colour', ['title', 'url', 'page_icon']); $children = []; foreach($colours as $colour) { // Each child item should be an array with the following keys $children[] = [ 'icon' => $colour['page_icon'], 'label' => $colour['title'], 'url' => $colour['url'], 'newtab' => false, ]; } $event->return = $children; } }); Create multiple levels of flyout menus
      It's also possible to create multiple levels of flyout submenus using a hook.

      For each level a submenu can be defined in a "children" item. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); if($menu_number === 1) { $children = [ [ 'icon' => 'adjust', 'label' => 'One', 'url' => '/one/', 'newtab' => false, ], [ 'icon' => 'anchor', 'label' => 'Two', 'url' => '/two/', 'newtab' => false, 'children' => [ [ 'icon' => 'child', 'label' => 'Red', 'url' => '/red/', 'newtab' => false, ], [ 'icon' => 'bullhorn', 'label' => 'Green', 'url' => '/green/', 'newtab' => false, 'children' => [ [ 'icon' => 'wifi', 'label' => 'Small', 'url' => '/small/', 'newtab' => true, ], [ 'icon' => 'codepen', 'label' => 'Medium', 'url' => '/medium/', 'newtab' => false, ], [ 'icon' => 'cogs', 'label' => 'Large', 'url' => '/large/', 'newtab' => false, ], ] ], [ 'icon' => 'futbol-o', 'label' => 'Blue', 'url' => '/blue/', 'newtab' => true, ], ] ], [ 'icon' => 'hand-o-left', 'label' => 'Three', 'url' => '/three/', 'newtab' => false, ], ]; $event->return = $children; } }); Showing/hiding menus according to user role
      You can determine which menu items can be seen by a role by checking the user's role in the hook.
      For example, if a user has or lacks a role you could include different child menu items in the hook return value. Or if you want to conditionally hide a custom menu altogether you can set the return value to false. Example:
      $wire->addHookAfter('CustomAdminMenus::getMenuChildren', function(HookEvent $event) { // The menu number is the first argument $menu_number = $event->arguments(0); $user = $event->wire()->user; // For custom menu number 1... if($menu_number === 1) { // ...if user does not have some particular role... if(!$user->hasRole('foo')) { // ...do not show the menu $event->return = false; } } });  
      https://github.com/Toutouwai/CustomAdminMenus
      https://processwire.com/modules/custom-admin-menus/
    • By tcnet
      This module for ProcessWire sends a notification email for each failed login attempt. Similar modules exists already in the module directory of ProcessWire. However, this module is designed to notify, even if specified user doesn't exist.
      Settings
      The settings for this module are located in the menu Modules=>Configure=>LoginFailNotifier.
      Notification email
      Specifies the email address to which the notification emails should be sent.
        Email subject
      Specifies the subject line for the notification email.
        Post variables
      Specifies the $_POST variables to be included in the notification email. Each variable must be separated by a comma. For example: login_name,login_pass
        Server variables
      Specifies the $_SERVER variables to be included in the notification email. Each variable must be separated by a comma. For example: REMOTE_ADDR,HTTP_USER_AGENT
      Link to ProcessWire module directory:
      https://processwire.com/modules/login-fail-notifier/
      Link to github.com:
      https://github.com/techcnet/LoginFailNotifier
    • By Fokke
      ProcessWire 3.x markup module for rendering meta tags in HTML document head section. Note that this module is not a full-blown SEO solution, but rather a simple tool for rendering meta tags based on module configuration. Adding custom meta tags is also supported.
      Built-in meta tags
      The following meta tags are supported out-of-the-box:
      Document title consisting of page title and site name Character set Canonical Viewport Description Keywords Hreflang tags Open Graph og:title og:site_name og:type og:url og:description og:image og:image:width og:image:height Twitter meta tags twitter:card twitter:site twitter:creator twitter:title twitter:description twitter:image Facebook meta tags fb:app_id The full documentation with configurable options can be found here: https://github.com/Fokke-/MarkupMetadata
       
      Requirements:
      ProcessWire>=3.0.0 PHP >=7.1 Installation using Composer
      composer require fokke/markup-metadata Manual installation
      Download latest version from https://github.com/Fokke-/MarkupMetadata/archive/master.zip Extract module files to site/modules/MarkupMetadata directory.
    • By m.sieber
      ITRK-Service for ProcessWire
      Module for the automated transfer of imprint, data protection declaration and terms and conditions from IT-Recht Kanzlei to your ProcessWire installation
      What is ITRK Service for ProcessWire?
      ITRK-Service for ProcessWire is a free module for ProcessWire CMS. It provides an interface to the update service of IT-Recht Kanzlei, via which the legal texts of your online presence are automatically updated. In this way, the texts remain legally secure and warning-proof in the long term. Imprint, data protection declaration, revocation and general terms and conditions are currently supported.
      You can find our documentation (in german language) here: https://www.pupit.de/itrk-service-for-processwire/dokumentation/

      Download: https://www.pupit.de/itrk-service-for-processwire/
      Github: https://github.com/pupit-de/pwItrkServiceConnector
    • By LuisM
      Symprowire is a PHP MVC Framework based and built on Symfony using ProcessWire 3.x as DBAL and Service-Provider
      It acts as a Drop-In Replacement Module to handle the Request/Response outside the ProcessWire Admin. Even tough Symfony or any other mature MVC Framework could be intimidating at first, Symprowire tries to abstract Configuration and Symfony Internals away as much as possible to give you a quick start and lift the heavy work for you.
      The main Goal is to give an easy path to follow an MVC Approach during development with ProcessWire and open up the available eco-system.
      You can find the GitHub Repo and more Information here: https://github.com/Luis85/symprowire
      Documentation
      The Symprowire Wiki https://github.com/Luis85/symprowire/wiki How to create a simple Blog with Symprowire https://github.com/Luis85/symprowire/wiki/Symprowire-Blog-Tutorial Last Update
      16.07.2021 // RC 1 v0.6.0 centralized ProcessWire access trough out the Application by wrapping to a Service https://github.com/Luis85/symprowire/releases/tag/v0.6.0-rc-1 Requirements
      PHP ^7.4 Fresh ProcessWire ^3.0.181 with a Blank Profile Composer 2 (v1 should work, not recommended) The usual Symfony Requirements Features
      Twig Dependency Injection Monolog for Symprowire Support for .env YAML Configuration Symfony Console and Console Commands Symfony Webprofiler Full ProcessWire access inside your Controller and Services Webpack Encore support Caveats
      Symfony is no small Framework and will come with a price in terms of Memory Usage and added Overhead. To give you a taste I installed Tracy Debugger alongside to compare ProcessWire profiling with the included Symfony Webprofiler

      So in a fresh install Symprowire would atleast add another 2MB of Memory usage and around 40ms in response time, should be less in production due to the added overhead of the Webprofiler in dev env
       
×
×
  • Create New...