Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a field from Views 3 programmatically?

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

I've tried unsetting the selected fields within hook_views_query_alter like so:

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

While that does unset that part of the fields array, I still get the description field populated in the csv export. I'm just not familiar enough with the views object structure to fully understand how to remove a given field from the view. I've searched the web for literally hours trying to find a post to shed some light on this. While I've found plenty of examples for using hook_views_query_alter to add filters or alter the WHERE statement of a query object, I haven't found anything having to do with removing the columns that a view query returns. Any advice on this would be very much appreciated!

Thanks, axl

like image 845
A. Roach Avatar asked Feb 21 '23 15:02

A. Roach


1 Answers

I was able to remove views fields for a CSV export by unsetting 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 great for me, and is performed earlier in the views life cycle, before the query is even built. In fact I started using it for my table display view as well as my CSV export, since it seems more efficient than using the "hide if empty" column checkbox on the Views table settings (which must iterate over every row in the result set to see if it's empty in order to hide the column heading). If you wish to do that too, you will need to change the if() statement at the top so it only checks $view->name. Then the fields will be removed from all displays in that view (not just the views_data_export_1 display).

like image 196
Professor Falken Avatar answered Mar 18 '23 20:03

Professor Falken