Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Removing a content type

From: Drupal 7 Custom Module Development

Video: Removing a content type

Let's continue with the best practice of leaving a clean slate upon uninstall by removing the content type that was created. If I just delete the content type, it doesn't take into account any fields or instances I've added. So those should be removed cleanly as well. Finally, if I remove the content type, the existing nodes will be orphaned and will really mess up functionality. Therefore, it makes sense to delete those nodes as well. I'll start by removing the existing content of type windfarm. To do that I'm going to leverage and Drupal function called node_delete_multiple which deletes a group of nodes based on array of their node IDs.

Removing a content type

Let's continue with the best practice of leaving a clean slate upon uninstall by removing the content type that was created. If I just delete the content type, it doesn't take into account any fields or instances I've added. So those should be removed cleanly as well. Finally, if I remove the content type, the existing nodes will be orphaned and will really mess up functionality. Therefore, it makes sense to delete those nodes as well. I'll start by removing the existing content of type windfarm. To do that I'm going to leverage and Drupal function called node_delete_multiple which deletes a group of nodes based on array of their node IDs.

I'll assemble that list using a database query. One of the features and Drupal 7 is a database abstraction layer which should be leveraged whenever dealing with user input. This layer unifies the interactions with different database servers and provides a structured interface for building queries, providing security, and other best practices. Interactions with a full object-oriented database abstraction layer will be covered in a later chapter. In this particular circumstance it's a cannon to kill a fly. I just need a list of all node IDs of type windfarm and no user input is required.

Therefore, it's acceptable within Drupal coding standards and in this circumstance to use db_query which executes an arbitrary query string against the database connection while still leveraging the database abstraction. In the IDE, open windfarm start install and navigate to hook uninstall. I'll start with a comment describing what I'm about to do, Get all node IDs with windfarm content type. Next, define the query itself. Nodes themselves are stored in a database table called node and their primary key is NID short for Node ID.

All we need is the Node ID. So I will select only that; $sql_query = 'SELECT nid'. Next, the from. One of the things that db_query does is perform string replacement in conjunction with the database settings. If for example, a database configuration had prefixed all tables with Drupal_ then "FROM node" wouldn't work. Therefore, table names are wrapped in curly braces; db_query will in turn replace those curly braces with whatever table prefix is necessary, and strip out the braces.

So the end result will look like a standard SQL query. Nodes are stored in the node table. So $sql_query .= 'FROM {node}';. Context is needed for the query. In particular, the content type should be specified as a filter. The type name is stored by machine name in the node table under the column type. In addition to replacing the curly braces with proper table names, db_query also performs variable replacement. There are two formats for placeholders for variable replacement, named and unnamed.

Best practice is to always use named placeholders as they're more flexible and provide context. Named placeholders always start with a colon, followed by letters, numbers, and underscores. Unnamed placeholders are just question marks. This works, but if you have a lot of placeholders this gets confusing, and therefore isn't recommended. When using a placeholder no quotes are necessary. $sql_query .= 'WHERE {node}.type = :type';.

Finally, assign the variable result to db_query. The first parameter is the query string itself followed by an array of arguments that are keyed by the placeholder name with a value of what we would like to filter. Db_query returned to prepare statement object that has been executed. These objects can be iterated through like an array which is quite convenient. Create an empty array to hold the node IDs; $nids = array(). Iterate through the result.

Results will return standard objects which relate each row returned from the database query. So foreach ($result as row). As I selected only the node ID, known as an nid, all a need to do is add that value to the nids = $row->nid;. Now that the array of node IDs has been prepared it can be passed to node_delete_multiple. That function doesn't return anything so it's okay just to call it on its own, Delete all windfarm content.

Node_delete_multiple ($nids); and inform the user of what just happened. Drupal_set_message($t('Wind Farms content removed.'));. Now that the content is deleted, let's get rid of the fields and field instances associated with the content type. Start with the logical comment, Removed all fields and field instances. Next, I'll call field_info_instances which gets all field instances of associated with the entity type and bundle.

Field info instances takes two parameters: the entity type, and the bundle name which in this case is node and windfarm. The instances are returned as a nested array known as the instant structure keyed by the field name. So I'm going to iterate foreach (field_info_instances( of 'node' and 'windfarm' to be specific, as $field_name => $instance);. Before I get rid of the instance I'll delete the field as well.

I will use method field_delete_field which just takes one parameter, the field name. Field_delete_field($field_name);. Then field_delete_instance, just takes an instance structure which field info instance returns. Again, let the user know what just happened. This is unnecessary in most contexts, but it's good for testing and development. Drupal_set_message($t('Wind Farms field and field instances removed.'));.

The fields and instances have been removed in one loop. Now that the content, fields, and field instances have been removed, the content type itself can be removed. After everything that has been done, the actual removal of the content type itself is a one line call function node_type_delete which takes one parameter, the name of the node type. Delete the content type. Node_type_delete('windfarm'); then provide a message to the user; drupal_set_message($t('Wind Farm Content Type removed.'));.

One final step remains and this is more of a regular maintenance. When deleted, a field actually persists for little while until it can be cleanly removed by a regularly scheduled cron. This can be accelerated especially when the removal is on-demand. The function field_purge_batch takes one parameter, the size of the batch, and can be used to remove these deleted fields. Clean up deleted fields and then we'll call field_purge_batch with the batch size of 1000.

Save the file then return to the browser. Go to the Modules list, then disable Wind Farms, Uninstall the Wind Farms Module, and confirm. The page now displays messages stating that everything has been removed relating to the Wind Farms module. Go to the Content tab and the Wind Farm Content is now missing. This is a good thing. All traces of the wind farms module have been removed from the system cleanly which eliminates the possibility of strange behaviors later with half broken references to missing code and content.

Go back to the Modules list and re-enable the Wind Farm content type as we'll be needing it later. In this chapter, I introduced content types, created a custom content type, added fields, and field instances through the content type, validated user input, then cleanly removed all data relating to the custom content type. Next, I'll explore how to build upon this foundation leveraging third-party modules and demonstrating new areas of Drupal functionality.

Show transcript

This video is part of

Image for Drupal 7 Custom Module Development
Drupal 7 Custom Module Development

24 video lessons · 5376 viewers

Jon Peck
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Drupal 7 Custom Module Development.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.