Frage

I have a requirement to perform an indexed search across content which must include a couple of tags in the result. The tags must be a random selection. The platform is Drupal 7.12

I have created a view that manages the results of a SOLR search through the search_api. The view returns the required content and seems to work as intended. I have included a couple of Global: custom text fields as placeholders for the tag entries.

I am now looking for a solution to manage the requirement to randomise the tag values. The randomisation is not the issue, the issue is how to include the random values into the view result.

My current approach is to write a views_pre_render hook to intercept the placeholders which appear as fields ([nothing] and [nothing_1]). The test code looks like the following

function MODULE_views_pre_render( &$view )
{
    $view_display = $view->display['default'];
    $display_option = $view_display->display_options;
    $fields = $display_option['fields'];
    foreach( $view->result as $result )
    {
        $fields['nothing']['alter']['text'] = sprintf("test %d", rand(1,9));
    }
}

I am currently not seeing any change in the placeholder when the view is rendered.

Any pointers to approach, alternate solutions etc would be gratefully received as this is consuming a lot of scarce time at the moment. Calling print_r( $view ) from within the hook dumps over 46M into a log file for a result set of 2 items.

War es hilfreich?

Lösung

There are two possible solutions for your task.

First approach is do everything on the template level. Define a template for the view field you want to randomize. In advanced settings of your display go to Theme: Information. Make sure that the proper theme is selected and find the template suggestions for your field. They are listed starting from most general to the most specific and you can choose whatever suits you better. I guess the most specific template suggestion for your field would be something like this: views-view-field--[YOR VIEW NAME]--[YOUR DISPLAY NAME]--nothing.tpl.php. Create the file with that name in the theme templates directory and in this template you can render what ever you want.

By default this template has only one line:

  print $output;

you can change this to:

  print sprintf("test %d", rand(1,9));

or to anything else, whatsoever :)

Second approach is to go with Views PHP module. WIth this module you can add a custom PHP field in which you can do whatever you want. Even though the module hasn't been released it seems to work quite well for the most of the tasks and most certainly for such a simple task as randomizing numbers it will work out for sure.

Andere Tipps

I stumbled upon this while searching for another issue and thought I would contribute.

Instead of adding another module or modifying a template, just add a views "sort criteria" of "Global: Random".

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top