Chapter 5. Product Reviews

With more and more options for shoppers arriving on the Internet every day, finding the right products can be a challenge. Special interest websites that feature specific kinds of products and reviews by dedicated hobbyists are a popular way to help consumers sort through all of the options and find the right stuff. In this chapter, we’re going to use a handful of Drupal modules to build a product review website that lets community members give their opinions on every featured product.

This chapter introduces the following modules:

Field Group

Allows fields to be grouped into fieldsets

Amazon

Gathers product information from Amazon.com

Voting API

Provides a framework for standardizing voting data

Fivestar

Allows rating of content

Search (core)

Indexes content and allows searching within a site

CSS Injector

Allows administrators to easily add CSS styling to the site

If you would like to participate in the hands-on exercises in this chapter, install Drupal using the Reviews installation profile from the book’s sample code. This will create the example website on your web server. The completed website will look as pictured in Figure 5-1 and found at http://reviews.usingdrupal.com. For more information on using the book’s sample code, see the Preface.

The completed Super Duper Chefs website

Figure 5-1. The completed Super Duper Chefs website

Case Study

Bob and Sarah are coworkers and food lovers who’ve both built up impressive kitchens full of gadgets, pots and pans, and other cooking tools. Supporting a culinary habit can be expensive, though, and they usually turn to fellow foodies for advice before purchasing new gear. They’ve decided to set up Super Duper Chefs, a website where they and their friends can write recommendations about the cooking equipment they use, share tips, and brag about their latest culinary achievements. They’d like it to be the kind of site they wanted when they were getting started: a fun place that highlights the most useful products and advice.

After talking things over with their friends, Bob and Sarah think they have a handle on what the site should offer. The most important feature is that kitchen products reviewed by the site’s official contributors should be listed with ratings and quick summaries of their best and worst features. Each review should also provide up-to-date pricing information. In addition to the official reviews, visitors to the site should be able to offer their opinions on the products and compare the official ratings with the opinions of other visitors who’ve read the reviews. Everyone who uses the site should also be able to search for reviews that match certain criteria. For example, it should be easy to find reviews of products by a particular manufacturer, or products that mention waffles.

Implementation Notes

The next step is figuring out how to translate that set of features into a shopping list of Drupal functionality. Bob and Sarah are fortunate: the core Drupal software can provide most of what they’re looking for without any additions. We’ll use Drupal’s administrative tools to create a custom “Product review” content type, and set up special permissions for contributors. Those product reviews will be the meat of the site’s content. Core also provides a way to add custom fields to the “Product review” content type for the various bits of information we want to record, with the Field module. We’ll use the Views module to build a listing page of products for quick scanning.

Three requirements for Bob and Sarah’s website, though, will require functionality that we haven’t seen yet: importing product information from another website, allowing users to rate and review content, and building a custom search page.

Product information

First, the site will need to display information about the product that is being reviewed. Who manufactured it? How much does it cost? Where can a visitor to the website purchase it? Although it’s possible to set up custom fields for each of these pieces of information with the core Field module, it’s a real hassle for the site’s editors to fill out all of them for every review. In addition, keeping the pricing information up-to-date can be a chore as the site grows older.

The easiest solution is to let someone else do the work! Amazon.com provides access to its full database of product information, including kitchen gadgets (shown in Figure 5-2), using the Amazon Product Advertising API. The Amazon module lets sites access that product information. That means that writers on the site can fill out one field about the product, and the rest will be handled behind the scenes.

The Amazon.com website, displaying kitchen products

Figure 5-2. The Amazon.com website, displaying kitchen products

In addition to saving time and energy spent entering in the product details, using the Amazon API means that Bob and Sarah can get referral fees whenever someone clicks from their website and purchases an item on Amazon.com. It’s a simple way of earning revenue, and for high-traffic sites, the commissions can add up quickly.

Product ratings

The second challenge is product ratings. The site will need every product to have an official review by an editor, but visitors reading the site need to be able to rate the products as well. Displaying the official rating and the users’ ratings separately will give a more trustworthy representation of how the products perform, reassuring new visitors that the site’s ratings aren’t dominated by a one-sided editor.

The Drupal community has built dozens of plug-in modules that add rating and voting capabilities to sites. A full list is available at http://drupal.org/project/modules?filters=tid:60. Modules such as the Plus1 module add the ability to vote items up in a queue, like the popular sites Reddit and Digg. Others allow each reader to rate content on a scale, then display the average to new visitors. Because it is this average rating capability that we’re interested in, we’re going to use the Fivestar module.

In addition to letting users vote on content, Fivestar provides a Field to separate “official ratings” by a site editor from the normal ratings given by visitors. We can use the Views module to list the two kinds of ratings side by side for comparison. The Fivestar module, like most rating and evaluation modules, is based on Voting API, another Drupal module that handles storage and presentation of voting and rating information for content. We’ll need to install it to use Fivestar.

Custom searching

The third piece of the puzzle is the custom search page that will let visitors to the site find the product reviews they’re looking for. Drupal’s built-in Search module can index the contents of each post, and give visitors a general search page to find posts that contain specific keywords. However, it’s difficult to customize how search results are presented to users, and difficult to control exactly what kinds of content are searched. For example, finding reviews of kitchen appliances written by Bob and sorting them by price would be tricky. Fortunately, the Views module allows us to tie into that search index as well, giving full control over how the results are displayed. We’ll use it to build our custom product search page.

Hands-On: Basic Product Reviews

Before we get started, log into the site with the admin account. We’ll begin with a few things that we are going to need.

The first is a new content type for the product reviews. Based on the Super Duper Chefs requirements, we’ll need the following for each review:

  • A Pros field and a Cons field to list quick summaries of each product’s strengths and weaknesses

  • An Amazon Product field to hold detailed product information

  • A Rating field, so that visitors can quickly find the cream of the crop

  • A Field Group that combines the rating with the pros and cons for a more attractive presentation

  • Comments so that visitors can weigh in with their own opinions

Creating the Product Review Content Type

We’ll start by creating the base content type and adding the simplest pieces: the basic text fields needed for the Pros and Cons, grouping those fields together, and allowing comments:

  1. First, in the administrative toolbar, click Modules (admin/modules) and enable the following modules:

    • Chaos Tools Suite package

      • Chaos tools

    • Fields package

      • Fieldgroup

  2. Next, in the administrative toolbar, click Structure“Content types” (admin/structure/types) and add a new content type called “Product review,” using the settings indicated in Table 5-1.

    Table 5-1. Settings for the “Product review” content type

    Setting

    Value

    Name

    Product review

    Description

    A featured Product review by a contributing editor.

    Submission form settings

     

    Title field label

    Headline

    Comment settings

    Allow comment title

    Unchecked

  3. Save the changes you’ve made by clicking the “Save and add fields” button, and you’ll be taken to the “Product review fields” screen to begin setting up the rest of our fields.

  4. First, let’s change the label on the Body field to something that makes more sense for our editors. Click the “edit” link for the Body field and change the Label to Review. Click the “Save settings” button, and we’ll be returned to the fields listing.

  5. Because we want to group several of the fields in this content type together (the Pros and Cons, ratings, and so on), we’ll first create a Field group to organize them. Under “Add new group,” create a new group with a label of Summary and a group name of “summary”; leave the widget at the default, Fieldset; and then save the form.

  6. Next, create a new field using the settings indicated in Table 5-2 and click the Save button.

    Table 5-2. Settings for the Pros field

    Setting

    Value

    Label

    Pros

    Field name

    pros

    Field type

    Long text

    Widget type

    Text area (multiple rows)

  7. On the following screen, click the “Save field settings” button to move on to the full field settings screen. All of the additional settings for the new field can be left at their default values; click the “Save settings” button. Next, repeat the process to create a second field using the same settings, but using the label Cons and the field name “cons.”

  8. We have added the fields and a group to the content type. Now let’s group the Pros and Cons together in the Summary group and move them to the top of the form. Drag the fields into the following order (make sure to drag Pros and Cons to the right in order to indent them):

    • Headline

    • Summary

      • Pros

      • Cons

    • Review

    When you’re finished, click the Save button. Your screen should look as pictured in Figure 5-3.

The Fieldgroup module allows grouping multiple fields together

Figure 5-3. The Fieldgroup module allows grouping multiple fields together

Now that we have the “Product review” content type started, we need to add permissions to allow the right people to create them. Bob and Sarah’s friends will each have their own account and be able to post and edit their own reviews as editors of the site. Bob and Sarah themselves will be the administrators of the site and will therefore be able to edit or delete anyone’s posts so that they can keep the site tidy, if needed. In the administrative toolbar, click People, then the Permissions tab (admin/people/permissions), and fill in the values shown in Table 5-3. Click “Save permissions” when you are done.

Table 5-3. Permissions for the “Product review” content type

Permission

anonymous user

authenticated user

editor

administrator

Node

    

Product review: Create new content

  

Checked

Checked

Product review: Edit own content

  

Checked

Checked
Product review: Edit any content   Checked

Product review: Delete own content

  

Checked

Checked
Product review: Delete any content   Checked

Once you have everything set up, go to Create Content“Product review” (node/add/review) and enter a simple review. Your new review creation form should look like Figure 5-4.

Creating a product review

Figure 5-4. Creating a product review

The “Product review” content type is well on its way—it’s now possible to create a new review, fill out the pros and cons, and display the results on the front page of the site. The finished review should look something like Figure 5-5. In the next section, we’ll be adding more complete product information, straight from Amazon.com.

A completed review with basic information

Figure 5-5. A completed review with basic information

Spotlight: Amazon Module

Amazon.com is one of a large number of web-based businesses that have opened up their product information databases for other sites to access. In the case of Super Duper Chefs, we want to retrieve useful data like product photos, pricing, and manufacturer information for display on our own website. The Amazon module for Drupal allows us to do just that.

What’s Included?

The Amazon module is actually a collection of modules, each with its own purpose:

  • The core Amazon API module handles communication with the Amazon.com website and ensures that pricing information on products stays up-to-date. All of the other modules included in the package require this one.

  • The Amazon Field module allows administrators to add a field to any content type that stores an Amazon product ID, and displays a photo of the product straight from Amazon.com. This module is the one that we’ll be using to enhance our “Product review” content type.

  • The Amazon Filter module allows writers to insert product images and information into the text of any piece of content using the [amazon] tag. It’s useful for bloggers or writers who want to link to products occasionally but don’t need the structure of an explicit field just for product links.

  • The Amazon Media module stores extra information about certain types of products. For example, it’s responsible for storing and displaying the MPAA rating for movies and the console that video games run on.

  • The Amazon Search module adds the ability to search for Amazon.com products from Drupal’s default Search page.

Additionally, the Amazon module’s configuration page exposes a number of settings. Next, we’ll provide an overview of a few of them before we dive into the hands-on steps.

Locale

Because each country that Amazon operates in has a separate database of products, prices, and availability information, you’ll want to choose the locale where your website’s users reside in the Amazon module’s configuration settings. This setting will determine which Amazon website (http://www.amazon.com, http://www.amazon.jp, and so on) will be used to look up the information for a given product. In addition, whenever links from your site to Amazon.com are generated, they’ll point to the local Amazon site for the locale you’ve chosen. If you don’t choose a specific locale, the Amazon module will assume that your site is operating in the United States.

Referral Settings

Although it’s not required, setting up an Associate ID at http://affiliate-program.amazon.com/gp/associates/join allows Amazon to credit your site when your visitors click on an Amazon.com link and purchase a product. If you’re feeling generous, the Amazon module also allows you to use the Drupal Association’s ID, automatically donating any commissions from purchases to support the Drupal project.

Amazon Keys

To have our Drupal site communicate with Amazon’s API, we will need to get an Amazon AWS account. This is a free account and service provided by Amazon. Once you create an account, Amazon will provide you with the keys you need to enter into these fields on the configuration page. You can find more information on getting an AWS account at http://aws.amazon.com.

Hands-On: Adding an Amazon Field

In the previous section of this chapter, we set up a content type for our product reviews. Now, we’re ready to add a field to store a link to the product on Amazon.com. We need to do a few things to get set up before we add the field to our content type:

  1. First, in the administrative toolbar, click Modules (admin/modules) and enable the following modules:

    • Amazon package

      • Amazon API

      • Amazon Field

  1. Next, in the administrative toolbar, click ConfigurationAmazon SettingsAmazon API (admin/config/amazon_settings/amazon), pictured in Figure 5-6. Select your locale and set the Amazon Associate ID to the one you wish to use. If you are in the United States and do not have an Amazon Associate ID, you can use the default settings for the first two settings on the page. This gives the Drupal Association, the nonprofit organization that supports the Drupal community, a tiny financial kickback.

    The Amazon module’s settings page

    Figure 5-6. The Amazon module’s settings page

  2. Log into (or create) your Amazon AWS account at http://aws.amazon.com and navigate to the Security Credentials section (there is also a direct link to this page in the key field descriptions on the Amazon module’s configuration page). In the Access Credentials area of the page, there is a tab for Access Keys, which will provide you with the keys you need to copy into the Drupal site, as shown in Figure 5-7. Copy these into the appropriate fields back in Drupal, and click the “Save configuration” button.

  3. To test that the Amazon module is working properly, click the Test tab (admin/config/amazon_settings/amazon/test) and enter a valid Amazon Product ID such as “9781449390525” to ensure that a result comes back without errors.

AWS access credential information

Figure 5-7. AWS access credential information

Adding the Product Field

Having set up the Amazon module, we’re ready to continue customizing the “Product review” content type:

  1. In the administrative toolbar, click Structure“Content types” (admin/structure/types) and click the “manage fields” link (admin/structure/types/manage/product-review/fields) for the “Product review” content type. Create a new field using the settings indicated in Table 5-4.

    Table 5-4. Creating the Product ID field

    Setting

    Value

    Label

    Amazon Product ID

    Name

    product_id

    Field type

    Amazon item

    Widget

    Amazon ASIN text field

  2. Click the Save button to create the field and then click the “Save field settings” button to proceed. You’ll be taken to the next screen to fill out the product review field settings. Add some Help text, like “Enter the Amazon product ID of the item you’re reviewing. Often indicated by an ASIN, ISBN, or other field in the product details of an Amazon product page.”

An Amazon product page’s URL, with the product ID highlighted

Figure 5-8. An Amazon product page’s URL, with the product ID highlighted

An Amazon product page’s details section

Figure 5-9. An Amazon product page’s details section

  1. Click the “Save settings” button to complete the process, and you’ll be returned to the “Manage fields” page for the “Product review” content type.

  2. On the “Manage fields” page (admin/structure/types/manage/product-review/fields), rearrange the new Amazon field so that it is listed just above the Review field, like so:

    • Headline

    • Summary

      • Pros

      • Cons

    • Amazon product ID

    • Review

  3. Click the Save button to save your ordering. In the administrative toolbar, click “Add content”“Product review” (node/add/product-review) and add a new review. This time, fill out the Amazon Product field as well as the normal Headline, Pros and Cons, and Review fields. Your new review should look something like Figure 5-10 (showing Amazon product ID B0007GAWRS).

A review with Amazon.com product details

Figure 5-10. A review with Amazon.com product details

Later, we’ll use the field display settings to control what information is output by Amazon on these nodes, as well as the order in which it is displayed with the other review information.

For even more fine-grained control over the display of Amazon product data, particularly on more standard “media” products such as books and software, the Amazon Media module we touched on in Spotlight: Amazon Module includes a series of template files that can be customized to grab the specific fields you want for your site.

Our product reviews now contain fields for product pros and cons, and a link to Amazon.com for each product. What’s left? We need some way to capture the editorial rating for each product that’s reviewed, and a way for visitors to the site to add their own ratings as well. For that, we’ll take a look at the Voting API and Fivestar modules.

Spotlight: Voting API and Fivestar

Giving visitors a chance to evaluate and rate content is an extremely common pattern on content-rich websites. In addition to giving visitors a way to jump to the best content, it can give you—the site’s administrator—a way to determine what content on your site is most effective.

Almost all rating and evaluation modules for Drupal rely on a shared module called Voting API. Though it offers no features for your site on its own, it gives developers a set of tools for building rating systems and provides a common format for storing votes and calculating the results. This allows developers to focus on what makes their work unique (presenting vote results in a novel way, for example) while Voting API handles the grunt work.

The Fivestar module offers numerous configuration options, from the style and color of stars that it uses to display ratings to how results are presented when visitors look at a new piece of content. Figure 5-11 shows the Fivestar module’s selection of rating widgets. The widget visitors use to rate each post can be displayed in the post itself, in a floating sidebar block, or even in the commenting form when visitors submit a reply.

The Fivestar module’s selection of rating widgets, available on its configuration screen

Figure 5-11. The Fivestar module’s selection of rating widgets, available on its configuration screen

Despite what its name suggests, Fivestar can display any number of stars: 10 stars, 3 stars—even 1-star scales can be used. In addition, it provides a custom field type: a simple numeric field on any piece of content can be displayed using Fivestar’s custom widget, separate from the ratings cast with Voting API.

Hands-On: Adding Ratings

For the Super Duper Chefs site, we’ll be using both of the Fivestar module’s unique features: adding a static Rating field to the “Product review” content type for the editors to use, and attaching a voting widget to the comment form on each review for the site readers to use. That approach will keep the official rating on each review separate from the reader ratings.

First, in the administrative toolbar, click Modules (admin/modules) and enable the following modules:

  • Voting package

    • Fivestar

    • Voting API

Adding the Product Rating Field

  1. In the administrative toolbar, click Structure“Content types” (admin/structure/types), click the “manage fields” link for the “Product review” content type (admin/structure/types/manage/product-review/fields), and create a new field using the settings indicated in Table 5-5.

    Table 5-5. Creating the Rating field

    Setting

    Value

    Label

    Editor Rating

    Name

    editor_rating

    Field type

    Fivestar Rating

    Widget

    Stars

  2. Click the Save button to create the field, and you’ll be taken to the field settings page. Leave the default settings and click the “Save field settings” button. On the following screen, check the Required checkbox and click “Save settings” to add the field.

  3. We’ll also add this field to the Summary group so that it’s displayed with the pros and cons. When you return to the “Manage fields” tab (admin/structure/types/manage/product-review/fields), rearrange the new Rating field above Pros and Cons in the Summary group. After you click the Save button, the list should look like this:

    • Headline

    • Summary

      • Editor rating

      • Pros

      • Cons

    • Amazon product ID

    • Review

Adding the Reader Rating Field

As we’ve pointed out elsewhere in the book, fields can be added to anything in Drupal that is exposed as an entity. Now we will make use of this in practice, by adding a Rating field to the comments, so visitors can comment and rate the products as well.

  1. In the administrative toolbar, click Structure“Content types” (admin/structure/types), click the “edit” link for the “Product review” content type (admin/structure/types/manage/product-review), and then click the Comment Fields tab (admin/structure/types/manage/product-review/comment/fields). Add a new field using the settings in Table 5-6.

    Table 5-6. Creating the Rating field for comments

    Setting

    Value

    Label

    Reader Rating

    Name

    reader_rating

    Field type

    Fivestar Rating

    Widget

    Stars

  2. Click the Save button. On the field settings screen, it is important to set the “Voting target” to “Parent node,” so that these votes will add ratings to the node; then, click the “Save field settings” button. We’ll use the defaults on the “Product review” comment settings page, so just click “Save settings” to finish.

  3. When you return to the Comment Fields screen, reorder the fields so that the “Reader rating” field is at the top and then click Save.

    Note

    Remember that you can play with the settings by going to the administrative toolbar, then ConfigurationFivestar (admin/config/content/fivestar), to choose fun icons such as hearts or flames that readers can use to rate content. If you choose a widget listed under “Custom color widgets,” you can even choose a color scheme that matches your site.

  4. With the ratings in place, we need to allow the site users to actually rate things. In the administrative toolbar, click People, then the Permissions tab (admin/people/permissions), and set the permissions shown in Table 5-7. Click the “Save permissions” button to finish up.

    Table 5-7. Permissions for Fivestar ratings

    Permission

    anonymous user

    authenticated user

    editor

    administrator

    Fivestar

        

    Rate content

     

    Checked

    Checked

    Checked
    Use PHP for Fivestar target   Checked

    Note

    Recall from Hands-On: Configuring Permissions that any permission name with “PHP” in it should only be given to extremely trusted users.

All of the essentials for the reviews are now in place. Editors on the site can write reviews that include pros and cons about the product, rate the product using an intuitive five-star scale, and pull in product information from Amazon.com. In addition, visitors can post their own comments about the product and rate it themselves. Figure 5-12 shows our new Fivestar ratings in action.

A product with an editorial rating, along with a user review in progress

Figure 5-12. A product with an editorial rating, along with a user review in progress

Spotlight: CSS Injector

Drupal’s theming system gives designers complete control over how a site’s content is rendered for a web browser, and custom themes (like the Tarski theme that we’re using for the Super Duper Chefs site) can give any site a distinctive look. But sometimes it’s useful to make minor tweaks to a site’s appearance using nothing but CSS rules. They allow designers to tweak font sizes, colors, and so on without altering the underlying HTML that defines the site’s structure.

The CSS Injector module gives administrators the ability to add those snippets in an administration screen within your site, without having to make changes to the current theme’s files. This feature can be useful when a new version of your site’s theme is released on Drupal.org—if you change the theme to add your own CSS, it’s easy to lose those modifications when you download the new version. Keeping them in CSS Injector will preserve them even if you change themes.

CSS Injector offers a number of advanced options, including the ability to add the CSS rules conditionally on certain pages. If your CSS tweaks only apply to the front page, for example, you can ensure that it won’t add the unnecessary rules to the entire site. You can also specify a media type for your CSS, which makes it possible to add styling information that applies only when a page is being printed. Finally, each rule can use the Preprocess CSS checkbox to control whether Drupal should merge its rules with the current theme’s CSS. In most cases, this step saves time, because a visitor’s web browser makes only a single trip to your site’s web server to download all the stylesheets. If you’re adding extremely large amounts of CSS code that only apply to one or two pages, it can be more efficient to keep that code separate by turning preprocessing off. Otherwise, leave it enabled.

Note

If you’re mystified by CSS, the Mozilla Developer Network documentation provides information and tutorials for learning all types of web technologies, including CSS. It’s a great resource to keep bookmarked.

Hands-On: Polishing the Presentation

In this section, we’ll do some final tweaking to make the review display look nice and tidy, as pictured in Figure 5-13.

Completed review display

Figure 5-13. Completed review display

Setting Field Display Options

Although our “Product review” content type has all of the data we need, and our product listing pages are looking great, the individual reviews still look a bit untidy. Fortunately, we can use the Field module’s display settings to tweak how each type of field is displayed in the reviews.

  1. In the administrative toolbar, click Structure“Content types” (admin/structure/types) and click the “manage display” link for the “Product review” content type (admin/structure/types/manage/product-review/display).

  2. The first thing we want to do is to add a field group to the display for our Editor Rating, Pros, and Cons fields, just like we did for the form input fields. This time, we’ll make the HTML element a <div> for tidy markup. Fill out the “Add new group” settings as shown in Table 5-8. Save the settings.

    Table 5-8. Settings for the Summary fieldset

    FieldSetting
    LabelSummary
    Group namesummary
    FormatDiv
  3. Click the gear icon next to the Summary format information and change the “Fieldgroup settings” to Open. Click the Update button and then the Save button to save the settings.

  4. Drag the fields into the proper order so that they look like this:

    • Summary

      • Editor rating

      • Pros

      • Cons

    • Amazon Product ID

    • Review

  5. Click the Teaser subtab (admin/structure/types/manage/product-review/display/teaser) and repeat the preceding steps to create a Summary div (set to “open”) on the teaser display as well. Then drag the fields so that you have the following fields displayed in this order (note that the Review field should be moved down to the Hidden part of the form):

    • Summary

      • Editor rating

      • Pros

      • Cons

    • Amazon Product ID

    • Review

  6. Finally, fill out the settings as shown in Table 5-9 for the default and teaser displays, respectively. Figure 5-14 shows the default display settings after we’ve made these changes; the teaser display will look very similar. Click the Save button when you are done.

    Table 5-9. Display settings for the “Product review” content type

    Field

    Label

    Format

    Default  

    Editor Rating

    Inline

    As Stars (default)

    Pros

    Inline

    Default (default)

    Cons

    Inline

    Default (default)

    Amazon Product ID

    <Hidden>

    Thumbnail with details

    Review

    <Hidden> (default)

    Default (default)

    Teaser  

    Editor Rating

    Inline

    As Stars

    Pros

    Inline

    Default

    Cons

    Inline

    Default

    Amazon Product ID

    <Hidden>

    Thumbnail with title

    Review

    <Hidden>

    <Hidden>

Settings for the default product review display; the teaser display will look very similar

Figure 5-14. Settings for the default product review display; the teaser display will look very similar

If you navigate back to one of your reviews, the node view will look essentially the same at this point. In the next section, though, we’ll add some fanciness!

Configuring CSS Injector

Changing the display settings for our reviews cleans things up quite a bit, but the Summary information still seems awkward. We can significantly improve things by adding some CSS rules using CSS Injector. We’ll use it to reduce the width of the Summary box and float it to the side of each review, turning it into a floating sidebar rather than a header at the top of each review. Here’s how:

  1. In the administrative toolbar, click Modules (admin/modules) and enable the Other: CSS Injector module.

  2. In the administrative toolbar, click ConfigurationDevelopmentCSS Injector (admin/config/development/css_injector) and click the “Create a new rule” link to add a new CSS rule.

  1. Name the rule “Floating Summary fields,” and enter the following text into the CSS code field. You can see the completed form in Figure 5-15:

    div.group_summary {
      border: 1px solid lightgrey;
      float: right;
      padding: 10px;
      width: 250px;
      font-size: .9em;
    }
    
    div.group_summary div.field-label {
      font-weight: bold;
    }
    
    div.field-type-asin {
      clear: none;
      width: 400px;
      margin-bottom: 10px;
      border: none;
    }
    
    div.field-type-asin img {
      float: left;
      padding-right: 10px;
    }

    Note

    Not a fan of typing? Not to worry. This code is also available in the assets/ch05-reviews/amazon.css file in the book’s source code for easy copying and pasting.

  2. Click the Save button to add the new rule.

Adding a new CSS Injector rule

Figure 5-15. Adding a new CSS Injector rule

Depending on your web browser’s settings, you may need to clear the browser’s cache to see the changes to the stylesheet. Once you’ve done that, return to one of the product reviews added earlier. It should look quite a bit more attractive, as shown earlier in Figure 5-13. What a difference a dash of CSS makes!

Hands-On: Building a Product List

Now that we have a few products, we really ought to add a listing page that lets visitors look over all of the products that have been reviewed, comparing official ratings with visitor ratings and sorting by various criteria, as pictured in Figure 5-16. This page will be simple to build with the Views module.

Product Finder view

Figure 5-16. Product Finder view

  1. In the administrative toolbar, click Modules (admin/build/modules) and enable the following modules:

    • Other package

      • Advanced help

    • Views package

      • Views

      • Views UI

  2. In the administrative toolbar, click StructureViews (admin/structure/views), click on the “Add new view” link (admin/structure/views/add), and fill in the new view settings using Table 5-10.

    Table 5-10. Settings for creating the Product Finder view

    View setting

    Value

    View name

    Product Finder

    View description

    Checked: List of reviewed products

    Show

    Content of type Product review sorted by Newest first

    Display format

    Table of fields

    Items to display10 (default)
    Use a pagerChecked (default)

    Create a menu link

    Checked

    Menu: Navigation

    Link text: Product finder (default)

    Include an RSS feedUnchecked (default)
    Create a blockUnchecked (default)
  3. After clicking the “Continue & edit” button, we want to add some more fields to our view. We are going to go ahead and do that in a minute, but first we need to create a relationship for our fields so that we can use Amazon-specific fields in the view and display the average rating given to each product by visitors to the site.

    Open the Advanced fieldset and click the “add” button in the Relationships section. Check both the “Content: Amazon Product ID (field_product_id)” and “Content: Vote results” relationships. Click the “Apply (all displays)” button to add the relationships and then fill out the settings in Table 5-11 when prompted. Click the “Apply (all displays)” button after each form is presented.

    Table 5-11. “Vote results” relationship settings for the Product Finder view

    Defaults: Relationships

    Value

    Content: Amazon Product ID (field_product_id)

    Identifier: Product ID

    Content: Vote results

    Value type: Percent

    Vote tag: vote

    Aggregate function: Average vote

  4. In the Fields section of the View, click the “add” button, check the following fields, and click “Add and configure fields.” This will give us the product title, price, official rating, and reader rating:

    • Amazon: Amazon price (formatted)

    • Amazon: Title

    • Content: Editor rating

    • Vote results: Value

  5. Configure the settings for each new field as shown in Table 5-12. Click “Apply (all displays)” when you’re finished configuring each field’s settings.

    Table 5-12. Field configuration settings for the Product Finder view

    Defaults: Field configure setting

    Value

    Amazon: Amazon price (formatted)

    Relationship: Product ID (default)

    Label: List price

    Amazon: Title

    Relationship: Product ID (default)

    Label: Product

    Link behavior: A link to the product’s Amazon page (default)

    Content: Editor rating

    Keep all defaults

    Vote results: Value

    Relationship: Vote results

    Label: Reader rating

    Appearance: Fivestar Stars (display only)

  6. Let’s rearrange the fields into a different order and remove the review title from the list. In the Fields section, click the drop-down next to the “add” button, and select “rearrange.” Drag the “(Product ID) Amazon: Title Product” field to the top of the list so that the product title is listed first. Then click “remove” for the “Content: Title” field. Click Apply to save your changes.

  7. Now that we have the fields, under Format, ensure the format is set to Table, then click the Settings link next to it. Use the values listed in Table 5-13 for a sortable table. Click Apply when finished.

    Table 5-13. Table style options for the Product Finder view

    Defaults: Table style option

    Value

    Sortable

    All checked

    Default sort

    Editor rating

    Editor rating: Default order

    Descending

When all those steps have been completed, save the view, which should look like Figure 5-17.

Completed Product Finder view settings

Figure 5-17. Completed Product Finder view settings

With the settings we’ve used, you should now see a “Product finder” link (product-finder) in the site’s Navigation menu. Upon clicking it, you should see a tidy listing of all the reviews on the site, with official and reader ratings compared side by side, as shown earlier in Figure 5-16.

Only one feature remains from our to-do list: build searching capabilities into our product list so visitors can easily filter it down to find products that interest them.

Spotlight: The Search Module

Drupal’s built-in Search module offers powerful, flexible searching features and intelligent ranking of results. Behind the scenes, it’s silently building an index of all the words used in the site’s content. When users search for a phrase on the site, content is ranked using customizable rules and displayed in order of relevance. On any Drupal site, you can refine these rules by going to the administrative toolbar and clicking Configuration“Search and Metadata”Search Settings (admin/config/search/settings) and changing the Content Ranking weights, pictured in Figure 5-18.

The Search module’s content ranking settings

Figure 5-18. The Search module’s content ranking settings

The Search module also offers more detailed options for sites with large amounts of content. The Advanced Search screen, pictured in Figure 5-19, allows users to choose exactly what content they want to search, filtering based on content type, free tagging terms, and other criteria.

The Advanced Search page in action

Figure 5-19. The Advanced Search page in action

Searching with Views

Although the Advanced Search form allows quite a bit of control for users, it’s very difficult to change how that page appears and how the results are displayed. It also can present a daunting array of options, especially when a site has lots of taxonomy terms.

The Views module is one way to exercise more control over searching: its filters can narrow down lists of content based on words indexed by the search system. A view might list only blog posts mentioning kittens, for example. For the Super Duper Chefs site, we’ll be using this module to add custom filtering to our Product Finder page.

Hands-On: Make the Product List Searchable

To transform the Product Finder page into a searchable index, we’ll be adding two new filters to the view: one that restricts the results by manufacturer and another that restricts results to reviews that mention specific words.

Normally, these filters are locked in place and can’t be modified except by the site’s administrator. We need users to enter their own criteria, however. Fortunately, Views allows us to “expose” any of its normal filters. Doing so adds a small form to the heading of the view’s display page. Visitors to the site can use it to change how Views filters its results, turning any view into a simple search tool, as pictured in Figure 5-20.

Searchable Product Finder view

Figure 5-20. Searchable Product Finder view

Here are the steps to get your searchable list:

  1. In the administrative toolbar, click StructureViews (admin/structure/views) and click the “edit” button for our Product Finder view (admin/structure/views/view/product_finder/edit).

  2. Click the “add” button in the “Filter criteria” section to check the “Amazon: Manufacturer” and “Search: Search Terms” filters, and click the “Apply (all displays)” button.

  3. On the settings form for each of the filters, click the “Expose this filter to visitors, to allow them to change it” checkbox, which will present the filter as a form field that a site visitor can interact with. Configure the exposed filter settings for each filter using the values in Table 5-14. As usual, click “Apply (all displays)” to move between the configuration forms.

    Table 5-14. Settings for the search filters

    Defaults: Configure filter setting

    Value

    Amazon: Manufacturer

    Operator: Contains

    Search: Search Terms

    Label: Keywords

    On Empty Input: Show All (default)

  4. Click the drop-down next to the “add” button in the “Filter criteria” section and select “and/or, rearrange.” Move “Search: Search Terms” above “Amazon: Manufacturer” so that its box will appear first.

    Note

    By creating filter groups here, we can do very complex conditions, like “Product has this search keyword OR this manufacturer AND this price.” For the purpose of our search form, though, a straight-up “AND” between all filter criteria will work fine.

  5. Save the view, which should now look like Figure 5-21.

Completed Product Finder view settings

Figure 5-21. Completed Product Finder view settings

Before we test our new search feature, we need to make sure that we give search permissions to the users. We want everyone who visits the site to be able to search. In the administrative toolbar, click People, then the Permissions tab (admin/people/permissions), and set the permissions as indicated in Table 5-15, which will give the option to all users, both logged in and anonymous. Save the permissions.

Table 5-15. Permissions for searching

Permission

anonymous user

authenticated user

editor

administrator

Search

 
Administer search   Checked

Use search

CheckedCheckedCheckedChecked
Use advanced search  CheckedChecked

If you search for a keyword like “whistle” that ought to be returning results but find that it is not, fear not! The last thing we need to do is make sure that our site has been indexed, so that when we do a search the keywords will be accessible. While testing things out, we will manually update our site so we can see that our search is working properly. In the administrative toolbar, click ConfigurationSystemCron (admin/config/system/cron), and click the “Run cron” button.

Now go to our Product Finder page (http://example.com/product-finder). You should see the normal page full of products, this time with filter fields above the list. Enter a phrase that appears in one of your reviews, and click the Apply button. You should see an attractive list of the top results that contain the phrase, as we saw earlier in Figure 5-20.

Rewriting Views Field Output

We’re almost done! The only problem with our view now is that clicking the titles in the view links to Amazon.com instead of to our own website. Fortunately, Views provides a handy trick for just this sort of situation; we can “rewrite” the output of the Title field to create a link back to its referring node instead.

Doing this requires two steps: first, adding the field(s) you want to use as a replacement value, and then configuring the output settings for the field:

  1. Return back to the Product Finder view settings—either by clicking “edit view” in the Product Finder’s contextual links, or by navigating to StructureViews—then click “edit” next to Product Finder (admin/structure/views/view/product_finder/edit).

  2. Under Fields, click “add” and add the “Content: Nid” field. Check the “Exclude from display” checkbox on the field’s settings screen, which will ensure the output of this field is hidden from view. We don’t actually want “1” and “63” showing up in the table; we merely need that value to create the URL node/NODE_ID. Click “Apply (all values)” to save.

  3. Next, click the drop-down next to the “add” button in the Fields section, and click “rearrange.” Move the new “Content: Nid” field to the top and click Apply. This field needs to precede the “Amazon: Title Product” field so that we can use the node ID as a replacement value. Click “Apply (all values)” to save.

  4. Next, click on the “(Product ID) Amazon: Title (Product)” field to change its settings. Change “Link behavior” to “No link” to remove the automatic linking to Amazon.com. Expand the “Rewrite results” fieldset and check the “Output this field as a link” checkbox. Checking this box will expose a new field, “Link path,” for the link destination.

  5. Scroll down to the “Replacement patterns” collapsed fieldset below, and expand it to see a list of possible dynamic tokens you can choose from, including [nid] for the node ID, and [title_1] for the Amazon product title. Scroll back up to the “Link path” field and enter “node/[nid]” as the value, as shown in Figure 5-22. Click “Apply (all displays)” to save changes.

  6. Finally, save the view when finished. Now, when you click on the titles in the view, you should be taken to the product review, not the Amazon.com product page.

The Views module allows you to rewrite field output using dynamic values

Figure 5-22. The Views module allows you to rewrite field output using dynamic values

Taking It Further

Congratulations! All of the major features for the site are in place. If you’re interested in experimenting further, there are quite a few opportunities for additional enhancements using other Drupal modules:

AdSense

This module allows Bob and Sarah to place ads in the sidebar to offset the costs of hosting the site.

Display Suite

For even more control over the layout of a content body than CSS Injector provides, check out the Display Suite module, which provides regions within content that fields can be moved around within.

Blog (core)

This module allows the site’s writers to each have their own blogs on which to discuss their cooking tips, latest recipes, and other culinary exploits, even when they’re not reviewing products.

Recipe

For taking our cooking site further, the Recipe module—one of the longest-running modules on Drupal.org—might be a welcome addition. It provides a means of adding detailed ingredient information and can show details like overall cooking time.

Summary

After all that work, where have we arrived? We’ve hit all of the major pieces of functionality that Bob and Sarah wanted. Using Field, Amazon, and Fivestar, writers can post their reviews of cool kitchen products to the site. With Fivestar and Voting API, visitors to the site can offer their opinions on those same products and participate in the reviewing process. And with Views’ Search module integration, it’s easy for them to find the exact products that they’re interested in. Finally, the CSS Injector module allowed us to sprinkle on those finishing touches that make the site really shine.

Here are the modules that we referenced in this chapter:

Here are some other resources we referenced:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset