How to programmatically remove a field from Views 3?

Hi, I am using Drupal 7 and Views 3. I have a view (named 'export') that generates csv export of selected node objects. However, I put some native code that displays all the fields contained in the selected node object and allows the user to select fields (via checkboxes) that they do not want to include in the export.

I tried to disable selected fields in hook_views_query_alter as follows:

function mymodule_views_query_alter (&$view, &$query) { if ($view->name == "export") { unset($query->fields['field_data_field_description_node_entity_type']); } } 

Until this cancels this part of the array of fields, I still get the description field populated in the csv export. I'm just not good enough at the structure of views objects to fully understand how to remove a given field from a view. I searched the Internet for literally hours trying to find a message to shed light on this. Although I found many examples of using hook_views_query_alter to add filters or modify the WHERE clause of a query object, I did not find anything related to removing the columns returned by the view request. Any advice on this is greatly appreciated!

Thanks Axl

+4
source share
2 answers

I managed to remove view fields for CSV export by disabling the field in hook_views_pre_build () in my custom module .:

 function mymodule_views_pre_build(&$view) { if ($view->name == 'campaign_report' && $view->current_display == 'views_data_export_1') { // You'll have your own list of fields to remove that you create somehow... $fields_to_remove = array('field_name_to_remove_1','field_name_to_remove_2'); foreach ($fields_to_remove as $field_name) { unset($view->field[$field_name]); unset($view->display_handler->handlers['field'][$field_name]); } } } 

This seems to work just fine for me, and is done earlier in the views lifecycle before the query is even built. In fact, I started using it to display in the form of a table, as well as to export CSV, since it seems more efficient than using the "Hide if empty" column in the settings of the viewing table (which should go through each row in the result set, see if it is empty it to hide the column heading). If you also want to do this, you will need to change the if () operator at the top so that it only checks the name $ view->. Then the fields will be removed from all the displays in this view (and not just for the views_data_export_1 display).

+8
source

Try removing the column from the $view object.

 unset($view->field['field_name']; 
0
source

Source: https://habr.com/ru/post/1394019/


All Articles