Creating preview-specific view modesfor Drupal 8 , 9 , 10 , and 11

Last updated :  

In the world of headless CMS, especially with Drupal, the ability to create preview-specific view modes allows for a highly customizable and flexible content authoring experience. In this lesson, you will learn how to configure these view modes, providing precise control over how draft or unpublished content is presented during the preview stage.

Understanding View Modes

View modes in Drupal are configurations that determine how content entities, such as nodes, are displayed. By creating new view modes, you can define different presentations for various use cases, like teasers, full content, or, in this case, content previews. This is particularly useful in a headless setup where you need to separate the editorial view from the live view.

Setting Up a Preview-specific View Mode

To create a preview-specific view mode, follow these steps:

Step 1: Enabling Required Modules

Ensure that the Display Suite module (or another layout management tool) is enabled, as it provides the additional flexibility needed to manage view modes:

drush en ds

Step 2: Create a New View Mode

Add a new view mode specifically for previews:

  1. Navigate to Structure > Display Modes > View modes.
  2. Click on Add new view mode.
  3. Enter a name like "Preview Mode" and save your changes.

Step 3: Configure Content Types

Enable and arrange fields for your newly created view mode:

  1. Go to Structure > Content types, select a content type (e.g., Article).
  2. Under Manage display, find the "Preview Mode" and enable it.
  3. Drag and drop fields to arrange them as you want them to appear in the preview.

Viewing Content with Preview View Modes

Once your view mode is set up in Drupal, your headless frontend needs to integrate this view into its content workflow. This usually involves querying the API for content with the specific view mode settings.

Accessing via JSON:API

Request the content data through JSON:API utilizing the custom view mode parameter:

GET /jsonapi/node/article/{node-id}?resourceVersion=rel:working-copy
&resource-view-mode=preview_mode

Accessing via GraphQL

For GraphQL users, ensure your queries target custom fragment definitions that respond to the view mode logic:

query {
  nodeById(id: "article-id") {
    ...on NodeArticle {
      title
      body {
        value
      }
      viewMode(mode: "PREVIEW") {
        rendered
      }
    }
  }
}

Incorporating Previews in Your Frontend

Update your frontend application to process and display data from the configured preview view mode:

// src/components/PreviewComponent.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const PreviewComponent = ({ articleId }) => {
    const [article, setArticle] = useState(null);

    useEffect(() => {
        axios.get(`https://example-drupal-site.com/jsonapi/node/article/${articleId}`, {
            params: { 'resource-view-mode': 'preview_mode' }
        })
        .then(response => {
            setArticle(response.data.data);
        })
        .catch(error => {
            console.error('Error fetching preview:', error);
        });
    }, [articleId]);

    return (
        <div>
            {article && (
                <div>
                    <h2>{article.attributes.title}</h2>
                    <div dangerouslySetInnerHTML={{ __html: article.attributes.body.value }} />
                </div>
            )}
        </div>
    );
};

export default PreviewComponent;

Conclusion

Creating preview-specific view modes in a headless Drupal setup not only streamlines the content management process but also enhances collaboration between technical and non-technical teams. It ensures that content is previewed with an accurate representation of its structure and appearance before going live.

In future lessons, you will learn more about using structured content types to effectively manage and deliver complex data for both backend and frontend integration. Continue your journey as we refine and expand your headless Drupal applications!