How to add Javascript in Drupal 7 with jQuery
I thought this would be an easy one. Not so. What works in Drupal 6 doesn't necessarrily work in Drupal 7.
Let's take a simple example. How about a script that allows you to show/hide one or more paragraphs. I did a quick Google search and found numerous examples. Here's the one I picked & slightly modified for the sake of clarity.
<script type="text/javascript">
$(document).ready(function(){
$(".toggler").click(function(){
$(this).next().slideToggle("slow");
return false;
}).next().hide();
});
</script>
<p class="toggler" style="cursor:pointer;">Show/Hide the following paragraph(s).</p>
<div>
This paragraphe is initially hidden. Clicking on the link above will reveal (Show) all the content inside the DIV that immediately follows a "toggler" class paragraph.
</div>
In Drupal 6, simply paste this code in the Body field of a Page or Article node and it works. Well, as usual, there are a few requirements. For the most part, this should do it.
- Go to admin/settings/filters/2 (Full html settings) and uncheck the HTML filter.
- Set the Input format of the Body field to Full html.
- Disable rich-text
- Paste the above code, save and enjoy a moment of true happiness.
The Drupal 7 way
I tried this exact same method in Drupal 7 but by default the <script></script> tags and its content are removed (deleted) by the system for security reasons. There are probably ways to bypass this but it's bad practice.
So we can't embed this script in a Drupal 7 Article node. In the present case, the next best way - a proper way - is to embed the script directly into the Article template of the theme. In doing so, the script will be available for all nodes created with the Article content type. Now, that's even better. So how do we do this?
Show me /Don't show me
I'm using the Antonelli theme, a fluid width subtheme for Bartik. In the Antonelli theme folder (sites/all/themes/antonelli), there is not a simgle template. So I had to look to Antonelli's parent theme for help. In the Bartik folder (themes/bartik), under templates, there is no template for nodes created with the Article content type. But I found node.tpl.php, a generic template for all nodes. This is the template I'll use to create a custom node template for the Article content type. Here's how to do it.- Duplicate node.tpl.php and rename it node--article.tpl.php.
- Open it up with your favorite text editor.
- Paste just the script part of the code before the first line of html.
- The script must then be wrapped inside a jQuery closure function. Otherwise it just won't work. See the References block for more information.
<script type="text/javascript">
(function($) {
// Javascript code
}) (jQuery);
</script>- Save it in your theme's folder. For me, that would be sites/all/themes/antonelli.
- To load the template you just created Resave your theme or Flush all caches.
In the end, here's what the node--article.tpl.php should roughly look like.
...
* @see template_preprocess()
* @see template_preprocess_node()
* @see template_process()
*/
?>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
$(".toggler").click(function(){
$(this).next().slideToggle("slow");
return false;
}).next().hide();
});
})(jQuery);
</script>
<div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
...
Ready for some magic?
- Create a new article.
- Make sure the Input format of the Body field is set to Full html.
- Disable rich-text.
- Paste the following code.
<style type="text/css">
p.toggler:hover {
color:#0071B3;
}
</style>
<p class="toggler" style="cursor:pointer;">Show/Hide the following paragraph(s).</p>
<div>
This paragraphe is initially hidden. Clicking on the link above will reveal (Show) all the content inside the DIV that immediately follows a "toggler" class paragraph.
</div>
Save and then Show/Hide to your heart's content!
Tags:
References: Managing JavaScript in Drupal 7Adding JavaScript to your theme or moduleJavaScript and jQueryIntroducing Drupal Behaviors (Slideshare)Javascript richtig einbindenSolving "$(document).ready is not a function" and other problemsJavaScript Startup Guide (Drupal 6)Uberdrupal: from distribution to profile - Part II
This is part 2 of Uberdrupal: from distribution to profile. Images and more references are on the way.
In Part I of this post, I wrote about the context that led me investigate ways to speedup the installation of various Drupal websites.
Just as you might grab a napkin to sketch out an idea in your favorite joint or reach out for a pad of paper to test a concept with fellow developers at work, one often needs a fresh Drupal code-base (a Drupal napkin) to test and validate ideas. Practice makes perfect. If only installing a fresh Drupal code-base was as easy as grabbing a paper napkin under the glassy gaze of a disillusioned waitress... Actually, piece of cake! As we will soon see. Sort of.
There are many reasons why you would want to grab a Drupal code-base and start playing with it within seconds. I already mentioned testing concepts or bringing ideas to life. But there's much more: checking out the latest version of a module in an isolated environment, tracking down pesky bugs, comparing the many ways to implement a photo gallery or an animated banner, validating assumptions, etc.
In my case, I was looking for a way to quickly setup a Drupal 6 Ubercart store with some pre-built generic content. As far as I know, there's only one distribution that fits this bill and it's UberDrupal. In fact, UberDrupal does exactly what I want: it creates a Home and About us page and a $10 Example product. That's great! Now then, can I use this distribution's inner workings to create the pages, menus and products I need for my own use case? Yes you can!
The first issue is that UberDrupal's magic is frozen into the distribution (hard-coded if you prefer). The second issue is that with a release date going back to 2010-Oct-19, UberDrupal is, let's face ot, getting old. It was shrink-wrapped in October 2010 with the latest versions of Drupal core & Ubercart available at that time i.e. Drupal 6.19 and Ubercart 2.4. That's not bad per se. In fact, UberDrupal 6.x-1.0-alpha8 will install without a hitch. But wouldn't it be nice if you could upgrade to today's latest versions of Drupal (6.22) and Ubercart (2.7)? Wouldn't it be great if you could add a few of your favorite modules and libraries to the list? And while we're at it, let's be greedy, wouldn't it be awesome if you could have it create the basic products, menus and pages (nodes) that you will otherwise have to generate every time you create a fresh install?
Well, thanks to Ryan Szrama (rszrama), UberDrupal does all that. All we need to do is (1) crack open the distribution, (2) extract the installation profile, (3) change it so it will do exactly what we want it to do. Sounds like we have a plan.
Requirements - Note: each one of those requirements is worth a separate article. Look for more info in the Related content and References & documentation blocks.
- a tested & working local development environment (e.g. MAMP, LAMP, WAMP, etc.)
- appropriate entries in etc/hosts and httpd.conf.
- a fresh MySQL database (you can use phpMyAdmin for that)
- Drush
- Drush Make
OK, here we go!
- Download a copy of Uberdrupal.
- Once unpacked, what you will see is a standard Drupal 6 directory structure. All the magic is hidden in the profiles/uberdrupal directory. Makes sense.
- The mere presence of the modules and themes directories inside profiles/uberdrupal (along with Drupal core, on the outside) tells you that this package is a distribution.
- Because we're creating an installation profile (and not a distribution), we can safely delete the modules and themes directories (as well as Drupal core) keeping only the uberdrupal directory because the profile will download fresh copies (obviously, you will need a live Internet connection for this to work).
Now in order to transform the UberDrupal distribution into a self-contained installation profile, we need to make some changes. As mentioned in Part I of this post, a basic installation profile is made up of 3 files. In the present case, these files are: uberdrupal.info, uberdrupal.make and uberdrupal.profile. As you've probably noticed, uberdrupal.info doesn't exist. So let's create it.
- Create an empty text-only file and save it as uberdrupal.info
- Add the following lines to the file, save it and close it. We're done with this one.
; Use semi-colons to add comments. ; Installation profiles are great! name = UberDrupal description = Installs and creates a basic Ubercart store. core = 6.x theme = acquia_proper
Next on our list is drupal-org.make. In this file, you can get a sense of what the original UberDrupal distribution was made of (Drupal core 6.19, etc.). The first thing we need to do is to rename this file to uberdrupal.make. Then replace its contents with what follows.
; This is the installation profile's makefile (the inner one). core = 6.x api = 2 ; CONTRIB MODULES ;projects[name_of_project] = version_number ;projects[name_of_project][subdir] = name_of_subdir projects[cck] = 2.9 projects[cck][subdir] = contrib projects[imagefield] = 3.10 projects[imagefield][subdir] = contrib projects[filefield] = 3.10 projects[filefield][subdir] = contrib projects[imageapi] = 1.10 projects[imageapi][subdir] = contrib projects[imagecache] = 2.0-beta12 projects[imagecache][subdir] = contrib projects[lightbox2] = 1.11 projects[lightbox2][subdir] = contrib projects[skinr] = 1.6 projects[skinr][subdir] = contrib projects[token] = 1.18 projects[token][subdir] = contrib projects[ubercart] = 2.7 projects[ubercart][subdir] = contrib ; THEMES projects[fusion] = 1.12 projects[acquia_prosper] = 1.1 ; PROFILER - 2.0-beta2 ; The following are required by Profiler when you create an installation profile. libraries[profiler][download][type] = "get" libraries[profiler][download][url] = "http://ftp.drupal.org/files/projects/profiler-6.x-2.0-beta2.tar.gz"
Why this content you ask? And why is it formated that way? I won't answer these questions here. But if you must know, watch Dmitri's Drupalcon Chicago presentation. Not only is it informative, it's quite entertaining. Dmitri is simply awesome. If you're in a bit of a hurry, check out Drush Make and Profiler - a brief overview.
Next on our list is uberdrupal.profile. Remember, this is the file that holds the installation script. We need to make one change here. Copy the following code and simply paste it at the top of the file, just below the <? php/ tag.
!function_exists('profiler_v2') ? require_once('libraries/profiler/profiler.inc') : FALSE;
profiler_v2('uberdrupal');Why? Because Drush Make requires this library to generate php code from the makefile (uberdrupal.make). See References & documentation for more background information. If you want to customize the script, go right ahead. It's pretty self-explanatory. For now, I'm going to leave it as is.
There is a fourth file in the uberdrupal directory named ubercart_image.pkg.inc. We don't need to change anything for this one. Just leave it as is.
We have a working installation profile. Now what? The simple answer is: we need a trigger. And then, we need to pull on that trigger. Before we move on, make a tar.gz archive of the uberdrupal directory with the 4 files in it. We will need it later.
The trigger itself is just another makefile. It is the overarching or parent makefile that we will use to call the uberdrupal installation profile.
Create a new text-only file, paste in the following lines and save it as uberdrupal_inst_profile.make. The name could be anything you fancy as long as it ends with .make.
; This is the overarching or parent makefile for the Uberdrupal installation profile. ; It will install Drupal as well as all the projects listed below. core = 6.x api = 2 ; REMINDER: when creating an installation profile, this is the proper place to download Drupal core. projects[] = drupal ; Calling the profile. projects[uberdrupal][type] = profile projects[uberdrupal][download][type] = get projects[uberdrupal][download][url] = "http://path-to-dir/uberdrupal.tar.gz" ; The following modules will be downloaded into sites/all/modules projects[admin_menu][version] = 1.8 projects[module_filter][version] = 1.6 projects[devel][version] = 1.26
Two quick comments here. First, I like to keep my installation profiles where I can access them from anywhere and from any machine. But you can also keep/store them locally. Just set the URL accordingly.
Second, you'll notice that I'm downloading the admin_menu, module_filter and devel modules. Why here you ask? And the answer is: that's just the way I like to work. See References if you're curious or just ask by posting a comment.
Only one thing left and that is to pull on the trigger. Any volunteers? Assuming your dev environment is drush-make ready (see requirements above):
- open up a terminal window (command line)
- go to the root of your development environment (for me it is /Applications/MAMP/ htdocs)
- run the following command
drush make --prepare-install uberdrupal_inst_profile.make uberd
This command tells Drush to install UberDrupal as per the installation profile's instructions into the uberd directory. Watch the magic and smile. From here on, just do as you would normally do for a regular Drupal install (i.e. go to your website's URL, choose the profile we've just created, and so on...).
If it doesn't work at first, don't be discouraged, just backtrack a few steps and try again, slowly. A little reading always helps. You'll eventually get it right and, like me, you'll soon be jumping up and down, stretching your t-shirt in all directions. And there's nothing silly about that... or is there?

Tags:
References: From Zero to Distribution using Features, Profiler, and Drush Makesites/all/modules vs profiles, the pros and consDrush Make Files for Production Drupal sitesEvery Drupal Site is an Install ProfileInstalling Drush on Mac OS XUberdrupal: from distribution to profile - Part I
I've been experimenting with installation profiles for some time now. It all started with a Drupalcon Chicago presentation by Dmitri Gaskin (dmitrig01): From Zero to Distribution using Features, Profiler, and Drush Make. A year ago, on a bad day, setting up a fresh Drupal installation in order to test a module or try some new tricks in Views could take me as much as two hours. The possibility of installing Drupal with a custom list of contrib modules in less than a minute seemed like science-fiction at the time.
Setting up a Drupal website on a shared server or locally with MAMP, LAMP or WAMP requires a fair bit of 'prior' technical knowledge that experienced Drupal users take for granted. The lack of which inevitably stumps a newcomer into an uncontrolled rage of frustrations. I know. I've been there.
The first time I installed Drupal, I think it must of taken me a month or so. Plain ignorance, as in 'not knowing much in general', was one reason it took me so long. Ego also played its part: I thought I would skip a few 'classes' and tackle a multisite installation right off the bat. In the end, after a stubborn and somewhat senseless battle, I eventually succeeded. When I finally read 'Welcome to {Your Site Name}', I stood up in front of my computer, jumping up & down with my two arms raised above my head and then pulling on my t-shirt like I just scored the gold-medal-winning goal at the 2014 Mundial. Silly me.
Nowadays, every Drupal project I work on starts with a distribution profile. It helps me to quickly map out my goals and visualize the best way to get there.
As a side note, I've been thinking about sharing what I've learned in a mini-series of tutorials or screencasts. Maybe this post will ring the bell for round 1.
So in case I'm not making myself clear, this post is about how I modified an existing distribution into an installation profile and what I gained in doing so. The distribution I used is UberDrupal and you can download it here: http://drupal.org/project/uberdrupal.
On the UberDrupal project page, one can read the following. 'UberDrupal is an installation profile designed to help you get a Drupal site running Ubercart up as quickly as possible.' In fact, the UberDrupal distribution contains in a single download: Drupal core, Ubercart's core set of modules and an installation script that guides you through the setup of a very basic online store in one go. If all goes well, your new 'empty' site will be up before your eyes within 5 minutes. Not bad when you consider that doing it piecemeal will easily cost you a couple of hours - assuming you know what you're doing.
I should clarify one thing before I continue and that is the difference between a distribution and an installation profile.
A distribution is a package that includes all modules & files required for installing a fresh Drupal website. It includes an installation profile. A distribution cannot exist without an installation profile. When you download and install Drupal 7, you're actually downloading a distribution which offers you the choice between 3 different installation profiles: minimal, standard or testing. The UberDrupal distribution weighs in at 3.34 MB.
You can think of an installation profile as the genetic signature of a particular Drupal install or codebase. It can perfectly exist withtout modules & files. When called or invoked with an appropriate command, an installation profile will fetch all modules & libraries that appears in its internal list and build a Drupal website on the fly. The UberDrupal installation profile weighs in at just 6,267 bytes.
The makings of an installation profile are very similar to that of a module. A basic profile is made up of 3 files: a '.info' file which minimally names and describes the profile; a '.make' file which lists the required modules & libraries; and a '.profile' file that contains the script (if any) for setting up and configuring the Drupal website.
In Part II of this post, I'll drop the theory and show how easy it is to transform the UberDrupal distro into a profile, update it and customize it the way you want it.
Uberdrupal: from distribution to profile - Part II