Search code examples
drupalsolrdrupal-7drupal-theming

Drupal 7 print content field in search results


I'm using drupal 7, with apache solr...

I want to print a content field in the search results...Sounded easy enough,

I placed this function in a custom module:

function module_name_apachesolr_modify_query(&$query, &$params) { $query->params['fl'] .= ',im_field_name'; }

I verified that the field name was correct in /admin/reports/apachesolr. I enabled the module, and everything so far looked correct.

Then in search-result.tpl.php I've done several variations of,

<?php print render($content['im_field_name']); ?>

With no success...I figured i might be doing something stupid. I'll keep plugging away at it, but any help is very appreciated! Thanks!


Solution

  • Currently learning this and I was looking for the same thing, but managed to get it working. Unfortunately, there doesn't seem to be much documentation around for Drupal 7, but there is a small chapter about it in The Definitive Guide to Drupal 7 book.

    I used hook_apachesolr_query_alter(), for example:

    function MODULE_apachesolr_query_alter(&$query, &$params, $caller) {
        $query->addParam('fl', 'im_field_name');
    }
    

    Adding the above meant it was now visible in the preprocess function for the template, so I did the below:

    function THEME_preprocess_search_result(&$vars) {
        $vars['im_field_name'] = $vars['result']['fields']['im_field_name'][0];
    }
    

    Then it was available to the template:

    <?php if ($im_field_name) : ?>
        <?php print $im_field_name; ?>
    <?php endif; ?>