How to change a grouping field in a view programmatically? 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(&amp;$view, &amp;$query) 
{
    $view_name = 'MYVIEW';
    $display_name = 'MYDISPLAY';
    if ($view-&gt;name == $view_name &amp;&amp; $view-&gt;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-&gt;display['default']-&gt;handler-&gt;options['style_options'];
        $style_options['grouping'][0]['field'] = $custom_field;
    }
}
function MYMODULE_views_pre_build( &amp;$view ) {
  $custom_field = 'field_MYFIELD_value';
  $view-&gt;display[$view-&gt;current_display]-&gt;handler-&gt;options["style_options"]["grouping"] = $custom_field;
}