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

Exploring best practices with variable persistence

From: Drupal 7 Custom Module Development

Video: Exploring best practices with variable persistence

In the previous video, I used variable_get with a default value to populate the form with sensible defaults. This works quite well when the form is submitted, but what happens if functionality that requires those variables is triggered? They just won't be there unless I use a variable_get that also has default values. That doesn't scale well however. What if I want to use that variable in a dozen places? Then I have to define a default value a dozen times. Then if I ever change the default then I have to re-factor all those places, and so forth.

Exploring best practices with variable persistence

In the previous video, I used variable_get with a default value to populate the form with sensible defaults. This works quite well when the form is submitted, but what happens if functionality that requires those variables is triggered? They just won't be there unless I use a variable_get that also has default values. That doesn't scale well however. What if I want to use that variable in a dozen places? Then I have to define a default value a dozen times. Then if I ever change the default then I have to re-factor all those places, and so forth.

That approach doesn't scale well. Instead, I will leverage a one-time triggered event when a module is installed to set the defaults in one place using hook_install. Return to the IDE. By convention, hook_install is always placed in its own file named module name.install. Therefore for the windfarms module I will create a New > Empty File called windfarms.install, windfarms.install. Install files are just PHP scripts, so I will start the file with an open PHP tag and a file level doc block, Wind Farms installation.

Then create a new doc block for the hook_ install implementation, Implements hook_install. Create a new function called windfarms.install. Hook_install takes no parameters. Then add an in-line comment. I'm initializing the variables in hook_install, so I'll just say that, Set default variables.

Using variable_set, set the four variables with the appropriate defaults; windfarms_gmap set to 1, variable_set ('windfarms_default_center_lat') set to 42.91455, variable_set ('windfarms_default_center_long') is set to -75.569851, variable_set ('windfarms_default_gmap_zoom') is set to 8.

Include a message to the user to describe what happened. Now before I do that there is a gotcha that can be slightly confusing. While the t localization function is used extensively throughout module development, there are times when the t function is not directly available. Drupal doesn't have access to the database in the early parts of the installation process, and as such there are actually multiple mechanisms available for translation. Depending on when it's invoked, Drupal requires the use of one of two translation functions.

This can be bit unwieldy but there is a compromise. By using the get_t function in an ambiguous circumstance such as a module installation the contextually appropriate translation function can be used. Start with a comment, Get localization function for installation as t() may be unavailable. Assign the t variable to get_t. Using the t variable give the user feedback, drupal_ set_message ($t ('Wind Farms variables created.')).

When removing a program it's common to find bits and pieces left around. This is at best annoying. Therefore it's best practice to clean up when removing a module. There is a companion hook to hook_ install called hook_uninstall. Similar to hook_install, hook_uninstall is only called once, but unlike hook_install it must be explicitly executed after the module is disabled. Start with the doc block stating that this function implements hook_uninstall, Implements hook_uninstall().

Like hook_install, hook_uninstall takes no parameters; function windfarms_uninstall using the variable_del function delete the variables that were created, variable_del ('windfarms_gmap'), variable_del. I'll copy and paste from above to save time, variable_del for longitude, variable_del and the zoom.

Next inform the user of the removal using drupal_set_message and using the t variable to provide access to the translation function. Inform the user of the removal, $t = get_t(), then drupal _set_message ($t('Wind Farms variables removed.')). Save, then return to windfarms.module and remove the default values, so there is a single point of entry for the defaults.

First the Google Maps toggle, the latitude and longitude and the zoom. Save the module and return to the browser. Reload the page without the form submission to verify that the persistence is working. Next, go to the Modules Interface, scroll to Other, unchecked the box next to Wind Farms to disable it and click Save configuration.

Now that the module is disabled you can go to the Uninstall tab. The Wind Farms module will be listed, check the Uninstall box next to Wind Farms, then click Uninstall. You'll be given a confirmation screen confirmed by clicking Uninstall. Two messages are displayed. The first is the custom message that I set about Wind Farms variable being removed, and the second is a generic message. Return to the module list, let's scroll to the bottom and enable Wind Farms.

This time an additional message is shown, Wind Farms variables created. This act of customizing settings for a module from an administrative interface is a common and sometimes repetitive task. Drupal has some mechanism that will simplify this process by performing the repetitive aspects. In particular, the Submit button, saving the variables and giving a message to the user. For the purposes of this course, it's useful to show how the Drupal form API interacts which is why I'd walk you through that process. Now that the demonstration is complete, I'll simplify the form leveraging an additional function and reduce the overall amount of code.

Return to the IDE and open windfarms.module, completely remove the submit handler. Next, go to the bottom of the form creation and remove the Submit button. Replace the return form with a call to another function, system_settings_form, which takes one parameter the form. This will allow Drupal to add additional form elements, save the variables and give a generic message to the user, Save, then return to the browser.

Go to Configuration, then Wind Farms Settings. Notice that the Submit button now says Save configuration. This is the default. Change the zoom and some other elements and click Save configuration, you'll now see a more generic message, The configuration options have been saved. Leveraging built-in Drupal functionality the system still performs in the same manner, but with a lot less repetitive code.

I'll reload the page and verify that the persistence works. There is one final touch that I will add to the admin interface, an easy link to the configuration page from the module list. Go to the IDE and open windfarms.info. Add line at the end of the file with a key configure, and the value as the path to the administrative interface that was just created, admin/config/windfarms/manage.

Save then return to the Drupal site and go to the Modules list. Scroll to the bottom and a new link to the configuration page is now shown next to Wind Farms, click on it to see how it works. Throughout this chapter, the administrative interface has been created. I demonstrated the Menu and Form API, variable persistence, how to install and uninstall a module, then how to simplify the creation of an administrative interface. In the next chapter I will create and populate the new content type for storing instances of a Wind Farm.

Show transcript

This video is part of

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

24 video lessons · 5300 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.