2

I've added a custom field to a view and want to display results as a grid grouped by this field. How do I set that "Grouping field Nr.1" option in my code? I tried the following but it doesn't work (probably I'm doing it in the wrong place or change wrong setting...)

function MYMODULE_views_query_alter(&$view, &$query) 
{
    $view_name = 'MYVIEW';
    $display_name = 'MYDISPLAY';
    if ($view->name == $view_name && $view->current_display == $display_name)
    {
        $custom_field = 'field_MYFIELD_value';

        //code piece adding this field to a view's SELECT statement, sorting by it etc

        $style_options = $view->display['default']->handler->options['style_options'];
        $style_options['grouping'][0]['field'] = $custom_field;
    }
}

2 Answers 2

2
function MYMODULE_views_pre_build( &$view ) {
  $custom_field = 'field_MYFIELD_value';
  $view->display[$view->current_display]->handler->options["style_options"]["grouping"] = $custom_field;
}
0

this worked for me in Drupal 8 https://www.drupal.org/project/views/issues/1907940

function utility_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {
    $view->getStyle()->options['grouping'][0]['field'] = 'field_category';
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.