Creating a View Display Switcher in Drupal 8
For one of our client sites, we created several related content blocks using the Views module. These blocks are a recurring feature on the site, and had a specific design requirement. We had to create a view switcher that allowed users to switch the display of the view between a card and list view.
Card View
List View
Initially, our approach was to create a view with two block displays. One would be the list view and the other would be the card view. The card view would use Masonry format, which would help create a nice grid layout for the cards. Under advanced settings at the bottom, there is a section to add a class to the view. We added a class to each display, list-view and card-view. We would use these classes to style each view display appropriately.
The last step was to install the Quicktabs module, which allows creating blocks of tabbed content. Users could click on the different tabs to view the corresponding content. The plan was to use this module to allow the user to switch between the list view and card view. While this approach worked in the sense that the user could switch between the list view and card view, it did, however, cause a significant problem.
In our case, our view also includes exposed dropdown filters; and when the user would switch between the two displays, the same exposed filter options were not applied. For example, if a user filtered by author on the list view, and then decided to switch to the card view, the card view content list would not be filtered by author. The reason is because these were two separate view displays. Even though they used the same exposed filters, what you did on one view display did not apply to the other. Because this caused a bad user experience, we had to change our approach.
Instead, we focused on only using one display, which was the card display. As shown below, we used a form alter hook to alter the views exposed form by adding html markup for the view switcher. This markup created a dropdown select list that allowed users to choose between a card view or list view.
Then, we used JavaScript to toggle a class called ‘destroy-masonry’ based on the view switcher select list value. Below is our JavaScript code, which adds the ‘destroy-masonry’ class when the select list value is equal to ‘list-view’. Otherwise, it removes the ‘destroy-masonry’ class.
The styling differences between the list display and card display were added and/or removed based on the existence or absence of the ‘destroy-masonry’ class.
Using this approach, we now have a working view switcher that allows users to easily change the display of the view based on their preference, while also keeping the rest of the view functionality user-friendly.