Start learning with our library of video tutorials taught by experts. Get started

Drupal 7 Custom Module Development

Removing a content type


From:

Drupal 7 Custom Module Development

with Jon Peck

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.

Watch this entire course now—plus get access to every course in the library. Each course includes high-quality videos taught by expert instructors.

Become a member
Please wait...
Drupal 7 Custom Module Development
2h 57m Advanced Oct 16, 2012

Viewers: in countries Watching now:

Extend your Drupal 7 sites with custom modules, which allow you to create everything from admin interfaces to forms. Author Jon Peck describes how modules extend your base Drupal installation, then walks through how to write your own module with a practical example featuring geo-positioned alternative energy centers. The course also describes how to control access to site features, create new content types, build forms, understand data persistence, embrace coding standards, and much more.

Topics include:
  • Creating your first module
  • Interacting with hooks
  • Working with permissions and roles
  • Controlling access
  • Adding a menu item to an admin interface
  • Using the Form API (FAPI) to quickly create a form
  • Creating custom form validation
  • Manually creating a custom content type
  • Validating user input
  • Importing content using feeds
  • Creating a block
  • Understanding best practices and coding standards
Subjects:
Developer Web CMS Blogs Web Design Programming Languages Web Development
Software:
Drupal
Author:
Jon Peck

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.

Find answers to the most frequently asked questions about Drupal 7 Custom Module Development.


Expand all | Collapse all
Please wait...
Q: gmap3_tools is not working the way I expected it to. What version of gmap3_tools should I be using?
A: Use the free exercise file containing the version of gmap3_tools used for recording; the published version of the module on drupal.org has changed since recording and is not backwards compatible.
Q: I attempted to run the Drupal site root from the project files, but the site isn't loading. Why not?
A: The Drupal configuration file in sites/default/settings.php contains database configuration specific to the environment used to record the movie. This may be different than your environment. Edit the file and search for "windfarms" - you may need to change the database host, username, password, db name and port to match your specific environment.
Share a link to this course
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.
Upgrade now


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.

join now

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
Welcome to the redesigned course page.

We’ve moved some things around, and now you can



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.

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