Will be good to see integration with Views Bulk Operations module. This add feature for exporting to csv and other format many custom selected data, instead of building separated view for them.
You can do this via provide some rules via hook_node_operations() and re-use your current export functions.
Good example that exports to csv you can find here: http://britesparkz.com/tennessee-drupal-blogs/ubercart-vbo-and-cvs-exports

Comments

bojanz’s picture

hook_node_operations() is not supported by VBO for D7.
You either provide a core action, or a rules action (or even a complete rules component).

murz’s picture

For Drupal 7.x you can use hook_action_info(). I done for my needs csv export in custom module, here is example:

 function caramba_action_info() {
  return array(
    'caramba_action_csv_export' => array(
      'type' => 'entity',
      'label' => t('Export to CSV'),
      'configurable' => FALSE,
      'behavior' => array('caramba_export_csv'),
    ),
  );
}

function caramba_action_csv_export($entity, $context) {
  static $csv;
  
  if(empty($csv)) {
    $data=array(
      'sku',
      'title',
      'alt_name',
      'price',
      );
      $csv="\"".implode('","',$data)."\"\n";
  }
  $data=array(
    addslashes($entity->sku),
    addslashes($entity->title),
    addslashes($entity->field_alt_name[LANGUAGE_NONE][0]['value']),
    addslashes($entity->field_price[LANGUAGE_NONE][0]['amount']),
    );
  $csv .= "\"".implode('","',$data)."\"\n";
  
  if ($context['progress']['current'] == $context['progress']['total']) {
    $GLOBALS['devel_shutdown'] = FALSE;
    
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export_price.csv"');

    die(print iconv('UTF-8','CP1251',$csv));
  }
}

It is very basic and not configurable, but works for my needs very good.
This is not views-related code, but will be good to see this functional in this module or separate module.

texas-bronius’s picture

Status: Active » Closed (works as designed)

Hey @Murz, pretty slick. Thanks for sharing this info-- works like a boss!

I had a spot of trouble with it (only got one record out from your snippet adapted for my use case) and wanted to share my observations and load this issue queue with some SEO on this elegant solution to giving Views Bulk Operation the ability to export CSV of the selected records. Maybe you can comment on them and confirm?

* It appears that you've configured your VBO action not as aggregate => TRUE and yet it still runs. This is because you're iterating the whole set of VBO provided entities against a growing, static variable and terminating iteration on VBO's $context variable status of completion field.
* Note that setting aggregate => TRUE breaks the solution and only returns results for 1 record
* what is configurable => FALSE in this case?

[edit: OOps, I misread the title of this issue queue and its project namespace -- reopening the issue]

Thanks!
-Bronius

texas-bronius’s picture

Title: Add integrations with Views Bulk Operations » Add integrations with Views Bulk Operations (sample VBO action to expose selected records to CSV export included herein)
Status: Closed (works as designed) » Active

(padding with some SEO in the title, even though it's more specific that the original author had requested and setting status back to Active)

a_thakur’s picture

Hey Murz,

The code in comment #2 does not work for me. I suspect the line die(print iconv('UTF-8','CP1251',$csv)); is causing problem.

murz’s picture

a_thakur, this is not good code for use, this is only example how I solve this issue for only my site, I not recommend to use it on other sites. String

 die(print iconv('UTF-8','CP1251',$csv));

does codepage converting for Cyrillic language, so if you don't need this, you can use

 print $csv; die();
kenorb’s picture

kenorb’s picture

Status: Active » Needs review
StatusFileSize
new52.95 KB

Ignore this one.

kenorb’s picture

StatusFileSize
new2.26 KB

Attached initial patch.
Tested with the following patch:
#1902104: Allow batching to be skipped
and option to disable batch process.

Status: Needs review » Needs work

The last submitted patch, vbo-csv-export-1436726.patch, failed testing.

kenorb’s picture

StatusFileSize
new3.1 KB

Known problems:
- it has problem exporting profile data
- could not work without #1902104: Allow batching to be skipped

kenorb’s picture

Status: Needs work » Needs review
StatusFileSize
new3.43 KB

This version is with entity dependency.

Status: Needs review » Needs work

The last submitted patch, vbo-csv-export-1436726.patch, failed testing.

kenorb’s picture

Status: Needs work » Needs review
StatusFileSize
new1.31 KB

Ignore this one.

kenorb’s picture

StatusFileSize
new1.31 KB

Better, simpler patch which uses views_data_export handler.
To make it working, new display for views_data_export should be created.

It still requires 'Don't use batch/queue' option after applying #1902104: Allow batching to be skipped patch, otherwise it has some problems. Not sure how to workaround them.

In case of some issues:
- make sure that you've set 'Provide as file' in Format Settings,
- test with 'Attach to' to None

bojanz’s picture

There is no reason why such an action couldn't work with batching.
Also, VBO itself depends on Entity API.

kenorb’s picture

@bojanz:
When using in batch, it generates the error like:

An error has occurred.
Please continue to the error page
An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /batch?id=241&op=do StatusText: OK ResponseText: "Event ID","Event booking ID","Date","Event","Attendee ID","Attendee: E-mail","Attendee: First name","Attendee: Last name","Attendee: Telephone number" "4430","4431","2013-09-02T09:53:47+01:00"

, so basically it's dumping the CSV content.

Also what I noticed, is that the export action has some problems when View is embedded in Panel. But it could be some specific case.
The other thing is, that the export works for all the rows, despite of the user selection. Not sure how to change it.

Adon Irani’s picture

#15: vbo-csv-export-1436726.patch queued for re-testing.

kenorb’s picture

The other issue with CSV export is, that it doesn't export selected rows.

As workaround, it can be solved by creating 'Pass ids as arguments to a page' action with URL to the view data export page.

Related:
#1784156: Only first page of view results 'rows' passed to action on VBO execution
#1477760: Provide a way to get all ids of a row
#1180538: Pass the selected views row(s) to the action

chi’s picture

15: vbo-csv-export-1436726.patch queued for re-testing.

ndewhurst’s picture

Issue summary: View changes
StatusFileSize
new3.03 KB

Here's a follow-up to @kenorb's work that's functioning well for me. The underlying idea is unchanged (look for a views_data_export display in the same view, and execute that to generate the CSV).
Notes:

  • This seems to be a proper case for using an aggregate action, rather than a standard action that only does the bulk of its work on the last of many iterations.
  • This works with a batched or non-batched data export. Both versions could use some extra work to properly return to the VBO view if desired.
  • Perhaps most importantly, this will export only the selected entities to CSV. My approach was to provide the list of selected entity IDs as a sort of stowaway argument to the view/display, and then utilize that list in a query alter hook that applies to any views_data_export display's query (and will therefore work for batched jobs, which have a couple custom query plugins, or non-batched jobs, which use a standard Views query).
  • I thought it would be nice to know the total number of rows in the VBO view without having to re-execute the view just for that purpose. That piece of data might be something we can just add to VBO (https://www.drupal.org/node/2488146)
  • This should currently work regardless of the "provide as file" setting you choose. Enabling that option will simply let you specify a filename [pattern].

There may be some other assumptions or use cases I'm glossing over. Hopefully this is useful to others as well!

ndewhurst’s picture

Another thought: in the query alter, we could probably replace existing conditions with the entity ID condition rather than just adding it. We know that the entities with those IDs already satisfied the other view conditions, by virtue of the fact that they appeared in the VBO view and were selectable. (Right?) Presumably that could be a bit more efficient.

maxplus’s picture

Hi ndewhurst,

your patch from #21 works for me.

As described in #52 https://www.drupal.org/node/1875456, I would like to find a more generic solution where I could combine several rules actions together (including the csv export of the selected items)

Thanks already for the work that is done

kenorb’s picture

Status: Needs review » Reviewed & tested by the community
joelpittet’s picture

RTBC++ I've been using this for some time now too.

djpable’s picture

#21 works fine, but it would be awesome if you could add the possibility to add multiple actions for multiple views_data_export displays

jgullstr’s picture

Aggregated actions limit (by memory) the amount of entities that can be exported, as all selected entities will be loaded on a single request. Ideally, there should be an option to only pass entity ids to the action, but this does not (to my knowledge) exist. Hence, using aggregate in #21 restricts the possible use cases.

Provided patch provides a workaround without aggregate. I also moved selecting display id to a VBO setting.

joelpittet’s picture

@jgullstr could you post an interdiff between your patch and the previous one?
@see https://www.drupal.org/documentation/git/interdiff

jgullstr’s picture

StatusFileSize
new6.69 KB

Interdiff attached.

Explained:

  • Removed aggregate from hook_action_info()
  • Added a VBO configuration form for selecting views_data_export display id
  • Changed views_data_export_action_csv_export to work with single entities instead of an aggregated list:
    • The entity id for each entity passed to views_data_export_action_csv_export is saved to a static variable. If batching is used, the list of entity ids is persisted to the batch array (@see views_data_export_action_context()).
    • When the last row is processed, the generated array of entity ids is passed as a filter to the view (Similar to #21).
    • If batched, the batch array redirect callback is changed. Redirect in form_state has to be FALSE for this callback to be reached.
    • Form state rebuild has to be set in order to be able to access the form state on last row call (@see _batch_finished()). On the last call, form state is available in $_SESSION['batch_form_state'].
  • Replaced die() with drupal_exit()
  • Renamed entity_ids argument to views_data_export_entity_ids for easier recognition

I have only tested this on batched exports. An added benefit to this approach is that you will see the progress while entities are being loaded.

joelpittet’s picture

@jgullstr thank you for the explanation also:)

den tweed’s picture

Used patch #28 to make a VBO button for export, works good. Only problem I found is that the file downloads but the batch progress bar keeps on spinning, no redirect to the original page/view

jgullstr’s picture

Status: Reviewed & tested by the community » Needs work

Notice: Array to string conversion in view->get_url() (line 1639 of /modules/contrib/views/includes/view.inc).

The additional argument added to the view by this patch is generating notices.

poindexterous’s picture

I am getting the same notices as above but it doesn't seem to effect the export.

djpable’s picture

#28 is configurable and return to the view page, but it does not download anything for me :-(
I still have to use using #21 here.

retiredpro’s picture

StatusFileSize
new23.56 KB

#28 worked for me. After patching the module I had to clear my site cache before I could see the new VBO option to export to CSV. The only thing that is strange is the operation confirm page does not display a name for any of the items that I have selected.

Here is my current setup.

  • Views 7.x-3.14
  • Views Bulk Operations 7.x-3.3
  • Views Data Export 7.x-3.x-dev (2016-Sep-21)

My view pulls Ubercart Order entity if that matters.

graber’s picture

Hi all, didn't notice this issue earlier and developed a module. You can check the code and maybe integrate the solution to views_data_export so we have all the functionality in one module. On the other hand no point having 5 display options and a few more actions to achieve 1 simple goal sometimes.. Anyway, take a look.

https://www.drupal.org/project/vbo_export

joel_osc’s picture

I am also seeing the issue where the CSV file downloads fine and contains the correct information, however the batch job does not return to the original page/view. Disabling batch mode works but this brings in some scaling concerns.

Jorrit’s picture

I am also seeing the issue where the CSV file downloads fine and contains the correct information, however the batch job does not return to the original page/view. Disabling batch mode works but this brings in some scaling concerns.

Me too, I think this makes patch #28 unacceptable at this point. The only solution, I think, is to save the entity ids in a SESSION variable somewhere, redirect back to the view and initiate the download from there. This is much more complicated.

Notice: Array to string conversion in view->get_url() (line 1639 of /modules/contrib/views/includes/view.inc).

This happens because $args may only contain strings and this patch adds an array. This can be fixed by implode()'ing the array before putting it in $args and expode()'ing it when changing it to a where condition.

I want to update the patch to change this, but at this point, I rather use patch #21 than #28.

Jorrit’s picture

This is an updated version of patch 21 to prevent this notice:

Notice: Array to string conversion in view->get_url() (line 1639 of /modules/contrib/views/includes/view.inc).

kenorb’s picture

Status: Needs work » Needs review
capysara’s picture

I'm not getting the expected results with #40, but I have a really specific use case (panel panes and facetapi, e.g.) so my issues may not be helpful here.

However, one thing I noticed is that the VBO action downloads more than just CSV, so the action "Export to csv" is misleading. Maybe "Export via Views Data Export" or "Views Data Export"?

steven jones’s picture

Status: Needs review » Closed (won't fix)

Sorry for the lack of attention to your issue, please accept my apologies.

Drupal 7 is going to be end-of-life'd by the community in approximately 1 month.

As such, I am closing all non-critical looking, non-PHP compatibility issues for Views Data Export to tidy up the issue queues and reduce the noise. You can read about this on #3492246: Close down Drupal 7 issues.

If you feel like this issue has been closed by mistake, please do comment about re-opening it.
If you feel like the ticket is still relevant for the 8.x-1.x version of the module, then please search for a duplicate issue first, and if there really isn't one (and you've looked properly) then change the version on the ticket and re-open.

Thanks to everyone involved in this issue: for reporting it, and moving it along, it is truly appreciated.
The Drupal community wouldn't be what it is today without your involvement and effort, so I'm sorry that we couldn't get this issue resolved. Hopefully we'll work together in a future issue though, and get that one resolved :)