Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Web Development

1802 Articles
article-image-social-bookmarking-wordpress-plugin
Packt
08 Oct 2009
6 min read
Save for later

Social Bookmarking with WordPress Plugin

Packt
08 Oct 2009
6 min read
You will learn these by creating a Social Bookmarking type of plugin that adds a Digg button to each post on your blog As you probably know, Digg is a very popular service for promoting interesting content on the Internet. The purpose of a Digg button on your blog is to make it easier for Digg users to vote for your article and also to bring in more visitors to your blog. The plugin we'll create in this article will automatically insert the necessary code to each of your posts. So let's get started with WordPress plugin development! Plugging in your first plugin Usually, the first step in plugin creation is coming up with a plugin name. We usually want to use a name that is associated with what the plugin does, so we will call this plugin, WP Digg This. WP is a common prefix used to name WordPress plugins. To introduce the plugin to WordPress, we need to create a standard plugin header. This will always be the first piece of code in the plugin file and it is used to identify the plugin to WordPress. Time for action – Create your first plugin In this example, we're going to write the code to register the plugin with WordPress, describe what the plugin does for the user, check whether it works on the currently installed version of WordPress, and to activate it. Create a file called wp-digg-this.php in your favorite text editor. It is common practice to use the plugin name as the name for the plugin file, with dashes '-' instead of spaces. Next, add a plugin information header. The format of the header is always the same and you only need to change the relevant information for every plugin: <?php /* Plugin Name: WP Digg This Version: 0.1 Description: Automatically adds Digg This button to your posts. Author: Vladimir Prelovac Author URI: http://www.prelovac.com/vladimir Plugin URI: http://www.prelovac.com/vladimir/wordpress-plugins/ wp-digg-this */ ?> Now add the code to check the WordPress version: /* Version check */ global $wp_version; $exit_msg='WP Digg This requires WordPress 2.5 or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress">Please update!</a>'; if (version_compare($wp_version,"2.5","<")) { exit ($exit_msg); } ?> Upload your plugin file to the wp-content/plugins folder on your server using your FTP client. Go to your WordPress Plugins admin panel. You should now see your plugin listed among other plugins: This means we have just completed the necessary steps to display our plugin in WordPress. Our plugin can be even activated now—although it does not do anything useful (yet). What just happened? We created a working plugin template by using a plugin information header and the version check code. The plugin header allows the plugin to be identified and displayed properly in the plugins admin panel. The version check code will warn users of our plugin who have older WordPress versions to upgrade their WordPress installation and prevent compatibility problems. The plugin information header To identify the plugin to WordPress, we need to include a plugin information header with each plugin. The header is written as a PHP comment and contains several fields with important information. This code alone is enough for the plugin to be registered, displayed in the admin panel and readied for activation. If your future plugin has more than one PHP file, the plugin information should be placed only in your main file, the one which will include() or require()  the other plugin PHP files. Checking WordPress versions To ensure that our plugin is not activated on incompatible WordPress versions, we will perform a simple WordPress version check at the very beginning of our code. WordPress provides the global variable $wp_version that provides the current WordPress version in standard format. We can then use PHP function version_compare() to compare this and our required version for the plugin, using the following code: if (version_compare($wp_version,"2.6","<")) { // do something if WordPress version is lower then 2.6 } If we want to stop the execution of the plugin upon activation, we can use the exit() function with the error message we want to show. In our case, we want to show the required version information and display the link to the WordPress upgrade site. $exit_msg='WP Digg This requires WordPress 2.6 or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress">Please update!</a>'; if (version_compare($wp_version,"2.6","<")) { exit ($exit_msg); } While being simple, this piece of code is also very effective. With the constant development of WordPress, and newer versions evolving relatively often, you can use version checking to prevent potential incompatibility problems. The version number of your current WordPress installation can be found in the footer text of the admin menu. To begin with, you can use that version in your plugin version check (for example, 2.6). Later, when you learn about WordPress versions and their differences, you'll be able to lower the version requirement to the minimal your plugin will be compatible with. This will allow your plugin to be used on more blogs, as not all blogs always use the latest version of WordPress. Checking the plugin You can go ahead and activate the plugin. The plugin will be activated but will do nothing at this moment. Time for Action – Testing the version check Deactivate the plugin and change the version check code to a higher version. For example, replace 2.6 with 5.0. if (version_compare($wp_version,"5.0","<")) Re-upload the plugin and try to activate it again. You will see a WordPress error and a message from the plugin: What just happened? The version check fails and the plugin exits with our predefined error message. The same thing will happen to a user trying to use your plugin with outdated WordPress installation, requiring them to update to a newer version. Have a go Hero We created a basic plugin that you can now customize. Change the plugin description to include HTML formatting (add bold or links to the description). Test your plugin to see what happens if you have two plugins with the same name (upload a copy of the file under a different name).
Read more
  • 0
  • 0
  • 7031

article-image-taxonomy-and-thesauri-drupal-6
Packt
08 Oct 2009
6 min read
Save for later

Taxonomy and Thesauri in Drupal 6

Packt
08 Oct 2009
6 min read
What and Why? Taxonomy is described as the science of classification. In terms of how it applies to Drupal, it is the method by which content is organized using several distinct types of relationship between terms. Simple as that! This doesn't really encompass how useful it is, though, but before we move on to that, there is a bit of terminology to pick up first: Term: A term used to describe content (also known as a descriptor) Vocabulary: A grouping of related terms Thesaurus: A categorization of content that describes is similar to relationships Taxonomy: A categorization of content into a hierarchical structure Tagging: The process of associating a term (descriptor) with content Synonym: Can be thought of as another word for the current term. It may help to view the following diagram in order to properly grasp how these terms inter-relate. This serves to illustrate the fact that there are two main types of vocabulary. Each type consists of a set of terms, but the relationships between them are different in that a taxonomy deals with a hierarchy of information, and a thesaurus deals with relationships between terms. The terms (shown as small boxes) and their relationships (shown as arrows) play a critical role in how content is organized. One of the things that makes the Drupal taxonomy system so powerful, is that it allows content to be categorized on the fly (as and when it is created). This unburdens administrators because it is no longer necessary to moderate every bit of content coming into the site in order to put it into pre-determined categories. We'll discuss these methods in some detail in the coming sections, but it's also worth noting quickly that it is possible to tag a given node more than once. This means that content can belong to several vocabularies, at once. This is very useful for cross-referencing purposes because it highlights relationships between terms or vocabularies through the actual nodes. Implementing Controlled Taxonomies in Drupal The best way to talk about how to implement some form of categorization is to see it in action. There are quite a few settings to work with and consider in order to get things up and running. Let's assume that the demo site has enlisted a large number of specialists who will maintain their own blogs on the website so that interested parties can keep tabs on what's news according to the people in the know. Now, some people will be happy with visiting their blog of choice and reading over any new postings there. Some people, however, might want to be able to search for specific topics in order to see if there are correlations or disagreements between bloggers on certain subjects. As there is going to be a lot of content posted once the site has been up and running for a few months, we need some way to ensure that specific topics are easy to find, regardless of who has been discussing them on their blogs. Introduction to Vocabularies Let's quickly discuss how vocabularies are dealt with in the administration tool in order to work out how to go about making sure this requirement is satisfied. If you click on the Taxonomy link under Content management, you will be presented with a page listing the current vocabularies. Assuming you have created a forum before, you should have something like this: Before we look at editing terms and vocabularies, let's take a look at how to create a vocabulary for ourselves. Click on the add vocabulary tab to bring up the following page that we can use to create a vocabulary, manually: By way of example, this vocabulary will deal with the topic of hunting. This vocabulary only applies to blog entries because that is the only content (or node) type for which it is enabled—you can select as many or as few as you like, depending on how many content types it should apply to. Looking further down the page, there are several other options that we will discuss in more detail, shortly. Clicking on Submit adds this vocabulary to the list, so that the main page now looks like this: So far so good, but this will not be of much use to us as it stands! We need to add some terms (descriptors) in order to allow tagging to commence. Dealing with Terms Click on add terms link for the Hunting vocabulary to bring up the following page: The term Trapping has been added here, with a brief description of the term itself. We could, if we choose, associate the term Poaching with Trapping by making it a related term or synonym (of course, you would need to create this term first in order to make it a related term). Click on the Advanced options link to expose the additional features, as shown here: In this case, the term Trapping is specified as being related to Poaching and by way of example, gin traps is a synonym. Synonyms don't actually do anything useful at the moment, so don't pay too much mind to them yet, but there are modules that expose additional functionality based on related terms and synonyms, such as the Similar by Terms module. The Parents option at the start of the Advanced options warrants a closer inspection, but as it relates more closely to the structure of hierarchies, we'll look at it in the section on Hierarchies that's coming up. For now, add a few more terms to this vocabulary so that the list looks something like this: It's now time to make use of these terms by posting some blog content. Posting Content with Categories Enabled Using any account with the requisite permissions to add blog content, attempt to post to the site. You should now be able to view the newly inserted Hunting category, as shown here: Now comes the clever bit! Once this blog node has been posted, users can view the blog as normal, except that it now has its term displayed along with the post (bottom right): Where does the descriptor link take us? Click on the term, in this case Canned hunting, and you will be taken to a page listing all of the content that has been tagged with this term. This should really have you quite excited, because with very little work, users can now find focused content without having to look that hard—this is what content management is all about!
Read more
  • 0
  • 0
  • 2450

Packt
08 Oct 2009
8 min read
Save for later

jQuery UI—The Dialog: Part 2

Packt
08 Oct 2009
8 min read
Using dialog animations The dialog provides us with built-in effect abilities and also allows us to specify effects to use when the dialog is opened or closed. Using these effects is extremely easy and gives a great visual flair. Let's look at how these effects can be enabled. Create the following new page: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"> <head> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.dialog.css"> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.resizable.css"> <link rel="stylesheet" type="text/css" href="styles/dialogTheme.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>jQuery UI Dialog Example 6</title> </head> <body> <div id="myDialog" class="flora" title="This is the title">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti. Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div> <script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.dialog.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.resizable.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.draggable.js"></script> <script type="text/javascript"> //define function to be executed on document ready $(function(){ //define config object var dialogOpts = { hide: true }; //create the dialog $("#myDialog").dialog(dialogOpts); }); </script> </body></html> Save this as dialog6.html. In this example, our configuration object contains just one property—the hide property. The hide property accepts the boolean true as its value. This enables the built-in hide effect, which gradually reduces the dialog's size and opacity until it gracefully disappears. We can also enable the show effect, which is the opposite of the hide animation. However, at this stage in the component's development, this causes a slight issue with its display. The following screenshot shows the hide effect in progress: Controlling a dialog programmatically The dialog requires few methods in order to function. As implementers, we can easily open, close, or destroy the dialog at will. The full list of methods we can call on a dialog instance are as follows: Method Used to close Closes or hides the dialog destroy Permanently disables the dialog isOpen Determines whether a dialog is open or not moveToTop Moves the specified dialog to the top of the stack open Opens the dialog Let's look at opening and closing the widget, which can be achieved with the simple use of the open and close methods. Create the following new page in your text editor: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"> <head> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.dialog.css"> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.resizable.css"> <link rel="stylesheet" type="text/css" href="styles/dialogTheme.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>jQuery UI Dialog Example 7</title> </head> <body> <div id="myDialog" class="flora" title="This is the title"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti. Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div> <button id="openDialog">Open the Dialog!</button> <script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.dialog.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.resizable.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.draggable.js"></script> <script type="text/javascript"> //define function to be executed on document ready $(function(){ //define doOk function var doOk = function() { //close the dialog $("#myDialog").dialog("close"); } //define config object var dialogOpts = { modal: true, overlay: { background: "url(img/modal.png) repeat" }, buttons: { "Ok!": doOk }, height: "400px", autoOpen: false }; //create the dialog $("#myDialog").dialog(dialogOpts); //define click handler for the button $("#openDialog").click(function() { //open the dialog $("#myDialog").dialog("open"); }); }); </script> </body></html> The open and close methods require no additional arguments and do exactly as they say, pure and simple. Save the file as dialog7.html. The destroy method for a dialog works in a slightly different way than it does for the other widgets we've seen so far. Instead of returning the underlying HTML to its original state, the dialog's destroy method completely disables the widget, hiding its content in the process. Change dialog7.html to make use of the destroy method: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"> <head> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.dialog.css"> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.resizable.css"> <link rel="stylesheet" type="text/css" href="styles/dialogTheme.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>jQuery UI Dialog Example 8</title> </head> <body> <div id="myDialog" class="flora" title="This is the title"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti. Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div> <button id="openDialog">Open the Dialog!</button> <button id="destroy">Destroy the dialog!</button> <script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.dialog.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.resizable.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.draggable.js"></script> <script type="text/javascript"> //define function to be executed on document ready $(function(){ //define doOk function var doOk = function() { //close the dialog $("#myDialog").dialog("close"); } //define config object var dialogOpts = { modal: true, overlay: { background:"url(img/modal.png) repeat" }, buttons: { "Ok!": doOk }, height: "400px", autoOpen: false }; //create the dialog $("#myDialog").dialog(dialogOpts); //define click handler for the button $("#openDialog").click(function() { //open the dialog $("#myDialog").dialog("open"); }); //define click handler for destroy $("#destroy").click(function() { //destroy dialog $("#myDialog").dialog("destroy"); }); }); </script> </body></html> Save the changes as dialog8.html and try out the new file. You'll find that you can open and close the dialog as many times as you want until the Destroy the dialog! button is clicked. After this, the dialog will no longer appear (although it will still exist in the DOM). To fully remove the dialog mark-up from the page, we can simply chain the remove jQuery method onto the end of the destroy method call.
Read more
  • 0
  • 0
  • 1703

article-image-jquery-ui-dialog-part-1
Packt
08 Oct 2009
8 min read
Save for later

jQuery UI—The Dialog: Part 1

Packt
08 Oct 2009
8 min read
The following screenshot shows a dialog widget and the different elements that it is made of: A basic dialog A dialog has a lot of default behavior built-in, but few methods are needed to control it programmatically, making this a very easy widget to use that is also highly configurable. Generating it on the page is very simple and requires a minimal underlying mark-up structure. The following page contains the minimum mark-up that's required to implement the dialog widget: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"> <head> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.dialog.css"> <link rel="stylesheet" type="text/css" href="jqueryui1.6rc2/themes/flora/flora.resizable.css"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>jQuery UI Dialog Example 1</title> </head> <body> <div id="myDialog" class="flora" title="This is the title">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean sollicitudin. Sed interdum pulvinar justo. Nam iaculis volutpat ligula. Integer vitae felis quis diam laoreet ullamcorper. Etiam tincidunt est vitae est. Ut posuere, mauris at sodales rutrum, turpis tellus fermentum metus, ut bibendum velit enim eu lectus. Suspendisse potenti. Donec at dolor ac metus pharetra aliquam. Suspendisse purus. Fusce tempor ultrices libero. Sed quis nunc. Pellentesque tincidunt viverra felis. Integer elit mauris, egestas ultricies, gravida vitae, feugiat a, tellus.</div> <script type="text/javascript" src="jqueryui1.6rc2/jquery-1.2.6.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.core.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.dialog.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.resizable.js"></script> <script type="text/javascript" src="jqueryui1.6rc2/ui/ui.draggable.js"></script> <script type="text/javascript"> //define function to be executed on document ready $(function(){ //create the dialog $("#myDialog").dialog(); }); </script> </body></html> Dialog properties An options object can be used in a dialog's constructor method to configure various dialog properties. Let's look at the available properties: Save this as dialog1.html in the jqueryui folder. A few more source files are required, specifically the ui.resizable.js and ui.draggable.js files and the flora.resizable.css stylesheet. The JavaScript files are low-level interaction helpers and are only required if the dialog is going to be resizable and draggable. The widget will still function without them. The dialog flora theme file is a mandatory requirement for this component, although the resizable one isn't. Other than that, the widget is initialized in the same way as other widgets. When you run this page in your browser, you should see the default dialog widget shown in the previous screenshot, complete with draggable and resizable behaviors. One more feature that I think deserves mentioning here is modality. The dialog comes with modality built-in, although it is disabled by default. When modality is enabled, a modal overlay element, which covers the underlying page, will be applied. The dialog will sit above the overlay while the rest of the page will be below it. The benefit of this feature is that it ensures the dialog is closed before the underlying page becomes interactive again, and gives a clear visual indicator that the dialog must be closed before the visitor can proceed. Custom dialog skins The dialog's appearance is easy to change from the flora theme used in the first example. Like some of the other widgets, certain aspects of the default or flora themes are required to make the widget function correctly. Therefore, when overriding styles, we need to be careful to just override the rules related to the dialog's display. When creating a new skin for the default implementation, including resizable behavior, we have a lot of new files that will need to be created. Apart from new images for the different components of the dialog, we also have to create new images for the resizing handles. The following files need to be replaced when skinning a dialog: dialog-e.gif dialog-n.gif dialog-ne.gif dialog-nw.gif dialog-s.gif dialog-se.gif dialog-sw.gif dialog-title.gif dialog-titlebar-close.png dialog-titlebar-close.png To make it easier to remember which image corresponds to which part of the dialog, these images are named after the compass points at which they appear. The following image illustrates this: Note that these are file names as opposed to class names. The class names given to each of the different elements that make up the dialog, including resizable elements, are similar, but are prefixed with ui- as we'll see in the next example code. Let's replace these images with some of our own. In a new file in your text editor, create the following stylesheet: .flora .ui-dialog, .flora.ui-dialog { background-color:#99ccff;}.flora .ui-dialog .ui-dialog-titlebar, .flora.ui-dialog.ui-dialog-titlebar { background:url(../img/dialog/my-title.gif) repeat-x; background-color:#003399;}.flora .ui-dialog .ui-dialog-titlebar-close, .flora.ui-dialog.ui-dialog-titlebar-close { background:url(../img/dialog/my-title-close.gif) no-repeat; }.flora .ui-dialog .ui-dialog-titlebar-close-hover, .flora.ui-dialog.ui-dialog-titlebar-close-hover { background:url(../img/dialog/my-title-close-hover.gif) norepeat;}.flora .ui-dialog .ui-resizable-n, .flora.ui-dialog .ui-resizable-n { background:url(../img/dialog/my-n.gif) repeat center top;}.flora .ui-dialog .ui-resizable-s, .flora.ui-dialog .ui-resizable-s { background:url(../img/dialog/my-s.gif) repeat center top;}.flora .ui-dialog .ui-resizable-e, .flora.ui-dialog .ui-resizable-e { background:url(../img/dialog/my-e.gif) repeat right center; }.flora .ui-dialog .ui-resizable-w, .flora.ui-dialog .ui-resizable-w { background:url(../img/dialog/my-w.gif) repeat left center;}.flora .ui-dialog .ui-resizable-ne, .flora.ui-dialog .ui-resizable-ne{ background:url(../img/dialog/my-ne.gif) repeat;}.flora .ui-dialog .ui-resizable-se, .flora.ui-dialog .ui-resizable-se{ background:url(../img/dialog/my-se.gif) repeat;}.flora .ui-dialog .ui-resizable-sw, .flora.ui-dialog .ui-resizable-sw{ background:url(../img/dialog/my-sw.gif) repeat;}.flora .ui-dialog .ui-resizable-nw, .flora.ui-dialog .ui-resizable-nw{ background:url(../img/dialog/my-nw.gif) repeat;} Save this as dialogTheme.css in the styles folder. We should also create a new folder within our img folder called dialog. This folder will be used to store all of our dialog-specific images. All we need to do is specify new images to replace the existing ones used by flora. All other rules can stay the same. In dialog1.html, link to the new file with the following code, which should appear directly after the link to the resizable stylesheet: <link rel="stylesheet" type="text/css" href="styles/dialogTheme.css"> Save the change as dialog2.html. These changes will result in a dialog that should appear similar to the following screenshot: So you can see that skinning the dialog to make it fit in with your existing content is very easy. The existing image files used by the default theme give you something to start with, and it's really just a case of playing around with colors in an image editor until you get the desired effect. Dialog properties An options object can be used in a dialog's constructor method to configure various dialog properties. Let's look at the available properties: Property Default Value Usage autoOpen true Shows the dialog as soon as the dialog method is called bgiframe true Creates an <iframe> shim to prevent <select> elements showing through the dialog in IE6 - at present, the bgiframe plugin is required, although this may not be the case in future versions of this widget buttons   {} Supplies an object containing buttons to be used with the dialog dialogClass ui-dialog Sets additional class names on the dialog for theming purposes draggable true Makes the dialog draggable (use ui.draggable.js) height 200(px) Sets the starting height of the dialog hide none Sets an effect to be used when the dialog is closed maxHeight none Sets a maximum height for the dialog maxWidth none Sets a maximum width for the dialog minHeight 100(px) Sets a minimum height for the dialog minWidth 150(px) Sets a minimum width for the dialog modal false Enables modality while the dialog is open overlay {} Object with CSS properties for the modal overlay position center Sets the starting position of the dialog in the viewport resizable true Makes the dialog resizable (also requires ui.resizable.js) show none Sets an effect to be used when the dialog is opened stack true Causes the focused dialog to move to the front when several dialogs are open title none Alternative to specifying title on source element width 300(px) Sets the original width of the dialog
Read more
  • 0
  • 0
  • 1768

article-image-creating-new-zen-cart-template
Packt
08 Oct 2009
11 min read
Save for later

Creating a new Zen Cart Template

Packt
08 Oct 2009
11 min read
Creating A File System Let us start building a new template for Zen Cart by creating a new folder under includes/templates/. Let us name it Packt (or whatever you like). But remember to use underscore instead of spaces in a long name. Avoid using Book Shop. Instead, use book_shop or BookShop. images' folder —will contain all the images needed for the template. css' folder — will contain all the CSS files for the template. It's better to copy all the files from the includes/templates/template_default/css directory to this css folder. common' folder — will contain the common files for the template. You may copy the files from the includes/templates/template_default/common folder, and edit those to suit your needs. sideboxes'folder — will contain module-specific sideboxes. Here, you can add new sideboxes, which you are going to use. templates folder — contains page-specific templates. Whenever you want to change a page's layout, copy the template for that page to this directory and modify it as required. Information regarding a template is located in the template_info.php file. You need to create a new template_info.php file for the new template. Copy the file called includes/templates/template_default/template_info.php into the new template folder, and then open the template_info.php file in your favorite text editor. Change the text between each set of single quotes to suit your new template. <?php $template_name = 'Packt Publishing'; $template_version = 'Version 1.0'; $template_author = 'Suhreed Sarkar'; $template_description = 'This template is designed for Packt Publishing'; $template_screenshot = ''; ?> Remember to keep the single quotes. Your template name does not need to be identical to your folder name, and you can use spaces to make it read well, but it is best to keep them similar. Leave the space between the quotes for the template screenshot field empty for now, as you don't have one yet. When you've finished, your new file structure should appear as follows: Open your Admin panel and navigate to Tools | Template Selection. Click the Edit button, then choose Packt Publishing from the drop-down menu and click the Update button. Now, navigate to Tools | Layout boxes controller, and click the Reset button at the bottom of the page. Your new template is now enabled and ready to be customized. Using Overrides When building a new template for Zen Cart, you can use its powerful overriding feature. Overriding means using some template as the base and extending it by adding different properties through separate templates. For example, you may want to make some modifications to the default template—template_default. You could modify the files in the template_default directory to do this. But due to its overriding character, you can add the changes in the new template, say packt, which will apply the changes to the shop. In fact, you can override any file in the path includes/templates/ template_default. Files in this directory generally determine the layout and the HTML formatting of your web pages. By default, Zen Cart has two standard templates: template_default and classic, both of which are located in the includes/templates/ folder. Out of these two standard templates, only template_default contains a full set of files. Every other template contains only the files that differ from template_default. If your template does not contain a particular file, Zen Cart will pull that file from template_default. Graphics You need to add your templates graphics to the appropriate folders. The header image, logo, background image, background image for sidebox headings, and so on should be placed in the images directory under your template directory. If you want to change the buttons and icons, create the graphic files in the GIF, JPG or PNG format and put them in the /includes/templates/template_name/buttons/language_name folder. Then, update the button_names.php file to define the button image file name, and the ALT texts for those images. Sideboxes You do not need to copy existing sideboxes from the template_default directory, as these will automatically be displayed. If you are planning to develop a new sidebox, put the template for that sidebox in the sideboxes folder under your template directory. A sidebox consists of three files, which are located in the includes directory: modules/sideboxes/template_name/name_of_sidebox.php' languages/english/extra_definitions/template_name/ name_of_sidebox_defines.php ' templates/template_name/sideboxes/tpl_name_of_sidebox.php ' You need to replace template_name and name_of_sidebox with you template name and the sidebox name respectively. For example, let us build a sidebox named my_sidebox. Then, my_sidebox.php file will read like this: <?php $show_my_sidebox = true; if ($show_my_sidebox == true){ require($template->get_template_dir('tpl_my_sidebox.php', DIR_WS_TEMPLATE, $current_page_base,'sideboxes'). '/tpl_my_sidebox.php'); $title = BOX_HEADING_MY_SIDEBOX; $left_corner = false; $right_corner = false; $right_arrow = false; require($template->get_template_dir($column_box_default, DIR_WS_TEMPLATE, $current_page_base,'common') . '/' . $column_box_default); } ?> This page actually defines what is to be shown in that sidebox. Note that this page also includes the corresponding template file. Here, we have used a constant BOX_HEADING_MY_SIDEBOX. You need to define this in the includes/languages/english/extra_definitions/packt/my_sidebox_defines.php file. This file will look like this: <?php define('BOX_HEADING_MY_SIDEBOX', 'My Sidebox'); ?> Now, you have to build its template file includes/templates/packt/sideboxes/tpl_my_sidebox.php, which will read as: <?php $content = "This is my first Sidebox. I have created it in 5 minutes. Although it is not of practical use yet, I hope I can eventually build a good sidebox."; ?> If you have created these files for the packt template, you can try it by going to Tools | Layout Boxes Controller in the administration panel. From here, turn the sidebox ON and set it up to display in the left or the right side column. This sidebox will look like the following figure. Stylesheets All stylesheets for your new template should be placed in the /includes/templates/template_name/css folder. You should follow stylesheet naming conventions. It is a good idea to copy an old stylesheet and then modify it to suit your needs. You can have multiple stylesheets for your shop you can even add a stylesheet for each page. As a design rule, try to keep the declarations minimal, simple, and self explanatory. Try to restrain yourself from changing the class and ID names in the core files. Creating and Modifying Email Templates As a store owner, you need to send several mails to your existing and potential customers. All these emails use some templates that reside in the /email folder under the Zen Cart installation directory. To change these emails to your style, you may edit these templates. The email's structure is determined in one of two ways. If you are sending plain text emails, the email structure is determined by the way you put together the various items (customer greeting, order number, link to detailed invoice, and so on) in a string variable that is then passed to the zen_mail() function. If you are sending HTML emails, the structure is determined by the template you use. Text Email Template You can rearrange, add, or delete items in a plain text email. To do so, you will need to edit the Zen Cart files where the email is created. For example, if you want to edit the order confirmation email, you will need to edit the file includes/classes/order.php. In your example, open up includes/classes/order.php and scroll down to the bottom of the file, in the function send_order_email(). There, you will see the lines that construct the plain text email message: [Line 827]$email_order = EMAIL_TEXT_HEADER . EMAIL_TEXT_FROM . STORE_NAME . "nn" . $this->customer['firstname'] . ' ' . $this->customer['lastname'] . "nn" . EMAIL_THANKS_FOR_SHOPPING . "n" . EMAIL_DETAILS_FOLLOW . "n" . EMAIL_SEPARATOR . "n" . EMAIL_TEXT_ORDER_NUMBER . ' ' . $zf_insert_id . "n" . EMAIL_TEXT_DATE_ORDERED . ' ' . strftime(DATE_FORMAT_LONG) . "n" . EMAIL_TEXT_INVOICE_URL . ' ' . zen_href_link(FILENAME_ACCOUNT_HISTORY_INFO, 'order_id=' . $zf_insert_id, 'SSL' [Line 848]$email_order .= zen_db_output($this->info['comments']) . "nn";[Line 855]$email_order .= EMAIL_TEXT_PRODUCTS . "n" . EMAIL_SEPARATOR . "n" . $this->products_ordered . EMAIL_SEPARATOR . "n"; In this file, the variable that holds the plain text email message is called $email_order. It generally has a different name in each file, such as $email or $email_text. Whatever its name, this is the place where you will make your changes. You can add, delete, and rearrange the order of the items to suit your wishes. HTML Email Templates HTML Email templates have two parts: embedded CSS and HTML codes. You may be surprised to see the embedded stylesheet in each mail template, and may want to know why linked stylesheets have not been used. One reason for not using the linked stylesheet is that you may not know how the email clients will behave. Most email clients used today can handle HTML emails and stylesheets to some extent. But there is no guarantee that every customer will have an email client that can retrieve linked stylesheets and render the emails in the desired format. Stylesheets The first portion of the email template is devoted to defining styles for different parts of the mail. Open the /email/email_template_welcome.html file in your favorite text editor to examine the stylesheet in an email template. The stylesheet in this template will appear as follows: <style type="text/css">.body {background-color:#ffffff; color:#000000; font-family:Verdana, Arial, Helvetica, sans-serif;}....header {font-size:10px; padding:0px; width:550px;}.content {font-size:10px; padding:5px; width:550px;}.content-line {padding:5px;}.coupon-block { padding: 5px; border: 1px #cccccc solid; background-color: #FFFF99; }....disclaimer1 a:link {color:#666666;}.disclaimer1 a:visited {color:#666666;}.disclaimer2 { color: #666666; padding: 5px; }.copyright { border-bottom: 0px #9a9a9a solid; padding: 5px; }</style> Style declarations in this stylesheet are straight-forward. First, it has defined style for the body and hyperlinks. Then, it defines the content and email related styles. Most of the style names are self-explanatory. You will find the HTML blocks with these names in the template. HTML with variables The main part of the email template is the HTML code with style classes and variables. The following are some of the variables used to construct content for the email: $EMAIL_GREETING $EMAIL_WELCOME $COUPON_BLOCK $GV_BLOCK $EMAIL_MESSAGE_HTML $EMAIL_CONTACT_OWNER $EMAIL_CLOSURE $EMAIL_FOOTER_COPYRIGHT $EMAIL_DISCLAIMER $EMAIL_SPAM_DISCLAIMER $EXTRA_INFO These variables are defined in several PHP files, such as create_account.php. Once you have found the files that need to be edited, you may want to add a definition for your new HTML item to each one. For example, you have added an item called $EMAIL_HOURS_OF_OPERATION to the email_template_order_status.html template. One of the files that you will need to edit is admin/orders.php. Find the part of that file where the email message is being constructed. In this case, it begins around line 100. You can see that the HTML message is constructed with several statements such as: $html_msg['EMAIL_CUSTOMERS_NAME'] = $check_status->fields['customers_name'];$html_msg['EMAIL_TEXT_ORDER_NUMBER'] = EMAIL_TEXT_ORDER_NUMBER . ' ' . $oID; All you need to do is add a new statement under all of these, to define your new item: $html_msg['EMAIL_HOURS_OF_OPERATION'] = 'We are open from 9 AM to 5 PMevery day of the week.'; Use a $ in front of the name of your new item in the HTML template, but do not use the $ where you define it. To change the text displayed in your emails, edit the corresponding language file. You can change an existing text, or add a new one (if you've added it to your email structure). You add or change text values using the define() statements: define(EMAIL_LOVELY_YOU_DROPPED_BY,'We are just so immeasurably delighted that you stopped by our store today!'); There is another language file you need to modify when altering text for your emails, includes/languages/english/email_extras.php. This file contains several text strings common to all emails sent from your store. Summary Thus we have seen how to create new template using Zen Cart.   If you have read this article you may be interested to view : Integrating Zen Cart with Content Management Systems Installing Zen Cart Troubleshooting Zen Cart  
Read more
  • 0
  • 0
  • 4215

article-image-jquery-embedded-dojo-accordion-panes
Packt
08 Oct 2009
4 min read
Save for later

jQuery Embedded in Dojo Accordion Panes

Packt
08 Oct 2009
4 min read
Basic DOJO 123 accordion In my earlier article I had used the version of the Toolkit which had the accordion in the Widgets. In the latest version which I am using, the accordion is found in digit/layout. The code is similar to that in the earlier article. Basically you create a accordion container and then place the accordion panes inside the container. In referencing the Dojo library I am using part of the references from the Dojo Toolkit 123 installed on my local IIS and part of the reference from the AOL site (uses the 1.0.0 script). Listing 1: AccordionOrig.htm: A basic accordion with three panes [DOJO 123] <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Accordion Pane with jQueries</title> <style type="text/css"> @import "http://localhost/Dojo123/dojo123/dijit/themes/tundra/tundra.css"; @import "http://localhost/Dojo123/dojo123/dojo/resources/dojo.css" </style> <script type="text/javascript" src="http://o.aolcdn.com/dojo/1.0.0/dojo/dojo.xd.js" djConfig="parseOnLoad: true"></script> <script type="text/javascript"> dojo.require("dojo.parser"); dojo.require("dijit.layout.AccordionContainer"); </script> </head> <body class="tundra"> <div dojoType="dijit.layout.AccordionContainer" duration="200" style="margin-right: 30px; width: 400px; height: 400px; overflow: scroll"> <!--Pane 1 --> <div dojoType="dijit.layout.AccordionPane" selected="true" title="Page 1" style="color:red;overflow: scroll; background-color:#FFFF80;"> <!--Pane 1 content--> <p >Test 1</a></p > </div> <!--Pane 2 --> <div dojoType="dijit.layout.AccordionPane" title="Page 2" style="overflow: scroll;background-color:#FFFF80;"> <!--Pane 2 content--> <p >Test 2</p > </div> <!-- Pane 3--> <div dojoType="dijit.layout.AccordionPane" title="Page 3" style="color:magenta;overflow: scroll;background-color:#FFFF80;"> <!--Pane 3 content--> <p >Test 3</a></p > </div> </div> </body> </html> This page when browsed to, will display the accordion as shown in Figure 1. This was cross-browser compatible in the following browsers: IE 6.0, Opera 9.1, Firefox 3.0.5, and Safari 3.2.1. The page did not render correctly (all panes completely open) in Google Chrome 1.0.154.43. Figure 1 jQuery API Components used in the article jQuery 1.3 downloaded from this site is used as a source for the script. From the API reference only two simple components were chosen to be embedded in the panes - the Selector and the Effects. The slideUp() effect where in, when you click on the code sensitive area the region of the area on the web page slides up. H1 Selector styled using jQuery Using jQuery you can selectively apply style to tags, ids, etc. In the example shown in the code that follows the H1 tag is styled using jQuery. Listing 2: H1SelectorJQry.htm: Tag styling with jQuery <html> <head></head> <body> <script language="JavaScript" src="http://localhost/JayQuery/jquery-1.3.min.js"> </script> <h1>Jquery inside a DOJO Accordion Pane</h1> <script type="text/JavaScript"> $(document).ready(function(){ $("h1").css("color", "magenta");}); </script> </body> <html> In the above, the jQuery code (inside the script tags) renders the h1 tag in the color shown as in Figure 2. Figure 2 jQuery Effect: slideUp() The htm page with the listing 3 when browsed to, displays a pale green 300 x 300 square corresponding to the styling of the p tag as shown in Figure 4. When clicked anywhere inside this square, the square slides up and disappears. This is the slideUp() effect. Listing 3: p_slideUp.htm: Jquery Effect <html> <head></head> <body> <script language="JavaScript" src="http://localhost/JayQuery/jquery-1.3.min.js"> </script> <div><p style="width:300; height:300; background-color:palegreen; color:darkgreen;">Test</p></div> <script type="text/JavaScript"> $("p").click(function () { $(this).slideUp(); }); </script> </body> <html> This page gets displayed as shown in Figure 3. When you click anywhere in the pale green area the "P" region slides up. Figure 3
Read more
  • 0
  • 0
  • 2636
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-safely-manage-different-versions-content-plone
Packt
08 Oct 2009
2 min read
Save for later

Safely Manage Different Versions of Content with Plone

Packt
08 Oct 2009
2 min read
(For more resources on Plone, see here.) Introducing versioning Now that you have learned how to add various types of content, from pages to events to news items, we're ready to introduce a feature of Plone called versioning, which is an important part of content management. The content items you work with in your Plone site may go through many changes over time. Plone provides versioning information to help you manage your content from the time it was initially created through to the current version. By default, Plone provides versioning for the following content types: Pages News Items Events Links Other content types can be configured to provide versioning through the Plone Control Panel under Types. Although you may enable the File type to use versioning, the only changes that are tracked are those items actually describing the File (for example, Title, Description, and so on). The changes to the contents of the File are not tracked. Creating a new version Versions are created each time you save your content. Note that there is a Change note field at the bottom of the Edit page for content items with versioning enabled: The information entered in the Change note field will be stored along with other versioning information, which you are able to view through the History tab. Viewing the version history You can view the list of all of the versions of a content item by clicking on the History tab for that content item. In the History view that you can see in the following screenshot, the most recent version is listed fi rst. Clicking on any of the column headers will re-sort the listing based on that column heading. The most current version is always labeled Working Copy in the History view. Previewing previous versions To preview a specific version, simply click the preview link of the desired revision. In the following example, revision 3 has been identified, and will be displayed if this link is clicked: On the subsequent page, you may either click on the jump down link to the point of the content preview: or you may scroll down the page in order to see the actual preview:
Read more
  • 0
  • 0
  • 2602

article-image-interacting-students-using-moodle-19-part-1
Packt
08 Oct 2009
11 min read
Save for later

Interacting with the Students using Moodle 1.9 (part 1)

Packt
08 Oct 2009
11 min read
We are going to carry out a role-play activity. This activity will be geography-based, but the Moodle activities are the same for any subject. Hopefully, this will help you gain some ideas for your own teaching. Having learned about the course of a river and about the landscape at the location where the river meets the coast, the students are now going to be given the job of developers—planning and designing a riverside campsite. The students will undertake various tasks during the project, all of them within Moodle. We, the teachers, having set the scene, are going to sit back and observe their progress, online. When the entire mini-project is complete, we're going to get them to tell us, personally, how much they feel they have learned. We can use their responses to plan our future Moodle activities. How do we do all this? The words in bold above are examples of activities that we can do in Moodle. There are others too, but for you—as a newbie—these activities are more than enough. To set up any of them, we first need to turn editing on, either via the button on the upper right of the screen, or via the Administration block. Then, in the topic section where we want to add our activity, we click on the space next to Add an activity…. This will bring up a list of options, which might vary depending upon your particular Moodle course. The following screenshot shows some typical options that might show up when you click Add an activity....Be aware that Certificate and Game don't appear in standard Moodle courses. Getting our class to reflect and discuss Have you ever come across a child who is too shy to speak up in class but then produces the most thoughtful written work? Moodle is Godsend for these students, because it has a forum and a chat facility, both of which enable classes and their teachers to have a discussion without actually being together, in the same room. And often, the shy child will happily have their say online, where they can plan it out first and feel comfortable without the interference of their peers. We're going to set some homework where the students will discuss, in general, the kinds of things to keep in mind when planning a riverside campsite. Hopefully, someone will realize it's not a good idea to have it too close to the water. Time for action-setting up a discussion forum on Moodle Let's create an online discussion area for the students to share their views and comments. This discussion area is called the Forum. With editing turned on, click on Add an activity and select Forum. As a result, the following information will appear on the screen. In the Forum type field, click on the drop-down arrow and choose Single Simple Discussion (we'll investigate on the other options later). In the Forum name field, enter some text that will invite your students to click on it to join the discussion. In the Message field, enter your starting topic, with images and hyperlinks, if you wish. Change the option Force everyone to be subscribed to Yes, if you want people to get an email every time somebody adds their comments or suggestions to the forum. Leave the option Read tracking as it is, and people can decide whether to track read or unread messages. The option, Maximum attachment size lets you decide how big a file or an image people can attach with a message. Grade—alter these settings to give each post a mark. But be aware that this will put younger children off. You can put a number in the Post threshold for blocking option if you want to limit the number of posts that a student can make. Click on Save and return to course. What just happened? We have just set up an online discussion area (forum) on a specific topic for our class. Let's go back to our course page and click on the forum that we just prepared. The final output will look like this: Our students will see an icon (usually with two faces) that will prompt them to join the preliminary discussion on where best to locate the campsite. They'll click on the Reply link at the bottom (as you can see in the preceding screenshot), to post their response. How do we moderate the forum? Hopefully, we can just read the students' responses and let them discuss the topic amongst themselves. But as a teacher, we do have three other options: We can edit the response posted by the student (change the wording if it's inappropriate). We can delete the post altogether. We can reply to it when we think it is really important to do so. A student only has the option to reply (as you see if you click on Student view at the upper right of the course page). When we need to get rid of an unsuitable post, or perhaps alter the wording of something one of our students has typed, this extra power we teachers have is helpful. For our starter discussion, we chose a Single Simple Discussion as we wanted the students to focus totally on one issue. However, in other situations, you might need a slightly different type of forum. So the following table gives a brief overview of the other kinds that are available, and explains how you could use them: Name What it does Why use it Single Simple Discussion Only one question they can all answer Best for focused discussions-they can't get distracted Standard forum  Everyone can start a new topic More scope for older students Q and A Pupils must answer first before they can see any replies Useful for avoiding peer pressure issues Each person posts 1 discussion Pupils can post ONE new topic only Handy if you need to restrict posting but still allow some freedom Why use a forum? Here are a few other thoughts on forums, based on my own experiences: A cross-year or cross-class forum can be useful, as the older students can pass on their experiences to the younger students. For example, each year my first year high school students make a volcano as a homework project. As they enter their second year, they use a dedicated forum to pass on their wisdom and answer technical questions sought by the inexperienced first-year students—who are about to begin their own creations. A homework exercise could be set on a forum, as a reflective plenary to the learning done in the class. Once, my class watched a documentary based on the Great New Orleans flood of 2004, and the students were asked, on a forum, to imagine they had been there. They had to suggest some words or phrases to describe their feelings—which we then collated into the next lesson to make poems about the flood. Let's add a little bit of confusion. Instead of simply asking a question, why not make a statement that you know will inspire, annoy, and divide the students. As a result, you can see the variety in the responses. I once posted the topic: “If people live near rivers, and their homes get flooded out, it is surely their own fault for living near rivers. Why should the rest of us have to help them?” In response to this, some violently disagreed with the statement—quoting examples from developing countries, whereas some agreed with the statement—and were then blasted down by their classmates for doing so. But at least the forum got visited! Carrying on the conversation in real time—outside of school A discussion forum, as illustrated above, is a useful tool to get the children to think and to contribute their ideas. It has an advantage over the usual class discussion, in that the shyer pupils are more likely to open up in such discussion forums. However, there is no spontaneity involved. You might post a comment in the morning, and the response may arrive at dinnertime, and so on. Why not combine the advantages of online communication with the advantages of a real time conversation, and make a Moodle chat room? If your students live several miles away from each other, as my students do, and are keen to get on with the project, Moodle chat rooms can have real benefits. We can set a time for the chat—say, Saturday afternoon. This would be a time when we can be present too, if we wish, and the students can move ahead with their plans even though they're not with each other in the classroom. Even though this implementation has its own drawbacks, it provides us with a set-up. Eventually, we can see how it goes and then think about how best we can use it. Time for action-setting up a chat room in Moodle Let's create a chat room where the students can have a chat even when they are not in the same classroom. This way, they can share their views, comments, and suggestions. With editing turned on, go to Add an activity, and select the Chat option. In the Name of this chat room field, enter an appropriate title for the discussion. In the Introduction text field, type in what the discussion is going to be about. For the Next chat time option, choose when you want to open the chat room. For the Repeat sessions option, choose whether you want to chat regularly, or just once. For the Save past sessions option, choose how long, if at all, to keep a record of the conversation. It is up to you to decide whether to allow everyone to view the past sessions or not. For now, you can ignore the Common module settings option. Click on Save and Display. What just happened? We have set up the place and time on Moodle for our students to talk to each other—and even with us if necessary—online. Students will see an icon—usually a speech bubble—on the course page, alongside the name given to the chat. The students just have to click on the icon at the correct time for the chat. When the room is open, they will see this: Clicking on the link will take the students to a box where they'll be able to see their user photo (if they have one) and the time at which they have entered the chat. When others join in, their photos will be shown, and the time of their arrival will be recorded. You talk by typing into the long box at the bottom of the screen, and when submitted, your words appear in the larger box above it. This can get quite confusing if a lot of people are typing at the same time, as the contributions appear one under the other, and do not always follow on from the question or response to which they are referring. Why use Chat? (and why not?) I have to confess that I have switched off the ability for people to use Chat on my school's Moodle site. Chat does have one advantage over the Forum, which is that you can hold discussions in real time with the others who are not physically present in the same room as you. This could be useful on occasions, such as when the teacher is absent from school (but available online). He or she can contact the class at the start of the lesson to check whether they know what they are doing. The students in our school council use Chat for meetings out of school hours, as do our school Governors. You can also read the transcript of a chat (the chat log) after it has happened. However, everyone really has to stay focused on the discussion topic, otherwise, you risk having nothing but a list of trite comments, and no real substance. I've found this to be the case with younger children. Personally, I find a single and a simple discussion in a Forum to be of much more value, than Chat. However, you can try using Chat and see what you think. Your experience could be different from mine.
Read more
  • 0
  • 0
  • 2524

article-image-schema-validation-using-sax-and-dom-parser-oracle-jdeveloper-xdk-11g
Packt
08 Oct 2009
6 min read
Save for later

Schema Validation using SAX and DOM Parser with Oracle JDeveloper - XDK 11g

Packt
08 Oct 2009
6 min read
The choice of validation method depends on the additional functionality required in the validation application. SAXParser is recommended if SAX parsing event notification is required in addition to validation with a schema. DOMParser is recommended if the DOM tree structure of an XML document is required for random access and modification of the XML document. Schema validation with a SAX parser In this section we shall validate the example XML document catalog.xml with XML schema document catalog.xsd, with the SAXParser class. Import the oracle.xml.parser.schema and oracle.xml.parser.v2 packages. Creating a SAX parser Create a SAXParser object and set the validation mode of the SAXParser object to SCHEMA_VALIDATION, as shown in the following listing: SAXParser saxParser=new SAXParser();saxParser.setValidationMode(XMLParser.SCHEMA_VALIDATION); The different validation modes that may be set on a SAXParser are discussed in the following table; but we only need the SCHEMA-based validation modes: Validation Mode Description NONVALIDATING The parser does not validate the XML document. PARTIAL_VALIDATION The parser validates the complete or a partial XML document with a DTD or an XML schema if specified. DTD_VALIDATION The parser validates the XML document with a DTD if any. SCHEMA_VALIDATION The parser validates the XML document with an XML schema if any specified. SCHEMA_LAX_VALIDATION Validates the complete or partial XML document with an XML schema if the parser is able to locate a schema. The parser does not raise an error if a schema is not found. SCHEMA_STRICT_VALIDATION Validates the complete XML document with an XML schema if the parser is able to find a schema. If the parser is not able find a schema or if the XML document does not conform to the schema, an error is raised. Next, create an XMLSchema object from the schema document with which an XML document is to be validated. An XMLSchema object represents the DOM structure of an XML schema document and is created with an XSDBuilder class object. Create an XSDBuilder object and invoke the build(InputSource) method of the XSDBuilder object to obtain an XMLSchema object. The InputSource object is created with an InputStream object created from the example XML schema document, catalog.xsd. As discussed before, we have used an InputSource object because most SAX implementations are InputSource based. The procedure to obtain an XMLSchema object is shown in the following listing: XSDBuilder builder = new XSDBuilder();InputStream inputStream=new FileInputStream(new File("catalog.xsd"));InputSource inputSource=new InputSource(inputStream);XMLSchema schema = builder.build(inputSource); Set the XMLSchema object on the SAXParser object with setXMLSchema(XMLSchema) method: saxParser.setXMLSchema(schema); Setting the error handler As in the previous section, define an error handling class, CustomErrorHandler that extends DefaultHandler class. Create an object of type CustomErrorHandler, and register the ErrorHandler object with the SAXParser as shown here: CustomErrorHandler errorHandler = new CustomErrorHandler();saxParser.setErrorHandler(errorHandler); Validating the XML document The SAXParser class extends the XMLParser class, which provides the overloaded parse methods discussed in the following table to parse an XML document: Method Description parse(InputSource in) Parses an XML document from an org.xml.sax.InputSouce object. The InputSource-based parse method is the preferred method because SAX parsers convert the input to InputSource no matter what the input type is. parse(java.io.InputStream in) Parses an XML document from an InputStream. parse(java.io.Reader r) Parses an XML document from a Reader. parse(java.lang.String in) Parses an XML document from a String URL for the XML document. parse(java.net.URL url) Parses an XML document from the specified URL object for the XML document. Create an InputSource object from the XML document to be validated, and parse the XML document with the parse(InputSource) object: InputStream inputStream=new FileInputStream(newFile("catalog.xml"));InputSource inputSource=new InputSource(inputStream);saxParser.parse(inputSource); Running the Java application The validation application SAXValidator.java is listed in the following listing with additional explanations: First we declare the import statements for the classes that we need. import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import oracle.xml.parser.schema.*;import oracle.xml.parser.v2.*;import java.io.IOException;import java.io.InputStream;import org.xml.sax.SAXException;import org.xml.sax.SAXParseException;import org.xml.sax.helpers.DefaultHandler;import org.xml.sax.InputSource; We define the Java class SAXValidator for SAX validation. public class SAXValidator { In the Java class we define a method validateXMLDocument. public void validateXMLDocument(InputSource input) {try { In the method we create a SAXParser and set the XML schema on the SAXParser. SAXParser saxParser = new SAXParser();saxParser.setValidationMode(XMLParser.SCHEMA_VALIDATION);XMLSchema schema=getXMLSchema();saxParser.setXMLSchema(schema); To handle errors we create a custom error handler. We set the error handler on the SAXParser object and parse the XML document to be validated and also output validation errors if any. CustomErrorHandler errorHandler = new CustomErrorHandler();saxParser.setErrorHandler(errorHandler);saxParser.parse(input);if (errorHandler.hasValidationError == true) {System.err.println("XML Document hasValidation Error:" + errorHandler.saxParseException.getMessage());} else {System.out.println("XML Document validateswith XML schema");}} catch (IOException e) {System.err.println("IOException " + e.getMessage());} catch (SAXException e) {System.err.println("SAXException " + e.getMessage());}} We add the Java method getXMLSchema to create an XMLSchema object. try {XSDBuilder builder = new XSDBuilder();InputStream inputStream =new FileInputStream(new File("catalog.xsd"));InputSource inputSource = newInputSource(inputStream);XMLSchema schema = builder.build(inputSource);return schema;} catch (XSDException e) {System.err.println("XSDException " + e.getMessage());} catch (FileNotFoundException e) {System.err.println("FileNotFoundException " +e.getMessage());}return null;} We define the main method in which we create an instance of the SAXValidator class and invoke the validateXMLDocument method. public static void main(String[] argv) {try { InputStream inputStream = new FileInputStream(new File("catalog.xml")); InputSource inputSource=new InputSource(inputStream); SAXValidator validator = new SAXValidator(); validator.validateXMLDocument(inputSource); } catch (FileNotFoundException e) { System.err.println("FileNotFoundException " + e.getMessage()); }} Finally, we define the custom error handler class as an inner class CustomErrorHandler to handle validation errors. private class CustomErrorHandler extends DefaultHandler {protected boolean hasValidationError = false;protected SAXParseException saxParseException = null;public void error(SAXParseException exception){hasValidationError = true;saxParseException = exception;}public void fatalError(SAXParseException exception){hasValidationError = true;saxParseException = exception;}public void warning(SAXParseException exception){}}} Copy the SAXValidator.java application to SAXValidator.java in the SchemaValidation project. To demonstrate error handling, add a title element to the journal element. To run the SAXValidator.java application, right-click on SAXValidator.java in Application Navigator, and select Run. A validation error gets outputted. The validation error indicates that the title element is not expected.
Read more
  • 0
  • 0
  • 6063

article-image-developing-seam-applications
Packt
08 Oct 2009
10 min read
Save for later

Developing Seam Applications

Packt
08 Oct 2009
10 min read
Seam application architecture As most enterprise Java developers are probably familiar with JSF and JSP, we will be using this as the view technology for our sample applications. Facelets is the recommended view technology for Seam-based applications once we have a solid understanding of Seam. In a standard Java EE application, Enterprise Application Resource (EAR) files contain one or more Web Application Resource (WAR) files and one or more sets of Java Archive (JAR) files containing Enterprise JavaBeans (EJB) functionality. Seam applications are generally deployed in exactly the same manner as depicted in the following diagram. It is possible to deploy Seam onto a servlet-only container (for example, Tomcat) and use POJOs as the server-side Seam components. However, in this situation, we don't get any of the benefits that EJBs provide, such as security, transaction handling, management, or pooling. Seam components Within Seam, components are simple POJOs. There is no need to implement any interfaces or derive classes from a Seam-specific base class to make Seam components classes. For example, a Seam component could be: A simple POJO a stateless Session Bean a stateful Session Bean a JPA entity and so on Seam components are defined by adding the @Name annotation to a class definition. The @Name annotation takes a single parameter to define the name of the Seam component. The following example shows how a stateless Session Bean is defined as a Seam component called calcAction. package com.davidsalter.seamcalculator; @Stateless @Name("calcAction") public class CalcAction implements Calc { ... } When a Seam application is deployed to JBoss, the log output at startup lists what Seam components are deployed, and what type they are. This can be useful for diagnostic purposes, to ensure that your components are deployed correctly. Output similar to the following will be shown in the JBoss console log when the CalcAction class is deployed: 21:24:24,097 INFO [Initialization] Installing components...21:24:24,121 INFO [Component] Component: calcAction, scope: STATELESS, type: STATELESS_SESSION_BEAN, class: com.davidsalter.seamcalculator.CalcAction, JNDI: SeamCalculator/CalcAction/local Object Injection and Outjection One of the benefits of using Seam is that it acts as the "glue" between the web technology and the server-side technology. By this we mean that the Seam Framework allows us to use enterprise beans (for example, Session Beans) directly within the Web tier without having to use Data Transfer Object (DTO) patterns and without worrying about exposing server-side functionality on the client. Additionally, if we are using Session Beans for our server-side functionality, we don't really have to develop an additional layer of JSF backing beans, which are essentially acting as another layer between our web page and our application logic. In order to fully understand the benefits of Seam, we need to first describe what we mean by Injection and Outjection. Injection is the process of the framework setting component values before an object is created. With injection, the framework is responsible for setting components (or injecting them) within other components. Typically, Injection can be used to allow component values to be passed from the web page into Seam components. Outjection works in the opposite direction to Injection. With Outjection, components are responsible for setting component values back into the framework. Typically, Outjection is used for setting component values back into the Seam Framework, and these values can then be referenced via JSF Expression Language (EL) within JSF pages. This means that Outjection is typically used to allow data values to be passed from Seam components into web pages. Seam allows components to be injected into different Seam components by using the @In annotation and allows us to outject them by using the @Out annotation. For example, if we have some JSF code that allows us to enter details on a web form, we may use an <h:inputText …/> tag such as this: <h:inputText value="#{calculator.value1}" required="true"/> The Seam component calculator could then be injected into a Seam component using the @In annotation as follows: @In private Calculator calculator; With Seam, all of the default values on annotations are the most likely ones to be used. In the preceding example therefore, Seam will look up a component called calculator and inject that into the calculator variable. If we wanted Seam to inject a variable with a different name to the variable that it is being injected into, we can adorn the @In annotation with the value parameter. @In (value="myCalculator") private Calculator calculator; In this example, Seam will look up a component called myCalculator and inject it into the variable calculator. Similarly, if we want to outject a variable from a Seam component into a JSF page, we would use the @Out annotation. @Out private Calculator calculator; The outjected calculator object could then be used in a JSF page in the following manner: <h:outputText value="#{calculator.answer}"/> Example application To see these concepts in action, and to gain an understanding of how Seam components are used instead of JSF backing beans, let us look at a simple calculator web application. This simple application allows us to enter two numbers on a web page. Clicking the Add button on the web page will cause the sum of the numbers to be displayed. This basic application will give us an understanding of the layout of a Seam application and how we can inject and outject components between the business layer and the view. The application functionality is shown in the following screenshot. The sample code for this application can be downloaded from the Packt web site, at http://www.packtpub.com/support. For this sample application, we have a single JSF page that is responsible for: Reading two numeric values from the user Invoking business logic to add the numbers together Displaying the results of adding the numbers together <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <html> <head> <title>Seam Calculator</title> </head> <body> <f:view> <h:form> <h:panelGrid columns="2"> Value 1: <h:inputText value="#{calculator. value1}" /> Value 2: <h:inputText value="#{calculator. value2}" /> Add them together gives: <h:outputText value=" #{calculator.answer} "/> </h:panelGrid> <h:commandButton value="Add" action= "#{calcAction.calculate}"/> </h:form> </f:view> </body> </html> We can see that there is nothing Seam-specific in this JSF page. However, we are binding two inputText areas, one outputText area, and a button action to Seam components by using standard JSF Expression Language. JSF EL Seam Binding calculator.value1 This is bound to the member variable value1 on the Seam component called calculator. This value will be injected into the Seam component. calculator.value2 This is bound to the member variable value2 on the Seam component called calculator. This value will be injected into the Seam component. calculator.answer This is bound to the member variable answer on the Seam component called calculator. This value will be outjected from the Seam component. calcAction.calculate This will invoke the method calculate() on the Seam component called calcAction. Our business logic for this sample application is performed in a simple POJO class called Calculator.java. package com.davidsalter.seamcalculator; import java.io.Serializable; import org.jboss.seam.annotations.Name;@Name("calculator") public class Calculator { private double value1; private double value2; private double answer; public double getValue1() { return value1; } public void setValue1(double value1) { this.value1 = value1; } public double getValue2() { return value2; } public void setValue2(double value2) { this.value2 = value2; } public double getAnswer() { return answer; } public void add() { this.answer = value1 + value2; } } This class is decorated with the @Name("calculator") annotation, which causes it to be registered to Seam with the name, "calculator". The @Name annotation causes this object to be registered as a Seam component that can subsequently be used within other Seam components via Injection or Outjection by using the @In and @Out annotations. Finally, we need to have a class that is acting as a backing bean for the JSF page that allows us to invoke our business logic. In this example, we are using a Stateless Session Bean. The Session Bean and its local interface are as follows. In the Java EE 5 specification, a Stateless Session Bean is used to represent a single application client's communication with an application server. A Stateless Session Bean, as its name suggests, contains no state information; so they are typically used as transaction façades. A Façade is a popular design pattern, which defines how simplified access to a system can be provided. For more information about the Façade pattern, check out the following link: http://java.sun.com/blueprints/corej2eepatterns/Patterns/SessionFacade.html Defining a Stateless Session Bean using Java EE 5 technologies requires an interface and an implementation class to be defined. The interface defines all of the methods that are available to clients of the Session Bean, whereas the implementation class contains a concrete implementation of the interface. In Java EE 5, a Session Bean interface is annotated with either the @Local or @Remote or both annotations. An @Local interface is used when a Session Bean is to be accessed locally within the same JVM as its client (for example, a web page running within an application server). An @Remote interface is used when a Session Bean's clients are remote to the application server that is running within a different JVM as the application server. There are many books that cover Stateless Session Beans and EJB 3 in depth, such as EJB 3 Developer's Guide by Michael Sikora, published by Packt Publishing. For more information on this book, check out the following link: http://www.packtpub.com/developer-guide-for-ejb3 In the following code, we are registering our CalcAction class with Seam under the name calcAction. We are also Injecting and Outjecting the calculator variable so that we can use it both to retrieve values from our JSF form and pass them back to the form. package com.davidsalter.seamcalculator; import javax.ejb.Stateless; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Out; import org.jboss.seam.annotations.Name; @Stateless @Name("calcAction") public class CalcAction implements Calc { @In @Out private Calculator calculator; public String calculate() { calculator.add(); return ""; } } package com.davidsalter.seamcalculator; import javax.ejb.Local; @Local public interface Calc { public String calculate(); } That's all the code we need to write for our sample application. If we review this code, we can see several key points where Seam has made our application development easier: All of the code that we have developed has been written as POJOs, which will make unit testing a lot easier. We haven't extended or implemented any special Seam interfaces. We've not had to define any JSF backing beans explicitly in XML. We're using Java EE Session Beans to manage all of the business logic and web-tier/business-tier integration. We've not used any DTO objects to transfer data between the web and the business tiers. We're using a Seam component that contains both state and behavior. If you are familiar with JSF, you can probably see that adding Seam into a fairly standard JSF application has already made our development simpler. Finally, to enable Seam to correctly find our Seam components and deploy them correctly to the application server, we need to create an empty file called seam.properties and place it within the root of the classpath of the EJB JAR file. Because this file is empty, we will not discuss it further here. To deploy the application as a WAR file embedded inside an EAR file, we need to write some deployment descriptors.
Read more
  • 0
  • 0
  • 2126
article-image-slider-dynamic-applications-using-scriptaculous-part-1
Packt
08 Oct 2009
5 min read
Save for later

Slider for Dynamic Applications using script.aculo.us (part 1)

Packt
08 Oct 2009
5 min read
Before we start exploring the slider, let me try to give you a complete picture of its functionality with a simple example. Google Finance uses a horizontal slider, showing the price at a given day, month, and year. Although this particular module is built in Flash, we can build a similar module using the script.aculo.us slider too. To understand the concept and how it works, look at the following screenshot: Now that we have a clear understanding of what the slider is and how it appears in UI, let's get started! First steps with slider As just explained, a slider can handle a single value or a set of values. It's important to understand at this point of time that unlike other features of script.aculo.us, a slider is used in very niche applications for a specific functionality. The slider is not just mere functionality, but is the behavior of the users and the application. A typical constructor syntax definition for the slider is shown as follows: new Control.Slider(handle, track [ , options ] ); Track mostly represents the <div> element. Handle represents the element inside the track and, as usual, a large number of options for us to fully customize our slider. For now, we will focus on understanding the concepts and fundamentals of the slider. We will surely have fun playing with code in our Code usage for the slider section. Parameters for the slider definition In this section we will look at the parameters required to define the slider constructor: track in a slider represents a range handle in a slider represents the sliding along the track, that is, within a particular range and holding the current value options in a slider are provided to fully customize our slider's look and feel as well as functionality It's time to put the theory into action. We need the appropriate markup for working with the slider. We have <div> for the track and one <div> for each handle. The resulting code should look like the snippet shown as follows: <div id="track"><div id="handle1"></div></div> It is possible to have multiple handles inside a single track. The following code snippet is a simple example: <div id="track"><div id="handle1"></div><div id="handle2"></div></div> Options with the slider Like all the wonderful features of script.aculo.us, the slider too comes with a large number of options that allow us to create multiple behaviours for the slider. They are: Axis: This defines the orientation of the slider. The direction of movement could be horizontal or vertical. By default it is horizontal. Increment: This defines the relation between value and pixels. Maximum: This is the maximum value set for the slider to move to. While using a vertical slider from top-to-bottom, the bottom most value will be the maximum. And for a horizontal slider from left-to-right, the right most value will be the maximum value. Minimum: This is the minimum value set for the slider to move to. While using a vertical slider from top-to-bottom, the top most value will be the minimum. And for a horizontal slider from left-to-right, the left most value will be the minimum value approach for horizontal slider. Range: This is the fixed bandwidth allowed for the values. Define the minimum and maximum values. Values: Instead of a range, pass a set of values as an array. SliderValue: This sets the initial value of the slider. If not set, will take the extreme value of the slide as the default value. Disabled: As the name suggests, this disables the slider functionality. Some of the functions offered by the slider are: setValue:This will set the value of the slider directly and move it to the value position. setDisabled: This defines that the slider is disabled at runtime. setEnabled: This can enable the slider at runtime. Some of the callbacks supported by the slider are: onSlide: This is initiated on every slide movement. The called function would get the current slider value as parameter onChange: Whenever the value of the slider is changed, the called function is invoked. The value can change due to the slider movement or by passing the setValue function. Types of slider script.aculo.us provides us the flexibility and comfort of two different orientations for the slider: Vertical slider Horizontal slider Vertical slider When the axis orientation of a slider is defined as vertical, the slider becomes and acts as a vertical slider. Horizontal slider When the axis orientation of a slider is defined as horizontal, the slider becomes and acts as a horizontal slider. So let's get our hands dirty with code and start defining the constructors for horizontal and vertical slider with options. Trust me this will be fun.
Read more
  • 0
  • 0
  • 2437

article-image-slider-dynamic-applications-using-scriptaculous-part-2
Packt
08 Oct 2009
4 min read
Save for later

Slider for Dynamic Applications using script.aculo.us (part 2)

Packt
08 Oct 2009
4 min read
Code usage for sliders with options We are now done with the most important part of the slider: the implementation of the slider in our applications. But wait, we need the slider to suit our applications, right? So let's customize our slider with options. We have mentioned earlier that track is the range of values. So let's first define the range for our slider. window.onload = function() { new Control.Slider('handle1' , 'track1', { axis:'vertical', range:$R(1,100)} The range option uses the Prototypes' objectRange instance. Hence, we declare it using $R (minimum, Maximum). Everything looks neat until here. Let's add some more options to our constructor, onSlide(). Using the onSlide() callback every time, we drag the slider and the callback is invoked. The default parameter passed to onSlide() is the current slider value. window.onload = function() { new Control.Slider('handle1' , 'track1', { axis:'vertical', range:$R(1,100), onSlide: function(v) { $('value1').innerHTML = "New Slide Value="+v;} }} We have added a div called value1 in our HTML code. On dragging the slider, we will update the value1 with the current slider value. OK, so let's see what happened to our slider to this point. Check out the following screenshot: Impressed? And, we are not done yet. Let's add more options to the slider now. You may ask me, what if the slider in the application needs to be at a particular value by default? And I will say use the sliderValue option. Let's make our slider value 10 by default. Here is the snippet for the same: window.onload = function() {      new Control.Slider('handle1' , 'track1',     {   axis:'vertical',   range:$R(1,100),   sliderValue: 10,   onSlide: function(v) { $('value1').innerHTML = "New Slide                                                 Value="+v;}} And, you should see the slider value at 10 when you run the code. Now your dear friend will ask, what if we don't want to give the range, but we need to pass the fixed set of values? And you proudly say, use the values option. Check out the usage of the values options in the constructor. window.onload = function() { new Control.Slider('handle1' , 'track1', { range:$R(1,25), values:[1, 5,10,15,20,25], onSlide:function(v){ $('value1').innerHTML = "New Slide Value="+v;} } );} We have added a set of values in the array form and passed it to our constructor. Let's see what it looks like. Tips and tricks with the slider After covering all the aspects of the slider feature, here is a list of simple tips and tricks which we can make use of in our applications with ease. Reading the current value of the slider script.aculo.us "genie" provides us with two callbacks for the slider to read the current value of the slider. They are: onSlide onChange Both these callbacks are used as a part of options in the slider. onSlide contains the current sliding value while the drag is on. The callback syntax is shown as follows: onSlide: function(value) {// do something with the value while sliding. Write or Edit thevalue //of current slider value while sliding} onChange callback will contain the value of the slider while the sliding or the drag event ends. After the drag is completed and if the value of the slider has changed then the onChange function will be called. For example, if the slider's current value is set to 10 and after sliding we change it to 15, then the onChange callback will be fired. The callback syntax is shown as follows: onChange: function(value){// do anything with the "changed" and current value} Multiple handles in the slider Now, a thought comes to our mind at this point: Is it possible for us to have two handles in one track? And, the mighty script.aculo.us library says yes! Check out the following code snippet and screenshot for a quick glance of having two handles in one track: HTML code<div id="track1"><div id="handle1"></div><div id="handle2"></div></div> JavaScript code for the same: window.onload = function() { new Control.Slider(['handle1','handle2'] , 'track1');} Now, check out the resulting screenshot having two handles and one track: The same can also be applied for the vertical slider too.
Read more
  • 0
  • 0
  • 2130

article-image-non-default-magento-themes
Packt
07 Oct 2009
4 min read
Save for later

Non-default Magento Themes

Packt
07 Oct 2009
4 min read
Uses of non-default themes Magento's flexibility in themes gives a lot of scope for possible uses of non-default themes. Along with the ability to have seasonal themes on our Magento store, non-default themes have a range of uses: A/B testing Easily rolled-back themes Changing the look and feel of specific pages, such as for a particular product within your store Creating brand-specific stores within your store, distinguishing your store's products further, if you sell a variety of the same products from different brands A/B testing A/B testing allows you to compare two different aspects of your store. You can test different designs on different weeks, and can then compare which design attracted more sales. Magento's support for non-default themes allows you to do this relatively easily. Bear in mind that the results of such a test may not represent what actually drives your customers to buy your store's products for a number of reasons. True A/B testing on websites is performed by presenting the different designs to your visitors at random. However, performing it this way may give you an insight in to what your customers prefer. Easily rolled-back themes If you want to make changes to your store's existing theme, then you can make use of a non-default theme to overwrite certain aspects of your store's look and feel, without editing your original theme. This means that if your customers don't like a change, or a change causes problems in a particular browser, then you can simply roll-back the changes, by changing your store's settings to display the original theme. Non-default themes A default theme is the default look and feel to your Magento store. That is, if no other styling or presentational logic is specified, then the default theme is the one that your store's visitors will see. Magento's default theme looks similar to the following screenshot: Non-default themes are very similar to the default themes in Magento. Like default themes, Magento's non-default themes can consist of one or more of the following elements: Skins—images and CSS Templates—the logic that inserts each block's content or feature (for example, the shopping cart) in to the page Layout—XML files that define where content is displayed Locale—translations of your store The major difference between a default and a non-default theme in Magento is that a default theme must have all of the layout and template files required for Magento to run. On the other hand, a non-default theme does not need all of these to function, as it relies on your store's default theme, to some extent. Locales in Magento: Many themes are already partially or fully translated into a huge variety of languages. Locales can be downloaded from the Magento Commerce website at http://www.magentocommerce.com/langs. Magento theme hierarchy In its current releases, Magento supports two themes: a default theme, and a non-default theme. The non-default theme takes priority when Magento is deciding what it needs to display. Any elements not found in the non-default theme are then found in the default theme specified. Future versions of Magento should allow more than one default theme to be used at a time, as well as allow more detailed control over the hierarchy of themes in your store. Magento theme directory structure Every theme in Magento must maintain the same directory structure for its files. The skin, templates, and layout are stored in their own directories. Templates Templates are located in the app/design/frontend/interface/theme/template directory of your Magento store's installation, where interface is your store's interface (or package) name (usually default), and theme is the name of your theme (for example, cheese). Templates are further organized in subdirectories by module. So, templates related to the catalog module are stored in app/design/frontend/interface/theme/template/catalog directory, whereas templates for the checkout module are stored in app/design/frontend/interface/theme/template/checkout directory. Layout Layout files are stored in app/design/frontend/interface/theme/layout. The name of each layout file refers to a particular module. For example, catalog.xml contains layout information for the catalog module, whereas checkout.xml contains layout information for the checkout module.
Read more
  • 0
  • 0
  • 2607
article-image-exporting-data-ms-access-2003-mysql
Packt
07 Oct 2009
4 min read
Save for later

Exporting data from MS Access 2003 to MySQL

Packt
07 Oct 2009
4 min read
Introduction It is assumed that you have a working copy of MySQL which you can use to work with this article. The MySQL version used in this article came with the XAMPP download. XAMPP is an easy to install (and use) Apache distribution containing MySQL, PHP, and Perl. The distribution used in this article is XAMPP for Windows. You can find documentation here. Here is a screen shot of the XAMPP control panel where you can turn the services on and off and carry out other administrative tasks. You need to follow the steps indicated here: Create a database in MySQL to which you will export a table from Microsoft Access 2003 Create a ODBC DSN that helps you connecting Microsoft Access to MySQL Export the table or tables Verify the exported items Creating a database in MySQL You can create a database in MySQL by using the command 'Create Database' in MySQL or using a suitable graphic user interface such as MySQL workbench. You will have to refer to documentation that works with your version of MySQL. Herein the following version was used. The next listing shows how a database named TestMove was created in MySQL starting from the bin folder of the MySQL program folder. Follow the commands and the response from the computer. The Listing 1 and the folders are appropriate for my computer and you may find it in your installation directory. The databases you will be seeing will be different from what you see here except for those created by the installation. Listing 1: Login and create a database Microsoft Windows XP [Version 5.1.2600](C) Copyright 1985-2001 Microsoft Corp.C:Documents and SettingsJayaram Krishnaswamy>cdC:>cd xamppmysqlbinC:xamppmysqlbin>mysql -h localhost -u root -pEnter password: *********Welcome to the MySQL monitor. Commands end with ; or g.Your MySQL connection id is 2Server version: 5.1.30-community MySQL Community Server (GPL)Type 'help;' or 'h' for help. Type 'c' to clear the buffer.mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || cdcol || expacc || mengerie || mydb || mysql || phpmyadmin || test || testdemo || webauth |+--------------------+10 rows in set (0.23 sec)mysql> create database TestMove;Query OK, 1 row affected (0.00 sec)mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || cdcol || expacc || mengerie || mydb || mysql || phpmyadmin || test || testdemo || testmove || webauth |+--------------------+11 rows in set (0.00 sec)mysql> The login detail that works error free is shown. The preference for host name is localhost v/s either the Machine Name (in this case Hodentek2) or the IP address. The first 'Show Databases' command does not display the TestMove we created which you can see in response to the 2nd Show Databases command. In windows the commands are not case sensitive. Creating an ODBC DSN to connect to MySQL When you install from XAMPP you will also be installing an ODBC driver for MySQL for the version of MySQL included in the bundle. In the MySQL version used for this article the version is MySQL ODBC5.1 and the file name is MyODBC5.dll. Click Start | Control Panel | Administrative Tools | Data Sources (ODBC) and open the ODBC Data Source Administrator window as shown. The default tab is User DSN. Change to System DSN as shown here. Click the Add... button to open the Create New Data Source window as shown. Scroll down and choose MySQL ODBC 5.1 Driver as the driver and click Finish. The MySQL Connector/ODBC Data Source Configuration window shows up. You will have to provide a Data Source Name (DSN) and a description. The server is the localhost. You must have your User Name/Password information to proceed further. The database is the name of the database you created earlier (TestMove) and this should show up in the drop-down list if the rest of the information is correct. Accept the default port. If all information is correct the Test button gets enabled. Click and test the connection using the Test button. You should get a response as shown. Click the OK button on the Test Result window. Click OK on the MySQL Connector/ODBC Data Source Configuration window. There are a number of other flags that you can set up using the 'Details' button. The defaults are acceptable for this article. You have successfully created a System DSN 'AccMySQL' as shown in the next window. Click OK. Verify the contents of TestMove The TestMove is a new database created in MySQL and as such it is empty as you verify in the following listing. Listing 2: Database TestMove is empty mysql> use testmove;Database changedmysql> show tables;Empty set (0.00 sec)mysql>
Read more
  • 0
  • 0
  • 9070

article-image-debugging-and-validation-wordpress-theme-design
Packt
07 Oct 2009
15 min read
Save for later

Debugging and Validation in WordPress Theme Design

Packt
07 Oct 2009
15 min read
As you work on and develop your own WordPress themes, you will no doubt discover that life will go much smoother if you debug and validate at each step of your theme development process. The full process will pretty much go like this: Add some code, check to see the page looks good in Firefox, validate, then check it in IE and any other browsers you and your site's audience use, validate again if necessary, add the next bit of code... repeat as necessary until your theme is complete. Don't Forget About Those Other Browsers and Platforms I'll mostly be talking about working in Firefox and then 'fixing' for IE. This is perhaps, unfairly, assuming you're working on Windows or a Mac and that the source of all your design woes will (of course) be Microsoft IE's fault. You must check your theme in all browsers and if possible, other platforms, especially the ones you know your audience uses the most. I surf with Opera a lot and find that sometimes JavaScripts can 'hang' or slow that browser down, so I debug and double-check scripts for that browser. I'm a freelance designer and find a lot of people who are also in the design field use a Mac (like me), and visit my sites using Safari, so I occasionally take advantage of this and write CSS that caters to the Safari browser. (Safari will interpret some neat CSS 3 properties that other browsers don't yet.) Generally, if you write valid markup and code that looks good in Firefox, it will look good in all the other browsers (including IE). Markup and code that goes awry in IE is usually easy to fix with a work-around. Firefox is a tool, nothing more! Firefox contains features and plug-ins that we'll be taking advantage of to help us streamline the theme development process and aid in the validation and debugging of our theme. Use it just like you use your HTML/code editor or your image editor. When you're not developing, you can use whatever browser you prefer. Introduction to Debugging Have a look at our initial work-flow chart. I was insistent that your work-flow pretty much be as edit -> check it -> then go back and edit some more. The main purpose of visually checking your theme in Firefox after adding each piece of code is so that you can see if it looks OK, and if not, immediately debug that piece of code. Running a validation check as you work just doubly ensures you're on the right track. So, your work-flow really ends up looking something more like this: You want to work with nice, small pieces or 'chunks' of code. I tend to define a chunk in XHTML markup as no more than one div section, the internal markup, and any WordPress template tags it contains. When working with CSS, I try to only work with one id or class rule at a time. Sometimes, while working with CSS, I'll break this down even further and test after every property I add to a rule, until the rule looks as I intend and validates. As soon as you see something that doesn't look right in your browser, you can check for validation and then fix it. The advantage of this work-flow is you know exactly what needs to be fixed and what XHTML markup or PHP code is to blame. All the code that was looking fine and validating before, you can ignore. The recently added markup and code is also the freshest in your mind, so you're more likely to realize the solution needed to fix the problem. If you add too many chunks of XHTML markup or several CSS rules before checking it in your browser, then discover something has gone awry, you'll have twice as much sleuthing to do in order to discover which (bit or bits) of markup and code are to blame. Again, your fail-safe is your backup. You should be regularly saving backups of your theme at good stable stopping points. If you do discover that you just can't figure out where the issue is, rolling back to your last stable stopping point and starting over might be your best bet to getting back on track. Here, you'll primarily design for Firefox and then apply any required fixes, hacks, and workarounds to IE. You can do that for each piece of code you add to your theme. As you can see in the preceding figure, first check your theme in Firefox and if there's a problem, fix it for Firefox first. Then, check it in IE and make any adjustments for that browser. At this point, you guessed it, more than half of the debugging process will depend directly on your own eyeballs and aesthetics. If it looks the way you intended it to look and works the way you intended it to work, check that the code validates and move on. When one of those three things doesn't happen (it doesn't look right, work right, or validate), you have to stop and figure out why. Troubleshooting Basics Suffice to say, it will usually be obvious when something is wrong with your WordPress theme. The most common reasons for things being 'off' are: Mis-named, mis-targeted, or inappropriately-sized images. Markup text or PHP code that affects or breaks the Document Object Model (DOM) due to being inappropriately placed or having syntax errors in it. WordPress PHP code copied over incorrectly, producing PHP error displays in your template, rather than content. CSS rules that use incorrect syntax or conflict with later CSS rules. The first point is pretty obvious when it happens. You see no images, or worse, you might get those little ugly 'x'd' boxes in IE if they're called directly from the WordPress posts or pages. Fortunately, the solution is also obvious: you have to go in and make sure your images are named correctly if you're overwriting standard icons or images from another theme. You also might need to go through your CSS file and make sure the relative paths to the images are correct. For images that are not appearing correctly because they were mis-sized, you can go back to your image editor, fix them, and then re-export them, or you might be able to make adjustments in your CSS file to display a height and/or width that is more appropriate to the image you designed. Don't forget about casing! If by some chance you happen to be developing your theme with an installation of WordPress on a local Windows machine, do be careful with the upper and lower casing in your links and image paths. Chances are, the WordPress installation that your theme is going to be installed into is more likely to be on a Unix or Linux web server. For some darn reason, Windows (even if you're running Apache, not IIS) will let you reference and call files with only the correct spelling required. Linux, in addition to spelling, requires the upper and lower casing to be correct. You must be careful to duplicate exact casing when naming images that are going to be replaced and/or when referencing your own image names via CSS. Otherwise, it will look fine in your local testing environment, but you'll end up with a pretty ugly theme when you upload it into your client's installation of WordPress for the first time (which is just plain embarrassing). For the latter two points, one of the best ways to debug syntax errors that cause visual 'wonks' is not to have syntax errors in the first place (don't roll your eyes just yet). This is why, in the last figure of our expanded work-flow chart, we advocate you to not only visually check your design as it progresses in Firefox and IE, but also test for validation. Why Validate? Hey, I understand it's easy to add some code, run a visual check in Firefox and IE, see everything looks OK, and then flip right back to your HTML editor to add more code. After-all, time is money and you'll just save that validation part until the very end. Besides, validation is just icing on the cake. Right? The problem with debugging purely based on visual output is, all browsers (some more grievously than others) will try their best to help you out and properly interpret less than ideal markup. One piece of invalid markup might very well look OK initially, until you add more markups and then the browser can't interpret your intentions between the two types of markup anymore. The browser will pick its own best option and display something guaranteed to be ugly. You'll then go back and futz around with the last bit of code you added (because everything was fine until you added that last bit, so that must be the offending code) which may or may not fix the problem. The next bits of code might create other problems and what's worse that you'll recognize a code chunk that you know should be valid! You're then frustrated, scratching your head as to why the last bit of code you added is making your theme 'wonky' when you know, without a doubt, it's perfectly fine code! The worst case scenario I tend to see of this type of visual-only debugging is that the theme developers get desperate and start randomly making all sorts of odd hacks and tweaks to their markup and CSS to get it to look right. Miraculously, they often do get it to look right, but in only one browser. Most likely, they've inadvertently discovered what the first invalid syntax was and unwittingly applied it across all the rest of their markup and CSS. Thus, that one browser started consistently interpreting the bad syntax! The theme designer then becomes convinced that the other browser is awful and designing these non-WYSIWYG, dynamic themes is a pain. Avoid all that frustration! Even if it looks great in both browsers, run the code through the W3C's XHTML and CSS validators. If something turns up invalid, no matter how small or pedantic the validator's suggestion might be (and they do seem pedantic at times), incorporate the suggested fix into your markup now, before you continue working. This will keep any small syntax errors from compounding future bits of markup and code into big visual 'uglies' that are hard to track down and troubleshoot. PHP Template Tags The next issue you'll most commonly run into is mistakes and typos that are created by 'copying and pasting' your WordPress template tags and other PHP code incorrectly. The most common result you'll get from invalid PHP syntax is a 'Fatal Error.' Fortunately, PHP does a decent job of trying to let you know what file name and line of code in the file the offending syntax lives (yet another reason why I highly recommend an HTML editor that lets you view the line number in the Code view). If you get a 'Fatal Error' in your template, your best bet is to open the file name that is listed and go to the line in your editor. Once there, search for missing < ?php ? > tags. Your template tags should also be followed with parenthesis followed by a semicolon like ( ) ; . If the template tag has parameters passed in it, make sure each parameter is surrounded by single quote marks, that is, template_tag_name('parameter name', 'next_parameter');. CSS Quick Fixes Last, your CSS file might get fairly big, fairly quickly. It's easy to forget you already made a rule and/or just accidentally create another rule of the same name. It's all about cascading, so whatever comes last, overwrites what came first. Double rules: It's an easy mistake to make, but validating using W3C's CSS validator will point this out right away. However, this is not the case for double properties within rules! W3C's CSS validator will not point out double properties if both properties use correct syntax. This is one of the reasons why the !important hack returns valid. (We'll discuss this hack just a little further down in this article under To Hack or Not to Hack.) Perhaps you found a site that has a nice CSS style or effect you like, and so you copied those CSS rules into your theme's style.css sheet. Just like with XHTML markup or PHP code, it's easy to introduce errors by miscopying the bits of CSS syntax in. A small syntax error in a property towards the bottom of a rule may seem OK at first, but cause problems with properties added to the rule later. This can also affect the entire rule or even the rule after it. Also, if you're copying CSS, be aware that older sites might be using depreciated CSS properties, which might be technically OK if they're using an older HTML DOCTYPE, but won't be OK for the XHTML DOCTYPE you're using. Again, validating your markup and CSS as you're developing will alert you to syntax errors, depreciated properties, and duplicate rules which could compound and cause issues in your stylesheet down the line. Advanced Troubleshooting Take some time to understand the XHTML hierarchy. You'll start running into validation errors and CSS styling issues if you wrap a 'normal' (also known as a 'block') element inside an 'in-line' only element, such as putting a header tag inside an anchor tag (<a href, <a name, etc.) or wrapping a div tag inside a span tag. Avoid triggering quirks mode in IE! This, if nothing else, is one of the most important reasons for using the W3C HTML validator. There's no real way to tell if IE is running in quirks mode. It doesn't seem to output that information anywhere (that I've found). However, if any part of your page or CSS isn't validating, it's a good way to trigger quirks mode in IE. The first way to avoid quirks mode is to make sure your DOCTTYPE is valid and correct. If IE doesn't recognize the DOCTYPE (or if you have huge conflicts, like an XHTML DOCTYPE, but then you use all-cap, HTML 4.0 tags in your markup), IE will default into quirks mode and from there on out, who knows what you'll get in IE. My theme stopped centering in IE! The most obvious thing that happens when IE goes into quirks mode is that IE will stop centering your layout in the window properly if your CSS is using the margin: 0 auto; technique. If this happens, immediately fix all the validation errors in your page. Another big obvious item to note is if your div layers with borders and padding are sized differently between browsers. If IE is running in quirks mode it will incorrectly render the box model, which is quite noticeable between Firefox and IE if you're using borders and padding in your divs. Another item to keep track of is to make sure you don't have anything that will generate any text or code above your DOCTYPE. Firefox will read your page until it hits a valid DOCTYPE and then proceed from there, but IE will just break and go into quirks mode. Fixing CSS Across Browsers If you've been following our debug -> validate method described in the article, then for all intents and purposes, your layout should look pretty spot-on between both the browsers. Box Model Issues In the event that there is a visual discrepancy between Firefox and IE, in most cases it's a box model issue arising because you're running in quirks mode in IE. Generally, box model hacks apply to pre IE 6 browsers (IE 5.x) and apply to IE6 if it's running in quirks mode. Again, running in quirks mode is to be preferably avoided, thus eliminating most of these issues. If your markup and CSS are validating (which means you shouldn't be triggering quirks mode in IE, but I've had people 'swear' to me their page validated yet quirks mode was being activated), you might rather 'live with it' than try to sleuth what's causing quirks mode to activate. Basically, IE 5.x and IE6 quirks mode don't properly interpret the box model standard and thus, 'squish' your borders and padding inside your box's width, instead of adding to the width as the W3C standard recommends. However, IE does properly add margins! This means that if you've got a div set to 50 pixels wide, with a 5 pixel border, 5 pixels of padding, and 10 pixels of margin in Firefox, your div is actually going to be 60 pixels wide with 10 pixels of margin around it, taking up a total space of 70 pixels.. In IE quirks mode, your box is kept at 50 pixels wide (meaning it's probably taller than your Firefox div because the text inside is having to wrap at 40 pixels), yet it does have 10 pixels of margin around it. You can quickly see how even a one pixel border, some padding, and a margin can start to make a big difference in layout between IE and Firefox!
Read more
  • 0
  • 0
  • 2444
Modal Close icon
Modal Close icon