Drupal 7 Fields/CCK Beginner's Guide
Explore Drupal 7 fields/CCK and master their use
Dave Poon
BIRMINGHAM - MUMBAI
Drupal 7 Fields/CCK Beginner's Guide
Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2011
Production Reference: 1050711
Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK. ISBN 978-1-849514-78-1 www.packtpub.com
Cover Image by Rakesh Shejwal (
[email protected])
Credits Author Dave Poon Reviewers Maurice Green, PhD
Project Coordinator Michelle Quadros Proofreader Kevin McGowan
Abdul Hafeez Dan Stefan Poka
Indexer Tejal Daruwale
Acquisition Editor Usha Iyer
Graphics Nilesh Mohite
Development Editor Neha Mallik
Production Coordinator Aparna Bhagat
Technical Editor Vanjeet D'souza
Cover Work Aparna Bhagat
Copy Editor Neha Shetty
About the Author Dave Poon is a web developer and designer based in Sydney. He started his career as a freelance graphic and web designer in 1998 and works with web development agencies and medium sized enterprises. He graduated from Central Queensland University with a degree in Multimedia Studies and a Master's degree in IT. His love affair with Drupal began afterwards, and he now works for a variety of companies using Drupal. He is the founder and Technical Director of Erlango (http://erlango.com), a web product development startup, located in Sydney and Hong Kong, which uses Drupal as a framework to create web products and customized CMS. He is also the technical reviewer of Drupal Intranets with Open Atrium by Tracy Smith (Packt Publishing, 2011). I would like to thank my wife Rita (she should be my wife at the time of the printing of this book) for her endless patience and support. Without her, what I do would be meaningless. I would also like to thank my father for his continued encouragement. It is my great fortune to have worked with a great team of publishing professionals at Packt Publishing. I extend my sincerest gratitude to Usha Iyer, Neha Mallik, Vanjeet D'souza, Neha Shetty, and Michelle Quadros for their cooperation and help in writing this book.
About the Reviewers Maurice Green (PhD) began his love affair with computers in 1963 as a graduate student in biochemistry using Fortran and punch cards. Retiring after a 40 year career as a medical laboratory director specializing in automated laboratory instrumentation and information systems and an IT manager in the Department of Medicine at Stanford University, he turned his attention to photography, video editing, and web design. He is currently the president of the Silicon Valley Computer Society and leads the Web Design special interest group. He is the developer and webmaster for the Silicon Valley Computer Society website (http://svcs.net/). He presented several talks at the Design 4 Drupal conference at Stanford. He was the reviewer for Drupal 7 First Look by Mark Noble (Packt Publishing, 2010).
Abdul Hafeez is a professional software developer, technology consultant, and an avid Drupal user as well as developer. He has completed his Bachelor's degree in Information Technology. Abdul has spent a number of years in the development of software projects specifically in Drupal. He has provided patches and support for many contributed Drupal modules and has been involved with the Drupal community since 2008. He has developed and maintained many custom modules for clients. Abdul's Drupal user account (rightchoice2c_me) can be found at http://drupal.org/user/315349. Abdul is focused on the integration and interoperability of different technologies, especially ones related to PHP, Ruby on Rails, and the web. He is an active member in the open source community, especially in Drupal. I would like to thank my parents and my friends, for their encouragement and for giving me time to pursue and support Drupal-related tasks, including reviewing this book.
Dan Stefan Poka is an avid Drupal developer, active mainly in the London (UK) area, with roughly three years' Drupal experience, having been involved in the community since Drupal 5. He acquired this experience by working in small teams and big teams alike and technologies as different as Ubercart and ApacheSolr. He feels comfortable taking on all parts of Drupal development from module development to theme development. His first experience in reviewing was for the well known Pro Drupal Development (Second Edition) from Apress by sending corrections to code examples, all of which made it into the book's errata. I would like to thank my colleagues from whom I've learned a lot, and my family for their patience.
www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packts online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe? Fully searchable across every book published by Packt Copy and paste, print and bookmark content On demand and accessible via web browser
Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Table of Contents Preface Chapter 1: Nodes and Content types in Drupal 7 The book example project A preview of the final project What is a content type? Default content types in Drupal 7 core The Basic page content type The Article content type Time for action – creating contents using the article content type Creating custom content types Creating the Cooking Tip content type Time for action – creating the Cooking Tip content types Creating the Recipe content type Time for action – creating the Recipe content type Adding content using custom content types Adding content using the Cooking Tip content type Time for action – adding content using the Cooking Tip content type Adding content using the Recipe content type Time for action – adding contents using the Recipe content type Summary
Chapter 2: Fields What is CCK? Fields in Drupal 7 Enabling the Field module Time for action – enabling the Field module Field, Field UI, and Field SQL storage modules Time for action – finding the Field UI Field types and input widgets
1 7 8 8 13 14 15 16 16 20 20 20 24 25 27 27 27 30 30 32
33 33 35 35 35 37 38 40
Table of Contents
Time for action – finding the field types and input widgets in Field UI Drupal 7 core default fields Drupal 7 core field related modules Number modules Text modules List modules Taxonomy modules Image modules File modules
40 42 42 42 43 44 44 45 45
Adding fields to content types Adding text fields using the text module Time for action – adding Long text fields using the text module Text fields Time for action – adding text fields using the text module Rearranging the order of fields Rearranging the order of the Notes field Time for action – rearranging the order of the Notes field Adding fields to comments Adding text fields to comments Time for action – adding a text field to comments Time for action – rearranging the order of the Email field Reusing existing fields Time for action – reusing the Notes field for the Recipe content type Time for action – reusing the Source field for the Recipe content type Time for action – rearranging the order of the Notes field Time for action – reusing the Email text field in the Recipe content type Time for action – rearranging the order of the Email field Summary
Chapter 3: Multiple Value Fields
46 46 46 50 51 53 53 53 55 55 55 58 59 59 60 61 62 62 64
65
Enabling multiple values Time for action – enabling multiple values Adding Boolean fields Time for action – adding a Boolean field Setting default values Time for action – setting default values Adding list fields Time for action – adding list fields Multiple value widgets Time for action – changing the number of the values Time for action – checkboxes/radio buttons widget with multiple values Summary [ ii ]
65 66 72 72 75 75 78 78 83 86 87 90
Table of Contents
Chapter 4: Taxonomy
91
What is taxonomy? Creating vocabularies Time for action – creating the Cooking Tip Category vocabulary Time for action – creating the Recipe Category vocabulary Adding terms to vocabularies Time for action – adding terms to Cooking Tip Category Adding term references to content types Time for action – adding a term reference field to the Cooking Tip content type Categorizing content using taxonomy Time for action – categorizing Cooking Tip Content using taxonomy Adding fields to vocabularies Time for action – adding a field to the Cooking Tip Category vocabulary Summary
Chapter 5: File and Image Fields
91 93 94 96 98 98 102 103 108 108 113 113 118
119
Adding and configuring file fields to content types Time for action – adding and configuring a file field to the Recipe content type Using file fields Time for action – using the file field Adding image fields to content types Time for action – adding an image field to the Recipe content type Configuring image field settings Time for action – configuring an image field for the Recipe content type Creating custom image styles Time for action – creating a custom image style Summary
Chapter 6: Managing Field Display
120 120 128 128 133 134 135 136 141 141 146
147
Field display Time for action – a first look at the field display settings Formatting field display in the Teaser view Time for action – formatting the Body field display in teaser view Custom display settings Time for action – enabling the Full content view mode in custom display settings Formatting the image field display on Full content Time for action – formatting the image field display on Full content Formatting the comment field display
[ iii ]
148 148 153 153 157 158 160 160 163
Table of Contents
Time for action – formatting the comment field display Formatting the vocabulary field display Time for action – formatting the vocabulary field display Summary
Chapter 7: Contributed Field Modules
163 165 165 167
169
Drupal modules Contributed modules Finding modules Time for action – finding contributed field modules through the Drupal website Time for action – finding contributed field modules through the drupalmodules.com website Installing and enabling contributed modules Time for action – installing a module Time for action – installing a module using Update manager Contributed field modules Email field module Link module Table field module Computed field module Content Templates (Contemplate) module Summary
Chapter 8: Field Level Permissions
170 170 171 171 173 176 176 180 184 184 185 185 185 185 185
187
Downloading the Field Permission module Time for action – downloading the Field Permission module Installing and enabling the Field Permission module Time for action – installing and enabling the Field Permission module Enabling field-level permissions Time for action – enabling field-level permissions Configuring field-level permissions on the PERMISSIONS administration page Time for action – configuring field-level permissions on the PERMISSIONS administration page Field-level permission reports Time for action – the Field permissions report page Summary
Chapter 9: Theming Fields
188 188 189 190 192 192 195 196 199 199 202
203
What is a theme? What is theming? How Drupal renders a webpage How to get started on theming Creating a Drupal theme
204 204 205 206 207 [ iv ]
Table of Contents
Time for action – creating a Drupal theme by cloning the existing theme Overriding template files Time for action – creating a template file for the Recipe content type Editing template files Time for action – editing a template file Styling the page using CSS Time for action – styling the page using CSS Summary
207 211 212 214 214 221 221 224
Chapter 10: A Database Perspective of Fields
225
Key elements in Fields Entities Bundles Field storages Field types Fields Field instances Field widgets Field formatters Fieldable entities Taxonomy New concepts in Drupal 7 Understanding nodes in Drupal Turning everything into a node Is everything an entity? Entities are the new nodes? Are they entities or objects? A database perspective of fields Content types Time for action – creating a new content type Fields Field-related database tables Summary
226 226 226 226 226 227 227 227 227 227 228 228 229 229 230 230 231 232 232 234 238 240 250
Pop Quiz Answers
251
Chapter 1, Nodes and Content types in Drupal 7 Pop quiz – understanding the default content types Pop quiz – creating content types Pop quiz – adding content using custom content types
[v]
251 251 251 251
Table of Contents
Chapter 2, Fields Pop quiz – enabling the Field module Pop quiz – finding the Field UI Pop quiz – finding the field types and input widgets in Field UI Pop quiz – adding text fields using the text module Pop quiz – rearranging the order of fields Pop quiz – adding text fields to comments Pop quiz – rearranging the order of fields in comments Pop quiz – reusing fields in content types Pop quiz – reusing fields in content types Chapter 3, Multiple Value Fields Pop quiz – multiple values in fields Pop quiz – understanding the Boolean field Pop quiz – setting default values Pop quiz – adding list fields Pop quiz – understanding multiple value widgets Chapter 4, Taxonomy Pop quiz – creating vocabularies Pop quiz – adding terms to vocabularies Pop quiz – adding term references to content types Pop quiz – categorizing content using taxonomy Pop quiz – adding fields to vocabularies Chapter 5, File and Image Fields Pop quiz – adding and configuring file field settings Pop quiz – using the file field Pop quiz – configuring image field settings Pop quiz – creating custom image styles Chapter 6, Managing Field Display Pop quiz – a first look at the field display settings Pop quiz – formatting field display in the teaser Pop quiz – custom display settings Pop quiz – formatting image field display on Full content Pop quiz – formatting comment field display Pop quiz – formatting vocabulary field display Chapter 7, Contributed Field Modules Pop quiz – finding a contributed field module Pop quiz – installing and enabling contributed modules
[ vi ]
252 252 252 252 252 252 252 253 253 253 253 253 253 253 254 254 254 254 254 254 255 255 255 255 255 255 256 256 256 256 256 256 257 257 257 257 257
Table of Contents
Chapter 8, Field Level Permissions Pop quiz – installing and enabling the Field Permission module Pop quiz – enabling field-level permissions Pop quiz – configuring field-level permissions on the PERMISSIONS administration page Pop quiz – the Field permissions report page Chapter 9, Theming Fields Pop quiz – creating a Drupal theme by cloning the existing theme Pop quiz – creating a template file for the Recipe content type Pop quiz – editing a template file Pop quiz – styling the page using CSS Chapter 10, A Database Perspective of Fields Pop quiz – key elements in Fields Pop quiz – new concepts in Drupal 7 Pop quiz – creating a new content type Pop quiz – a database perspective of fields
Index
257 257 258 258 258 258 258 258 259 259 259 259 259 260 260
261
[ vii ]
Preface Drupal is changing the way we create a feature and content-rich website. When I created my first web-based Content Management System (CMS) website in Drupal, I was amazed at the power of the Drupal CMS system. It allows me to rapidly create a high quality web application in a short period of time without sacrificing the application functionality. Drupal is not only an open source CMS, but is also a web application development framework. The extensible and flexible architecture of Drupal can be used for any size of business including freelancers, agencies, governments, universities, and enterprises. The White House, Digg, Fast Company, Sony Music, McDonald's, and Stanford University are all using Drupal for their sites. One of the most important milestones in Drupal was the Content Construction Kit (CCK). Most of this module has been integrated into Drupal 7 core. It is now called Field API. So when you install Drupal 7, it will come with this powerful module in core, and you can start to create custom fields for your site without downloading an extra module. The Field API module is not just the CCK module moved to the Drupal core. It has been completely rewritten and redesigned in Drupal 7. It has been optimized to run faster and work more efficiently. It provides you with more field type options, and it has given you more flexible options to allow you to create custom fields not only for content types, but also for comments, taxonomy, and more, that was not possible to achieve before Drupal 7. After reading this book, you will learn how the new Fields API module works, and understand the concept of fields and how to implement them. In this book, we will use Drupal 7 fields to build a fictional website from scratch. We will explore the power of fields within Drupal 7, then you can apply these techniques to your own projects.
Preface
What this book covers
Chapter 1, Nodes and Content Types in Drupal 7 explains the concept of nodes and content types in Drupal. It will explain the default content types that Drupal 7 core comes with. This chapter will also teach you how to create contents and create custom content types in Drupal. Chapter 2, Fields explains the concept of the new core module in Drupal 7 and demonstrates to how to add fields to content types, rearrange the order of fields, and reuse existing fields. It will also show how to add fields to comments, which is new in Drupal 7. Chapter 3, Multiple Value Fields focuses on using field modules to creating multiple value fields for the site. We will look in detail at the new field type and other multiple value field type options such as Boolean, List, List (Numeric), and List (Text) field types. Chapter 4, Taxonomy focuses on using fields in taxonomy; at the beginning of the chapter we will learn what taxonomy is. We will then create custom vocabularies, and add taxonomy terms. We will also look at how to add fields to vocabularies and term references to content types. Chapter 5, File and Image Fields focuses on using the file and image fields modules. We will look at adding file and image fields to content types, configuring file and image field settings, using and creating image styles, as well as adding those fields to content types. Chapter 6, Managing Field Display focuses on field display management. We will look at how we control field display on the pages, format field display on teaser and full content pages, customize display settings, format comment fields display, and format vocabulary fields display. Chapter 7, Field Modules focuses on using field related modules. We will learn where to find the contributed modules and field related modules, we will also learn about downloading modules and installing them. We will also look at some of the most popular field related modules such as the Content Templates module and Field permission modules. Chapter 8, Field Level Permissions focuses on using the field permission module. We will discuss how to use this powerful module to control the permissions of fields. At the beginning of this chapter, we will start from scratch, by downloading the module, installing the module, and enabling it. Then we will continue with enabling permissions in fields, viewing field-level permissions report and configuring permissions in the PERMISSIONS administration page. Chapter 9, Theming Fields focuses on themes. We will discuss what theming is. We will look at where to find the template files for fields, creating template files, editing template files, creating CSS files, and theming field display.
[2]
Preface
Chapter 10, A Database Perspective of Fields explains the difference between CCK fields and the Drupal 7 fields in the database. This chapter also shows you how to find the content types and fields we created in the example project from the database, and shows the interaction between Drupal and the database.
What you need for this book
To follow along with the examples in this book, you will need a computer which can run MySQL, PHP, and the Apache web server, which are all prerequisites for Drupal. Drupal is written in PHP and can run on many platforms and environments including Windows, Mac OS X, and Ubuntu Linux. You may want to create an account with a website hosting company to test your work, although you can also use a regular desktop or a laptop computer. But all that is required is a development environment set up on your computer; some of the most popular development environment bundles are Acquia Drupal, WAMP, XAMPP, and MAMP. You will also need the Drupal 7 core, which is available at http://www.drupal.org
Who this book is for
This book is designed primarily for people that have a basic knowledge of Drupal and want to familiarize themselves with Field API to add fields to content types using the new Drupal 7 fields. However, technical users will also find the book useful, as we will explore a wide variety of techniques that are used to build websites with fields. Previous experience with website development or programming languages is not required, although it is helpful to have some experience with using Drupal 7, and CSS will be useful for some parts of this book.
Conventions
In this book, you will find several headings appearing frequently. To give clear instructions of how to complete a procedure or task, we use a title section like this:
Time for action – heading Action 1 Action 2 Action 3 [3]
Preface
Instructions often need some extra explanation so that they make sense, so they are followed with:
What just happened? This heading explains the working of tasks or instructions that you have just completed. You will also find some other learning aids in the book, including:
Pop quiz – heading These are short multiple choice questions intended to help you test your own understanding.
Have a go hero – heading These set practical challenges and give you ideas for experimenting with what you have learned. In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "Let's take a deeper look at each directive used in the Drupal robots.txt file". A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: [4]
Preface
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: " I added the site logo file into the Test URLs box". Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply drop an email to
[email protected], and mention the book title in the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or email
[email protected]. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
[5]
Preface
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration, and help us to improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub. com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata added to any list of existing errata. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or web site name immediately so that we can pursue a remedy. Please contact us at
[email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at
[email protected] if you are having a problem with any aspect of the book, and we will do our best to address it.
[6]
1
Nodes and Content types in Drupal 7 At the beginning of this chapter, we will have a look at a preview of our final project, it will give you a better idea of what we need to do, and what will be achieved when we reach the end of this book. We will also explain the concept of nodes and content types in terms of Drupal. After that we will get our hands dirty with a hands-on tutorial on creating content and content types using the default content types in Drupal. We will go even further to create our own custom content types and add more content by using these custom content types to create a website. Sounds cool! Let's get started!
We shall discuss the following topics in this chapter: The book example project A preview of the final project What is a content type? Default content types in Drupal 7 core Creating content using article content types Creating custom content types Adding content using custom content types
Nodes and Content types in Drupal 7
The book example project This book will show you how to create a website using Drupal 7 and Fields. Instead of explaining how the Fields module works in theory, we will learn about it by creating a fictional project. We will guide you through the complete project by following a set of steps or tasks, and thus you will learn: How to create custom web content by creating your own content types and fields How to create fields for displaying multiple values How to create taxonomy vocabularies and terms for categorizing web content How to use the file field to provide file uploading functionality to the website How to use the image field to provide image uploading, extension validation, and image processing functionality to the website How to format images using image styles How to control the display of fields in teasers and full content view modes How to set field level permissions for specific fields that only authenticated users can access Finally, how to theme fields using templates and CSS You also have a choice of downloading the final project file from www.packtpub.com or www.drupal7fieldsbook.com to follow along with the book. Alternatively, you can compare your project with the final project if you have any problem while following the book.
A preview of the final project The website that we are going to build in this book is a cooking website filled with recipes. Let's take a look at some of the most important sections the website has, before starting the project.
[8]
Chapter 1
[9]
Nodes and Content types in Drupal 7
This is the homepage of the cooking website; it shows a list of the latest content uploaded to the site. This website is composed of a mixture of content types like Article, Recipe, and Cooking Tip. Each content type contains various field types and configurations. We will show you how to create these content types in this chapter, and then we will create custom fields in Chapter 2.
The preceding screenshot shows the Article content type which is one of the default content types that comes with Drupal. This means that it has some fields already created for us such as Title, Body, image, and Tag fields, by default. The screenshot shows the Article content type in teaser view mode such as you would get in a listing format. Furthermore, as you can see, the body text is positioned on the right side of the image. The default layout is body text below the image, but we will use CSS to manipulate the teaser view mode layout to a different position. We will guide you on how to do this by theming fields in Chapter 9. The site administrators or authors (users with permissions to create article content) will use this content type to create cooking articles for the website.
[ 10 ]
Chapter 1
The preceding screenshot depicts the Cooking Tip content type that is one of the custom content types we will create in this book. The Cooking Tip content type contains the Title, Image, Body, Tip Owner (Boolean field), and cooking tip Category (Term reference) fields. We will see all these fields in detail later. We will also use the Field UI to manage the field displays and change their order.
The preceding screenshot is of the Recipe content type. It is another custom content type we are going to create. This content type contains more fields than the others. It will contain Title, Body, Image, File, Difficulty (List: text), and recipe Category (Term reference) fields.
[ 11 ]
Nodes and Content types in Drupal 7
The Recipe content type is similar to the Cooking Tip content type, but it has a special field type, which is list, and we will create the Difficulty field by using this field type to define the difficulty level of a recipe. The site administrators or authors can create a recipe using this content type, and indicate the difficulty level of a recipe on the website.
[ 12 ]
Chapter 1
We will do some advanced theming for the Recipe content type to look like the preceding screenshot. As you can see, we will change the body field position to the left of the page, and position the Difficulty level and the Recipe Category (term reference field) to the right, so people may find it easier to look at both information in different boxes at the center of the page. If the body field has got a lot of information, it is more difficult for users to find the difficulty level and the recipe category information. We will guide you on how to theme fields in Chapter 9.
There is a file field created in the recipe content type, which allows the site administrators or authors to upload PDF versions of recipes or other materials such as wallpapers and coupons.
What is a content type? Most of the time there is a need for more than one type of content on a website. We usually see a newspaper website that contains news, pictures, videos, and forums sections. In terms of Drupal, a node is a piece of content, and every piece of content belongs to a unique content type, a content type that can contain various configurations and settings to define its own composition and behavior.
[ 13 ]
Nodes and Content types in Drupal 7
It is similar to a pancake maker, we set up a pancake maker to make a red bean pancake. Once we turn it on, it will keep making the same type of red bean pancake again and again. It will not suddenly make us a strawberry pancake, unless we use other ingredients and set up the pancake maker to create another type of pancake. Nodes/Contents Title Image Body Tag
Content types / Node types
Title Image Body Tag
Article Title Image Body Tag
Title Image Body Tag
Title Image Body Tag
Default content types in Drupal 7 core After installing Drupal, there are two default content types that come with Drupal out of the box, they are the Basic page content type and the Article content type. We can use these content types to create a simple website.
[ 14 ]
Chapter 1
The Basic page content type The Basic page content type only contains the Title and Body fields. We can write plain text and also insert HTML markup in the Body field.
Text format will finally determine what type of format the Body field will support and display:
For example, if we install and enable the PHP filter module, it allows us to insert PHP code in the Body field, which means we can write PHP code to connect to databases, and extract data from the databases, and output the information on the website. There are many other filter modules on the Drupal website such as Markdown filter module, BBCode filter module, and so on. You can go to the website module download page to see more, and give them a try; you may find one or two filter modules useful for your projects. [ 15 ]
Nodes and Content types in Drupal 7
The Article content type The Article content type is similar to the Basic page content type, except it allows us to upload images and enter a set of tags to categorize the content.
The default content types are basically enough for a general purpose content managed website. For example, we can use the default content types to create a blog website. The Basic page content type can be used for creating About Us and Contact Us pages, and the article content type can be used for creating blog posts.
Time for action – creating contents using the article content type Let's get started by creating some web content using the default content type. Our first task is to add cooking articles to the cooking website using the Article content type.
1.
First log in to the website as an administrator, and go to the administration menu at the top of the page, click on the Add content link to create new content:
[ 16 ]
Chapter 1
2.
It will show two content types on the page, one is Article, the other is Basic page. Click on the Article link to add a cooking article to the site:
3.
You can type content in the fields, or copy and paste content from the final project folder if you have downloaded it. It contains a file called content.txt, you will find all the text to input in this file. Also there is a directory called images, which contains all the images for you to use when following along with the book. There is a file called salad.jpg, you can use it for this tutorial.
[ 17 ]
Nodes and Content types in Drupal 7
4.
After filling in all the details, we leave the other settings to their defaults. Then go to the bottom of the page and click the Save button to save the content:
5.
Once you have saved the content, it will redirect you to the full content view mode of the content, and it will show a message saying the content has been successfully created:
[ 18 ]
Chapter 1
6.
If you go back to the homepage, you will see the content listed on the page as in the following screenshot.
What just happened? We have just added content using the Article content type. We entered the Title, the Body text, and we also attached an image to it.
Pop quiz – understanding of the default content types 1. Which of the following types are the default content types in Drupal 7? a. Page and Image content type b. Basic page and Page content type c. Article and Basic page content type d. Article and Page content type 2. To which default content type can we attach images? a. Image content type b. Article content type c. Basic page content type
[ 19 ]
Nodes and Content types in Drupal 7
Creating custom content types This time we will be creating two custom content types, which are called the Cooking Tip and the Recipe content type. We will mainly use these custom content types to create our cooking website.
Creating the Cooking Tip content type The Cooking Tip content type will contain all the cooking tips information on the website. Users can navigate around the cooking tips to learn and share tips with other people.
Time for action – creating the Cooking Tip content types Let's create the Cooking Tip content type now. Follow these steps:
1.
Go to the administration menu bar at the top of the page. We will see a Structure link between the Content and Appearance, just click on it.
[ 20 ]
Chapter 1
2.
A page will show up with the following options. We can ignore the other options for now. Let's just focus on creating our custom content types. Click Content types, which is below the Blocks link and above the Menus link on the page:
3.
It will go to the Content types administration page, and this page will show all the existing content types in your Drupal site. Currently it only shows the default content types:
[ 21 ]
Nodes and Content types in Drupal 7
4.
Click the Add content type link:
5.
On this page we will enter our content type information such as the name of the content type, a description of the content type, and other specific settings:
[ 22 ]
Chapter 1
6.
We enter Cooking Tip as the name of the content type, and enter a sentence to describe the content type, and then we just leave the other setting as default. Click the Save content type button at the bottom of the page.
7.
The Save and add fields button is also very useful, if we want to start adding more fields after saving the content type. But we will not use it for now; we will add more fields in the next chapter.
[ 23 ]
Nodes and Content types in Drupal 7
8.
After clicking the Save content type button, it will redirect you back to the Content types administration page with a message saying that the content type has been successfully added to Drupal:
9.
Now we can see our recently added content type Cooking Tip in the list on the Content types administration page.
What just happened? Now the Cooking Tip content type is created. We will use the same procedure to create the Recipe content type.
Creating the Recipe content type The Recipe content type will contain the ingredients used in the recipe, the instructions, the difficulty of the recipe, and we can also define a set of terms for the content.
[ 24 ]
Chapter 1
Time for action – creating the Recipe content type Now we will create the Recipe content type, and we will create fields in the later chapters to enhance the functionality of this content type. Follow these steps to create this content type:
1.
In the Content types administration page, click the Add content type link:
2.
Now you can enter Recipe as the name of the content type, similar to the Cooking Tip content type. You can enter a sentence to describe this content type.
[ 25 ]
Nodes and Content types in Drupal 7
3.
When you are done, like the last exercise, go to the bottom of the page, and click on the Save content type button to save this content type in Drupal.
4.
If we go back to the Content types administration page, you can check the existing content types in Drupal, just like the following screenshot. It shows that we have a total of four content types, namely, two custom content types and two default content types:
What just happened? We have created the Cooking Tip content type and the Recipe content type. All the content types are created, the foundation of the website is built, we will use these content types for the rest of the cooking website.
Pop quiz – creating content types 1. Can we change the name of the content type after creating it? a. Yes b. No 2. Which of the following statements is true? a. We can create a content type with the same name as another existing content type. b. We can recreate default content types if we deleted any of the default content types. [ 26 ]
Chapter 1
Adding content using custom content types We have already created two custom content types. We will add content using these content types. You will find that adding content using the custom content types does not differ greatly from adding content using the default content types. It is only when we start creating more fields in the custom content types that you will gradually understand the differences and characteristics of each content type.
Adding content using the Cooking Tip content type In this section, we will add content using the Cooking Tip content type.
Time for action – adding content using the Cooking Tip content type Let's get started by adding some content to the website using our custom content types. Follow these steps to add content using Cooking Tip:
1.
Go to the administration menu bar at the top of the page, and click Add content:
[ 27 ]
Nodes and Content types in Drupal 7
2.
You will see that Cooking Tip and Recipe are added on the Add new content page because we have created those content types previously. Click the Cooking Tip link:
3.
It is similar to the Basic page content type, which only contains the Title and Body fields. We will add more fields later. We can start entering text in the Title and the Body fields, but for your convenience, you can also copy and paste the text from the content.txt file if you have downloaded the final project files:
[ 28 ]
Chapter 1
4.
Then we click the Save button at the bottom of the page, and just leave other settings as default:
5.
Once the content is saved, it will redirect you to the full content view mode of the content you just created. There are two tabs at the top of the content, which are the View and the Edit tabs. If we want to edit or update the content, we can click the Edit tab. It will show you the edit page of the content, and we can start to do any modification on that page:
[ 29 ]
Nodes and Content types in Drupal 7
What just happened? We have added content using the Cooking Tip content type to the cooking website. We entered the title of the cooking tip, and we also entered the cooking tip content to the website. Visitors can now read our cooking tip on the website.
Adding content using the Recipe content type Now we should understand the workflow of how to add content using the custom content types. This time we will add content using the Recipe content type, this shouldn't be a problem for us, and we should be able to do it quicker now.
Time for action – adding contents using the Recipe content type In this section, we will add content using the Recipe content type.
1.
Go to the administration menu bar at the top of the page, and click Add content.
2.
Click the Recipe link on the Add new content page.
3.
On the Create Recipe page, enter text in the Title and the Body fields or copy and paste the text from the content.txt file:
[ 30 ]
Chapter 1
4.
Click the Save button at the bottom of the page to save the content. It will show the full view mode of the content as in the following screenshot:
What just happened? We have added content using the Recipe content type to the cooking website. We have entered the ingredients and the cooking method of the cake recipe, and now, users can make a cake by following the recipe you just posted. As we have seen so far, adding content using the Recipe custom content type is not much different from adding content using the Cooking Tip content type. However, in later chapters, we will learn and add a variety of fields to these different content types, and you will understand more about the real power of fields and the relationship between fields and content types. [ 31 ]
Nodes and Content types in Drupal 7
Pop quiz – adding content using custom content types 1. Can we clone an existing node/content using default Drupal functionality? a. Yes b. No 2. Can we change the content type of a node/content to different content type? a. Yes b. No
Have a go hero – creating more content using the custom content types Now it is time to test your skills in creating more content using the custom content types. You can try to enter more content with the methods we have learned. Also there are options at the bottom of the page when creating content. You can try to change those settings, and see what they give you. Try to do all the steps on your own without looking at the chapter first. If you encounter any difficulties, read the chapter again to get familiar with the steps.
Summary In this chapter, we have dealt with the following key topics: A preview of the complete project in this book. We have an overview of the structure of the final project, and we have an idea of what will be achieved when we reach the end of this book. What a node and a content type is, and the meaning and the relationship between those terms in Drupal. Understanding what default content types are in Drupal 7 core and what are the fields created in those content types by default. How to add content using the default content types. Understanding the workflow of creating custom content types. Adding content using custom content types. Now that we've learned how to create content types, we're ready to learn how to create fields and add them to the custom content types. This is the main purpose of fields, and we will discover the power of fields, which is the topic of the next chapter.
[ 32 ]
2
Fields In this chapter we will learn the concepts needed to work with the fields available in Drupal. It also gives a brief explanation of what the fields set of modules are designed for and what has changed since the arrival of the new and improved Drupal 7. This chapter also guides you on how to add fields to content types, rearranging the order of fields, reusing existing fields, and adding fields to comments.
The topics that will be discussed in this chapter are: What is CCK? Fields in Drupal 7 Drupal 7 core default fields Adding fields to content types Rearranging the order of fields Adding fields to comments Reusing existing fields
What is CCK? So what is CCK? Content Construction Kit (CCK) is a set of modules developed for Drupal which allows us to add custom fields to any kind of content type including core content types and custom content types, all through a web interface.
Fields
But when and why do we need it? Unless the functionality provided by the default Article and Basic page content types is all you need for your website you'll need a way to define a mold or more for the content on your website. This is what CCK does for you. It lets you define the composition and behavior of you site's content. As we have learned so far, we can create custom content types to solve a specific problem, but content types by default contain exactly the same number of fields. The only difference between them is the name of content types. We need a solution that allows us to add more fields and functionalities to content types, so that each content type is responsible for different jobs. The functionality provided by custom fields varies greatly. Some of the more useful ones allow users to upload images, display them on the page, or upload videos so users can share their travel videos with friends. The CCK set of modules can enrich a simple website to be a social media website, sharing photos, and sharing ideas between different groups of people on the Internet. Our clients require that the website allows users the ability to submit cooking tips and recipes to the website. They require that cooking tips and recipes have different, custom functionalities like displaying food pictures and setting difficulty levels for recipes. The default content types cannot satisfy such requirements. So, in the previous chapter, we tried to fulfill the client requirements by creating two custom content types. However, if you have noticed the custom content types we created have the exact same structure. They both contain the Title and the Body field and, as such, those fields cannot do very much other than allowing users to enter the title and the body details. The following image shows the Cooking Tip content type fields:
The following image shows the Recipe content type fields:
[ 34 ]
Chapter 2
They cannot be used to set the difficulty level of recipes or for displaying images. We need more fields to satisfy these requirements, so we will add more custom fields using the Field module in this chapter.
Fields in Drupal 7 In Drupal 6, the CCK module is a contributed module; we have to download the CCK module from http://drupal.org/project/cck, and add it to the sites/all/modules directory, and then go to the ourwebsite.com/admin/build/modules page to install the module. The good news is that most of the functionality of the CCK modules is available in Drupal 7 core, and now it is simply called Fields. From now on, we do not need to download a separate module to add fields to content types. We simply install Drupal 7 and the ability to create custom fields is enabled as part of it. As a result of the name change, to avoid any confusion in the later chapters, we will call the CCK module or CCK Fields to the field module. For example, the instruction will be "we will use the Field module to add a text field to the recipe content type", but not "we will use the CCK module to add a text field to the recipe content type".
Enabling the Field module When we installed Drupal 7, the Field module is installed and enabled by default. If you want to make sure the Field module is installed and enabled, we can carry out the following steps.
Time for action – enabling the Field module Let's enable the Field module in this section. Follow these steps:
1.
We login as the site administrator. Go to the administration toolbar at the top of the page, and click the Modules link to go to the module administration page:
[ 35 ]
Fields
2.
We will find the Field module when we scroll down the page as shown in the following screenshot. You will also see the page which not only contains the Field module, but also two more field related modules, one is called Field UI and the other Field SQL storage. We have to also make sure these modules are installed and enabled; otherwise, Fields will not function correctly in Drupal.
3.
If you cannot find the Field module on the module administration page or it is disabled, you have to make sure you have downloaded the correct version of Drupal, and double check the downloaded file has no file corruption. If you find your Drupal 7 installation file has got errors, you should download the Drupal 7 installation file from http://drupal.org/project/drupal, and reinstall Drupal.
[ 36 ]
Chapter 2
What just happened? We learned how to view the module administration page to verify that the Field modules are installed and enabled.
Pop quiz – enabling the Field module 1. Which of the following statements is true? a. The field module is enabled by default. b. The field module is not installed by default when installing Drupal.
Field, Field UI, and Field SQL storage modules The Field module is an Application Programming Interface (API) for Drupal developers to develop custom fields that can be embedded to Drupal entities such as nodes, comments, users, and terms. The Field module will do all the heavy lifting work for you to store, load, edit, and render field data, so we don't have to develop each individual function to create custom fields. What is an API? API stands for "Application Programming Interface" and is a set of tools usually in the form of code libraries aiding in the development of software programs. You can find out more information from: http://en.wikipedia.org/wiki/Application_programming_ interface
However, site builders usually do not create custom fields through the Field API directly, because we have to develop Drupal modules, in order to use the Field API to create Drupal entities and to add fields to Drupal entities. Instead, we will use the Field UI module to create custom fields, this module provides us with user-friendly interfaces that allow us to interact with the Field API easily. So we can create and configure custom fields without any programing knowledge, through a web interface, the Field UI module will automatically create custom fields for us. The Field SQL storage module is an API that performs database operations for the Field API. This module is like the Field API in the sense that it has no user interfaces; this module is intended for managing internal field data operations. This is an advanced topic, so the Field SQL storage API will not be covered in this book.
[ 37 ]
Fields
Time for action – finding the Field UI If you need to find out where the web interface the Field UI has provided for us is located inside our website, we can perform the following steps:
1.
Click the Structure link on the administration toolbar at the top of the page:
2.
Click the Content types link on the structure administration page. It will direct us to the content types administration page.
3.
There are two columns in the table as you see in the following screenshot, the first column is the names of the content types on your website, the second column is the operations we can perform on the content types.
[ 38 ]
Chapter 2
4.
There are two options provided by the Field UI module, which are manage fields and manage display in the operations column. If you cannot see the links on the page, it means that the Field UI module is disabled or problems have come from a possibly corrupted Drupal 7 installation file.
What just happened? We have identified the Field UI options on the Content type administration page. There are two options we have found, one is manage fields, and the other is manage display. Once the Field module is enabled, these two options will be available on the content types administration page.
Pop quiz – finding the Field UI 1. Which of the following statement is true? a. The manage fields link is on the Add new content administration page. b. The manage fields link is on the Content type administration page. c. The manage display link in on the Appearance administration page.
[ 39 ]
Fields
Field types and input widgets The Field module provides the foundation for fields; extra modules are needed for field types and input widgets. Some of the field types and input widgets are available in the core, such as Number, Text, and List modules.
Time for action – finding the field types and input widgets in Field UI But where can I find the field types and input widgets in field UI? To find them you will need to carry out the following steps:
1.
Navigate to the content types administration page, and click one of the manage fields links as shown in the following screenshot:
2.
There is a table of five columns on the page. The first column represents the labels of the fields, the second column is the names of the fields, the third columns is the field types of the fields, the fourth column is the input widgets of the fields, and the last column is the operations for the fields. The manage fields page provides all the information about each field for a content type, and we can also check which field types and input widgets have been applied to the fields.
[ 40 ]
Chapter 2
3.
If you need more field types and input widgets, there are other contributed modules that are available from http://drupal.org/project/modules and we can search the CCK/field related modules using the filters provided on that page, we can select CCK in the Modules categories drop-down menu, and select 7.x in the Filter by compatibility drop-down menu. It will provide a list of field related modules that provide you more features and functionalities for fields:
What just happened? We have identified the field types and input widgets on the manage fields page through the Field UI. The manage fields page shows the available field types and input widgets on the table. We can easily identify what field is used for what type of field types and input widgets. We can obtain more field types and input widgets from the Drupal.org website, they provide a variety of fields related modules to extend the functionality of field modules.
[ 41 ]
Fields
Pop quiz – finding the field types and input widgets in Field UI 1. In which page can we find out what fields are used in a content type? a. Manage fields page b. Content types administration page 2. Are Field types and input widgets extensible? a. Yes b. No
Drupal 7 core default fields There is a list of field related modules that are part of Drupal 7 core. Some of these modules are required by the Field module and Drupal, but some of them are optional. We can easily disable them from the modules administration page. Furthermore, not all of these modules provide both field types and input widgets for fields, some of them may only provide you with field types and no additional input widgets. And some of them will only provide you with input widgets without giving you a new field type. If you download contributed modules from drupal.org, it would be better to read the module documentation to understand what the modules can do for you.
Drupal 7 core field related modules Drupal 7 core includes the following field-related modules: Number (required) Text (required) List (required) Taxonomy (optional) Image (optional) File (optional)
Number modules The number module provides different numeric field types for fields such as Integer, Decimal, and Float formats:
[ 42 ]
Chapter 2
Text modules The text module provides different text field types for fields such as Text, (single row), Long text, and Long text with summary fields (multiple rows):
[ 43 ]
Fields
List modules The list module provides a facility to store a list of items for fields, and often these items are inputted from select lists, checkboxes, and radio button input widgets:
Taxonomy modules The taxonomy module provides a facility to categorize content on a website, and the taxonomy term fields can be attached to content types for users to categorize the content.
[ 44 ]
Chapter 2
Image modules The image module provides a facility that allows us to attach images to fields.
File modules The file module provides a facility that allows us to attach files to a field.
[ 45 ]
Fields
Adding fields to content types There are usually cases in which we need to add a field to content types; site administrators can enter data to the custom fields for a specific purpose. Now, we go back to our cooking website, we will add more custom fields to the Recipe content type and the Cooking Tip content type, because our clients want to have a field to enter notes for the recipes and the cooking tips. Additionally they would like to have another field to enter the source of recipes and cooking tips, so authors can enter where they found the recipes or tips.
Adding text fields using the text module In this case, the text module can perfectly handle this requirement. Authors can enter text into a text area field that contains a note for a recipe or a cooking tip. We can also create a text field, and authors can enter details for the source of a recipe and a cooking tip.
Time for action – adding Long text fields using the text module Text areas allow users to enter more than one line of text, which can be used for news postings and user enquiries. In this section, we will add a Long text field using the text module. Follow these steps:
1.
Navigate to the Content types administration page:
[ 46 ]
Chapter 2
2.
Click the manage fields link on the Cooking Tip row as shown in the following screenshot. We will only manage the fields for the Cooking Tip content type for now. We cannot manage fields for multiple content types at the same time, we have to do it one by one.
3.
We can enter "Notes" for the field label. Then enter "notes" for the field name (you can only use numbers, lower-case letters, and the underscore character for the field name).
4.
Select Long text from the Select a field type drop-down menu in the FIELD column. After you select the field type, the Text area widget will be automatically selected as the input widget. Because the Long text field type is only supported by the text area input widget, no other widget can be selected.
[ 47 ]
Fields
5.
Click Save to save the field.
6.
After clicking the Save button, the following message is displayed: These settings apply to the Notes field everywhere it is used. These settings impact the way that data is stored in the database and cannot be changed once data has been created. Which means, all the settings here will be used for the Notes field of the Cooking Tip content type in Drupal, and all the data created by this field that will be saved in the database. However, once the data were created and saved in the database, you cannot change the saved data in the database by modifying the field settings.
7.
Click the Save field settings button to confirm the message, and we will start to configure the field on the field setting page.
8.
On this page, the Label field is automatically filled in based on the label name we entered earlier; we can change it in here if we need.
9.
We will not check the Required field checkbox because we want the Notes field to be optional.
10. Rows defines how many rows the text area will be; we just leave it as the default value (5).
[ 48 ]
Chapter 2
11. There are two options for Text processing, one is Plain text, and the other is Filtered text (user selects text format).
12. The Help text text area allows us to enter some tips and description to help users
understand more about what this field is, and what information users should enter. In this case, we can enter Enter notes to the cooking tip for this field.
13. For now, we can leave the DEFAULT VALUE field, and proceed to the next field. We use the DEFAULT VALUE field in a later chapter.
[ 49 ]
Fields
14. We also leave the Number of values as 1, so we don't change anything here, we just click the Save settings button on the field settings:
Drupal will direct us back to the Manage fields page. As we can see on the page, the Notes field is added below the Body field in the table, and we can see it shows what field type and input widget it is using. If we would like to go back and edit the notes field settings, we can easily just click the edit link to edit the field settings. We can even delete the field by clicking the delete link, but you have to make sure the field is not needed, because there is no undo button to recover your deleted fields, so use it wisely and carefully:
What just happened? We have successfully created a Long text field by using the text module, and users will use it to enter the note of cooking tips.
Text fields This time we will create a field using the text field type, and authors can enter a short paragraph for the source of cooking tips. We just learned how to add a field to content types, and the text area field type is similar to the text field type. We should able to create it easily. [ 50 ]
Chapter 2
Time for action – adding text fields using the text module Text fields allow users to enter a line of text, which can be used for users entering username or postal numbers. In this section, we will create a text field using the text module. Follow these steps:
1.
Type "Source" in the Label field, and then type "source" in the Field name field, and select text from the Select a field type drop-down menu in the FIELD column. The input widget will be automatically changed to a Text field widget. This is just like the text area field type, there is only a text field widget that supports the text field type, so the text field widget will be selected by default.
2.
Then click Save to save the field.
3.
Next, it will display a page with a message that is similar to the one we have seen before. All data cannot be changed, once the data is saved in the database. But the bottom part, which is a little different from the text area field type, here provides the Maximum length option, so we can set the maximum length of the field, and this option only applies to the Text field field type. We leave the default value, and click the Save field settings button.
[ 51 ]
Fields
4.
This page, as you can see, is similar to the text area field setting page, so the same settings will not be covered again, because we already know what they do.
5.
Now we enter "Enter the source of cooking tips" into the Help text field:
6.
Click the Save settings button to save the field settings.
7.
In the Manage fields page, the source field has been successfully added to the Cooking Tip content type now.
Now, we know how to create Long text and Text field fields to the Cooking Tip content type. There are many cases where we need to add our own custom Text area and Text field to content types, but from now on, this is not a question for us anymore, because we know how to create them easily through the Field UI. [ 52 ]
Chapter 2
What just happened? We have created a text field by using the text module. Users will use it to enter the source of cooking tips.
Pop quiz – adding text fields using the text module 1. How many types of fields can the text module create? a. 1 b. 2 c. 3 2. Which type of field does the text module can support? a. Image field b. Long text field c. List field
Rearranging the order of fields So far we have seen how to create fields to content types. The latest created fields will be appended to the existing fields, so the latest created fields will be positioned at the bottom of the page. But what if we want the Source field to sit at the top of the page, rather than sitting at the bottom of the page. The Field UI provides a user-friendly interface that lets us easily rearrange the order of each field.
Rearranging the order of the Notes field Our client wants the Notes field to be positioned just below the Title field, because they want to check the notes quicker. They don't want to scroll down the page to check the notes.
Time for action – rearranging the order of the Notes field In this section, we will rearrange the order of the Notes field. Follow these steps:
1.
Navigate to the Content types page, in the table, locate the row that contains the Cooking Tip content type, and click the manage fields link.
[ 53 ]
Fields
2.
There are four-headed arrow icons on the left of each row in the table. We locate the Notes field, and then drag the four-headed arrow icon up to the position that as just below the Title field.
3.
After dragging it, we should see the highlights and the message as in the following screenshot:
4.
Click the Save button at the bottom of the page. (After changing the order, you should save the settings otherwise the order will not be saved.)
5.
The highlighted message is gone after saving the page, and the Notes field is now positioned below the Title field:
[ 54 ]
Chapter 2
What just happened? We just rearranged the order of the Notes field. As you saw, rearranging the order of fields is so easy to do using the Field UI, by dragging and dropping, any field on this page can be rearranged. Also we saw the highlighted message when we dragged the Notes field. Actually, it just warns us that we have just made a change to the fields in the table, but it will not take effect until we click the Save button to save the change. Rearranging the order of fields affects the node/content forms, full content, and teaser mode outputs. When you add or edit a Cooking Tip content, you will see the order of the Notes field has now moved below the Title field, and the Node field has also changed its position on the full content page.
Pop quiz – rearranging the order of fields 1. Does the reordering of fields affect the page output? a. Yes b. No
Adding fields to comments Drupal 7 allows us to add fields to comments; it was not possible to do this in Drupal 6 and earlier versions. Though you can write a custom module, by default Drupal 6 doesn't allow adding of fields in the comments form. In the cooking website, our client wants to add a text field that contains commenter e-mail addresses when they post a comment on the website.
Adding text fields to comments We just learnt how to add a text field to the Cooking Tip content type. In this section, we will create a text field and attach it to the comments form.
Time for action – adding a text field to comments Now we will add a text field to comments. Follow these steps:
1.
Navigate to the Content types page, in the table, locate the row that contains the Cooking Tip content type, and click the manage fields link.
[ 55 ]
Fields
2.
Click the COMMENT FIELDS tab. It is positioned between the MANAGE DISPLAY and COMMENT DISPLAY tabs:
3.
In the Add new field row in the table, enter "Email" for the Label field, enter "email" for the Field name field, and then select Text for the field type, the Text field widget will be automatically selected.
4.
Click the Save button.
5.
Click the Save field settings button. We leave the settings as default:
[ 56 ]
Chapter 2
6.
In the following page, we also leave all the settings as default, and then click the Save settings button to save the field settings:
7.
We should get something like the following screenshot:
What just happened? We have added a Text field to comments. Commenters can use this field to enter their e-mail address when submitting comments.
[ 57 ]
Fields
Pop quiz – adding text fields to comments 1. Can we add Text area fields to comments? a. Yes b. No
Time for action – rearranging the order of the Email field Our client prefers the Email field to be positioned below the Author field. We just learnt how to do this in the earlier section; we should replicate the same thing here easily:
1.
Locate the Email field, and then drag the four-headed arrow icon up to the position that is just below the Author field.
2.
Then click the Save button.
3.
The result should look like the following screenshot:
What just happened? We have rearranged the order of the Email field for comments.
Pop quiz – rearranging the order of fields in comments 1. Can we reorder any field in comments? a. Yes b. No
[ 58 ]
Chapter 2
Reusing existing fields So far we have created fields and applied the changes to the Cooking Tip content type, but what about the Recipe content type. The Recipe content type also needs the Notes field, the Source field, and the Email field. We can go through all the steps to create the same fields, but there is a time saving feature in the Field module. We can reuse the existing fields, without the need to recreate new fields to mimic the defined fields in other content types.
Time for action – reusing the Notes field for the Recipe content type In this section, we will reuse the Note field for the Recipe content type. Follow these steps:
1.
Navigate to the Content types page. In the table, locate the row that contains the Recipe content type, and click the manage fields link.
2.
In the Add existing field row in the table, select Long text: field_notes (Notes) from the drop-down menu, the Text area widget will be automatically selected, and then enter "Notes" for the Label name.
3.
Click the Save button to save the change.
4.
The Field settings page is exactly the same as the one we saw when creating the Notes field for the Cooking Tip content type.
5.
Click the Save settings button.
[ 59 ]
Fields
6.
On the Manage fields page, the Notes field is now added to the Recipe content type.
What just happened? We have just reused the Notes field for the Recipe content type.
Pop quiz – reusing fields in content types 1. Can we reuse the fields created in different content types? a. Yes b. No
Time for action – reusing the Source field for the Recipe content type This time we will reuse the Source field for the Recipe content type. Follow these steps:
1.
In the Add existing field row in the table, select Text: field_source (Source) from the drop-down menu. The Text field widget will be automatically selected. Then enter "Source" in the Label field.
[ 60 ]
Chapter 2
2.
Click the Save button to save changes.
3.
On the Field settings page, leave all the settings as default, just click the Save settings button to proceed to the next step.
4.
The final result should look like the following screenshot:
What just happened? We have reused the Source field for the Recipe content type.
Time for action – rearranging the order of the Notes field We have rearranged the order of the Notes field for the Cooking Tip content type. We will do the same thing here for the Recipe content type. Follow these steps:
1.
Locate the Notes field, and then drag the four-headed arrow icon up to the position that is just below the Title field.
2.
Click Save.
[ 61 ]
Fields
What just happened? We have rearranged the order of the Notes field in the Cooking Tip content type.
Time for action – reusing the Email text field in the Recipe content type Not only can fields created in content types be reused, but fields created in comments can also be reused. We will reuse the Email text field, which we created earlier for the Recipe content type. Follow these steps:
1.
Navigate to the Content types page, in the table, locate the row that contains the Recipe content type, and click the manage fields link.
2.
Click on the Comment Fields tab.
3.
In the Add existing field row in the table, select Text: field_email (Email) from the drop-down menu, the Text field widget will be automatically selected. Then enter "Email" as the label name.
4.
Click the Save button to save the changes.
5.
In the Field settings page, click Save settings.
What just happened? We have reused the Email text field in comments to the Recipe content type. Fields created in comments can be reused in content types.
Time for action – rearranging the order of the Email field We reused the Email text field for the Recipe content type, which needs to be reordered to make it more convenient for users to enter their details. Follow these steps:
1.
Locate the Email field, and then drag the four-headed arrow icon up to the position that is just below the Author field. [ 62 ]
Chapter 2
2.
Then click Save. The result should look like the following screenshot:
What just happened? We have rearranged the order of the Email text field in the Recipe content type. Once we have created fields in Drupal, we can reuse all the existing fields for any kind of Drupal entities such as nodes, comments, users, and terms. Therefore, if we created a field in a content type, we can also reuse it in comments, or vice versa. The architecture of fields has been completely rewritten, that is why we can use such a power feature in Drupal 7, and it was very hard to achieve in Drupal 6 and earlier versions.
Pop quiz – reusing fields in content types 1. Which of the following statements is not true? a. Fields created in content types can be reused in comments. b. We can reorder fields in comments. c. Fields created in comments can't be reused in content types.
Have a go hero – creating fields for content types and comments We have learned a lot. It is now time for a challenge we can use the same methods we have learned to create a field called an Extra Note for the Cooking Tip content type, so site owners can use it to write down some extra notes for the cooking tip. Also, you can try to create a Website text field for the cooking tip and recipe comments. The commenters can leave their website URLs in their comments.
[ 63 ]
Fields
Summary Now that you have finished this chapter, you should understand what CCK is and what a field is in the Fields module in Drupal 7. We also understand what fields and what field types the Drupal 7 core provides. By adding custom fields to content types and comments, we can add more variation and features to contents. Furthermore, we have also learnt how easily we can rearrange the order of fields, and reuse the existing fields for content types. In the next chapter, we will learn how to create multiple value fields for content types. We can create radio buttons, checkboxes, and select lists by using multiple value fields, and this type of field can be used for educational websites such as quizzes and online exams, which is the topic of the next chapter.
[ 64 ]
3
Multiple Value Fields In the previous chapter, we discussed all the necessities for creating long text and text field fields using the text module. In this chapter, we will cover multiple value fields and multiple value widgets in Drupal 7, which allow a field to have multiple values. Also, the interaction between the fields and the widgets when using the multiple value options will be covered in detail in this chapter.
In this chapter, we shall learn: Enabling multiple values Adding Boolean fields Setting default values Adding list fields Multiple values widgets
Enabling multiple values In the previous chapter, we created a source text field to store the source information for a cooking tip. However, there are times we need to enter more than one referenced source. It may be the case that we've put together a tip using three or four different websites, but, we cannot reference all of them because there is only one text field available, and also there is no option to create and enter more fields. Next, we will learn how to enable the multiple value option for the source field.
Multiple Value Fields
Time for action – enabling multiple values In this section, we will enable the multiple value option for the Source field in the Cooking Tip content type. Follow these steps:
1.
First, we have to login as an administrator—if you are following the book, you are already logged in as an administrator.
2.
Click the Structure link on the administration menu at the top of the page:
3.
Click the Content types link on the next screen:
4.
Click the manage fields link to go to the Manage fields administration page:
5.
We would like to edit the Source field, not the other fields. So we click the edit link, which is located at the Source row in the table:
[ 66 ]
Chapter 3
6.
Now we are on the Source field administration page, there are options we already filled up in the previous chapter. But we will pay attention to the bottom of the page, which has a special section for the source field, which is called Source Field Settings.
7.
We will use the options in the SOURCE FIELD SETTINGS page to change the source field from single value to multiple values. There is an option called Number of values, which is currently set to 1, now we click on the drop down menu, and select Unlimited to set the source field to accept multiple value entries:
8.
Leave other options as their default values and click the Save settings button at the bottom of the page to save the modified settings.
[ 67 ]
Multiple Value Fields
9.
The settings are saved. It will redirect us back to the Manage fields administration page. In order to see the changes we made in the Source field settings in the Cooking Tip content type, we will have to go to the Create Cooking Tip administration page under Add content.
10. First, we click the Add content link on the administration menu at the top of the page:
11. And then click the Cooking Tip link to create new content using the cooking tip content type.
12. We may not notice the change at first glance. However, if we go down to the bottom of the page, we will see the source field is now changed. If you forgot how that looked before, here are screenshots to demonstrate the difference between the single value source field and the multiple value source fields.
[ 68 ]
Chapter 3
13. Now we enter "http://uktv.co.uk/food/homepage/sid/5953" into the SOURCE field,
and then click the Add another item button to add one more item to the source field, and then enter "http://www.davidlebovitz.com/2007/01/chocolate-cake/" to the field we just added. Since we have selected unlimited in Number of values in Source field settings, we can keep adding as many items as we need, just by clicking the Add another item button. Also, it provides the drag-and-drop functionality for these values to rearrange the order.
14. Now we can enter the title and the body of the content, for example, we can enter "Chocolate Cake Recipe Tip" for the Title, and for the Body we can enter:
"Did you know that when a chocolate cake recipe says to 'grease a cake pan and dust it with flour', you can substitute unsweetened cocoa powder for the flour? Simply butter the cake pan then spoon in a heaping spoonful of cocoa powder, then shake the pan to distribute the cocoa over the bottom and sides of the pan."
[ 69 ]
Multiple Value Fields
So it will look like the following screenshot:
[ 70 ]
Chapter 3
15. Click Save to store the values. The final result will be displayed as in the following screenshot:
As you can see, the Source field will output the URL links that we entered, which can now output multiple values on the page using the source field.
What just happened? We have enabled the multiple value option for the Source field in the Cooking Tip content type. The Source field was set to only allow a single value to be entered, even though we might have liked to enter more than one value. There was no possibility to do this except by entering all the different sources one after the other in just one field but this could confuse the users. The good thing about the Field module is that it can accommodate these requirements. We can easily enable the option in the field administration page without any programming knowledge. Not only that, the Field module provides an elegant way to add items, we only need to click the Add another item button, and we can add more items as often as we want. Once we have saved the values, it will automatically output the entered values to the webpage.
[ 71 ]
Multiple Value Fields
Pop quiz – multiple values in fields 1. Which of the following statements is not true? a. A field cannot have more than five values. b. A field can have unlimited values. c. A field can have more than 99 values. 2. We have entered data into a field that allows two values as input. Later on if we want to change the field to a single value field, does it still output two values on the page? a. Yes b. No
Adding Boolean fields In Drupal 7, the Field module allows us to add a Boolean field type to a content type, which was not possible in Drupal 6 or earlier versions. Although Drupal 6 or earlier could achieve the same result by using different methodology, the Field module provides a simple and elegant way, which makes the process easier and makes more sense to Drupal users.
Time for action – adding a Boolean field In this section, we will add a Tip owner field using the Boolean field type to the Cooking Tip content type. Follow these steps:
1.
Click the Structure link on the administration menu at the top of the page.
2.
Click the Content types link, and then click the Manage fields link that is on the Cooking Tip row.
3.
Locate the Add new field table row, and enter "Tip owner" to the Label field, and then enter "tip_owner" into the Field name field, and select Boolean to be the type of data, and select Single on/off checkbox as the widget. And finally click the Save button at the bottom of the page to store the entered values. [ 72 ]
Chapter 3
4.
It will show a new window, where there is an On value field and an Off value field. In this case, we enter "My own tip" in the On value field, and enter "It's not my own tip" in the Off value field. Click the Save field settings button at the bottom of the page.
5.
We will leave the other values as the default. Go straight down to the bottom of the page, and click the Save settings button.
6.
Drupal will display a message saying the Tip owner field configuration is saved. But we will not see any major change on this page. We need to go to the Create content administration page to see the new option that is available to the Cooking Tip content type.
7.
Click the Add content link in the administration menu at the top of the page. Then click the Cooking tip link to add new Cooking Tip content.
[ 73 ]
Multiple Value Fields
8.
There is a My own tip checkbox at the bottom of the page, just below the source field, as shown in the following screenshot:
9.
Users or authors can now check or uncheck this checkbox to indicate the ownership of a cooking tip. We check the My own tip checkbox, and click Save. The output will be displayed as in the following screenshot. It will output the On value we entered.
10. If we uncheck the My own tip checkbox, and click Save, it will output the Off value we entered on the page.
What just happened? We have added a Tip owner field using the Boolean field type to the Cooking Tip content type. We use this field to indicate whether the person who posts this tip is actually the owner of the cooking tip. In this way users who create a cooking tip can check or uncheck the Tip owner field to indicate they are the owner of the cooking tip or not.
[ 74 ]
Chapter 3
The Boolean field provides two entries that we need to fill in: one is the On value field, the other is the Off value field. If we are unsure what values we should enter for these fields, we can consider that the On value field represents the value of true or yes, and the Off value field represents false or no.
Pop quiz – understanding the Boolean field 1. Can we enter more than three values in a Boolean field? a. Yes b. No 2. Which of the following statements is true? a. If we uncheck a Boolean checkbox, it will not display any value on the page. b. If we uncheck a Boolean checkbox, it will display the Off value on the page. c. If we uncheck a Boolean checkbox, it will only display the value to the owner of the content.
Setting default values The Field module provides an option to set a default value for a field. If we set a default value to a field, users will not necessarily need to fill in the field, the field will be filled with a default value. We will set a default value for the Tip owner field that we just created.
Time for action – setting default values In this section, we will set a default value to the Tip owner field, which will be checked by default. Follow these steps:
1.
Click the Structure link on the administration menu at the top of the page.
2.
Click the Content type link, and then manage fields on the Cooking Tip row in the table:
[ 75 ]
Multiple Value Fields
3.
Locate the Tip owner field row in the table, and then click the edit link:
4.
After clicking the edit link, it will direct us to the Tip owner field administration page. When we go to the middle of the page, we will find a heading called DEFAULT VALUE, there is a checkbox with a label called My own tip, which is the On value we entered.
5.
We check this checkbox to set My own tip as the default value of the Tip owner field.
6.
Then click the Save settings button at the bottom of the page, which will redirect us back to the Manage fields administration page.
7.
In order to see the configuration we created, we can add content using the Cooking Tip content type, so we click the Add content link on the administration menu at the top of the page, and then click the Cooking Tip link to create new content. [ 76 ]
Chapter 3
8.
Locate the Tip owner field, which is positioned just below the source field. See the following screenshot if you cannot find it:
9.
As you can see, the My own tip checkbox is now automatically checked by default. If anyone adds new content using the Cooking Tip content type, the Tip owner field will be set to the On value, which means S is set by default.
What just happened? We have set My own tip as the default value for the Tip owner field for the Cooking Tip content type. The default value option can be very useful for improving the usability of a website. If some of the values are used frequently by users, we can use those values to pre-fill those fields, thus making the process of completing the form much easier and more enjoyable. Normally, we can enter a hint message in the Help text field to let users know what they need to enter for a field. Another way of using the default value is to set a hint message. For a compact form design, we can hide field labels, and overlay the field labels over the fields. Normally, we have to use JavaScript to achieve this result. But there is another way that we can do that without JavaScript, we can pre-fill the fields using the default value. For example, we can set a message "Address" to an address text field as the default value. The users will easily recognize what they need to enter in the field.
Pop quiz – setting default values 1. Which of the following statements is true? a. Only Boolean fields can set the default value. b. Only text fields can set the default value. c. Almost all field types can set the default value.
[ 77 ]
Multiple Value Fields
Adding list fields We have learned how the Boolean field type works in Drupal, it can set one of two values, true/yes/1 or false/no/0. What if we need to create a field to have a selection list? For example, we would like to create a list of options, with which the users can give a rating to the post. The list should have Best, Good, Normal, Bad, or Very Bad as options. The users can select one of these options to vote. In order to create something like that, the list module provides us a list field type to create a selection list.
Time for action – adding list fields In this section, we will create a difficulty level field using the list field type for the Recipe content type. Follow these steps:
1.
Click the Structure link on the administration menu at the top of the page:
2.
Click the Content type link, and then click manage fields on the Recipe row in the table.
3.
Locate the Add new field table row, enter "Difficulty" in the Label field, and then enter "difficulty" in the Field name field. We then select List (text) to be the type of data, and select Check boxes/radio buttons as the widget. Finally click the Save button at the bottom of the page to store the value.
[ 78 ]
Chapter 3
4.
This will direct us to the Field settings administration page. This page allows us to enter a list of values, which will generate a selection list based on these values. There is a text area field called Allowed values list at the center of the page, we enter "Advanced, Intermediate, Normal, Easy, Super Easy" into this field, and make sure we enter one value per line, otherwise it will not work as expected. If you are not so sure, please refer to the following screenshot. After entering all the values, we can click the Save field settings button to store the values on this page.
[ 79 ]
Multiple Value Fields
5.
This will display a message saying the Difficulty field settings are updated. This page is similar to the other field settings page where we can set the Label, enter Help text, and set the Default value of the field, except the bottom part of the page is a little bit different from the others.
6.
The bottom part of the page is the same as the previous screen, where we can enter values into the Allow values list text area field. We can also set the number of values for this field, but for now, we just leave it as the default. Click the Save settings button to store the values.
[ 80 ]
Chapter 3
7.
This will redirect us back to the Manage fields administration page as shown in the following screenshot:
[ 81 ]
Multiple Value Fields
8.
Next, we can create content by clicking the Add content link on the administration menu at the top of the page, and then by clicking the Recipe link:
9.
We will find the Difficulty field at the bottom of the page. The values listed here are the values we entered in the Allowed values list. The order of the values is displayed according to the order of the values we entered.
10. Select Intermediate in the Difficulty field. Enter anything in the Title and Body
fields, and click Save. The output of the Difficulty field will look like the following screenshot. That will only display the selected value, the other values in the selection list will be hidden.
What just happened? We have added a Difficulty field using the list field type to the Recipe content type. The list field type can be used to create quizzes, questionnaires, support forms, and so on. The selection list is one of the most important elements to online forms and applications. The Field module provides the facility to easily create a selection list without writing any code. It makes creating a custom set of lists very simple, but, at the same time, it won't lose its functionality and power because of the Fields settings administration page which provides us all the flexibility to create our own list of values for selection lists. [ 82 ]
Chapter 3
Furthermore, the Allowed values in the list on the fields settings administration page have to be entered one value per line. If we enter multiple values on one line, it will treat it like a single value. The format of the value is in key|label format, the key value will be stored in the database; the label value is optional. For example, if we enter 1|Good, 2|Very good, and 3|Excellent, 1, 2, and 3 are the keys, and Good, Very good and Excellent are the labels. So 1, 2, and 3 will be stored in the database, and Good, Very good, and Excellent will be displayed on the web page, and they won't be stored in the database. If we don't enter the label, and we only enter the key, the key will be used as the label, and the key will be stored in the database. For example, in this case, Advanced, Intermediate, Normal, Easy, and Super Easy will be used as key and label, and these values will be stored in the database.
Pop quiz – adding list fields 1. Can we enter the key values without entering the label values in the Allowed value list text area field? a. Yes b. No 2. Which of the following statements is true? a. We need contributed modules to create selection lists/list fields. b. The list field is part of the Drupal 7 core. c. We cannot have more than two values in the list fields.
Multiple value widgets We have learned how to add multiple values to fields, and we have also learned how to create Boolean fields and list fields. There is an interaction between the multiple value fields and the multiple value widgets. We will learn how that works in the next section: Time for action – changing the multiple value widget
[ 83 ]
Multiple Value Fields
In this section, we will change the checkboxes/radio buttons widget to the select list widget. Follow these steps
1.
Click the Structure link on the administration menu at the top of the page:
2.
Click the Content types link, and then click manage fields on the Recipe row in the table.
3.
Locate the Difficulty field row in the table, and click the Check boxes/radio buttons link that is in the widget column:
4.
After clicking the Check boxes/radio buttons link, it will show us the CHANGE WIDGET administration page. Now we can click on the select list to choose Select list as the widget we want for the Difficulty field. This is a cool new feature added in Drupal 7. Earlier, in Drupal 6, if we wanted to edit any field or widget settings we would have had to configure the entire field settings. Now we can click the Continue button at the bottom of the page.
[ 84 ]
Chapter 3
5.
It will redirect us back to the Manage fields administration page. You can see the widget is changed from Check boxes/ radio buttons to Select list in the Difficulty row:
6.
Next, we can click the Add content link on the administration menu at the top of the page, and then click the Recipe link.
7.
Look for the Difficulty field on the page. You will see the field widget is now changed to select list. We can now click on the select list to select one of the values in the select list to set the difficulty of the recipe.
[ 85 ]
Multiple Value Fields
What just happened? We have demonstrated how to change the Check boxes/radio buttons widget into a Select list widget. The Field widget type can be changed at any time, which can be done easily through the Field UI.
Time for action – changing the number of the values In this section, we will change the number of the values for the Select list widget. Follow these steps:
1.
Click the Structure link on the administration menu at the top of the page:
2.
Click the Content types link, and then click manage fields on the Recipe row in the table:
3.
Locate the Difficulty field row in the table, and click the edit link that is in the widget column.
4.
Locate the DIFFICULTY FIELD SETTINGS option. There is a select list where we set the number of values we can enter for this field. The current value is 1, now we click on the select list to select Unlimited as the value for this field. After that, we click the Save Settings button to store the settings.
[ 86 ]
Chapter 3
5.
In order to see the update, we can click the Add content link on the administration menu at the top of the page, and then click the Recipe link.
6.
Locate the Difficulty field on the page; you will see the select list is changed, and we can select multiple values on the select list.
What just happened? We have learned how to change the number of values for the select list widget. Single or multiple values will affect how widgets interact with user inputs. As we can see, once the Difficulty field was changed to unlimited values, users could select multiple values on the select list. So, verification is needed to make sure we choose the correct widgets and values; otherwise, the site will collect wrong information due to the inappropriate field settings.
Time for action – checkboxes/radio buttons widget with multiple values In this section, we will change the select list widget back to the check boxes/radio buttons widget. Follow these steps:
1.
Click the Structure link on the administration menu at the top of the page:
[ 87 ]
Multiple Value Fields
2.
Click the Content types link, and then click manage fields on the Recipe row in the table:
3.
Locate the Difficulty field row in the table, and click the Check boxes/radio buttons link that is in the widget column:
4.
Select Check boxes/radio buttons on the select list, and click on the Continue button to save the change.
5.
Now, we can click the Add content link on the administration menu at the top of the page, and then click the Recipe link.
6.
Locate the Difficulty field on the page; the radio buttons are now changed to checkboxes. We can select multiple values on these checkboxes now.
[ 88 ]
Chapter 3
What just happened? We have demonstrated how multiple values affect the output of the checkboxes/radio buttons widget. So far we have changed the widgets to different multiple value widgets, and we have changed the number of values we could enter for each widget. We have changed the number of allowed values to unlimited and also the type of widget we used to collect and display the data, keeping only the field type the same. We thus see the widget is smart enough to change its behavior based on the number of allowed values. As such, radio buttons change to checkboxes in the case of the Checkboxes/ radio buttons widget, and the single select list element on the form changes to multiple select in the case of the Select list widget. It is completely up to us to decide when or what is the best time to use those widgets. We have all the control to pick the right widgets and values to solve our particular problem.
Pop quiz – understanding multiple value widgets 1. Widget type can determine the number of values a field can enter. a. True b. False 2. The number of values users can enter for a field will affect the type of widget that will be used. a. True b. False 3. Currently the widget type is using the Checkboxes/Radio buttons widget, and the number of values is set to unlimited. If the widget type is changed to select the list widget, does the number of values still remain unlimited? a. True b. False
Have a go hero – creating multiple value fields With what we have learned so far, it is time for a challenge. We can use what we have learned to create a multiple value field called a Cooking tip rating for the Cooking Tip content type. Site owners can give a rating to each cooking tip, so they can sort out the cooking tips into different levels and categories for later use. [ 89 ]
Multiple Value Fields
Summary In this chapter, we learned how to enable multiple values for fields, setting up the number of values for fields. We learned how to set default values for fields, such that values would be automatically set for fields when creating new content. After that, we learned how to create list fields, which gave us the ability to create selection lists easily. Following that, we learned the relationship between the number of values in a field and the widget types. In the next chapter, we will talk about what taxonomy is in Drupal, and the changes in Drupal 7. We will learn how to create custom vocabularies, how to properly configure vocabularies, add terms to vocabularies, add fields to vocabularies, and finally how to add term references to content types. We will learn all these topics in the next chapter.
[ 90 ]
4
Taxonomy Taxonomy is one of the most powerful features available in Drupal. The portion responsible for handling taxonomy has been redesigned and significantly improved in Drupal 7. The workflow necessary for categorizing content has been simplified and taxonomy is now fully integrated with content types and fields. In this chapter you will learn how to create taxonomy vocabularies and terms, how to add fields to vocabularies, and term references to content types.
In this chapter, we shall learn: What is taxonomy? Creating vocabularies Adding terms to vocabularies Adding term references to content types Categorizing content using taxonomy Adding fields to vocabularies
What is taxonomy? In scientific terms, taxonomy is the practice and science of classification according to a predetermined system. In Drupal terms, it is a system to categorize content in a Drupal website. One great example for where we need categorization is the yummy recipes website we are building.
Taxonomy
Suppose Drupal doesn't provide the functionality of taxonomy, and the website has grown to contain more than a thousand recipes, since it is a very popular website and the site owners and users keep posting their recipes to the website every day. That's all fine and great. But what if people would like to peruse all the French cuisine recipes on the website? Yes, they could do this but they would have to keep browsing through each page picking up only the French cuisine recipe posts. That is a really time consuming task and this process might drive our users and potential customers away. However, without the ability to categorize content there would be no better way of doing it. Sometimes we would like to find all the items of a category. In our case, it is easier for us to find out more useful information in this fashion. For instance, we would like to find out what other types of cooking methods are there because we've been having too much grill lately and would like to learn to prepare food using other methods. If we find a category name called cooking method, we should be able to find out the other cooking methods under the cooking method category. For instance: Cooking method Grill Fry Roast Stir-fry ... (term) Taxonomy provides all the tools for us to solve the above problems. This makes the website more user-friendly, because users can find their information easily and quickly. Managing content and organizing content is also much easier for site administrators. This is a win-win situation for both ends. In Drupal, taxonomy is made up of two components, vocabulary and term. The vocabulary is a list of multiple related terms. The term is used to distinctly describe content. Simply put, we can think of the vocabulary as a category, the term as a tag. To visualize it better, let's take a look at the type of cooking method example we talked about before. The following is a list of cooking methods and a list of cuisine type. Let's use taxonomy in the following example: Cooking method (vocabulary) Grill (term) Fry (term) Roast (term) Stir-fry (term) … (term) [ 92 ]
Chapter 4
Cuisine type (vocabulary) American (term) Chinese (term) Indian (term) Japanese (term) … (term) Without further explanation, we should have some idea of what's going on just by looking at the preceding lists. In this example, we created a vocabulary that is the type of Cooking method, and assigned terms to that vocabulary are Grill, Fry, Roast, and Stir-fry. In the other example, the Cuisine type is a vocabulary, and American, Chinese, Indian, and Japanese are the terms assigned to this Cuisine type vocabulary. The concept of taxonomy, vocabulary, and term might sound complicated, but when we look at the example, they are very normal to us, because this is the way we find things. One more real-life example: if we would like to buy a drill in a hardware warehouse, we usually look for a sign to see the type of product that belongs to that section in the warehouse. If the sign says tools and hardware in a section, we will go to that section directly to find our tools. In this case, tools and hardware can be a vocabulary, and sanders, welders, and drills can be the terms. Now we should have grasped the basic ideas of what taxonomy is in Drupal. We will create taxonomy vocabularies and terms in Drupal in the next section, and things will get easier because our foundation is already built.
Creating vocabularies The first step when using taxonomy in Drupal is to create vocabularies. We cannot create terms unless we create vocabularies first. In the yummy recipes website, the client would like to have the functionality to assign Recipe and Cooking Tip types to recipes and cooking tips, so users can easily find related recipes and cooking tips on the website. In other words, we will use Recipe Category vocabulary to categorize recipes and Cooking Tip Category vocabulary to categorize cooking tips.
[ 93 ]
Taxonomy
Time for action – creating the Cooking Tip Category vocabulary In this section, we will create two vocabularies, one is the Cooking Tip Category, and the other is the Recipe Category. Follow these steps:
1.
Click on the Structure link in the administration menu at the top of the page:
2.
We will see a list of options, and then we click on the Taxonomy link:
3.
On the Taxonomy administration page, there is an introductory text that explains what taxonomy and terms are. Also, by default, Tags vocabulary is created by Drupal as a generic vocabulary to group content into categories. To create a new vocabulary we need to click on the Add vocabulary link:
[ 94 ]
Chapter 4
4.
On this page, we can enter the name of the vocabulary and the description of the vocabulary. In the Name field, we enter "Cooking Tip Category", and in the Description field, we enter "A vocabulary to categorize cooking tips". After entering both fields, click the Save button.
5.
It will display a message saying the cooking tip category vocabulary is successfully created. On the same page, the taxonomy administration page, we will see the Cooking Tip Category has now appeared in the table:
What just happened? We have created the Cooking Tip Category vocabulary using taxonomy in Drupal, and we will use the same technique we have learnt here to create the Recipe Category vocabulary for the next section.
[ 95 ]
Taxonomy
Time for action – creating the Recipe Category vocabulary This time we will create the Recipe Category vocabulary. Follow these steps:
1.
Click on the Structure link in the administration menu at the top of the page:
2.
Then we click on the Taxonomy link to go to the taxonomy administration page.
3.
On this page, we click on the Add vocabulary link. In the Name field, we will enter "Recipe Category". In the Description field, we will enter "A vocabulary to categorize recipes". Once we have entered values in both fields, click Save to store the values in Drupal:
[ 96 ]
Chapter 4
4.
The new vocabulary Recipe Category is created. We will see the recipe category is now in the table:
What just happened? We have created the Cooking Tip Category vocabulary and the Recipe Category vocabulary using taxonomy in Drupal. The first step of using taxonomy is to create vocabularies before we can begin adding terms to vocabularies. In this section, the vocabularies are created. Although we may not see any major differences at this stage, this step is critical for the process of using taxonomy.
Pop quiz – creating vocabularies 1. Can we add terms before creating vocabularies? a. Yes b. No 2. What is the vocabulary created by default in Drupal? a. Cooking tip category b. Tags c. Type of Food
[ 97 ]
Taxonomy
Adding terms to vocabularies After creating vocabularies, the next step is to create terms that are related to the vocabularies. In this case, we can create related terms such as barbecue, cake, and curry to the Cooking Tip Category. For the Recipe Category, we can sort it by the type of cuisine. We can assign American, Chinese, Japanese, and Indian to the Recipe Category.
Time for action – adding terms to Cooking Tip Category In this section, we will create terms to Cooking Tip Category vocabulary. Follow these steps:
1.
Click on the Structure link in the administration menu at the top of the page.
2.
Then we click on the Taxonomy link to go to the taxonomy administration page:
3.
In order to add terms to the Cooking Tip Category, click on the add terms link as shown in the following screenshot:
[ 98 ]
Chapter 4
4.
On this page, in the Name field, we will enter "Barbecue". We can enter "A term used to categorize content related to cooking tip." in the Description field. We leave the other field as the default, and click the Save button at the bottom of the page:
[ 99 ]
Taxonomy
5.
Drupal will redirect us back to the same page with a message saying the term Barbecue is created. On this page, we can keep adding terms to the Cooking Tip Category. This time we enter "Cake" in the Name field, and enter "A term used to categorize content related to cooking tip" in the Description field. Once we have entered the values in both fields, click Save.
[ 100 ]
Chapter 4
6.
In order to see the complete list of terms for the vocabulary, we go back to the taxonomy administration page, click the list terms link as shown in the following screenshot:
7.
This page will show the entire list of terms for the vocabulary, we can also click the edit link to update the term or delete the term:
[ 101 ]
Taxonomy
What just happened? We have added terms to the Cooking Tip Category vocabulary. Once vocabularies are created, the next step is to add associated terms to the vocabularies. We usually add more than one term to a vocabulary. Drupal provides a user interface that allow us to quickly add terms to a vocabulary. After adding a term to a vocabulary, Drupal will redirect us to the same page to add other terms to the vocabulary, so we will not need to click the Structure | Taxonomy | add terms link. Drupal makes the site administrator's life easier, because it simplifies the process of adding terms.
Pop quiz – adding terms to vocabularies 1. Which of the following statements is true? a. After adding a term, Drupal directs us to the homepage. b. After adding a term, Drupal directs us to the Taxonomy administration page. c. After adding a term, Drupal directs us to the Add terms administration page. 2. Using Drupal's standard interface can we add multiple terms at once? a. Yes b. No
Have a go hero – adding terms to Recipe Category It's time for a little challenge. We have created terms to the Cooking Tip Category vocabulary. We can use the same method we have learned here to add terms to the Recipe Category vocabulary. We can add terms such as American, Chinese, Indian, Japanese, and Thai to the Recipe Category vocabulary.
Adding term references to content types Vocabularies and terms are created. The next step is to assign a vocabulary to a content type, so the content type can use the vocabulary to categorize content. In Drupal 7, assigning vocabularies to content types works a little bit different from previous versions of Drupal. We have to designate a field inside a content type to hold such information as to which vocabulary we can use to categorize instances of the aforementioned content type. The field type we need to use for this is called term reference.
[ 102 ]
Chapter 4
Time for action – adding a term reference field to the Cooking Tip content type In this section, we will create a term reference field in the Cooking Tip content type, and we will use the Cooking Tip Category vocabulary we created for the term reference.
1.
Click on the Structure link in the administration menu at the top of the page.
2.
It will show a list of options. Click on the Content types link as shown in the following screenshot:
[ 103 ]
Taxonomy
3.
The Content type administration page shows all the existing content types in the table. We click on the manage fields link, because we would like to add a new field in the Cooking Tip content type:
4.
This page displays the completed list of fields in the Cooking Tip content type. At the bottom of the page, we locate the section Add new field, and we enter "Cooking Tip Category" in the Label field, enter "cooking_tip_category" in the Field name field. In the next column, the field type column, we choose Term reference in the select list, and for the widget type we choose "Select list". After entering all the values, we click Save to proceed to the next page.
[ 104 ]
Chapter 4
5.
On this page, we can choose the vocabulary that provides the source for the list of terms that will show in the select list. In this case, we choose "Cooking Tip Category" in the select list, and click Save.
6.
After clicking the Save field settings, the next screen will display a message to say the Cooking Tip Category field settings have been updated.
[ 105 ]
Taxonomy
7.
The following page allows us to change the label name, specify whether it is a required field or not, insert help text, specify a default value, specify how many values you can choose, and change the vocabulary that provides the source for the list of terms that will show in the select list. (We have learnt all about these field level settings in Chapter 2 and Chapter 3.)
8.
We will leave all the other values as the default. Click on the Save settings button at the bottom of the page to store the entered values.
[ 106 ]
Chapter 4
9.
Drupal will direct us to the manage fields administration page with a message saying the Cooking Tip category configuration is saved, as shown in the following screenshot:
What just happened? We have created a term reference field in the Cooking Tip content type, and we chose the vocabulary that provides the source for the list of terms that will show in the select list. In order to use the taxonomy vocabularies and terms in content types, we have to assign the vocabulary to the content type. By assigning the vocabulary to the content type, we have to create a term reference field in the content type, and specify the vocabulary that could provide the source for the list of terms that will show in the field widget, in this case, the select list.
Pop quiz – adding term references to content types 1. Which of the following statements is true? a. Select list widget has to be used for term reference fields. b. Term reference fields can be created on the taxonomy administration page. c. Term reference fields have to be used when using taxonomy to categorize content. 2. If we already created a term reference field, and specified a vocabulary as the source, can we change the current term reference field to use a different vocabulary as the source? a. Yes b. No
[ 107 ]
Taxonomy
Have a go hero – adding a term reference to the Recipe content type It is time for a challenge. Use the same method we have learned here in this section to create a term reference field in the Recipe content type, and choose the Recipe Category vocabulary to provide the source for the list of terms that will show in the select list.
Categorizing content using taxonomy It is time to use what we have created to categorize content. The term reference field we created will provide us with a select list that allows us to select taxonomy terms to categorize the content.
Time for action – categorizing Cooking Tip Content using taxonomy In this section, we will create a new cooking tip and use taxonomy to categorize the content.
1.
Click the Add content link on the administration menu at the top of the page:
2.
Click the Cooking Tip link to add new content using the Cooking Tip content type.
[ 108 ]
Chapter 4
3.
We can enter "Marb Barbecue Tips" in the Title field. Enter "Whenever barbecuing, use tongs to turn the meat. A fork should never be used. It will punch holes in the flesh and allow the natural juices to escape and lose flavor and become chewy." in the Body field. Then enter "http://www.cookingtipexample.com" in the Source field.
4.
We will see a new select list that has appeared at the bottom of the page, namely Cooking Tip Category. Now we can select a term from the list of terms we created to categorize this content. In this case, we select Barbecue, and then click on the Save button at the bottom of the page.
5.
After clicking the Save button, Drupal will direct us to the full content view where we will see the output of the content we just entered.
[ 109 ]
Taxonomy
6.
We will notice that the Cooking Tip Category label and the Barbecue hyperlink are shown on the page. So what we have entered and selected will affect how the page renders the result.
7.
In this case, we click on the Barbecue link that is next to the Cooking Tip Category label:
8.
After clicking the Barbecue link, it will display the Barbecue taxonomy term page. This page will show all content that used the Barbecue taxonomy term. If we have more content, and we selected the Barbecue taxonomy term in the Cooking Tip Category select list, all that content will be displayed on this page.
[ 110 ]
Chapter 4
What just happened? We have categorized a Cooking Tip content type using a taxonomy term. To categorize content using taxonomy in Drupal, we have to specify a term in a vocabulary. In our case, we have selected Barbecue (a term) from the Cooking Tip Category (a vocabulary) select list (a field widget). As you've seen, Drupal will render taxonomy term pages automatically, which will show all of the content that is categorized under the selected terms. Drupal also automatically creates an RSS feed for all content categorized under a certain term.
[ 111 ]
Taxonomy
If we click the RSS feed icon it will render a list of content based on the selected terms, as in the following screenshot. It depends on your web browser. Some web browsers may not support rendering RSS feeds, which may require users to install RSS reader software to read RSS feeds properly.
Pop quiz – categorizing content using taxonomy 1. Which of the following statements is true? a. Drupal will not render taxonomy term pages automatically. b. Drupal will render taxonomy term pages automatically. c. Drupal will render vocabulary pages automatically. 2. Drupal creates an RSS feed automatically for all of the content that is related to the selected terms. Is it true or false? a. True b. False [ 112 ]
Chapter 4
Have a go hero – categorizing content using the Recipe Category vocabulary It is time for a challenge. Use the same method we have learnt here in this section to create three recipes using the Recipe content type, and specify any of the terms you have created in the Recipe Category vocabulary. After creating the content, try to click on the terms and RSS feed icons, and see what Drupal will generate for you.
Adding fields to vocabularies One of the most powerful and useful features in Drupal 7 is taxonomy, it is now fully integrated with fields. We can create, update, share, and delete fields in taxonomy. That was not possible in Drupal 6 or earlier. We could achieve the same result by using contributed modules or some hacking, though none as elegant as what Drupal 7 provides for us out of the box, because all these features are built into Drupal 7 core.
Time for action – adding a field to the Cooking Tip Category vocabulary We will add an introduction text field to the Cooking Tip Category vocabulary. People will see the introduction message when they are on Taxonomy term pages. Follow these steps:
1.
Click on the Structure link in the administration menu at the top of the page:
2.
Then we click on the Taxonomy link to go to the taxonomy administration page.
[ 113 ]
Taxonomy
3.
On the taxonomy administration page, we click on the edit vocabulary link as shown in the following screenshot:
4.
There are tabs on the right of the page. We click on the MANAGE FIELDS tab, and ignore the other tabs for now:
[ 114 ]
Chapter 4
5.
This page is similar to the Manage fields administration page in the Content types section. In the Label field, we enter "Introduction", in the Field name field, we enter "intro", the field type field we select "Long text" as the field, and then we select the Text area (multiple rows) widget for the last field. After entering all the values, we can click on the Save button at the bottom of the page.
6.
Click on the Save field settings button on the next screen.
7.
On the following page, we leave the other values as default, and click on the Save settings button to store the settings.
[ 115 ]
Taxonomy
8.
We go back to the Barbecue taxonomy term page; we will not see any difference because we haven't entered any data to the Introduction field. Now we can click on the Edit tab on the page to enter values to the Introduction field.
9.
At the bottom of the page, we will see a new text area field in which we can enter introduction text. In this example, we will enter "This page will show all the cooking tips based on the term you have selected." in the text area field, and then click on the Save button at the bottom of the page.
10. Drupal will redirect us to the same page, but we would like to see the output of the page, so we click on the View tab to render the result of the page.
[ 116 ]
Chapter 4
11. Now we will see the introduction text that has appeared on the Barbecue taxonomy term page.
What just happened? We have created a long text field for the Cooking Tip Category vocabulary. Adding fields to vocabularies is now possible in Drupal 7. We can easily add any field to taxonomy vocabulary terms, making it possible for each taxonomy term to contain its own information. It may not become instantly apparent but this is a very powerful feature lacking in previous versions of Drupal. It allows us to enrich taxonomy terms with additional information such as explanations, descriptions, or logos. A very good example of this is if we would be categorizing products by brand. Then on each brand vocabulary term we could store related information such as a link to a company website or indeed a brand logo.
Pop quiz – adding fields to vocabularies 1. We cannot reuse fields we created in content types for vocabularies. a. True b. False 2. We have entered a value to the introduction field for the Barbecue term; do the other terms display the same value on the taxonomy page? a. Yes b. No
[ 117 ]
Taxonomy
Have a go hero – creating fields for content types and comments With what we have learned so far, it's time for a challenge. We can use the same methods we have learned to create more fields in other vocabularies we have created. Try to enter values to different fields in different terms, and see what results you get
Summary In this chapter, we have learned what taxonomy is, and we have learned the difference between taxonomy terms and taxonomy vocabularies in Drupal. After that, we learned how to create vocabularies and add terms to vocabularies using the Drupal web user interface. Then, we learned how to add term references to content types, and to categorize content using the term reference we created. Finally, we examined how to add fields to vocabulary terms, and explored its potential use. The next chapter will be a fun chapter because we will learn how to attach files and images to content using the File and Image fields in Drupal, which makes the current text-only website more fun and eye-catching.
[ 118 ]
5
File and Image Fields Images play an important role in any website. Imagine an e-commerce website like Amazon without product images on product pages, a Facebook-like site where users cannot upload and share images with friends. The presence of images and the ease with which they can be handled has become essential in most of today's websites. Drupal 6 and earlier versions required the use of contributed modules to achieve effective file and image handling. With its well-known file and image add-on modules for CCK, Drupal could achieve many file and image handling tasks. The good news is that in Drupal 7, to get basic file and image handling functionality, you do not need to go anywhere further than Drupal core. You get image resizing, image styles, and effects just by installing Drupal. The improved usability and simplified interface of the new image system will undoubtedly be one of those features that will be used by almost every site built in Drupal 7.
In this chapter, we shall learn about: Adding and configuring file fields to content types Using file fields Adding image fields to content types Configuring image field settings Creating custom image styles
File and Image Fields
Adding and configuring file fields to content types There are many cases where we need to attach files to website content. For instance, a restaurant owner might like to upload their latest menu in PDF format to their website, or a financial institution would like to upload a new product catalog so customers can download and print out the catalog if they need it. The File module is built into the Drupal 7 core, which provides us with the ability to attach files to content easily, to decide the attachment display format, and also to manage file locations. Furthermore, the File module is integrated with fields and provides a file field type, so we can easily attach files to content using the already discussed field system making the process of managing files much more streamlined.
Time for action – adding and configuring a file field to the Recipe content type In this section, we will add a file field to the Recipe content type, which will allow files to be attached to Recipe content. Follow these steps:
1.
Click on the Structure link in the administration menu at the top of the page.
2.
The following page will display a list of options. Click the Content types link to go to the Content types administration page.
[ 120 ]
Chapter 5
3.
Since we want to add a file field to the Recipe content type, we will click the manage fields link on the Recipe row as shown in the following screenshot:
4.
This page will display the existing fields of the Recipe content type. In the Label field enter "File", and in the Field name field enter "file". In the field type select list select File as the field type, the field widget will be automatically switched to File as the field widget. After the values are entered, click Save.
[ 121 ]
File and Image Fields
5.
A new window will pop up which provides the field settings for the file field that we are creating. There are two checkboxes, and we will enable both these checkboxes. The last radio button option will be selected by default. Then click the Save field settings button at the bottom of the page.
6.
We clicked the Save field settings button to store the values for the file field settings that we selected. After that, it will direct us to the file field settings administration page, as in the following screenshot:
[ 122 ]
Chapter 5
[ 123 ]
File and Image Fields
7.
We can leave the Label field as default as it will be filled automatically with the value we entered previously. We will also leave the Required field as default, because we do not want to force users to attach files to every recipe. In the Help text field, we can enter "Attach files to this recipe".
8.
In the Allowed file extensions section, we can enter the file extensions that are allowed to be uploaded. In this case, we will enter "txt, pdf, zip". In the File directory section, we can enter the name of a subdirectory that will store the uploaded files, and in this case, we will enter "recipe_files":
9.
In the Maximum upload size section, we can enter a value to limit the file size when uploading files. We will enter "2MB" in this field. The Enable Description field checkbox allows users to enter a description about the uploaded files. In this case, we will enable this option, because we would like users to enter a description of the uploaded files.
[ 124 ]
Chapter 5
10. In the Progress indicator section, we can select which indicator will be used when uploading files. We select Throbber as the progress indicator for this field.
11. You will notice the bottom part of the page is exactly same as in the previous
section. We can ignore the bottom part and click on the Save settings button to store all the values we have entered.
[ 125 ]
File and Image Fields
12. Drupal will direct us back to the manage fields administration page with a message saying we have successfully saved the configuration for the file field.
13. After creating the file field, the file field row will be added to the table. This table will display the details about the file field we just created.
What just happened? We have configured and added the file field for the Recipe content type. In this section, we created a file field for the Recipe content type; we entered all the essential values for the file field such as the field label and field type. When we clicked on Save for the file field, the Field Settings page let us configure additional settings for the file field. The first option Enable Display field will provide a checkbox on the content form so we can specify if the file name is displayed on the content page. The second option Files displayed by default will cause the checkbox to be checked by default. If neither option is checked, the filename will be displayed on the content page. The last option is to choose the upload destination; currently the public file option is selected by default. If we have configured the private file system path on the file system administration page, we will see a private file option available on this page, the private file system configuration will be covered later in this chapter. Moreover, be cautious when saving the field settings, because the settings apply to the file field everywhere it is used, and they affect the way data is stored in the database and cannot be changed once data has been created. The file field contains quite a lot of settings. The Label field, the Required field and the Help text field are the common settings for fields. The specified file field settings are Allowed file extensions, File directory, Maximum upload size, Enable Description field, and Progress indicator.
[ 126 ]
Chapter 5
The Allowed file extensions settings will affect the type of file users can upload. If we only enter a "txt" extension for this field, users can only upload text files to content. This is not a setting found too often because it makes for too many limitations for users. So, in this case, we entered the "txt, zip, pdf" file extensions to allow users to upload files with some of the more common extensions. In the File directory settings, we can enter the name of the subdirectory that will store the uploaded files. This field is optional, if we do not enter anything here, all the files will be stored in the sites/default/files directory by default. Setting up some constraints for uploading files is necessary, because we cannot allow users to upload files without limitation, they might upload a 20 GB video file to our server, which absolutely wastes our server resources and is very cost ineffective. The maximum upload size settings can be used to set up the allowed file size, which can effectively limit the file sizes that users can upload. When uploading files to the server, it would be better to have a progress indicator to present the status of file upload. Luckily, the file module already provides us with such a feature. It allows us to choose the type of progress indicator for the file field. There are two types of progress indicators that we can choose, Throbber and Bar with progress meter. The Progress indicator option will only be available if the appropriate PHP extensions, either APC or PECL, are enabled on the server. Otherwise the Progress indicator section is not visible and neither is the throbber or the bar option. Throbber will be used by default, which does not show the progress of file upload, but it saves more space on the form, and it will not need extra PHP configuration to make it work properly. Bar with progress meter can indicate the progress of file upload, but it will take more space on the form, and it is more complicated to set up. This is because we have to install extra PHP packages and extensions (installing APC or PECL), and we have to set up the PHP configurations (configuring PHP.ini) properly in order to make the Bar with progress meter indicator work.
Pop quiz – adding and configuring file field settings 1. How do we enable an option so that links to uploaded files are displayed automatically when viewing the content? a. Enable the Enable Display Field option. b. Disable the Enable Display Field option. c. We cannot do this in Drupal.
[ 127 ]
File and Image Fields
2. Which of the following statements is true? a. There is only one field widget available for the file field type. b. There are more than two field widgets available for the file field type. c. There is no field widget support in the file field type. 3. Can we limit the type of file being uploaded? a. Yes b. No 4. Which of the following statements is true? a. We need to install contributed modules that give us the ability to choose different types of progress indicators for file fields. b. We can enter a description of the uploaded file if we enable the Description field in the file field settings. c. We can rename the uploaded files if we configure such settings in the file field settings.
Have a go hero – adding and configuring a file field to the Cooking Tip content type It's time for a challenge. We have created a file field for the Recipe content type. We can use the same method we have learned here to add and configure a file field to the Cooking Tip content type. So the Cooking Tip content can provide files for people to download. You will need to make configurations so that users are allowed to upload PDF, TXT, ZIP, and DOC files, and limit the upload size to 2 MB.
Using file fields We have gone through all the steps for creating the file field, and now, it's time to use what we have created.
Time for action – using the file field In this section, we will make use of the file field when creating new Recipe content. Follow these steps:
1.
Click on the Add content link in the administration menu at the top of the page.
[ 128 ]
Chapter 5
2.
This page displays a list of the existing content types. Because we would like to add recipe content, we click on the Recipe link to create new content.
3.
On this page we can enter new recipe content. In the Title field, we enter "Shortbread Biscuits". In the Body field, we enter the recipe details as in the following screenshot, or for your convenience you can copy and paste the content from the content.txt file if you have downloaded the project files.
[ 129 ]
File and Image Fields
4.
There are radio buttons in the Difficulty section. We select Intermediate for this recipe, and we enter "Biscuits" in the Recipe Category field. If you have followed the book and have finished the exercises, these fields should already be created. If you have used different type of field widgets for the same fields, you can still select or check your options.
5.
We will see there is a new section called File. This section provides a file widget that allows us to browse and upload a file to the website. We click the Browse… button that will open a file browser; we can find a file through the file browser, and click open to select the file. It does not actually upload any file until we click the Upload button.
6.
After clicking the Upload button, it will upload the file you selected through the file browser, and we will see that the Throbber progress indicator is shown while uploading the file. After uploading the file, it will change the file field interface, and in the Description field, we enter "Shortbread Biscuits Recipe". Click the Save button at the bottom of the page to store all the values we entered.
[ 130 ]
Chapter 5
7.
Drupal directs us to the full content view of the new content, and it displays a message saying Recipe Shortbread Biscuits has been created successfully.
8.
In the full content view, we will see the output of the Title, Body, Difficulty, Recipe categories, and File fields as shown in the following screenshot. Users can now click on the file name link to download the file to their computer.
[ 131 ]
File and Image Fields
What just happened? We have learned how to use the file field when creating new content. We uploaded a file using the file field when creating new recipe content. When the file field is created for the Recipe content type, the existing recipe content allows you to attach files. If we navigate to one of our existing recipe contents, and click the Edit tab, we will see the file field is also available on the Edit page of the content. Which means, when we add a new field to a content type, the ability to attach files to the existing content is there, so it is not only applied to the new content. While uploading the file, we will see the progress indicator appear next to the Upload button. The type of progress indicator is based on what we selected on the file field settings administration page. Since we selected the throbber as the progress indicator, the throbber was shown while uploading the file. Perhaps we might not see the throbber clearly, if the file we uploaded was a small file. If we upload a bigger file, we can clearly see the throbber is running. After uploading the file, Drupal will change the file field user interface. It will display the file name of the uploaded file and show the file size of the uploaded file.
The Include file in display option allows us to select whether the file will be displayed in the content. If it is checked, the file will be displayed when people are viewing the content, otherwise it will be hidden. The Include file in display option is provided, because we have enabled this option in the file field settings administration page. If you remember, there are two options, one is Enable Display field, the other is Files displayed by default. That's the reason this option is provided and the Include file in display option is there and is enabled by default.
[ 132 ]
Chapter 5
Below the Include file in a display option, there is the Enable Description field, which is the option we configured in the file field settings administration page. We have enabled the description field, so the option is shown when creating or editing content. It is a good idea to enter a description of the uploaded file, otherwise it will use the file name as the description of the uploaded file. Sometimes this does not make much sense to people. If the file name of a file is 19228_epd.pdf, people will not understand what it is for.
Pop quiz – using the file field 1. Which of the following statements is true? a. The Description field is enabled by default b. The Description field is disabled by default c. The Description field is provided in file fields. 2. Can we hide the Include file in display option? a. Yes b. No
Have a go hero – adding a file field to the Cooking Tip content type It's time for a little challenge. We have uploaded a file using the file field when creating new recipe content. We can use the same method we have learned here to create new Cooking Tip content, and attach files to the Cooking Tip content. You can try different settings to see the differences between the options when attaching files.
Adding image fields to content types We have learned how to add file fields to content types. In this section, we will learn how to add image fields to content types so that we can attach images to our content.
[ 133 ]
File and Image Fields
Time for action – adding an image field to the Recipe content type In this section, we will add an image field to the Recipe content type. Follow these steps:
1.
Click on the Structure link in the administration menu at the top of the page.
2.
Click on the Content types link to go to the content types administration page.
3.
Click the manage fields link on the Recipe row as in the following screenshot, because we would like to add an image field to the recipe content type.
[ 134 ]
Chapter 5
4.
Locate the Add new field section. In the Label field enter "Image", and in the Field name field enter "image". In the field type select list, select "image" as the field type; the field widget will be automatically switched to select Image as the field widget. After the values are entered, click Save.
What just happened? We added an image field to the Recipe content type. The process of adding an image field to the Recipe content type is similar to the process of adding a file field to the Recipe content type, except that we selected image field as the field type and we selected image as the field widget. We will configure the image field in the next section.
Configuring image field settings We have already added the image field. In this section, we will configure the image field, learn how to configure the image field settings, and understand how they reflect to image outputs by using those settings.
[ 135 ]
File and Image Fields
Time for action – configuring an image field for the Recipe content type In this section, we will configure image field settings in the Recipe content type. Follow these steps:
1.
After clicking the Save button, Drupal will direct us to the next page, which provides the field settings for the image field. The Upload destination option is the same as the file field settings, which provide us an option to decide whether image files should be public or private. In our case, we select Public files. The last option is the Default image field. We will leave this option for now, and click on the Save field settings button to go to the next step.
[ 136 ]
Chapter 5
2.
This page contains all the settings for the image field. The most common field settings are the Label field, the Required field, and the Help text field. We will leave these fields as default.
3.
The Allowed file extension section is similar to the file field we have already learned about. We will use the default value in this field, so we don't need to enter anything for this field. The File directory section is also the same as the settings in the file field. Enter "image_files" in this field.
[ 137 ]
File and Image Fields
4.
Enter "640" x "480" in the Maximum image resolution field and the Minimum image resolution field, and enter "2MB" in the maximum upload size field.
5.
Check the Enable Alt field and the Enable Title field checkboxes.
6.
Select thumbnail in the Preview image style select list, and select Throbber in the Progress indicator section.
7.
The bottom part of this page, the image field settings section, is the same as the previous page we just saved, so we don't need to re-enter the values. Click on the Save settings button at the bottom of the page to store all the values we entered on this page. [ 138 ]
Chapter 5
8.
After clicking the Save settings button, Drupal sends us back to the Manage fields setting administration page. Now the image field is added to the Recipe content type.
[ 139 ]
File and Image Fields
What just happened? We have added and configured an image field for the Recipe content type. We left the default values in the Label field, the Required field, and the Help text field. They are the most common settings in fields. The Allowed file extension section is similar to the file field that we have seen, which provides us with the ability to enter the file extension of the images which are allowed to be uploaded. The File directory field is the same as the one in the file field, which provides us with the option to save the uploaded files to a different directory to the default location of the file directory. The Maximum image resolution field allows us to specify the maximum width and height of image resolution that will be uploaded. If the uploaded image is bigger than the resolution we specified, it will resize images to the size we specified. If we did not specify the size, it will not have any restriction to images. The Minimum image resolution field is the opposite of the maximum image resolution. We specify the minimum width and height of image resolution that is allowed to be uploaded, not the maximum width and height of image resolution. If we upload image resolution less than the minimum size we specified, it will throw an error message and reject the image upload. The Enable Alt field and the Enable Title field can be enabled to allow site administrators to enter the ALT and Title attributes of the img tag in XHTML, which can improve the accessibility and usability of a website when using images. The Preview image style select list allows us to select which image style will be used to display while editing content. Currently it provides three image styles, thumbnail, medium, and large. The thumbnail image style will be used by default. We will learn how to create a custom image style in the next section.
Pop quiz – configuring image field settings 1. Can we specify image fields to only accept a specific range of image types to be uploaded? a. Yes b. No 2. If we upload an image that is bigger than the maximum image resolution we specified, what will happen to the image? a. Nothing. b. The upload will be rejected. c. The image will be resized. [ 140 ]
Chapter 5
Have a go hero – adding an image field to the Cooking Tip content type It's time for another challenge. We have created an image field to the Recipe content type. We can use the same method we have learned here to add and configure an image field to the Cooking Tip content type. You can apply the same steps used to create image fields to the Recipe content type and try to understand the differences between the settings on the image field settings administration page.
Creating custom image styles One of the most powerful and useful features in Drupal 7 core is the image styles feature, which allows us to resize and adjust the images on display. We will learn how to create a custom image style in this section.
Time for action – creating a custom image style In this section, we will create a custom image style that can be used in an image field if we need to. Follow these steps:
1.
Click on the Configuration link in the administration menu at the top of the page.
2.
Locate the Media block, and click on the Image styles link in the block.
[ 141 ]
File and Image Fields
3.
The following page lists all the existing image styles in Drupal.
4.
Click on the Add style link to add a new style.
5.
Enter "recipe_med" in the Style name field, and then click on the Create new style button to store the value.
[ 142 ]
Chapter 5
6.
The following page shows a preview of a sample image, and a preview of a sample image with an image style applied:
7.
At the bottom of the page, we select Scale and crop, and then click on the Add button.
[ 143 ]
File and Image Fields
8.
In the next screen, we enter "300" in the Width field, and also enter "300" in the Height field. After entering the values, we click on the Add effect button.
9.
The custom image effect is now created. The page shows a preview of a sample image with the effect applied, and the effects we used are also listed in the table at the bottom of the page.
[ 144 ]
Chapter 5
What just happened? We have created a custom image style using the image system in Drupal 7. In order to create image styles, we have to go to the configuration page, and then click on the Image styles link to go to the image styles administration page. The image styles administration page lists all the existing image styles in Drupal. We can check the details of each image style on this page. By default, Drupal generated three image styles for us to play with, which are thumbnail, medium, and large. They are the most common types of image styles used in a website, so it is really good that the Drupal core developers have already thought about what we need when creating websites. There is a Add style link on this page, which allows us to create our own image styles if the existing image styles cannot fulfill what we need. Creating a new image style is easy. Click on the Add style link, and then enter the name of an image style. After saving the image style, Drupal will direct us to the next screen, which provides us with the option to add effects to the image style we created. Adding effects to image styles is also a very straightforward process. At the bottom of the page there is a dropdown menu; we can add an effect by selecting an effect from this menu, and then clicking on the Add button to add the effect to the image style. We can also add multiple effects to one image style if we need to. In our case, the Scale and crop effect was added to the recipe_med image style. After clicking on the Add button, Drupal will send us to the next screen. This screen will provide the effect settings, we have to enter values to these settings in order to make the effect work as we expect. In this case, we enter 300 for the height and the width fields, so the Scale and crop effect will be based on these values to proportionally scale and crop images to 300 width by 300 height. After clicking on the Add effect button, Drupal will show us a preview of an original sample image on the left of the page, and a preview of a sample image with the effects we added on the right of the page. So it is really easy for us to appreciate the differences between the original image and the image with effects applied. It is also easier for us to test the effects and sizes. We can click on the Edit link to modify the values and see the change quickly. Furthermore, besides the default effects in Drupal—currently it has got six effects—we can install contributed modules to add more effects to the image system.
[ 145 ]
File and Image Fields
One more thing, if we go back to the image field administration page, and go down to the Preview image style section, and click on the Preview image style dropdown menu, we will see our custom image style appear on the menu. Once we create our own image styles, we can use them anywhere in Drupal if options are provided.
Pop quiz – creating custom image styles 1. Which of the following statements is true? a. The Image styles link is on the Structure page. b. The Image styles link is on the Add content page. c. The Image styles link is on the Configuration page. 2. Can we add multiple effects to one image style? a. Yes b. No
Have a go hero – adding an image field to the Cooking Tip content type This is a final challenge for this chapter. We have created an image style using the Scale and crop effect. We can use the same method we have learned here to add an image effect using a different effect or even add multiple effects to an image style.
Summary Image content handling is critical for any website, and Drupal has provided a new image system to simplify the process of attaching, adding, and modifying images on a Drupal website. We have learned how to add file fields and image fields to content types, and we have learned how to configure file fields and image fields. After that, we have learned how to create our custom image styles in Drupal. The next chapter will be another fun chapter because we will learn how to manage a field display. We will modify the format of fields, and we will use the image styles we created in this chapter to format the output of image fields. [ 146 ]
6
Managing Field Display In the previous chapters, we created a variety of fields in Drupal, which included text fields, multiple value fields, term reference fields, file fields, and image fields. The settings for those fields were configured to work as we wanted. However, we have only achieved very limited control on the visual representation of the fields so far. More often than not we will need to control the output of the fields on the web page. As we've seen so far, there is only one option available to us to control the output of the fields, that is, the order of the fields on the Manage fields administration page. We can arrange the order in which the fields will be rendered on the web page. But there will be times when we need more control over the way fields are rendered. In this chapter, we will talk about ways that we can arrange and format field displays. The great thing is that Drupal 7 provides more powerful options for us to control how fields look, and because the new Field API system is integrated with comments and taxonomy we can now format the comment fields display and the vocabulary fields display as well.
In this chapter, we shall learn about:
Field display Formatting field display on Teaser view Custom display settings Formatting image field display on full content Formatting comment field display Formatting vocabulary field display
Managing Field Display
Field display The purpose of managing the field display is not only to beatify the visual representation of fields, but also to affect how people read the information on a web page and the usability of a website. The design of a field display has to seem logical to users and easy to understand. Consider an online application form where the first name field is positioned in between the state and country fields. Although the application can gather the information just fine, this would be very illogical and bothersome to our users. It goes without saying that the first name should be in the personal details section while the state and country should go in the personal address section of the form.
Time for action – a first look at the field display settings In this section, we will learn where to find the field display settings in Drupal. Now, let's take a look at the field display settings:
1.
Click on the Structure link on the administration menu at the top of the page.
2.
Click on the Content types link on this page.
[ 148 ]
Chapter 6
3.
On the right of the table, click on the manage display link to go to the manage display administration page to adjust the order and positioning of, the field labels.
4.
Click on the manage display link to adjust the field display for the Recipe content type.
[ 149 ]
Managing Field Display
5.
This page lists all of the field display settings that are related to the content type we selected.
6.
If we click on the select list for any of the labels, there are three options that we can select, Above, Inline, and .
[ 150 ]
Chapter 6
7.
If we click on the select list for any of the formats, there are five options that we can select from, namely, Default, Plain text, Trimmed, Summary or trimmed, and .
8.
However, the options will vary with field types. As in the case of the Difficulty field the multiple values field, if we click on the select list for Format, will show three options, Default, Key, and .
[ 151 ]
Managing Field Display
What just happened? We have learned where to find the field display settings in Drupal, and we have taken a look at the options for the field display. When we click on the select list for labels, there are three options that we can use to control the display of the field label: Above: The label will be positioned above the field widget Inline: The label will be positioned to the left of the field widget : The label will not be displayed on the page When we click on the select list for formats, the options will be shown, but the options will be different, and depend on the field type we select. For the Body field, we will have four options that we can choose to control the body field display: Default: The field content will be displayed as we specified when we created the field Plain text: The field content will be displayed as plain text, which ignores HTML tags if the content contains any Trimmed: The field content will be truncated to a specified number of characters Summary or trimmed: The summary of the field will be displayed; if there is no summary entered, the content of the field will be trimmed to a specified number of characters : The field content will not be displayed
Pop quiz – a first look at the field display settings 1. Different field types will provide different options for the format of the display. a. True b. False 2. What option can we choose to truncate the Body field content to a specified number of characters? a. Default b. Hidden c. Trimmed
[ 152 ]
Chapter 6
Formatting field display in the Teaser view The teaser view of content is usually the first piece of information people will see on a homepage or a landing page, so it will be useful if there are options that could control the display in teaser view. For example, for the yummy recipe website, the client would like to have the number of characters displayed in teaser view limited to 300 characters, because they do not like to display too much text for each post on the homepage.
Time for action – formatting the Body field display in teaser view In this section, we will format the Body field of the Recipe content type in teaser view:
1.
Click on the Structure link on the administration menu at the top of the page.
2.
Click on the Content types link on the following page:
[ 153 ]
Managing Field Display
3.
Click on the manage display link to adjust the field display for the Recipe content type.
4.
At the top-right of the page, there are two buttons, the first one is Default, the second one is Teaser, now click on the Teaser button.
5.
This page lists all the available fields for the teaser view of the Recipe content type.
[ 154 ]
Chapter 6
6.
Now click on the gear icon to update the trim length settings:
7.
After clicking on the gear icon, which will display the Trim length settings. The default value of Trim length is 600, we change it to 300, and then click the Update button to confirm the entered value.
8.
Click the Save button at the bottom of the page to store the value into Drupal.
[ 155 ]
Managing Field Display
9.
If we go back to the homepage, we will see the recipe content in teaser view. It is now truncated to 300 characters.
What just happened? We have formatted the Body field of the Recipe content type in Teaser view. Currently there are two view modes, one is the Default view mode, and the other is the Teaser view mode. When we need to format the field content in Teaser view, we have to switch to the Teaser view mode on the Manage display administration page to modify these settings. Moreover, when entering data or updating the field display settings, we have to remember to click the Save button at the bottom of the page to permanently store the value into Drupal. If we just click on the Update button, it will not store the value into Drupal, it will only confirm the value we entered, therefore, we always need to remember to click on the Save button after updating any settings. Furthermore, there are other fields which are positioned in the hidden section at the bottom of the page, which means those fields will not be shown in Teaser view. In our case only the Body field is shown in Teaser view. We can easily drag and drop a field to the hidden section to hide the field, or drag and drop a field above the hidden section to show the field on the screen.
[ 156 ]
Chapter 6
Pop quiz – formatting field display in the Teaser 1. If we need to adjust a Teaser view for a field, what view mode do we need to be in? a. Full content view mode b. Default view mode c. Teaser view mode 2. How can we hide the field display in the Teaser view mode? a. Drag and drop the field to the hidden section b. Click the delete button to remove the field c. There is no option to hide a field display
Custom display settings Currently, we have seen two view modes, the Default view mode and the Teaser view mode. Drupal provides us with more than two view modes where we can adjust the field display. We will take a look at additional field display view modes in the next section.
[ 157 ]
Managing Field Display
Time for action – enabling the Full content view mode in custom display settings The following steps will demonstrate how to enable Full content view mode:
1.
We go back to the MANAGE DISPLAY administration page for the Recipe content type. Click on the CUSTOM DISPLAY SETTINGS link at the bottom of the page.
2.
After clicking on the CUSTOM DISPLAY SETTINGS link, which will show the extra view mode options, click the Full content checkbox to enable the Full content view mode. Click on the Save button to store the value.
[ 158 ]
Chapter 6
3.
Drupal will display a successful message saying the Full content mode is now enabled, and we can configure full content using the full content view mode on the MANAGE DISPLAY administration page.
What just happened? We have enabled the Full content view mode for the Recipe content type. There are, in total, five view modes in the custom display settings: Full content Teaser RSS Search index Search result Once they are enabled, we will have the extra options to configure the display of fields. For instance, if we enable the RSS view mode, we have an option to show or hide the image field on RSS feeds. Drupal provides us with an entire solution to customize the field display in a different context.
[ 159 ]
Managing Field Display
Pop quiz – custom display settings 1. How many view modes can we enable for use? a. 3 b. 4 c. 5
Formatting the image field display on Full content The Full content mode is enabled. Now we can configure the field display on Full content. In this section, we will adjust the image field display on Full content. We have created the image style in the previous chapter. We can use it to format the output of the image field display.
Time for action – formatting the image field display on Full content In this section, we will adjust the image field display on Full content.
1.
We go back to the MANAGE DISPLAY administration page, and click on the Full content link.
2.
On this page, we can drag and drop the fields to show or hide fields, and arrange the order of the fields on Full content view. Now we drag and drop the fields as shown in the following screenshot. The order of the fields will be Image, Body, Difficulty, Recipe Category, and File.
[ 160 ]
Chapter 6
3.
Click the gear icon to show the extra options for the image field.
4.
After clicking on the gear icon, which provide us more options for the display of the image field, click the Image style select list and select the recipe_med option. Then click on the Update button to confirm the settings.
[ 161 ]
Managing Field Display
5.
We would like to hide the labels for the Image and Body fields. So, we click on the select list, and select to hide the labels for both fields. After that, click the Save button to store the values.
6.
When we go to one of the recipe contents with an image uploaded, we will see the image is resized based on the recipe_med image style we defined. And also the order of the fields is positioned as Image, Body, Difficulty, Recipe Category, and File.
[ 162 ]
Chapter 6
What just happened? We have adjusted the image field display on full content. The image style we created in the previous chapter was used for formatting the output of the image field display. In this case, we used the recipe_med image style to format the image field display on the Full content view. We can create a different image style with such image effects and image resize actions as we need, and use it in Teaser view. So we will have complete control over which image styles can be used in which view modes. This is a very useful feature to customize the output of the image field for different view modes.
Pop quiz – formatting the image field display on Full content 1. Can we use a different image style for different view modes? a. Yes b. No 2. The Image style option is available in the Full content view mode only. a. True b. False
Formatting the comment field display In Drupal 7, we can easily format the comment field display through the field user interface. We can adjust the order of the comment fields, the position of the field labels, and the format of the comment field display. For the yummy recipe website, the client would like the comments display to output plain text only. Hyperlinks or images are not allowed in comments. We can easily achieve that using the comment fields display option.
Time for action – formatting the comment field display In this section, we will adjust the comment field display to output plain text for the Recipe content type. Follow these steps to do so:
1.
Go back to the MANAGE DISPLAY administration page for the Recipe content type. On the top-right of the page, click on the COMMENT DISPLAY tab.
[ 163 ]
Managing Field Display
2.
On this page, we click on the select list under FORMAT, and select Plain text. Click the Save button to store the value. From now on, all the comment displays will only output plain text, which ignore the HTML tags entered in the comments.
What just happened? We have adjusted the comment field display to output plain text for the Recipe content type. The user interface in the COMMENT DISPLAY administration page is the same as in the MANAGE DISPLAY administration page. We can easily use the same user interface to control the comment field display. Currently, only the comment field is available for use, but as long as we add more fields to comments, we will be able to control those field displays for the comment output as well.
Pop quiz – formatting comment field display 1. We cannot configure the format of labels for comment fields. a. True b. False
[ 164 ]
Chapter 6
Formatting the vocabulary field display As we have seen, the comment field display is configurable in Drupal 7. The good news is the vocabulary field display is also configurable. The new field system gives us the ability of finer control over fields without hacking the core or using contributed modules.
Time for action – formatting the vocabulary field display In this section, we will hide the Description field display for the Recipe category vocabulary. Follow these steps:
1.
Click the Structure link on the top of the administration menu.
2.
On the following page, click on the Taxonomy link.
3.
Then, click on the list terms for the Recipe Category vocabulary.
[ 165 ]
Managing Field Display
4.
On the top-right of the page, click on the MANAGE DISPLAY tab to go to the MANAGE DISPLAY administration page.
5.
Click on the select list under FORMAT, and choose hidden to hide the Description field in the Recipe Category vocabulary. Click the Save button at the bottom of the page.
When on the Recipe Category terms, even if we entered content into the Description field of them, the text will be hidden.
What just happened? We have hidden the Description field display for the Recipe category vocabulary. We've learned that the vocabulary field display administration page is located in a separate section. Because the fields are related to vocabulary, we need to go to the taxonomy administration page to find the MANAGE DISPLAY administration page. [ 166 ]
Chapter 6
The user interface of the MANAGE DISPLAY administration page is also the same as the one we have seen for the field display. The only difference is, this page only shows the available fields for the associated vocabulary. The format of the field display is similar to the format for the content type field display.
Pop quiz – formatting the vocabulary field display 1. Do we need to install contributed modules to control the vocabulary field display? a. Yes b. No
Have a go hero – adding an image field to the Cooking Tip content type It's time for a challenge. We have formatted the field display for the Recipe content type. We can use the same method we have learned here to format the existing fields in the Cooking Tip content type and its comments and vocabularies. We can try to apply a different image style to image fields on Teaser, RSS, and Full content views. And we can add more fields to comments and vocabularies, and adjust the field display settings to see the outcome of each setting.
Summary It appears that all of the tasks of controlling node displays which are described in this chapter were previously done in Views in Drupal 6. It might be instructive to compare and contrast the use of CCK plus Views in Drupal 6 with the new Field API in Drupal 7. In the next chapter, we will talk about field related modules. Contributed modules can extend the capability of the field module such as to add new field formats and new field widgets. We will learn what some of these modules do and how they help us solve real world problems.
[ 167 ]
7
Contributed Field Modules Drupal provides us with many powerful features out of the box. Nevertheless there are times when we need to have additional functionality and specialized features that the default Drupal core installation does not provide. One of the big advantages of using Drupal is its modular design. Thanks to this, site administrators can easily install contributed modules to enhance existing Drupal functionality. We can think of Drupal developers as module artists. They can create customized modules to extend Drupal capability for business needs, all without touching core code. The field module is a special module in the sense that it is meant to be extended, and as such, Drupal developers can create contributed modules to specifically extend the field functionality that is already present in core. There are many useful contributed field modules that help us fulfill our special requirements when building Drupal websites. In this chapter, we will learn how to find, download, and install contributed field modules, and explore some of the most popular contributed field modules out there.
In this chapter, we shall learn more about:
Drupal core modules
Contributed modules
Finding contributed modules
Installing and enabling contributed modules
Contributed field modules
Contributed Field Modules
Drupal modules Drupal core comes with a number of preinstalled modules; these Drupal core modules can be easily enabled or disabled through the Drupal web-based user interface or the Unix command lines using Drush. Drupal, unlike other frameworks on the market, does not necessarily require that you hire web developers to get the custom functionality that you desire for your website. Thanks to its hook system, which makes Drupal so easily extensible, and the large community behind it increasingly contributing new modules every day, makes it possible that you'll find what you're looking for on the contributed modules list available at drupal.org. Once you are set on a module or set of modules that you know will get you so much closer to what you need, you can focus on installing, enabling, and configuring these modules. The hard part has already been done for us by module developers. Drush (The Drupal Shell) is a command-line shell and Unix scripting interface for Drupal that allows you to perform many common tasks (such as installing and updating modules, and clearing caches) through the command line. You can find more information on the following websites: http://drupal.org/project/drush http://drush.ws
Contributed modules As we know, Drupal is an open source content management system, which is not to say that all modules written for Drupal must be free of cost. Generally speaking, Drupal modules can be categorized as follows:
Core modules that come with Drupal core which are necessarily open source
Custom modules that are created (tailor made) by Drupal developers for a company
The third category, which is also the most numerous, is the contributed modules category
These are modules created by the Drupal community and usually shared under the same GNU Public License (GPL) as Drupal, which means they are free to use, even for commercial purposes.
[ 170 ]
Chapter 7
Finding modules With Drupal module contributors all around the world, the amount of contributed modules is substantial. There will always be a module that can help you when building a Drupal website. The question is where do we find the information necessary to be able to choose the right modules for our task. In this section, we will spend some time learning where to find contributed modules. In particular, where to find the right modules to extend the functionality of the field module.
Time for action – finding contributed field modules through the Drupal website In this section, we will learn how to find contributed field modules through the Drupal website. Follow these steps:
1.
Go to http://drupal.org/project/modules using your favorite web browser.
2.
On this page, we can click on the select list at the top of the page to sort and search for modules.
[ 171 ]
Contributed Field Modules
3.
We select Content Construction Kit (CCK) for the Modules categories option, select 7.x for the Filter by compatibility option and select Most installed for the Sort by option. Click on the Search button.
4.
The result of the search will be shown at the bottom of the page. Because we didn't enter the module name in the Search Modules field, it will show all the modules that are CCK/field modules for Drupal 7. It will also sort them by the most installed modules.
[ 172 ]
Chapter 7
What just happened? We have learned how to find contributed modules related to fields. The drupal.org modules page is one of the best sources for finding contributed modules. At the top of the page, it provides search options that allow us to find a module quicker. Because we would like to find contributed field modules for Drupal 7, in the modules categories we selected Content Construction Kit (CCK) as the search condition, and 7.x was selected for the filter by compatibility. We would like to sort by most installed modules or most popular modules, so Most installed option was selected.
Time for action – finding contributed field modules through the drupalmodules.com website In this section, we will learn how to find contributed field modules through the third-party drupalmodules.com website. Follow these steps:
1.
Go to http://drupalmodules.com using your favorite web browser.
2.
Click on the Module Finder link on the menu.
[ 173 ]
Contributed Field Modules
3.
Select Content Construction Kit (CCK) for Category, and select 7.x for Version.
4.
There is no need to click any submit button, it will display the search result dynamically after selection.
What just happened? We have learned how to find contributed field modules through the drupalmodules.com website. We also tried to find contributed modules through the third-party drupalmodules.com website. The benefits of using drupalmodules.com is that we can see the ratings of a module such as features, reliability, ease of use, and documentation of a module.
[ 174 ]
Chapter 7
It is a big advantage to read other people's reviews about modules. The reviews are informative. They should help us choose the most appropriate module for the job at hand. Sometimes people recommend similar modules on reviews; this is a good chance to find alternative modules for solving similar problems.
Pop quiz – finding a contributed field module 1. All modules created for Drupal are required to be free of cost. a. Yes b. No 2. drupal.org is the only source for finding contributed modules. a. Yes b. No
[ 175 ]
Contributed Field Modules
Installing and enabling contributed modules After finding the right contributed module to use, it's now time to install it for our website. We will learn how to manually install a contributed module in this section. In the next section, we will use the new feature of Drupal 7, Update manager, to install a contributed module.
Time for action – installing a module In this section, we will learn how to install the Email field module.
1.
Visit http://drupal.org/project/modules, and select CCK for Module categories, 7.x for Filter by compatibility. Enter Email in the Search Modules field, select Most installed for the Sort by select list, and then click Search.
2.
Click on the Email Field link to go to the Email Field project page.
[ 176 ]
Chapter 7
3.
Click on the download link. We can download either tar.gz or the zip compressed file, and then save the file to the desktop.
4.
Extract the compressed file, and move the extracted directory to the modules directory as shown in the following screenshot.
[ 177 ]
Contributed Field Modules
5.
Go back to the Drupal website, and click on the Modules link at the top of the administration menu.
6.
At the bottom of the page, we will find that the Email field module has been added to the table. Now click the ENABLED checkbox and then click Save configuration to enable the module.
7.
After enabling the Email field module, we click on the Structure link on the top of the menu.
8.
Click on the Content types link. Click on the manage fields link for the Recipe content type.
[ 178 ]
Chapter 7
9.
When we select a field type, the Email field is now available in the select list.
What just happened? We have installed and enabled the Email field module. We have downloaded the Email field module through the Drupal.org website, and extracted the compressed file to a directory, and then moved the extracted directory to the contributed module directory in our Drupal installation. But remember we have to put the contributed modules to the drupal-root/sites/all/modules/ directory, not the drupal-root/modules directory. This is because drupal-root/modules is part of Drupal core. If we upgraded our Drupal installation, the new version of Drupal is going to overwrite that directory. Another advantage of following best practices is that it makes it easier for us to migrate functionality from one website to another. We can easily back up the entire sites/all/modules directory from one machine, and restore the sites directory to another Drupal installation on another machine. Once the Email field is enabled, we can find the Email field on the MANAGE FIELDS administration page. It gives us the ability to create an Email field field type through the Field UI in Drupal.
[ 179 ]
Contributed Field Modules
Time for action – installing a module using Update manager In this section, we will install the Link module using Update manager.
1.
Click on the Modules link at the top of the administration menu.
2.
Click on the Install new module link.
3.
Find the Link module through the drupal.org module page.
4.
The easiest way to get the download address is to simply copy the download link location using the web browser.
[ 180 ]
Chapter 7
5.
Then paste the link address in the Install from a URL field, and click on the Install button.
[ 181 ]
Contributed Field Modules
6.
After clicking the Install button, it will automatically extract the compressed file, and move all of the files and directories to the correct directories for you. If the installation was completed, it will show a message that says the installation was completed successfully without any error. You may encounter errors, such as a firewall issue on your local system. It might be unable to download modules, so it will throw a 10061 error. If you are getting any kind of errors like this, then try manually downloading and installing contributed modules.
What just happened? We have installed the Link module using Update manager. One of the nicer features in Drupal 7 is the ability of the Update manager to install modules for us. We can now easily download or update modules through the web-based user interface in Drupal. Update manager will not only download the necessary module files for us, but will also uncompress them and move the expanded files and directories to the appropriate directory, so we don't have to do all these steps manually like we had to do in previous sections. I have copied and pasted the URL from the module page in order to install the module. There is another way to install a module through Update manager. Firstly, we have to download the compressed module files to our local computer, and then we can choose the compressed module file by clicking on the Choose File button through the update manager.
[ 182 ]
Chapter 7
When using the Install from a URL method, it may ask you for the FTP details after clicking on the Install button. You need to enter your local computer username and password, and you may also need to turn on Share files and folders using FTP in your operating system. If FTP is not enabled on our server, and we try to install from a URL, we may encounter an error. Drupal cannot diagnose the problem, it only notifies us if there is a problem with the connection. We need to investigate to identify the actual problem.
For example, on Mac OS, we need to turn on Share files and folders using FTP through System preferences.
[ 183 ]
Contributed Field Modules
Pop quiz – installing and enabling contributed modules 1. Can we install a module coming from a module archive in its uncompressed form through Update manager? a. Yes b. No 2. If we manually install a module, in which directory should we locate the module? a. drupal-root/modules/ b. drupal-root/profiles/ c. drupal-root/sites/all/modules/
Have a go hero – installing and enabling contributed modules It's time for a challenge. We have learned how to install and enable modules. We can use the same method we have learned here to install all kinds of contributed field modules. We can install any kind of module using the methods we have learned in this chapter. After installing and enabling the modules, go ahead and play around with the installed modules. It's always fun to try out and explore contributed modules in Drupal.
Contributed field modules There are so many powerful and useful contributed field modules already available. We will go ahead and mention and also describe some of the most popular field modules in this section.
Email field module This module provides a field type for e-mail addresses. It has the following features:
Turns addresses into mail to links
E-mail address validation
E-mail address encryption
Contact form support
Tokens module support
Views module support
Rules module support
[ 184 ]
Chapter 7
Link module This module provides a field type for hyperlinks. We can control the URL, title, and link attributes of hyperlinks by using this module.
Table field module This module allows us to attach tabular data to content. It allows the user to specify the number of rows and columns when inputting the tabular data, and allows entry into each table cell using text fields. The output of the table will be nicely displayed based on the inputted values.
Computed field module This module allows us to add custom computed fields to content types or entities. We can use PHP code to populate them with values for the content fields. We can even pull and push any available values to or from Drupal. This is a powerful field module Drupal developers often use.
Content Templates (Contemplate) module The main purpose of this module is theming fields. You will find this module useful when you need to output fields in a way that Drupal does not provide. This module helps you control the output of fields easily if you are not familiar with Drupal theming.
Summary In this chapter, we have learned what a Drupal module is. We have learned how to find contributed modules through the drupal.org website and the third-party drupalmodules. com website. We have also learned how to manually install and enable contributed modules, and we have learned how to use Update Manager to quickly install and enable contributed modules. In the next chapter, we will talk about field level permissions; we will install and enable the field level permission module, and use it to control the field permissions when inputting and outputting field content. All in all, we will learn how to configure permissions in Drupal.
[ 185 ]
8
Field Level Permissions Within a website or a content management system, we usually need to limit access to specific pages or resources to specific people, or vice versa. We configure specific users or roles to access certain content or resources on the website. If you have managed users, roles, and permissions for a Drupal website, you will understand that Drupal provides facilities for site administrators to manage permissions easily through the Drupal administrative user interface. Site administrators can create an editor role, and assign certain permissions to this role such as creating any article content, and assign this role to certain people. Drupal provides us with APIs to plug into the content access system in Drupal core, so there are many add-on modules that provide such functionality. But what if we would like to manage permission on a field by field basis such as hiding or showing specific fields to certain people or roles. By default, Drupal 7 does not come with field access control features, but we can use the Field Permission module to add this feature to Drupal. In this chapter, we will look at where to download the Field Permissions module, how to install and enable the module, and how to use the module to configure field level permissions for a Drupal website.
In this chapter, we shall learn about:
Downloading the Field permission module Installing and enabling the module Enabling field level permissions Configuring field-level permissions on the permission administration page Field-level permissions reports
Field Level Permissions
Downloading the Field Permission module In order to have the field level permission control feature, we have to download the Field Permission module. This module gives us control over fields rather than content.
Time for action – downloading the Field Permission module In this section, we will find and download the Field Permission module through the drupal. org website.
1.
Visit http://drupal.org/project/modules, the Drupal module download website.
2.
Select Content Construction Kit (CCK) for the Module categories select list. Select 7.x for the Filter by compatibility select list and enter "Field permissions" for the Search Modules text field. Select Relevancy for the Sort by select list, and click on the Search button.
3.
Click on the Field Permissions link to go to the Field Permissions project page.
[ 188 ]
Chapter 8
3.
At the bottom of the page, click on the download link, and save the compressed file to your computer.
What just happened? We have downloaded the Field Permissions module. We will install and enable the module in the next section.
Installing and enabling the Field Permission module Once we have downloaded the module, we can manually extract the module files and directories to the Drupal installation. However, we will use Update manager, a new feature in Drupal 7, to install the Field Permission module. In this respect, the previous step, step 4 is completely unnecessary, we just wanted to show it can be done either way.
[ 189 ]
Field Level Permissions
Time for action – installing and enabling the Field Permission module In this section, we will install the Field Permission module using the Update manager.
1.
Go to the Field Permission module project page. Copy the link address by clicking on the right mouse button.
2.
Go back to our yummy recipe Drupal website, and click on the Modules link on the administration toolbar at the top of the page.
3.
Click on the Install new module link.
[ 190 ]
Chapter 8
4.
Paste the link address to the Install from a URL text field, and click on the Install button.
5.
Click on Enable newly added modules to go back to the module administration page.
6.
At the bottom of the MODULE administration page, click on the checkbox to enable the Field Permission module. Click on the Save configuration button to store the configuration.
[ 191 ]
Field Level Permissions
What just happened? We have installed and enabled the Field Permission module using the Update manager. If you have followed the previous chapter, you should be familiar with downloading, installing, and enabling modules. You should not have any major issues with the module installation process. If you are not sure about the module installation process, you can refer back to the previous chapter for more details.
Pop quiz – installing and enabling the Field Permission module 1. Drupal 7 comes with the feature that allows us to control field permissions. a. True b. False
Enabling field-level permissions Once the Field Permission module is installed and enabled, we can start assigning permissions to fields. It provides us a list of options that we use to limit field access to specific roles and people. If we do not assign permissions to individual fields, then permissions will be based on the permission for the content which was configured in Drupal.
Time for action – enabling field-level permissions In this section, we will enable and assign field-level permissions to the Image field in the Recipe content type.
1.
Click on the Structure link at the top of the administration menu.
2.
Click on the Content types link on this page.
[ 192 ]
Chapter 8
3.
Click on the manage fields link for the Recipe content type.
4.
On the recipe MANAGE FIELDS administration page, click on the edit link to update the image field settings.
5.
The Field permissions section is shown at the bottom of the page. For now just enable all the options. We will discuss more about each option later. After enabling all the field permission options, click on the Save settings button to store the settings we made.
[ 193 ]
Field Level Permissions
What just happened? We have enabled and assigned field permissions to the image field in the Recipe content type. When we set up the field permissions for the image field in the Recipe content type, there were five field permission options that we had enabled:
Here's a brief explanation of the options:
Create field_images (edit on content creation): People can create image field images (field_images field) when creating new content
Edit field_images, regardless of content author: An assigned role can edit image field images (field_images field)
Edit own field_images on content created by the user: Content owners can edit image field images (field_images field)
View field_images, regardless of content author: An assigned role can view image field images (field_images field)
View own field_images on content created by the user: Content owners can view image field images (field_images field)
There is a description below the options, as follows: Use these options to enable role based permissions for this field. When permissions are enabled, access to this field is denied by default and explicit permissions should be granted to the proper user roles from the permissions administration page. On the other hand, when these options are disabled, field permissions are inherited from the content view and/or edit permissions. In example, users allowed to view a particular node will also be able to view this field, and so on.
[ 194 ]
Chapter 8
What we are actually doing is enabling a set of permissions to be later assigned/configured on the permission administration page. It does have an immediate effect in the sense that those options come off disabled and have to be individually enabled on the permission administration page. The next step, enabling permissions for specific roles from the permission administration page, will be accomplished in the next section.
Pop quiz – enabling field-level permissions 1. When field permissions are enabled for a field, by default, which roles contain the permission to access the field? a. Authenticated users b. Anonymous users c. Nobody 2. When we disable field permissions for a field, field permissions will? a. Deny all users to access the field. b. Inherit the existing content/node permission settings from Drupal c. Allow all users to access the field.
Configuring field-level permissions on the PERMISSIONS administration page We enabled the permissions for the image field in the previous section. It is time to assign the previously enabled field permissions to roles. We can assign different permissions to different roles based on business requirements, so there is no wrong or right way of setting up permissions. If there are a large number of content types with many fields added, the field permission matrix will become quite large. But proper planning is a must for correctly configuring the permissions matrix, because it is critical to organizations to protect their information and not expose sensitive information to the pubic.
[ 195 ]
Field Level Permissions
Time for action – configuring field-level permissions on the PERMISSIONS administration page In this section, we will configure field-level permissions on the PERMISSIONS administration page. We will then assign different permissions to different roles on our Drupal site.
1.
Click on the People link at the top of the administration menu.
2.
Click on the PERMISSIONS tab on the right of the page.
3.
Browse to the Field Permission section. We will see that the enabled field permissions for the image fields are now available on the table as shown in the following screenshot:
[ 196 ]
Chapter 8
4.
Set up the permissions by following the next screenshot. Click on the Save permissions button at the bottom of the page to store the permission settings.
What just happened? We have configured field-level permissions on the PERMISSION administration page. The image field permissions in the Recipe content type are now activated and assigned to the existing roles. What we have done is assigned all the field permissions to administrator roles, which means people with administrator role can administer field permissions, create field_images fields, edit any and own field_images fields, and view any and own field_images fields. We restricted the AUTHENTICATED USER role to create content, create field_images fields, edit own field_images fields, view any and own field_images fields. And finally, we only allowed the ANONYMOUS USER role to only view any field_images field on the Drupal site.
[ 197 ]
Field Level Permissions
If we try to browse the content on the yummy recipe website, we may not notice any differences. But if we go back to the PERMISSION administration page, and disable View any field_images for the ANONYMOUS USER role, and now logout from our account and navigate to recipe content, we will notice the image will be hidden, because anonymous users do not have enough privileges to view the field_images field.
Pop quiz – configuring field-level permissions on the PERMISSIONS administration page 1. When we enable permissions to the authenticated user role, what will it also do? a. Enable the permissions to the administrator role. b. Disable the permissions to the administrator role. c. Enable the permissions to the anonymous user role.
[ 198 ]
Chapter 8
2. If we enable View any field_images, and disable View own field_images for the AUTHENTICATED USER role, what will happen? a. Authenticated users will not be able to view own field_image fields. b. Authenticated users will be able to view own field_image fields.
Field-level permission reports The field Permission module offers us some useful tools for site administrators to easily identify what permissions have been applied to fields on a Drupal site. In this section, we will show you where to find these tools.
Time for action – the Field permissions report page In this section, we will find the Field permissions report page, which generates reports about field permissions used on a Drupal site.
1.
Click on the Structure link at the top of the administration menu.
2.
Click on the Field permissions link on the list.
[ 199 ]
Field Level Permissions
3.
This page will list all the information about the field permissions used on the Drupal site.
What just happened? We have found the Field permissions report page on the Drupal site. The advantage of using the Field permission report page is that it makes it easy to get the overall picture of the fields and field permissions settings on a Drupal site. It makes the site administrator's life easier, because they don't need to go to each MANAGE FIELDS setting page to check what field permissions have been applied to a field. The Field permissions report page shows us everything we need, it even shows us what fields are used on what content types, field types, and so on. [ 200 ]
Chapter 8
There is another report page provided by the Field Permission module. We can click on the Reports link on the administration toolbar, and click on the Field list link.
It is a simplified version of the Field permissions report page. If you only need to know what fields are currently in use on a Drupal site, the Field list report page can be a good option.
Pop quiz – the Field permissions report page 1. What report tools can we use? a. Field permissions report and Field list report. b. Field list report c. Field permissions report
Have a go hero – setting up field permission It's time for a challenge. We have learned so far how to configure and enable field permissions using the Field Permission module. We can use the same method we have learned here to configure different permissions for different fields. We can set up the field permissions using the methods we have learned in this chapter.
[ 201 ]
Field Level Permissions
Summary In this chapter, we were shown how to download the Field Permission module. We learned how to download, install, and enable it. We also learned what the Field Permission module can do for us. We learned how to enable permissions to fields, and we also learned how to configure and assign field permissions for roles. We have learned that we can check the status of field permissions on a Drupal site by using the Field permission report page and field list report page to get the overview of fields in use on the site. In the next chapter, we will look at the theming system in Drupal 7, we will learn how theming works in Drupal 7. We will learn how to create and edit template files and CSS files to style our fields on a page in a Drupal website.
[ 202 ]
9
Theming Fields Occasionally we may want to amend the existing markup for field display. The theme system in Drupal provides us with a flexible way to restructure a webpage that Drupal has generated. Manage display in fields provides the basic functionalities for changing field display. If we need customized layouts or advanced theming solutions, Drupal offers the theme layer where we can wrap our fields and data in the HTML and CSS of our choice. In this chapter, we will look at the theme system in Drupal, and we will learn how theming is achieved in Drupal by creating and modifying template files and CSS files, and also by looking at some of the changes in the Drupal 7 theme system.
In this chapter, we shall learn: What is a theme What is theming How Drupal renders a webpage How to get started on theming Creating a Drupal theme Overriding template files Editing template files Styling the page using CSS
Theming Fields
What is a theme? A theme is a collection of associated files that define the look and feel of a Drupal site. It defines visual elements on the website such as: Layout of the webpage (header, footer, and number of columns for layouts) Navigation bars and menus The color scheme used on the webpage Fonts used on the webpage plus font size and font family Logos and branding of the website We can download off-the-shelf themes from http://drupal.org/project/themes, or we can create our own themes from scratch. In this chapter, we will cover how to customize an existing theme. Advanced theming will not be covered in this book such as Theme function overrides or Building a theme from scratch. I recommend you read Drupal 6 Themes by Ric Shreves (https://www.packtpub.com/drupal-6-themes/book) and Drupal 6 Theming Cookbook by Karthnik Kumar (https://www.packtpub.com/drupal6-theming-cookbook-to-create-powerful-drupal-themes/book) for a more complete description of the theming process. And I also highly recommend Drupal 7 Module Development by Matt Butcher, Larry Garfield, John Wilkins, Matt Farina, Ken Rickard, and Greg Dunlap (https://www.packtpub.com/drupal-7-module-development/book), which covers more details about advanced theming in Drupal 7.
What is theming? In terms of Drupal, Theming is the process of creating and modifying the presentation of data generated by Drupal. Drupal PHP scripts provide a way to generate data, HTML, and CSS in order to create a webpage. Drupal has provided tools and functionalities as much as possible to fulfill our general needs when creating websites. As we have learned, we can arrange the order of fields and change the field label positions easily by configuring the manage field settings through the Drupal administration user interface. When we need to fine-tune page layouts or do something very specific that Drupal administration user interface has not provided, the Drupal theme system provides everything we need to do this. There is a learning curve to Drupal theming in order to override, customize, and create Drupal themes. However, it is worth the effort to master Drupal theming because Drupal themers are usually the people who control the final output of Drupal sites. It is a joy to leverage the power you obtain when you become a Drupal theme master.
[ 204 ]
Chapter 9
How Drupal renders a webpage The following diagram is a simplified version of how Drupal renders a webpage. Each rectangle on the second level represents a point of customization available in Drupal theming. The meaning of the picture is as follows. If you are happy with the provided default theme, theming can stop there. If you find exactly what you want in an off-the-shelf community contributed theme, theming can stop here. If none of the previous two options suffice, you can either build your own theme or create a subtheme of an existing theme to satisfy your requirements.
Content
Drupal core
Off-The-Shelf themes or Your own themes (if provided)
Module theming
Subthemes and/or theme override (if provided)
Default themes
Page rendered in web browsers
The content presented on the site usually comes from the user input on a Drupal site. If the site is getting redesigned there might be a chance of getting content source from a previous version. Drupal core will process the data and add a theme implementation layer. HTML and CSS will not be rendered in this layer, it will pass the data including markup to the next layer. The theme implementation is to control the presentation logic of the Drupal theme output. Once modules provide the default theme implementation, a theme can have the option to override the default implementation. And the default Drupal theme implementation will be used if modules have nodefault theme implementation provided. Drupal modules will retrieve data from Drupal core and further manipulate the data. If a theme implementation is provided, it will override the Drupal core theme implementation, and output the themed data, which usually is the HTML markup and CSS. [ 205 ]
Theming Fields
The default Drupal theme will retrieve the themed data from modules and the default Drupal theme will be overridden if the module theming adds another theme implementation. If there are no other themes, subthemes or theme overrides added to Drupal, the default Drupal theme will render all the data using the theme engine in Drupal and output the HTML code to a webpage. If we have used off-the-shelf themes or created our own themes, this will also add another theme implementation on top of the default Drupal themes. The off-theshelf themes will override, manipulate, and add extra functionalities to the themes. Finally it sends the output to the browser which will render the HTML output into the webpage. If we have used subthemes, it will add another theme implementation on top of the base theme or parent theme output, and it will inherit and override the base theme in order to render the page. If theme overrides are provided, such as theme function overrides and/or template overrides, this step will intercept and override the theme function and template output. This is usually the last stage to modify and control the page output. Finally, web browsers will retrieve the final rendered HTML page from Drupal. There is no more raw data for extra processing. Everything is flattened and processed. The web browser will do its job to render HTML, CSS, and JavaScript to be a beautiful webpage. Furthermore, the diagram indicates an order of overriding the layer nearest the web browsers; it will override the other layers lower in the order. For example, the theme override layer will override the off-the-shelf theme layer.
How to get started on theming Where should we begin? We can start theming by using any of these options: Cloning the existing theme: We can clone the existing theme and give it a different name. Then update the theme.info file and other files such as template.php to correctly identify the new theme from Drupal. We can start the modification from there to fulfill our specific need. Starting with an off-the-shelf theme: We can download an off-the-shelf theme from http://drupal.org/project/themes. Just download a theme that is close to what you need. Clone and modify it to fulfill your specific requirements such as changing the color scheme, fields, and so on.
[ 206 ]
Chapter 9
Starting with a sub-theme or a starter theme: Some of the off-the-shelf starting themes provide a starter theme that makes theming easier such as Zen, Fusion, Tao, and others. The starter theme is usually a sub-theme of the off-the-shelf theme. The starter theme provides us a clean blank canvas, on which we can easily customize the layout and design of the page without worrying about what template variables and theme functions should be inserted in the theme, because it has done everything for us. Building a theme from scratch: We can build our own theme from scratch, if we cannot find any that suits our needs. This requires advanced knowledge and techniques which are beyond the scope of this book.
Creating a Drupal theme In order to demonstrate how theming works, we will not use any off-the-shelf theme or build the theme from scratch, we will be using the default Drupal theme—Bartik—for this chapter. We will clone the existing theme, modify the theme, and add template files to fulfill our need.
Time for action – creating a Drupal theme by cloning the existing theme In this section, we will clone the existing theme and move it to the correct location:
1.
Navigate to your Drupal installation directory, and go to the themes directory.
[ 207 ]
Theming Fields
2.
Find the bartik directory that should be in druaplroot/themes/, and copy the whole directory.
3.
Paste the directory to drupalroot/sites/all/themes.
[ 208 ]
Chapter 9
4.
Rename bartik to yummyrecipe and change the bartik.info file to yummyrecipe.info:
5.
Open the yummyrecipe.info file in your favorite text editor, and change the name Bartik to Yummy Recipe, and then just save and close the file. For contributed themes the user must also change the project name to a machine name like yummyrecipe.
6.
Open the template.php file in a text editor.
[ 209 ]
Theming Fields
7.
Use your text editor to replace the word bartik to yummyrecipe, and save and close the file.
8.
Now we can go back to our Drupal site, and click on the Appearance link on the administration toolbar at the top of the page.
9.
The Yummy Recipe theme is now added to the disabled themes section. We click on the Enable and set default link to enable the theme and set it as the default theme for the Drupal site.
[ 210 ]
Chapter 9
What just happened? We have cloned the existing theme and configured it as a new Drupal theme. This is one of the methods to create a Drupal theme. We just clone the existing Drupal theme and put the cloned theme in the drupalroot/sites/all/themes directory. We then rename the .info and theme directory name to our desired name. And we rename the old theme name to a new name in the .info file and template.php file. After that, we can go to our Drupal site to enable the theme we created. In Drupal 7, we can go to the Appearance administration page to enable or disable the theme on this page. One of the usability improvements that come with Drupal 7 is the Enable and set default link. We can now click on the Enable and set default link to enable and also set the theme as the default theme for the Drupal site, instead of clicking multiple times to achieve this.
Pop quiz – creating a Drupal theme by cloning the existing theme 1. Can we clone the existing theme without renaming it and still have the theme work alongside the existing theme? Is renaming the cloned theme optional? a. Yes b. No 2. I have cloned and renamed the essential files and directory; does Drupal automatically enable the new (cloned) theme for me? a. Yes b. No 3. Is creating a Drupal theme by cloning the existing theme the only option to create a Drupal theme? a. Yes b. No
Overriding template files In this section, we will theme the Recipe content on the yummy recipe Drupal site. It's a great idea to enter some dummy text and images into the Drupal site first before theming the site, because it is easier to visualize what will happen on the layouts. If we try to theme a webpage without content, it is very hard to know what elements could break the layout. A 200 characters sentence or a 100 x 80 pixel profile image may mess up your homepage layout. So often enter some content first, theme it, and then test it, if there are any issues go back to the theming, fix the problems, and test it again. [ 211 ]
Theming Fields
The great thing about Drupal is that there are many handy and useful modules on the Drupal.org website. There is a module that helps us to generate dummy text and images, which is the Devel module (http://drupal.org/project/devel). This module not only provides tools and functions for Drupal developers, it also comes with a bundled module that can generate dummy text and images. We just need to install and enable the Devel Generate module, and go to the Devel generate administration page. A few clicks later, it will generate dummy content for us, and it is ready for our Drupal development and theming.
Time for action – creating a template file for the Recipe content type In this section, we will create a template file for the Recipe content type. We would like to theme the recipe content to look a bit different from the other theme on the yummy recipe website, so that it is easier for people to recognize the content differences on the website.
1.
Go back to our yummyrecipe theme directory, drupalroot/sites/all/ themes/yummyrecipe.
[ 212 ]
Chapter 9
2.
Select the node.tpl.php file in the templates directory. Duplicate the file or copy and paste the file, and name the duplicate file node--recipe.tpl.php.
Drupal 7 requires two dashes, so there are two dashes between node and recipe, not one dash. Drupal 6 requires one dash when naming the template files.
What just happened? We have created a template file specifically for the Recipe content type. This will override the standardnode.tpl.php template file when rendering recipe content on the page. An override is an essential part of Drupal theming and development. This is how Drupal works and this is one of the most powerful and flexible features most content management systems do not provide and therefore cannot compare with Drupal. All modification and customization codes can and should be separated from the Drupal core. No hacking is needed for adding or overriding specific functions or theme outputs.
[ 213 ]
Theming Fields
In Drupal, we can override the default Drupal template files to gain more control. In this case, we have two custom content types, one is the Cooking tip content type, the other is the Recipe content type. We would like to customize the Recipe content, so we duplicate the standard node.tpl.php file, and name it node--recipe.tpl.php. This newly created template file that will override the node.tpl.php specifically for the Recipe node/content type.
Pop quiz – creating a template file for the Recipe content type 1. If we would like to create a template override for the Article content type, how should we name the template file? a. article.tpl.php b. node-article.tpl.php c. node--article.tpl.php
Editing template files We have created the template file; the next step is to modify the code in the template to fulfill our needs. If we have some background in PHP and HTML, it will be quite easy to understand how the code works in the template files. But no need to worry, if you don't have a deep knowledge of PHP, basic understanding of HTML and CSS is enough. The flow and the logic of the template code is quite easy to understand, just play around with the code, you will be amazed how easily you can control the output of a page by modifying the code in template files.
Time for action – editing a template file In this section, we will edit the code in the node--recipe.tpl.php template file. We will control the order of the fields by modifying the code, the order will start from Image, Body, Difficulty, Recipe category, and finally end with the File field.
1.
Open the node--recipe.tpl.php template file in your favorite text editor such as Textmate or Notepad++. If you scroll down, you will see some PHP and HTML code in this file, as shown in the following screenshot:
[ 214 ]
Chapter 9
2.
Navigate to one of the recipes in our yummy recipe Drupal site. In this example; we go to the Homemade Chocolate Cake recipe content.
[ 215 ]
Theming Fields
3.
To make sure we are hitting the right spot, we can try to remove one line of code from the node--recipe.tpl.php file. In this example, we will remove print render($content); from the template file, and then refresh the Drupal website (we should be on the Homemade Chocolate Cake recipe webpage) to see any change on the page.
If you don't see any change on the page, you may need to visit admin/config/ development/performance or click on the Configuration | Performance link, and then click on the Clear all caches button to clear the caches in Drupal. Drupal theme registry stores information about available templates and functions. We have rebuilt the theme registry when adding or modifying template files for the first time, otherwise Drupal cannot pick up the change in template files.
4.
After refreshing the page, the content of the page will disappear. This means, the template file is now overriding the standard node.tpl.php template file. Okay, redo the change, or put back the code print render($content); at the appropriate position.
5.
We will start to modify the code now. First we remove the following code:
Then copy and paste the following code to the position we just removed the code from:
The file will look something like the following screenshot:
[ 217 ]
Theming Fields
6.
Remember to save the file, and click refresh on the web browser to see the change. The content of the page is back, and the order of the fields is now as we wanted (Image, Body, Difficulty, Recipe category, and File field).
[ 218 ]
Chapter 9
What just happened? We have edited the node--recipe.tpl.php template file to reorder the field display for the Recipe content. It seems we have to do a lot of work in order to rearrange the order of the field displays, but if you have noticed, we have also inserted some additional HTML code. We can add HTML code to wrap some of the elements for CSS styling on the page, and we can add any HTML code to enhance the page. In the Drupal administration page, we could use the manage display option to arrange the order of fields, but it was not possible to add HTML anywhere we would like to. In the template files, we have all the power to remove, modify, and add HTML, and to print template variables and PHP code. For now, we ignore the other code in the template files, and we just focus on what we have changed in the code. We removed the following code:
But actually, the main purpose is to remove the print render($content); code, because it will render all the associated fields and content in one go. However, in our case, we would like to display specific fields and elements on the page, and control the order of each field display. In order to achieve that, we removed the $content variable from the page, which meant we removed a big chunk of content from the page, and we broke this down into smaller pieces. This allowed us to assign a different class to several of the items so that we could format them differently. Therefore, we inserted the following code to the template file:
The most important codes are the following: print render($content['field_images']); print render($content['body']); print render($content['field_difficulty']); print render($content['field_recipe_category']); print render($content['field_file']); Each part of this represents a field we created in Drupal earlier in this book. We created the Image, Difficulty, Recipe category, and File field through the Field UI. For instance, in order to render the Image field on the page, we type print render($content['field_ images']);. Just like the other fields, we used the same method to output each field on the page. But what if, instead of dealing with fields one by one, we would like to just hide a specific element. Sure we can do that in the field management page but here is how you do it in code. Remember you still have to do a print render($content);, if we wish to hide a field on the page, we can use hide($content['field_name']);. This is another useful function in Drupal 7, which was not available in Drupal 6. For instance, we can hide the file field by using hide($content['field_file']);, which will hide the file field display on the page. Remember, do not to enter print before hide($content['field_file']);, there is no need to enter a print or echo statement, otherwise, it will display some strange characters on the page. As we mentioned at the beginning of this section, we don't have to be PHP experts to understand how theming works. Drupal made the process of theming as simple as possible for us. In the next section, we will style the page using Cascading Style Sheet.
Pop quiz – editing a template file 1. Which of the following code is the correct syntax to output a field in a template file? a. print $field_name; b. print render('$field_name'); c. print render($content['field_name']); [ 220 ]
Chapter 9
2. Which of the following statements is true? a. We cannot add custom HTML to a template file. b. We can hide fields in a template file. c. We cannot hide fields in a template file.
Styling the page using CSS We have themed the recipe content in the previous section, but the visual representation of the information can be improved by using Cascading Style Sheet (CSS). CSS provides us with the ability to control the style and layout of webpages. For instance, we can use CSS to choose a specific font for the body text, and we can use CSS to pick a specific color for an article heading, as long as we have defined some CSS class and ID selectors in HTML files, template files, or through administrative user interfaces.
Time for action – styling the page using CSS In this section, we will style the recipe content using CSS.
1.
Go back to the yummyrecipe theme directory drupalinstall/sites/all/ themes/yummyrecipe/. Find the style.css file in the css directory, and open it in a text editor.
[ 221 ]
Theming Fields
2.
After opening the style.css file, we scroll down to the bottom of page. Copy and paste the following CSS code to the style.css file: /* ---------- Recipe Full Content View Mode ----------- */ .node-type-recipe .node-recipe .field-name-field-image { float: left; } .node-type-recipe .node-recipe .field-name-body { float: left; width: 320px; padding: 10px; border: 1px dotted #238DCF; } .node-type-recipe .node-recipe .content-sidebar { float: left; width:260px; padding: 10px; margin-left: 15px; border: 1px dotted #238DCF; } .node-type-recipe .node-recipe #comments-wrapper { clear: both; }
3.
Save the CSS file, and refresh the webpage in the web browser. Now it should output the page as in the following screenshot:
[ 222 ]
Chapter 9
What just happened? We have styled the recipe content using CSS. As you can see, we only add a few lines of CSS code. The look and feel of the recipe content has now been changed. Not only will this help make the page look nicer, but we can also improve the usability of a website using Drupal theming. If we would like to master Drupal theming, it requires us to have some knowledge of HTML, CSS, and PHP. It is recommended that you learn more about these technologies. There are a lot of excellent books on the PacktPublising website https://www.packtpub.com/. When we gain more and more knowledge and experience, we will realize how Drupal has been offering us such an excellent theming system to help us to create a website quicker than ever.
[ 223 ]
Theming Fields
Pop quiz – styling the page using CSS 1. We cannot control the font color using CSS. a. True b. False 2. We don't have to use CSS when theming a Drupal site. a. True b. False
Have a go hero – theming fields It's time for a challenge. We have learned how to theme a Drupal site by using template files and CSS. We can use the same method we have learned here to theme fields for different content types. We can theme the Cooking Tip content type by creating template files, and styling it using some CSS.
Summary In this chapter, we have learned what a theme is and what theming in Drupal is. We have learned how to create a Drupal theme by cloning the existing theme, and how to create a template file to achieve the template overriding ability in Drupal. We have also learned the basic syntax of how to show and hide fields in a template file. And finally, we have learned how to use CSS to style the page layout on the Drupal site. In the next chapter, we will take a look at a database perspective of how fields work in Drupal. We will learn how the field system manages its database tables in Drupal.
[ 224 ]
10
A Database Perspective of Fields Field API started a revolution in the way we create Drupal sites. It becomes natural to create fields and store data using Field API in the Drupal world. If we try to compare its ancestor, the Flexinode module and the Content Construction Kit module, we realize that field handling in Drupal has kept on adding functionalities and became more mature over the past few years (Field API only emerged in Drupal 7). The underlying database structure of fields has been vastly updated according to the new architecture of Field API in Drupal. In this chapter, we will look at how Field API interacts with the database and its database schema within Drupal. Field API automates much of the process for us, so we don't have to bother about the structure of database schemas or inserting data into tables manually or programmatically. After this chapter, we should have a good understanding of these brand new concepts in Drupal 7, and how Field interacts with database tables. Also we will get more familiar with the database schemas used for Fields within Drupal.
In this chapter, we will cover the following: Key elements in Fields Understand new concepts in Drupal 7 Everything is an Entity versus Everything is a Node dogma Content types (a database perspective) Fields (a database perspective) Field related database tables
A Database Perspective of Fields
Key elements in Fields By now we know that Entities are the new Nodes in Drupal 7. Field API introduces many new changes and concepts, because of the new architecture. Here we will take a look at the field elements available in Field API and give an explanation of what they are. Once we have grasped the concept of Field API we will feel more comfortable when creating our own modules using Field API.
Entities Entities are data units that are fieldable and interact with Drupal APIs. It is a generalization of nodes, users, and taxonomy terms. Entities are collected into bundles.
Bundles A bundle is a collection of fields or it is a thing to attach fields. For instance, Nodes are organized by node types, node modules define node types as bundles. Taxonomy terms are organized by vocabularies. Taxonomy modules define vocabularies as bundles. However, not all entity types have bundles. For instance, Users have no separate bundles.
Field storages Field storages define a primitive database operation that performs low-level control of loading, saving, and deleting data. By default, Field SQL storage modules are part of the Drupal core, which perform load, save, and delete operations for SQL database storage. Field storage modules provide us with the ability to define primitive database operations using Field Storage API in combination with Database API, which can store field data in several different ways. For instance, MongoDB, CouchDB, or Amazon S3 can be used to store field data instead of a MySQL database. Different fields can use different storage engines. This can improve scalability by using different storage engines for different cases.
Field types Field types contain field definitions and data structures, which define the business logic of fields. Field types define how data should be handled before saving the data to database storages. For instance, it decides what it needs to do when users enter data or enter invalid data through Drupal sites. However, Field type only defines the logic of how to handle data, it will not save data or control field displays.
[ 226 ]
Chapter 10
Fields A field comprises a field type and a particular configuration. The field has to have a field name, a field type, and it can have cardinality. Cardinality is the number of values this field will contain. Once the field is created the field type cannot be modified. For instance, we may create an Email field with Text field type, which cannot be changed to a file field at a later stage.
Field instances A field instance is created from a field when fields are attached to a bundle. Simply put, when fields are attached to a bundle, a field instance will be created. Field instances store settings such as formatter and widget settings. Its settings can be changed any time, unlike field type information that cannot be changed once it is created.
Field widgets Field widgets provide a user interface to interact with users. A field widget can be a select list for users to enter data. Field widgets are usually HTML form elements such as text fields, checkboxes, and radio buttons, but can also be as complex as an interactive JavaScript based widget. One more thing about field widgets is they can specify what type of field they can work with. For instance, image field type can only work with image widgets, or file field type can only work with file widgets. Validation is not performed in field widgets, they pass whatever data have been received.
Field formatters Field formatters handle how fields are displayed on screen. Technically, they consist of theme functions and Renderable arrays. Drupal 7 introduces Renderable arrays or Render arrays, which are the data structure of a Drupal page. Simply put, an array with the appropriate data can be used to output/render the content and layout of a page. Just like field widgets, field formatters can specify what type of field they can work with.
Fieldable entities Fieldable entities are entities that contain fields using Field Attach API. The functions of Field Attach API include load, store, and display operations, which also provide a bunch of functions for attaching fields to entities. Not every entity is fieldable, except if the entity is defined to be fieldable.
[ 227 ]
A Database Perspective of Fields
Taxonomy Taxonomy is rebuilt in Drupal 7. It is redesigned using Field API. It provides Term references that can store references to terms. If you have experience of using node reference modules and user reference modules in Drupal 6, Term references are similar. It works like the other fields. Term references can be attached to Bundles, so we can reuse a term reference field for comments and nodes. Taxonomy Vocabulary is also an entity, however, so we cannot attach any field to it. If we have used the Taxonomy hierarchy function in Drupal 6, it can organize terms into hierarchies. However, it is not supported yet in Drupal 7, it would be the job of a contributed module or Drupal upgrade to support this feature in the future.
Pop quiz – key elements in Fields 1. Field types contain a. Data structures only. b. Field definitions and data structures only. c. Field definitions and data structures, which define the business logic of fields. 2. Field widgets provide a. A database abstraction layer to communicate with database servers. b. A user interface to interact with users. c. A container to attach fields. 3. Field instance settings cannot be changed once they are created. a. True b. False
New concepts in Drupal 7 Before we start to look at the database schema of Fields in Drupal 7 we need to introduce a new concept in Drupal 7. This new version of Drupal has completely redesigned the way we deal with nodes and fields, therefore, we should understand the concept behind these changes and realize that the schemas have been redesigned accordingly
[ 228 ]
Chapter 10
Understanding nodes in Drupal If we have used Drupal 6 or any earlier version, almost every piece of content is a node. Drupal provides an extensive API to manipulate its data and extend its functionality.
Data objects
Nodes
Cant’t easily share Fields Image fields File fields ... Users
Comments
Taxonomy
Content
A database schema is a way to organize data such as tables and keys. Or we can think of it is a blueprint of how a database will be constructed.
We usually hear Drupal developers say "Okay, I use Node API to modify and add extra features to a node…". This is one of the hooks from the API that Drupal has provided for us. Nodes were objects, and there were several different types of objects that were part of Drupal core, such as comments and users. However, conceptually or practically, users and comments are not content, each individual object provides unique functionality. There was no easy method to share and reuse fields for different objects, although we could use the generic API to manipulate data. An object is a data structure that includes both data and functions together with interactions.
Turning everything into a node Why would we want to turn everything into a node? Prior to Drupal 7 one of the most compelling reasons to do that was that we could use CCK to add fields to them; another was that we could use all the goodness the Node API provides for us (versioning, update hooks, and so on). There are smart Drupal developers who have created a number of contributed modules, which turned comments and user profiles into nodes. [ 229 ]
A Database Perspective of Fields
These include the Node Comments module (http://drupal.org/project/ nodecomment) and the Content Profile module (http://drupal.org/project/ content_profile). These modules take advantage of the CCK module that allows comments and user profiles to have file fields, taxonomy terms, and revisions. This offers extra power and control to the non-node objects in Drupal.
Data objects Users
Nodes
Comments
Taxonomy
Sharable Fields between Nodes and Node Comments Imagefield Filefield ... Node Comments
A Node
A Node Comment
nid title created changed
cid pid nid title created changed ...
...
Is everything an entity? The statement "everything is a node" is no longer a desirable statement. In Drupal 7, not everything is a node, however, "everything is an entity". Nodes, comments, users, and taxonomy terms are entities. Nodes are a type of entity. Fields are extendable and reusable, which means we can easily create a field to an entity and reuse that field in another entity. If you have been following this book, you will have already experienced how powerful this new architecture is when adding fields to taxonomy terms.
Entities are the new nodes? Drupal 7 introduces the concept of entities, which work as a central piece of a data unit to group all the objects and codes together to be duplicated in different places and streamline the workflow. [ 230 ]
Chapter 10
With this new powerful tool, we don't need to create a module to make something work like a node in order to take advantage of fields. Now we can simply create our own entity, and this entity will make full use of sharable Fields between entities.
Entities
Sharable Fields between entitles Imagefield Filefield ...
Nodes
Users
Comments
Your own entity
Your entity content
Content
Are they entities or objects? This new concept is also a little confusing. Users, comments, and nodes were objects in Drupal 6, and those objects are now called entities in Drupal 7. The question is whether they are objects with a different name, or different data structures to objects. In Drupal 7, we should keep in mind that "objects are not entities". Entities are a Drupal term, just like nodes and taxonomy terms. There is no direct relation to the term used in software engineering and database design, so don't confuse them with ER diagrams and Entity Relationship models in database design. Entities are collections of data which are treated in a consistent manner. Entities, as used in Drupal, are data containers to which fields can be attached and which can be acted upon by Drupal APIs.
Pop quiz – new concepts in Drupal 7 1. Which of the following statements is true, in the context of Drupal 7? a. Everything is an object. b. Everything is a node. c. Everything is an entity.
[ 231 ]
A Database Perspective of Fields
2. Are fields shareable in Drupal 7? a. Yes b. No
A database perspective of fields Now we understand the key elements in Field API. In this section, we will take a look at how Fields interact with databases and its database schema. For instance, what happens to the databases when creating a new content type.
Content types At the very beginning of this book, we learned how to create new content types using Field UI. We can easily create custom content types with versions after Drupal 5. Prior to Drupal 5, we had to write custom code, or we could use Flexinode modules, which are the ancestors of the Content Construction Kit (CCK) modules, in order to create custom content types. With Drupal 6, the CCK module allows us to create, update, and delete content types through the administrative user interfaces. Furthermore, it allows us to enhance the data model of content types by adding additional fields such as texts, numbers, e-mail, images, and files. With this ability, we can create any combination of content types and fields for almost any situation. CCK manages its own database tables for all the content types and CCK fields we have defined in Drupal, which includes the default content types such as Page and Story content types. In Drupal 6, when we create a new content type (for example, Recipe), CCK adds a new entry (row) to the node_type table and creates a new table content_type_recipe in the database. The basic content for this is still stored in the node_revision table. If we now add a new field to the Recipe content type, then new entries are created in the content_node_field and content_node_field_instance tables and the content of the added field is stored in the new content_type_recipe table linked to the recipe node. With Drupal 7, fields inherit the capability and flexibility of CCK, and they have been extended and redesigned. With the new design, the database schema of content types and fields are dramatically updated.
[ 232 ]
Chapter 10
The following is the node_type table that stores information about node types or content types in Drupal: Field
Type
Null
Default
Description
type
varchar(32)
No
The machine-readable name of this type.
name
varchar(255)
No
The human-readable name of this type.
base
varchar(255)
No
The base string used to construct callbacks corresponding to this node type.
module
varchar(255)
No
description
mediumtext
No
A brief description of this type.
help
mediumtext
No
Help information shown to the user when creating a node of this type.
has_title
tinyint(3)
No
Boolean indicating whether this type uses the node.title field.
title_label
varchar(255)
No
The label displayed for the title field on the edit form.
0
A Boolean indicating whether this type is defined by a module (FALSE) or by a user via Add content type (TRUE).
custom
tinyint(4)
No
The module defining this node type.
modified
tinyint(4)
No
0
A Boolean indicating whether this type has been modified by an administrator; currently not used in any way.
locked
tinyint(4)
No
0
A Boolean indicating whether the administrator can change the machine name of this type.
disabled
tinyint(4)
No
0
A Boolean indicating whether the node type is disabled.
The original machine-readable name of this node type. This may be different from the current type name if the locked field is 0.
orig_type
varchar(255)
No
[ 233 ]
A Database Perspective of Fields
The following table stores the content type settings and essential information for each content type in Drupal. In our yummy recipe website, the table should contain the following data: type
article
cooking_tip
page
recipe
name
Article
Cooking Tip
Basic page
Recipe
base
node_content
node_content
node_content
node_content
module
node
node
node
node
description
Use <em>articles for timesensitive content...
Use <em>cooking tip for a cooking tip post.
Use <em>basic pages for your static content, ...
Use <em>recipe for recipes.
has_title
1
1
1
1
title_label
Title
Title
Title
Title
custom
1
1
1
1
modified
1
1
1
1
locked
0
0
0
0
disabled
0
0
0
0
orig_type
article
cooking_tip
page
recipe
help
As we can see, the first column of the table contains the type of content types. In our case, it contains four content types we have created, article, cooking_tips, page, and recipe. These names are the machine-readable names. They only allow lowercase letters, numbers, and underscores.
Time for action – creating a new content type In this section, we will create a new content type through the Drupal administrative user interface; this will demonstrate how content types interact with the node type database table.
1.
Login as administrator. Click on the Structure menu on the top of the administration toolbar, and click on the Content types link.
[ 234 ]
Chapter 10
2.
To create a new content type, click on the Add content type link.
3.
Enter "Recipe Photo" for the content type Name. For Description, we can enter any information to describe this content type.
4.
Click on the Save content type button to store the settings.
5.
If we have installed phpMyAdmin or other database administration tools on our computer, we can use it to manage the databases instead of the command line. This depends on our preference. In this case, we use phpMyAdmin to manage databases.
[ 235 ]
A Database Perspective of Fields
6.
Navigate to the phpMyAdmin administration page, and select the yummyrecipes database from the drop-down menu.
7.
To browse the node type table, we can click on the node_type link on the left of the page.
8.
After clicking on the node_type link, the data structure of the node type table will be displayed on the right of the page. Since we would like to see the table data, not the data structure, we click on the Browse tab to get more information.
[ 236 ]
Chapter 10
9.
As we can see, the Recipe Photo content type is added to the node type table. If we modify the name of the content type through the Drupal administrative user interface, this table will dynamically get updated with the new changes.
What just happened? We have demonstrated how content types interact with the node type table. The ability to create and extend content types is a must have feature in any good content management system. Many other CMS systems usually require us to write code to extend content types. However, Drupal offers us the tools to create content types without writing any code. Moreover, Drupal performs database operations automatically behind the scenes when updating content type data and configurations. As we can see, we could easily create a new content type through the Drupal administrative user interface without knowing the definition of the content type database schema and the PHP code behind the creation of the content type. [ 237 ]
A Database Perspective of Fields
Pop quiz – creating a new content type 1. If we update the content type values through Drupal, Drupal will usually store the values to: a. Files b. Memories c. A database
Fields Fields provide us with the ability to extend the data model of content types. There are a number of database tables that interact with fields closely in Drupal. We can get more information by looking at those tables. For instance, what entity types and fields are created in our Drupal site, and we can even find out which storage type is used for each individual field. The following table is the field_config table that stores field configuration information. Field
Type
Null
Default
Description
id
int(11)
No
The primary identifier for a field.
field_name
varchar(32)
No
The name of this field. Nondeleted field names are unique, but multiple deleted fields can have the same name.
type
varchar(128)
No
The type of this field.
module
varchar(128)
No
The module that implements the field type.
active
tinyint(4)
No
0
Boolean indicating whether the module that implements the field type is enabled.
storage_type
varchar(128)
No
The storage backend for the field.
storage_module
varchar(128)
No
The module that implements the storage backend.
storage_active
tinyint(4)
No
0
Boolean indicating whether the module that implements the storage backend is enabled.
locked
tinyint(4)
No
0
@TODO
data
longblob
No
Serialized data containing the field properties that do not warrant a dedicated column.
[ 238 ]
Chapter 10
Field
Type
Null
Default
Description
cardinality
tinyint(4)
No
0
How many values this field will contain.
translatable
tinyint(4)
No
0
Defines whether the field is translatable.
deleted
tinyint(4)
No
0
A Boolean that determines whether the field was deleted.
In our yummy recipe website, the field_config table should have the following data (note: the following table does not show all of the data from the table):
As we can see, we can find out the created fields, the type of the field, and the storage type of the field from this table for the Drupal site. The field_config_entity_type table has been removed in the final release of Drupal 7. Please refer to http://api. lullabot.com/field_sql_storage_update_7001/7
[ 239 ]
A Database Perspective of Fields
Field-related database tables This section shows the major field related database tables in core. By looking at these tables, we will get familiar with the design of field modules, because the database tables and database schemes reflect the business logic of Field API. This is also very useful when debugging custom modules. The field_config_instance table stores field configuration information. The fields are shown in the following table: Field
Type
Null
Default
Description
id
int(11)
No
The primary identifier for a field instance.
field_id
int(11)
No
The identifier of the field attached by this instance.
field_name
varchar(32)
No
Name of the field.
entity_type
varchar(32)
No
The type of entity associated with this configuration.
bundle
varchar(128)
No
The bundle that this configuration is associated with.
data
longblob
No
Stores the contents of the field.
deleted
tinyint(4)
No
0
A Boolean value that identifies whether this field configuration has been deleted.
The field_data_body table stores details about the body field of an entity. The fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
[ 240 ]
Chapter 10
Field
Type
Null
Default
Description
revision_id
int(10)
Yes
NULL
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields.
body_value
longtext
Yes
NULL
body_summary
longtext
Yes
NULL
body_format
int(10)
Yes
NULL
The field_data_comment_body stores information about comments associated with an entity. The fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
Yes
NULL
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item. The sequence number for this data item. Used for multi-value fields.
delta
int(10)
No
comment_body_ value
longtext
Yes
NULL
comment_body_ format
int(10)
Yes
NULL
[ 241 ]
A Database Perspective of Fields
The field_data_field_image table stores information about images associated with an entity, the fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
Yes
NULL
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields.
field_image_fid
int(10)
Yes
NULL
The files.fid being referenced in this field.
field_image_alt
varchar(128)
Yes
NULL
Alternative image text, for the image's alt attribute.
field_image_title
varchar(128)
Yes
NULL
Image title text, for the image's title attribute.
The field_data_field_tags table stores information about tags associated with an entity. The fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
[ 242 ]
Chapter 10
Field
Type
Null
Default
Description
entity_id
int(10)
No
The entity IDthis data is attached to.
revision_id
int(10)
Yes
NULL
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields.
field_tags_tid
int(10)
Yes
NULL
The field_data_taxonomy_forums table stores information about taxonomy terms associated with forums. (This table is shown if Forum modules are enabled.): Field
Type
Null
Default
Description
entity_type
varchar(128)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
Yes
NULL
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields
taxonomy_forums_tid
int(10)
Yes
NULL
[ 243 ]
A Database Perspective of Fields
The field_data_field_(filefield_name) table stores information about files associated with Entities. (This table is shown if file fields are created. The table name varies.): Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
Yes
NULL
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields.
field_file_fid
int(10)
Yes
NULL
The files.fid being referenced in this field.
field_file_display
tinyint(3)
No
1
Flag to control whether this file should be displayed when viewing content.
field_file_description
text
Yes
NULL
A description of the file.
The field_revision_body table stores information about revisions to body fields, the fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
[ 244 ]
Chapter 10
Field
Type
Null
Default
Description
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
No
0
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item, used for multi-value fields.
body_value
longtext
Yes
NULL
body_summary
longtext
Yes
NULL
body_format
int(10)
Yes
NULL
The field_revision_comment_body table stores information about revisions to comments. The fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
No
0
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
[ 245 ]
A Database Perspective of Fields
Field
Type
Null
Default
Description
delta
int(10)
No
The sequence number for this data item, used for multi-value fields.
comment_body_value
longtext
Yes
NULL
comment_body_format
int(10)
Yes
NULL
The field_revision_field_image table stores information about revisions to images. The fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
No
0
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields.
field_image_fid
int(10)
Yes
NULL
The files.fid being referenced in this field.
field_image_alt
varchar(128)
Yes
NULL
Alternative image text, for the image's alt attribute.
field_image_title
varchar(128)
Yes
NULL
Image title text. For the image's title attribute.
[ 246 ]
Chapter 10
The field_revision_field_tags table stores information about revisions to taxonomy terms/ tags associated with an entity. Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
No
0
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields.
field_tags_tid
int(10)
Yes
NULL
The field_revision_taxonomy_forums table stores information about revisions to taxonomy terms associated with forums. The fields are shown in the following table: Field
Type
Null
Default
Description
entity_type
varchar(128)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
No
The entity revision ID this data is attached to.
language
varchar(32)
No
The language for this data item.
[ 247 ]
A Database Perspective of Fields
Field
Type
Null
Default
Description
delta
int(10)
No
The sequence number for this data item. Used for multi-value fields.
taxonomy_forums_tid
int(10)
Yes
NULL
The field_revision_field_file table stores information about revisions to files. The fields are shown in the following table: Field
Type
Null
Default
Description
etid
int(10)
No
The entity type ID this data is attached to.
bundle
varchar(128)
No
The field instance bundle to which this row belongs. Used when deleting a field instance.
deleted
tinyint(4)
No
0
A Boolean indicating whether this data item has been deleted.
entity_id
int(10)
No
The entity ID this data is attached to.
revision_id
int(10)
No
0
The entity revision ID this data is attached to, or NULL if the entity type is not versioned.
language
varchar(32)
No
The language for this data item.
delta
int(10)
No
The sequence number for this data item, used for multi-value fields.
field_file_fid
int(10)
Yes
NULL
The files.fid being referenced in this field.
field_file_display
tinyint(3)
No
1
Flag to control whether this file should be displayed when viewing content.
field_file_description
text
Yes
NULL
A description of the file.
[ 248 ]
Chapter 10
The file_managed table stores information about uploaded files. The fields are as shown in the following table: Field
Type
Null
Default
Description
fid
int(10)
No
File ID.
uid
int(10)
No
0
The users.uid of the user who is associated with the file.
filename
varchar(255)
No
Name of the file with no path components. This may differ from the basename of the filepath if the file is renamed to avoid overwriting an existing file.
uri
varchar(255)
No
Path of the file relative to Drupal root.
filemime
varchar(255)
No
The file's MIME type.
filesize
int(10)
No
0
The size of the file in bytes.
status
int(11)
No
0
A bitmapped field indicating the status of the file. The least significant bit indicates temporary (0) or permanent (1). Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE
will be removed during a cron run. timestamp
int(10)
No
0
UNIX timestamp for when the file was added.
Pop quiz – a database perspective of fields 1. Which database table stores details about the Body field of an entity? a. field_data_body b. files_managed c. field_revision_taxonomy_forums 2. Which of the following database tables shows the storage type for fields? a. field_config_instance b. field_config_entity_type c. field_config
[ 249 ]
A Database Perspective of Fields
Have a go hero – monitoring value changes between fields and field database tables It's time for a challenge. We have a basic understanding of field database tables. We can use your favourite database administration tools to monitor the value changes from Drupal while we create several different types of fields in Drupal, and then we track the changes using the database administration tools. By doing this, we can understand more about the logic between field modules and field database tables.
Summary We have learned the most prevalent new concepts in Drupal 7. We also looked at the key elements in the new field system. We then moved on to take a look at how content types and fields interact with the database and its database schema within Drupal. Finally, we looked at the field related database tables in Drupal core. Fields automates much of the process for us, managing the database schema and inserting values into tables. After this chapter, we should have a good understanding of how a field interacts with its database tables and schema, and have become familiar with the field related database tables.
[ 250 ]
Pop Quiz Answers The answers to the pop quizzes from each chapter are provided here for your reference. How did you score?
Chapter 1, Nodes and Content types in Drupal 7 Pop quiz – understanding the default content types Question number
Answer
1
c
2
b
Pop quiz – creating content types Question number
Answer
1
a
2
b
Pop quiz – adding content using custom content types Question number
Answer
1
b
2
b
Pop Quiz Answers
Chapter 2, Fields Pop quiz – enabling the Field module Question number
Answer
1
a
Pop quiz – finding the Field UI Question number
Answer
1
b
Pop quiz – finding the field types and input widgets in Field UI Question number
Answer
1
a
2
a
Pop quiz – adding text fields using the text module Question number
Answer
1
a
2
a
Pop quiz – rearranging the order of fields Question number
Answer
1
a
Pop quiz – adding text fields to comments Question number
Answer
1
a [ 252 ]
Appendix
Pop quiz – rearranging the order of fields in comments Question number
Answer
1
a
Pop quiz – reusing fields in content types Question number
Answer
1
a
Pop quiz – reusing fields in content types Question number
Answer
1
c
Chapter 3, Multiple Value Fields Pop quiz – multiple values in fields Question number
Answer
1
a
2
b
Pop quiz – understanding the Boolean field Question number
Answer
1
b
2
b
Pop quiz – setting default values Question number
Answer
1
c [ 253 ]
Pop Quiz Answers
Pop quiz – adding list fields Question number
Answer
1
a
2
b
Pop quiz – understanding multiple value widgets Question number
Answer
1
b
2
a
3
a
Chapter 4, Taxonomy Pop quiz – creating vocabularies Question number
Answer
1
b
2
b
Pop quiz – adding terms to vocabularies Question number
Answer
1
c
2
b
Pop quiz – adding term references to content types Question number
Answer
1
c
2
a [ 254 ]
Appendix
Pop quiz – categorizing content using taxonomy Question number
Answer
1
b
2
a
Pop quiz – adding fields to vocabularies Question number
Answer
1
b
2
b
Chapter 5, File and Image Fields Pop quiz – adding and configuring file field settings Question number
Answer
1
a
2
a
3
a
4
b
Pop quiz – using the file field Question number
Answer
1
b
2
a
Pop quiz – configuring image field settings Question number
Answer
1
a
2
c [ 255 ]
Pop Quiz Answers
Pop quiz – creating custom image styles Question number
Answer
1
c
2
a
Chapter 6, Managing Field Display Pop quiz – a first look at the field display settings Question number
Answer
1
a
2
c
Pop quiz – formatting field display in the teaser Question number
Answer
1
c
2
a
Pop quiz – custom display settings Question number
Answer
1
c
Pop quiz – formatting image field display on Full content Question number
Answer
1
a
2
b
[ 256 ]
Appendix
Pop quiz – formatting comment field display Question number
Answer
1
b
Pop quiz – formatting vocabulary field display Question number
Answer
1
b
Chapter 7, Contributed Field Modules Pop quiz – finding a contributed field module Question number
Answer
1
b
2
b
Pop quiz – installing and enabling contributed modules Question number
Answer
1
b
2
c
Chapter 8, Field Level Permissions Pop quiz – installing and enabling the Field Permission module Question number
Answer
1
b
[ 257 ]
Pop Quiz Answers
Pop quiz – enabling field-level permissions Question number
Answer
1
c
2
b
Pop quiz – configuring field-level permissions on the PERMISSIONS administration page Question number
Answer
1
a
2
b
Pop quiz – the Field permissions report page Question number
Answer
1
a
Chapter 9, Theming Fields Pop quiz – creating a Drupal theme by cloning the existing theme Question number
Answer
1
b
2
b
3
b
Pop quiz – creating a template file for the Recipe content type Question number
Answer
1
c
[ 258 ]
Appendix
Pop quiz – editing a template file Question number
Answer
1
c
2
b
Pop quiz – styling the page using CSS Question number
Answer
1
b
2
a
Chapter 10, A Database Perspective of Fields Pop quiz – key elements in Fields Question number
Answer
1
c
2
b
3
b
Pop quiz – new concepts in Drupal 7 Question number
Answer
1
c
2
a
[ 259 ]
Pop Quiz Answers
Pop quiz – creating a new content type Question number
Answer
1
c
Pop quiz – a database perspective of fields Question number
Answer
1
a
2
c
[ 260 ]
Index A Add content link 108 Add vocabulary link 94 Allowed file extensions settings 127 Amazon S3 226 API 37 Application Programming Interface. See API Article content type about 10, 14, 16, 34 content, creating with 16-19
B Basic page content type 14, 15, 34 BBCode filter module 15 Body field display formatting, in teaser view 153-156 book example project 8 Boolean fields adding 72-74 bundle 226
C Cascading Style Sheet. See CSS CCK module about 33, 232 URL, for downloading 35 comment field display formatting 163, 164 comments fields, adding to 55 fields, creating for 63 text fields, adding to 55-57 Computed field module 185 Contemplate module 185
content adding, with Cooking Tip content type 27-30 adding, with custom content types 27 adding, with Recipe content type 30, 31 categorizing, Recipe Category vocabulary used 113 categorizing, taxonomy used 108-112 creating, with article content type 16-19 Content Construction Kit. See CCK module content_node_field_instance table 232 content_node_field table 232 Content Profile module 230 Content Templates module. See Contemplate module content.txt file 17, 28 content type about 10, 13, 14, 232 article 10, 16 basic page 15 cooking tip 11, 12, 20-24 creating 234-237 fields, adding to 46 fields, creating for 63 file field, adding to 120 file fields, configuring for 120 image fields, adding to 133 recipe 11-13, 24, 26 term references, adding to 102-107 content_type_recipe table 232 content types contributed field modules computed field 185 contemplate 185 email field 184 link 185 table field 185
contributed modules, Drupal about 170 searching 171 searching, through drupalmodules.com website 173-175 searching, through Drupal website 171-173 cooking method category 92 Cooking Tip Category vocabulary creating 94, 95 field, adding to 113-117 terms, adding to 98-102 Cooking Tip content type about 11, 12 categorizing, taxonomy used 108-112 content, adding with 27-30 creating 20-24 fields 34 file field, adding to 128 file field, configuring for 128 image field, adding to 141 term reference field, adding to 103-107 Cooking Tip link 108 cooking website about 8 homepage 10 core modules, Drupal 7 about 42 file 45 image 45 list 44 number 42 taxonomy 44 text 43 CouchDB 226 CSS about 221 webpage, styling with 221-223 custom content types content, adding with 27 creating 20 custom display settings Full content view mode, enabling in 158, 159 custom fields 34 custom image styles creating 141-145
D database schema 229 default content types 19 default values setting 75-77 Devel module 212 Difficulty level option 13 downloading Field Permission module 188, 189 Drupal advantages 169 contributed modules, searching 171 modules 170 theme 204 theming 204 webpage, rendering in 205, 206 Drupal 6 119 Drupal 7 about 8, 119 Boolean fields, adding 72-74 comment field display, formatting 163, 164 content, categorizing with taxonomy 108-112 content types 13, 14 core modules 42-45 custom image styles, creating 141-145 default values, setting 75-77 Field API 225 field display 148 field display, formatting in teaser view 153-156 field display settings 148-152 Field module, enabling 35, 37 fields 35 fields, adding to vocabularies 113-117 Field SQL storage module 37 Field UI, searching 38, 39 file fields, adding to content types 120 file fields, configuring for content types 120 file fields, using 128-132 file module 120 Full content view mode, enabling in custom display settings 158, 159 image field display, formatting on Full content view mode 160-163 image fields, adding to content types 133 image fields settings, configuring 135
[ 262 ]
list fields, adding 78-83 multiple values, enabling 65-71 multiple value widgets 83 taxonomy 91 term references, adding to content type 103107 terms, adding to vocabularies 98-102 vocabularies, creating 93-97 vocabulary field display, formatting 165, 166 Drupal developers 169 drupalmodules.com website contributed field modules, searching through 173-175 Drupal theme creating 207 creating, by cloning existing theme 207-211 Drupal website contributed field modules, searching through 171-173 Drush 170
E edit vocabulary link 114 Email field order, rearranging for 58, 62, 63 Email field module about 184 features 184 installing 176-179 Email text field reusing, in Recipe content type 62 entities 226, 230, 231 everything is a node concept 230 existing fields reusing 59
F fieldable entities 227 Field API 225 field_config_entity_type table 239 field_config_instance table 240 field_config table 238 field configuration information 238 field_data_body table 240, 241 field_data_comment_body 241
field_data_field_(filefield_name) table 244 field_data_field_image table 242 field_data_field_tags table 242, 243 field_data_taxonomy_forums table 243 field display about 148 formatting, in teaser view 153-156 settings 148-152 field formatters 227 field instances 227 field-level permissions configuring, on PERMISSIONS administration page 196-198 enabling 192-194 Field module about 35, 37, 169 enabling 35, 37 Field Permission module downloading 188, 189 enabling 190, 191 field-level permissions, enabling 192-194 Field permissions report page 199-201 installing 190, 191 Field permissions report page 199-201 field related database tables about 240 field_config_instance 240 field_data_body 240, 241 field_data_comment_body 241 field_data_field_(filefield_name) 244 field_data_field_image 242 field_data_field_tags 242, 243 field_data_taxonomy_forums 243 field_revision_body 244 field_revision_comment_body 245, 246 field_revision_field_file 248 field_revision_field_image 246 field_revision_field_tags 247 field_revision_taxonomy_forums 247 file_managed 249 field_revision_body table 244 field_revision_comment_body table 245, 246 field_revision_field_file table 248 field_revision_field_image table 246 field_revision_field_tags table 247 field_revision_taxonomy_forums table 247
[ 263 ]
fields about 8, 35, 227, 232, 238 adding, to comments 55 adding, to content types 46 adding, to Cooking Tip Category vocabulary 113-117 adding, to vocabularies 113-117 creating, for comments 63, 118 creating, for content types 63, 118 existing fields, reusing 59 order, rearranging for 53 Field SQL storage module 37 field storages 226 field types about 226 searching, in Field UI module 40, 41 Field UI module field types, searching in 40, 41 input widgets, searching in 40, 41 searching 38, 39 field widgets 227 file field adding, to content type 120 adding, to Cooking Tip content type 128 adding, to Recipe content type 120-127 configuring, for content types 120 configuring, for Cooking Tip content type 128 configuring, for Recipe content type 120-127 using 128-132 file_managed table 249 File module 45, 120 Full content view mode enabling, in custom display settings 158, 159 image field display, formatting on 160-163
images directory 17 input widgets searching, in Field UI module 40, 41 installation, Email field module 176-179 installing Email field module 176-179 Field Permission module 190, 191 Link module 180-183
K key elements, for fields about 226 bundle 226 entities 226 field 227 fieldable entities 227 field formatters 227 field instances 227 field storages 226 field types 226 field widgets 227 taxonomy 228
L Link module about 185 installing, Update manager used 180-183 list fields adding 78-83 list module 44 long text field adding, with text module 46-50
M
I image field adding, to content types 133 adding, to Cooking Tip content type 141 adding, to Recipe content type 134, 135 configuring, for Recipe content type 136-140 settings, configuring 135 image field display formatting, on Full content view mode 160-163 image module 45 images 119
manage fields page 41 Markdown filter module 15 modules directory 177 modules, Drupal 170 MongoDB 226 multiple values enabling 65-71 multiple value widgets about 83 changing 84, 85
[ 264 ]
file field, adding to 120-127 file field, configuring for 120-127 image field, adding to 134, 135 image field, configuring for 136-140 Notes field, reusing for 59, 60 Source field, reusing for 60, 61 template file, creating for 212-214 term reference, adding to 108
check boxes/radio buttons widget, switching to 87-89 number of values, changing 86, 87
N new content type creating 234-237 node 13, 229 Node Comments module 230 node--recipe.tpl.php template file 214 node_revision table 232 node_type table 233 Notepad++ 214 Notes field order, rearranging for 53, 55, 61 reusing, for Recipe content type 59, 60 number module 42
S salad.jpg file 17 Save and add fields button 23 Save settings button 106 Source field reusing, for Recipe content type 60, 61 starter theme 207 sub-theme 207
O
T
object 229 objects are not entities concept 231 order rearranging, for Email field 58, 62, 63 rearranging, for fields 53 rearranging, for Notes field 53, 55, 61
Table field module 185 taxonomy about 91, 228 Cooking Tip Content, categorizing with 108-112 example 92, 93 taxonomy module 44 Taxonomy term pages 113 teaser view about 153 Body field display, formatting in 153-156 field display, formatting in 153-156 template files craeting, for Recipe content type 212-214 editing 214-220 overriding 212 term reference field adding, to Cooking Tip content type 103-107 term references adding, to content types 102-107 adding, to Recipe content type 108 terms about 92, 93 adding, to Cooking Tip Category vocabulary 98-102 adding, to Recipe Category vocabulary 102 adding, to vocabularies 98-102
P PERMISSIONS administration page field-level permissions, configuring on 196-198 PHP filter module 15 phpMyAdmin 235
R Recipe Category vocabulary about 93 content, categorizing with 113 creating 96, 97 terms, adding to 102 Recipe content type about 11-13, 24 content, adding with 30, 31 creating 25, 26 Email text field, reusing in 62 fields 34
[ 265 ]
text areas 46 text fields adding, to comments 55-57 adding, with text module 46, 51, 52 Textmate 214 text module about 43 long text field, adding with 46-50 text fields, adding with 46, 51, 52 theme about 204 visual elements 204 theming about 204 options 206
V
U
webpage rendering, in Drupal 205, 206 styling, CSS used 221-223
Update manager Field Permission module, using with 190, 191 Link module, installing with 180-183
view modes, for custom display settings 159 vocabularies about 92, 93 Cooking Tip Category vocabulary, creating 94, 95 creating 93-97 fields, adding to 113-117 Recipe Category vocabulary, creating 96, 97 terms, adding to 98-102 vocabulary field display formatting 165, 166
W
[ 266 ]
Thank you for buying
Drupal 7 Fields/CCK Beginner's Guide About Packt Publishing Packt, pronounced 'packed', published its first book "Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions. Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks. Our solution based books give you the knowledge and power to customize the software and technologies you're using to get the job done. Packt books are more specific and less general than the IT books you have seen in the past. Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't. Packt is a modern, yet unique publishing company, which focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike. For more information, please visit our website: www.packtpub.com.
About Packt Open Source In 2010, Packt launched two new brands, Packt Open Source and Packt Enterprise, in order to continue its focus on specialization. This book is part of the Packt Open Source brand, home to books published on software built around Open Source licences, and offering information to anybody from advanced developers to budding web designers. The Open Source brand also runs Packt's Open Source Royalty Scheme, by which Packt gives a royalty to each Open Source project about whose software a book is sold.
Writing for Packt We welcome all inquiries from people who are interested in authoring. Book proposals should be sent to
[email protected]. If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, contact us; one of our commissioning editors will get in touch with you. We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise.
Drupal 7 ISBN: 978-1-849512-86-2 pages
Paperback: 416
Create and operate any type of Drupal 7 website quickly and efficiently 1.
Set up, configure, and deploy a Drupal 7 website
2.
Easily add exciting and powerful features
3.
Design and implement your website's look and feel
4.
Promote, manage, and maintain your live website
Drupal 6 Theming Cookbook ISBN: 978-1-84719-868-6 Paperback: 384 pages Over 100 clear step-by-step recipes to create powerful, great-looking Drupal themes 1.
Take control of the look and feel of your Drupal website
2.
Tips and tricks to get the most out of Drupal's theming system
3.
Learn how to customize existing themes and create unique themes from scratch
4.
Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible
Please check www.PacktPub.com for information on our titles
Drupal 7 Module Development ISBN: 978-1-849511-16-2 Paperback: 420 pages Create your own Drupal 7 modules from scratch 1.
Specifically written for Drupal 7 development
2.
Write your own Drupal modules, themes, and libraries
3.
Discover the powerful new tools introduced in Drupal 7
4.
Learn the programming secrets of six experienced Drupal developers
Drupal Web Services ISBN: 978-1-84951-098-1
Paperback: 320 pages
Integrate social and multimedia Web services and applications with your Drupal Web site 1.
Explore different Web services and how they integrate with the Drupal CMS.
2.
Reuse the applications without coding them again using the Web services protocols on your Drupal site.
3.
Configure your Drupal site to consume various web services by using contributed Drupal modules for each specific task or application.
4.
Drive the content from your Drupal site to Facebook, Twitter and LinkedIn using effective Drupal Web services
Please check www.PacktPub.com for information on our titles
Drupal 6 Themes ISBN: 978-1-847195-66-1 pages
Paperback: 312
Create new themes for your Drupal 6 site with clean layout and powerful CSS styling 1.
Learn to create new Drupal 6 themes
2.
No experience of Drupal theming required
3.
Techniques and tools for creating and modifying themes
4.
A complete guide to the system's themable element
Drupal 6 Social Networking ISBN: 978-1-847196-10-1 pages
Paperback: 312
Build a social or community web site, with friends lists, groups, custom user profiles, and much more 1.
Step-by-step instructions for putting together a social networking site with Drupal 6
2.
Customize your Drupal installation with modules and themes to match the needs of almost any social networking site
3.
Allow users to collaborate and interact with each other on your site
Please check www.PacktPub.com for information on our titles
Drupal 6 Performance Tips ISBN: 978-1-847195-84-5 pages
Paperback: 240
Learn how to maximize and optimize your Drupal framework using Drupal 6 best practice performance solutions and tools 1.
Monitor the performance of your Drupal website and improve it
2.
Configure a Drupal multisite environment for best performance
3.
Lot of examples with clear explanations
4.
Choose and use the best Drupal modules for improving your site's performance
Drupal 6 Site Builder Solutions ISBN: 978-1-847196-40-8 Paperback: 352 pages Build powerful website features for your business and connect to your customers through blogs, product catalogs, newsletters, and maps 1.
Implement the essential features of a business or non-profit website using Drupal
2.
Integrate with other "web 2.0" sites such as Google Maps, Digg, Flickr, and YouTube to drive traffic, build a community, and increase your website's effectiveness
3.
No website development knowledge required
Please check www.PacktPub.com for information on our titles