Main question: How to change the value for "Exclude from display" on runtime, programmatically ?
Background: I am rendering a View programmatically. The View has attached Data Export to it (exporting to CSV) The view has multiple fields (42 actually).
On some action (hook_node_update, etc.), I load a node object. The node object has 2 fields of interest.
field_views_filter
= field that is using the Field Embed Views module and stores exposed filter settingsfield_export_select_fields
= list(text) field that selects which of those 42 fields should be exported to csv. Sometimes all fields will need to be displayed, sometimes only 5 fields will have to be displayed.
Scenario: What I have tried:
<?php
function test () {
// Loading arbitrary node
$node = node_load(44165);
$select_fields = array();
$displayed_fields = array();
foreach ($node->field_export_select_fields[LANGUAGE_NONE] as $key => $value) {
$select_fields[] = $value['value'];
}
$name = 'MY_VIEW_NAME';
$display = 'views_data_export_1';
$view = views_get_view($name);
$view->set_display($display);
// Gets the exposed filters.
$exposed_filters = $node->field_views_filter[LANGUAGE_NONE][0]['settings'];
$view->set_exposed_input($exposed_filters);
foreach ($view->display['views_data_export_1']->display_options['fields'] as $key_field => $value_field) {
// This sets the value of "Exclude field from display to 1", but it is not working.
$view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 1;
}
$view->display['views_data_export_1']->display_options['fields']['title']['exclude'] = 0;
$output = $view->preview();
$file_string = 'sites/default/files/private/' . time() . '.xls';
file_unmanaged_save_data($output, $file_string, FILE_EXISTS_REPLACE);
$view->destroy();
}