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
All 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 - CMS & E-Commerce

830 Articles
article-image-user-security-and-access-control-jboss-portals
Packt
15 Oct 2009
6 min read
Save for later

User Security and Access Control in JBoss portals

Packt
15 Oct 2009
6 min read
Authentication Authentication in JBoss portal builds on the JEE security provided by the JBoss server. The JEE specification defines the roles and constraints under which certain URLs and components are protected. However, this might not always be sufficient for building enterprise applications or portals. Application server providers such as JBoss supplement the authentication and authorization features provided by the JEE specification with additional features such as role-to-group mapping and session logout. Authentication in JBoss portal can be divided into configuration files and portal server configuration. The jboss-portal.sar/portal-server.war file is the portal deployment on the JBoss application server. Assuming that the portal server is like any JEE application deployed on an application server, all user authentication configurations go into the WEB-INF/web.xml and the WEB-INF/jboss-web.xml files. The WEB-INF/web.xml entry defines the authentication mode, with the default being form-based authentication. This file is also used to define the login and error pages, as defined by the JEE specification. The default security domain defined by the JBoss application server is java:/jaas/portal for JBoss portal. The security domain maps the JEE security constructs to the operational domain. This is defined in a proprietary file, WEB-INF/jboss-web.xml. The portal security domain authentication stack is defined in the jboss-portal.sar/conf/login-config.xml file, and is deployed along with the portal. Login-config.xml houses the JAAS modules for authentication. Custom modules can be written and added here to support special scenarios. The server provides a defined set of JAAS login modules that can be used for various scenarios. For example, the IdentityLoginModule is used for authentication based on local portal data, SynchronizingLdapLoginModule for authentication using LDAP, and DBIdentityLoginModule for authentication using a database. Within the jboss-portal.sar/portal-server.war application, all portal requests are routed through a single servlet called org.jboss.portal.server.servlet.PortalServlet. This servlet is defined twice, as follows, in the configuration file WEB-INF/web.xml to ensure that all possible request sources are covered: PortalServletWithPathMapping for path mappings PortalServletWithDefaultServletMapping for the default servlet mapping The servlet is mapped four times with variations to address a combination of secure SSL access and authenticated URLs, as follows: /*: Default access, and with no security constraint, allows access to everybody /sec/*: All requests to a secure protocol are routed through this path, ensuring SSL transport /auth/*: Authenticated access. Requires user to be authenticated before accessing the content under this tree /authsec/*: An authenticated and secure access The following snippet from web.xml shows the entries: <!-- Provide access to unauthenticated users --> <servlet-mapping> <servlet-name>PortalServletWithPathMapping</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> <!-- Provide secure access to unauthenticated users --> <servlet-mapping> <servlet-name>PortalServletWithPathMapping</servlet-name> <url-pattern>/sec/*</url-pattern> </servlet-mapping> <!-- Provide access to authenticated users --> <servlet-mapping> <servlet-name>PortalServletWithPathMapping</servlet-name> <url-pattern>/auth/*</url-pattern> </servlet-mapping> <!-- Provide secure access to authenticated users --> <servlet-mapping> <servlet-name>PortalServletWithPathMapping</servlet-name> <url-pattern>/authsec/*</url-pattern> </servlet-mapping> The URL patterns can be changed based on personal preference. Authorization Authorization is the process of determining if an authenticated user has access to a particular resource. Similar to authentication, JBoss portal provides in-built support for authorization, through Java Authorization Contract for Containers(JACC). JACC is a JSR-115 specification for the authorization models of the Java2 and JEE enterprise platforms. In the next few sections, we will look at how JBoss portal facilitates authorization using JACC. However, before we go into the details of access controls and authorization configurations, let's quickly look at how roles are configured in JBoss Portal. User and role management A role is an authorization construct that denotes the group that a user of the portal belongs to. Typically, roles are used to determine the access rights and the extent of these rights for a given resource. We saw in an earlier section how to configured portal assets such as, portals, pages, and portlet instances, to restrict certain actions to specific roles. We used a role called SPECIAL_USER for our examples. However, we never really defined what this role means to JBoss portal. Let's use the JBoss portal server console to register this role with the server. Log in as admin, and then click on the Members tab. This takes us to the User Management and Role Management tabs. The User Management tab is used for creating new users. We will come back to this shortly, but for now, let's switch over to the Role Management tab and click on the Create role link on the bottom right of the page. We can now add our SPECIAL_USER role and provide a display name for it. Once we submit it, the role will be registered with the portal server. As we will see later, every attempt by an authenticated user to access a resource that has security constraints through a specific role will be matched by the portal before granting or denying access to the resource. Users can be added to a role by using the User Management tab. Each user has a role property assigned, and this can be edited to check all of the roles that we want the user to belong to. We can see that for the user User, we now have an option to add the user to the Special User role. The portal permission A permission object carries the relevant permission for a given entity. The org.jboss.portal.security.PortalPermission object is used to describe permission for the portal. Like all the other entity-specific permission classes, it extends the java.security.Permission class, and any permission checked in the portal should extend the PortalPermission as well. Two additional fields of significance are as follows: uri: A string that specifies the URI of the resource that is described by the permission collection: An object of class org.jboss.portal.security.PortalPermissionCollection, which is used when the permission acts as a container for other permissions The authorization provider The authorization provider is a generic interface of the type org.jboss.portal.security.spi.provider.AuthorizationDomain, and provides access to several services. public interface AuthorizationDomain{ String getType(); DomainConfigurator getConfigurator(); PermissionRepository getPermissionRepository(); PermissionFactory getPermissionFactory();} Let us look into these classes a bit more in detail: org.jboss.portal.security.spi.provider.DomainConfigurator provides configuration access to an authorization domain. The authorization schema consists of bindings between URIs, roles, and permissions. org.jboss.portal.security.spi.provider.PermissionRepository provides runtime access to the authorization domain. It is used to retrieve the permissions for a specific role and URI. It is used at runtime by the framework, to take security decisions. org.jboss.portal.security.spi.provider.PermissionFactory is a factory to instantiate permissions for the specific domain. It is used at runtime to create permission objects of the appropriate type by the security framework.
Read more
  • 0
  • 0
  • 2238

article-image-dotnetnukeskinning-creating-containers
Packt
15 Oct 2009
9 min read
Save for later

DotNetNukeSkinning: Creating Containers

Packt
15 Oct 2009
9 min read
Creating our first container In VWD (Visual Web Developer), from the Solution Explorer window, find the following location and create a new folder called FirstSkin: ~/Portals/_default/Containers/ Add a new item by right-clicking on this new folder. Add a new HTML file and call it Container.htm. Similarly, add a CSS and an XML file, Container.css and Container.xml respectively. Clear out all the code in the newly created files that VWD initializes it with. DNN tokens for containers These tokens, however, have applied mostly to creating skins, not containers. Containers have their own set of tokens to use here. The following is a listing of them. We'll be working with them throughout the rest of this article. Actions: This is the menu that will appear when you hover over the triangle. It is traditionally placed to the left of the icon and title of the module. Title: As you can imagine, this is the title of the module displayed in the container. This is usually placed at the top. Icon: Most of the modules don't have an icon, but many of the administrative pages in DotNetNuke have icons assigned to them. You can always assign icons to your modules, but none of them are set by default. Visibility: This skin object is traditionally displayed as a plus or a minus sign inside a small square. It acts as a toggle to show or hide/collapse or expand the content of the module. Content Pane: Similar to when we created our skin, this is where the content goes. The difference here is that we have only one content pane. It is required in order to make the container work. LINKACTIONS: This isn't used very often in containers. It is a listing of links that gives you access to the same things contained in the ACTIONS skin object. PRINTMODULE: This is the small printer icon you see in the preceding screenshot. When you click on it, it allows you to print the contents of the module. ACTIONBUTTON: This skin object allows you to display items as links or image links to commonly used items found in the actions menu. The last item on that list, the ActionButton, is different from the others in that we can have several uses of it in different ways. When used as a token, you would place them in your container HTM file as [ACTIONBUTTON:1], [ACTIONBUTTON:2], [ACTIONBUTTON:3], and so on. As you can imagine, we would define what each of these action buttons refer to. We do this in the XML file with an attribute called CommandName. For example, the following is a code snippet of what you could have to add as an action button: <Objects> <Object> <Token>[ACTIONBUTTON:1]</Token> <Settings> <Setting> <Name>CommandName</Name> <Value>AddContent.Action</Value> </Setting> <Setting> <Name>DisplayIcon</Name> <Value>True</Value> </Setting> <Setting> <Name>DisplayLink</Name> <Value>True</Value> </Setting> </Settings> </Object> Looking at the CommandName attribute, we can have several values which will determine which of the action buttons will be inserted into our container. The following is a listing: AddContent.Action: This typically allows you to add content, or in this case of the Text/HTML module, edit the content of the module. SyndicateModule.Action: This is an XML feed button, if it is supported by the module. PrintModule.Action: This is the printer icon allowing the users to print the content of the module. Yes, this is the second way of adding it as we already have the PRINTMODULE token. ModuleSettings.Action: This is a button/link which takes you to the settings of the module. ModuleHelp.Action—This is a help question mark icon/link that we've seen in the preceding screenshots. Adding to the container Now that we know what can be added, let's add them to our new container. We'll start off with the HTM file and then move on to the CSS file. In our HTM file, add the following code. This will utilize all of the container tokens with the exception of the action buttons, which we'll add soon. <div style="background-color:White;"> ACTIONS[ACTIONS] <hr /> TITLE[TITLE] <hr /> ICON[ICON] <hr /> VISIBILITY[VISIBILITY] <hr /> CONTENTPANE[CONTENTPANE] <hr /> LINKACTIONS[LINKACTIONS] <hr /> PRINTMODULE[PRINTMODULE]</div> Go to the skin admin page (Admin | Skins on the menu). Now that we have a container in the folder called FirstSkin, we'll now get a little added benefit: When you select FirstSkin as the skin to deal with, the container will be selected as well, so you can work with them as a unit or as a Skin Package. Go ahead, parse the skin package and apply our FirstSkin container. Go to the Home page. It may not be pretty, but pretty is not what we were looking for. This container, as it sits, gives us a better illustration of how each token is displayed with a convenient label beside each. There are a few things to point out here, besides we'll be taking out our handy labels and putting in some structure. Our module has no icon, so we won't see one here. If you go to the administrative pages, you will see the icon. The LINKACTIONS is a skin object that you'll use if you don't want to use the action menu ([ACTIONS]). Table Structure The structure of our container will be quite similar to how we laid out our skin. Let's start off with a basic table layout. We'll have a table with three rows. The first row will be for the header area which will contain things like the action menu, the title, icon, and so forth. The second row will be for the content. The third row will be for the footer items, like the printer and edit icon/links. Both the header and footer rows will have nested tables inside to have independent positioning within the cells. The markup which defines these three rows has been highlighted: <table border="0" cellpadding="0" cellspacing="0" class="ContainerMainTable"> <tr> <td style="padding:5px;"> <table border="0" cellpadding="0" cellspacing="0" class="ContainerHeader"> <tr> <td style="width:5px;">[ACTIONS]</td> <td style="width:5px;">[ICON]</td> <td align="left">[TITLE]</td> <td style="width:5px;padding-right:5px;" valign="top">[VISIBILITY]</td> <td style="width:5px;">[ACTIONBUTTON:4]</td> </tr> </table> </td> </tr> <tr> <td class="ContainerContent"> [CONTENTPANE] </td> </tr> <tr> <td style="padding:5px;"> <table border="0" cellpadding="0" cellspacing="0" class="ContainerFooter"> <tr> <td>[ACTIONBUTTON:1]</td> <td>[ACTIONBUTTON:2]</td> <td></td> <td>[ACTIONBUTTON:3]</td> <td style="width:10px;">[PRINTMODULE]</td> </tr> </table> </td> </tr></table> Making necessary XML additions The action buttons we used will not work unless we add items to our XML file. For each of our action buttons, we'll add a token element, then a few setting elements for each. There are three specific settings we'll set up for each: CommandName, DisplayIcon, and DisplayLink. See the following code: <Objects> <Object> <Token>[ACTIONBUTTON:1]</Token> <Settings> <Setting> <Name>CommandName</Name> <Value>AddContent.Action</Value> </Setting> <Setting> <Name>DisplayIcon</Name> <Value>True</Value> </Setting> <Setting> <Name>DisplayLink</Name> <Value>True</Value> </Setting> </Settings> </Object> <Object> <Token>[ACTIONBUTTON:2]</Token> <Settings> <Setting> <Name>CommandName</Name> <Value>SyndicateModule.Action</Value> </Setting> <Setting> <Name>DisplayIcon</Name> <Value>True</Value> </Setting> <Setting> <Name>DisplayLink</Name> <Value>False</Value> </Setting> </Settings> </Object> <Object> <Token>[ACTIONBUTTON:3]</Token> <Settings> <Setting> <Name>CommandName</Name> <Value>ModuleSettings.Action</Value> </Setting> <Setting> <Name>DisplayIcon</Name> <Value>True</Value> </Setting> <Setting> <Name>DisplayLink</Name> <Value>False</Value> </Setting> </Settings> </Object> <Object> <Token>[ACTIONBUTTON:4]</Token> <Settings> <Setting> <Name>CommandName</Name> <Value>ModuleHelp.Action</Value> </Setting> <Setting> <Name>DisplayIcon</Name> <Value>True</Value> </Setting> <Setting> <Name>DisplayLink</Name> <Value>False</Value> </Setting> </Settings> </Object></Objects> The CommandName is the attribute that determines which action button is used by the ordinal numeric values. Notice that these four action buttons use different CommandName values as you might expect. The DisplayIcon attribute is a Boolean (true/false or yes/no) value indicating whether or not the icon is displayed; the DisplayLink is similar and used for setting if the text is used as a link. A good example of both is the EditText ([ACTIONBUTTON:1]) in our Text/HTML module on the Home page. Notice that it has both the icon and the text as links to add/edit the content of the module.
Read more
  • 0
  • 0
  • 1025

article-image-html-php-and-content-posting-drupal-6
Packt
15 Oct 2009
9 min read
Save for later

HTML, PHP, and Content Posting in Drupal 6

Packt
15 Oct 2009
9 min read
Input Formats and Filters It is necessary to stipulate the type of content we will be posting, in any given post. This is done through the use of the Input format setting that is displayed when posting content to the site—assuming the user in question has sufficient permissions to post different types of content. In order to control what is and is not allowed, head on over to the Input formats link under Site configuration. This will bring up a list of the currently defined input formats, like this: At the moment, you might be wondering why we need to go to all this trouble to decide whether people can add certain HTML tags to their content. The answer to this is that because both HTML and PHP are so powerful, it is not hard to subvert even fairly simple abilities for malicious purposes. For example, you might decide to allow users the ability to link to their homepages from their blogs. Using the ability to add a hyperlink to their postings, a malicious user could create a Trojan, virus or some other harmful content, and link to it from an innocuous and friendly looking piece of HTML like this: <p>Hi Friends! My <a href="link_to_trojan.exe">homepage</a> is a great place to meet and learn about my interests and hobbies. </p> This snippet writes out a short paragraph with a link, supposedly to the author's homepage. In reality, the hyperlink reference attribute points to a trojan, link_to_trojan.exe. That's just HTML! PHP can do a lot more damage—to the extent that if you don't have proper security or disaster-recovery policies in place, then it is possible that your site can be rendered useless or destroyed entirely. Security is the main reason why, as you may have noticed from the previous screenshot, anything other than Filtered HTML is unavailable for use by anyone except the administrator. By default, PHP is not even present, let alone disabled. When thinking about what permissions to allow, it is important to re-iterate the tenet: Never allow users more permissions than they require to complete their intended tasks! As they stand, you might not find the input formats to your liking, and so Drupal provides some functionality to modify them. Click on the configure link adjacent to the Filtered HTML option, and this will bring up the following page: The Edit tab provides the option to alter the Name property of the input format; the Roles section in this case cannot be changed, but as you will see when we come around to creating our own input format, roles can be assigned however you wish to allow certain users to make use of an input format, or not. The final section provides a checklist of the types of Filters to apply when using this input format. In this previous screenshot, all have been selected, and this causes the input format to apply the: HTML corrector – corrects any broken HTML within postings to prevent undesirable results in the rest of your page. HTML filter – determines whether or not to strip or remove unwanted HTML. Line break converter – Turns standard typed line breaks (i.e. whenever a poster clicks Enter) into standard HTML. URL filter – allows recognized links and email addresses to be clickable without having to write the HTML tags, manually. The line break converter is particularly useful for users because it means that they do not have to explicitly enter <br> or <p> HTML tags in order to display new lines or paragraph breaks—this can get tedious by the time you are writing your 400th blog entry. If this is disabled, unless the user has the ability to add the relevant HTML tags, the content may end up looking like this: Click on the Configure tab, at the top of the page, in order to begin working with the HTML filter. You should be presented with something like this: The URL filter option is really there to help protect the formatting and layout of your site. It is possible to have quite long URLs these days, and because URLs do not contain spaces, there is nowhere to naturally split them up. As a result, a browser might do some strange things to cater for the long string and whatever it is; this will make your site look odd. Decide how many characters the longest string should be and enter that number in the space provided. Remember that some content may appear in the sidebars, so you can't let it get too long if they is supposed to be a fixed width. The HTML filter section lets you specify whether to Strip disallowed tags, or escape them (Escape all tags causes any tags that are present in the post to be displayed as written). Remember that if all the tags are stripped from the content, you should enable the Line break converter so that users can at least paragraph their content properly. Which tags are to be stripped is decided in the Allowed HTML tags section, where a list of all the tags that are to be allowed can be entered—anything else gets handled appropriately. Selecting Display HTML help forces Drupal to provide HTML help for users posting content—try enabling and disabling this option and browsing to this relative URL in each case to see the difference: filter/tips. There is quite a bit of helpful information on HTML in the long filter tips; so take a moment to read over those. The filter tips can be reached whenever a user expands the Input format section of the content post and clicks on More information about formatting options at the bottom of that section. Finally, the Spam link deterrent is a useful tool if the site is being used to bombard members with links to unsanctioned (and often unsavory) products. Spammers will use anonymous accounts to post junk (assuming anonymous users are allowed to post content) and enabling this for anonymous posts is an effective way of breaking them. This is not the end of the story, because we also need to be able to create input formats in the event we require something that the default options can't cater for. For our example, there are several ways in which this can be done, but there are three main criteria that need to be satisfied before we can consider creating the page. We need to be able to: Upload image files and attach them to the post. Insert and display the image files within the body of the post. Use PHP in order to dynamically generate some of the content (this option is really only necessary to demonstrate how to embed PHP in a posting for future reference). There are several methods for displaying image files within posts. The one we will discuss here, does not require us to download and install any contribution modules, such as Img_assist. Instead, we will use HTML directly to achieve this, specifically, we use the <img> tag. Take a look at the previous screenshot that shows the configure page of the Filtered HTML input format. Notice that the <img> tag is not available for use. Let's create our own input format to cater for this, instead of modifying this default format. Before we do, first enable the PHP Filter module under Modules in Site building so that it can easily be used when the time comes. With that change saved, you will find that there is now an extra option to the Filters section of each input format configuration page: It's not a good idea to enable the PHP evaluator for either of the default options, but adding it to one of our own input formats will be ok to play with. Head on back to the main input formats page under Site configuration (notice that there is an additional input format available, called PHP code) and click on Add input format. This will bring up the same configuration type page we looked at earlier. It is easy to implement whatever new settings you want, based on how the input format is to be used. For our example, we need the ability to post images and make use of PHP scripts, so make the new input format as follows: As we will need to make use of some PHP code a bit later on, we have enabled the PHP evaluator option, as well as prevented the use of this format for anyone but ourselves—normally, you would create a format for a group of users who require the modified posting abilities, but in this case, we are simply demonstrating how to create a new input format; so this is fine for now. PHP should not be enabled for anyone other than yourself, or a highly trusted administrator who needs it to complete his or her work. Click Save configuration to add this new format to the list, and then click on the Configure tab to work on the HTML filter. The only change required between this input format and the default Filtered HTML, in terms of HTML, is the addition of the <img> and <div> tags, separated by a space in the Allowed HTML tags list, as follows: As things stand at the moment, you may run into problems with adding PHP code to any content postings. This is because some filters affect the function of others, and to be on the safe side, click on the Rearrange tab and set the PHP evaluator to execute first: Since the PHP evaluator's weight is the lowest, it is treated first, with all the others following suit. It's a safe bet that if you are getting unexpected results when using a certain type of filter, you need to come to this page and change the settings. We'll see a bit more about this, in a moment. Now, the PHP evaluator gets dibs on the content and can properly process any PHP. For the purposes of adding images and PHP to posts (as the primary user), this is all that is needed for now. Once satisfied with the settings save the changes. Before building the new page, it is probably most useful to have a short discourse on HTML, because it is a requirement if you are to attempt more complex postings.  
Read more
  • 0
  • 1
  • 14392
Visually different images

article-image-layout-dojo-part-1
Packt
15 Oct 2009
17 min read
Save for later

Layout in Dojo: Part 1

Packt
15 Oct 2009
17 min read
Basic Dojo layout facts The Layout widgets in Dojo are varied in nature, but their most common use is as 'windows' or areas which organize and present other widgets or information. Several use the same kind of child elements the ContentPane. The ContentPane is a widget which can contain other widgets and plain HTML, reload content using Ajax and so on. The ContentPane can also be used stand-alone in a page, but is more usable inside a layout container of some sort. And what is a layout container? Well, it's a widget which contains ContentPanes, of course. A layout container can often contain other widgets as well, but most containers work very well with a different configuration of ContentPanes, which properly insulates the further contents. Take the TabContainer, for example. It is used to organize two or more ContentPanes, where each gets its own tab. When a user clicks on one of the tabs, the ContentPane inside it is shown and all others are hidden. Using BorderManager can bring the necessary CSS styling down to a minimum, while giving a simple interface for managing dynamic changes of child widgets and elements. ContentPane A ContentPane can look like anything of course, so it doesn't really help putting a screen-dump of one on the page. However, the interface is very good to know. The following arguments are detected by ContentPane and can be used when creating one either programmatically or by markup: // href: String //The href of the content that displays now. //Set this at construction if you want to load data externally //when the pane is shown.(Set preload=true to load it immediately.) //Changing href after creation doesn't have any effect; //see setHref(); href: "", //extractContent: Boolean //Extract visible content from inside of <body> .... </body> extractContent: false, //parseOnLoad: Boolean //parse content and create the widgets, if any parseOnLoad:true, //preventCache: Boolean //Cache content retreived externally preventCache:false, //preload: Boolean //Force load of data even if pane is hidden. preload: false, //refreshOnShow: Boolean //Refresh (re-download) content when pane goes from hidden to shown refreshOnShow: false, //loadingMessage: String //Message that shows while downloading loadingMessage: "<span class='dijitContentPaneLoading'>$ {loadingState}</span>", //errorMessage: String //Message that shows if an error occurs errorMessage: "<span class='dijitContentPaneError'>${errorState}</span>", You don't need any of those, of course. A simple way to create a ContentPane would be: var pane = new dojo.layout.ContentPane({}); And a more common example would be the following: var panediv = dojo.byId('panediv');var pane = new dojo.layout.ContentPane({ href: "/foo/content.html", preload: true}, panediv); where we would have an element already in the page with the id 'panediv'. As you see, there are also a couple of properties that manage caching and parsing of contents. At times, you want your ContentPane to parse and render any content inside it (if it contains other widgets), whereas other times you might not (if it contains a source code listing, for instance). You will see additional properties being passed in the creation of a ContentPane which are not part of the ContentPane itself, but are properties that give information specific to the surrounding Container. For example, the TabContainer wants to know which tab this is, and so on. Container functions All container widgets arrange other widgets, and so have a lot of common functionality defined in the dijit._Container class. The following functions are provided for all Container widgets: addChild: Adds a child widget to the container. removeChild: Removes a child widget from the container. destroyDescendants: Iterates over all children, calling destroy on each. getChildren: Returns an array containing references to all children. hasChildren: Returns a boolean. LayoutContainer The LayoutContainer is a widget which lays out children widgets according to one of five alignments: right, left, top, bottom, or client. Client means "whatever is left", basically. The widgets being organized need not be ContentPanes, but this is normally the case. Each widget then gets to set a layoutAlign property, like this: layoutAlign = "left". The normal way to use LayoutContainer is to define it using markup in the page, and then define the widgets to be laid out inside it. LayoutContainer has been superceeded by BorderContainer, and will be removed in Dojo version 2.0. SplitContainer The SplitContainer creates a horizontal or vertical split bar between two or more child widgets. A markup declaration of a SplitContainer can look like this: <div dojoType="dijit.layout.SplitContainer" orientation="vertical" sizerWidth="7" activeSizing="false" style="border: 1px solid #bfbfbf; float: left; margin-right: 30px; width: 400px; height: 300px;"> The SplitContainer must have a defined height and width. The orientation property is self-explanatory, as is sizerWidth. The property activeSizing means, if set to true, that the child widgets will be continually resized when the user changes the position of the sizer. This can be bad if the child widgets are complex or access remote information to render themselves, in which case the setting can be set to false, as in the above example. Then the resize event will only be sent to the child widgets when the user stops. Each child widget needs to define the sizeMin and sizeShare attributes. The sizeMin attribute defines the minimum size for the widget in pixels, but the sizeShare attribute is a relative value for the share of space this widget takes in relation to the other widget's sizeShare values. If we have three widgets inside the SplitPane with sizeShare values of 10, 40 and 50, they will have the same ratios in size as if the values had been 1:4:5. StackContainer The StackContainer hides all children widgets but only one at any given time, and is one of the base classes for both the Accordion and TabContainers. StackContainer exists as a separate widget to allow you to define how and when the child widgets are shown. Maybe you would like to define a special kind of control for changing between child widget views, or maybe you want other events in your application to make the Container show specific widgets. Either way, the StackContainer is one of the most versatile Containers, along with the BorderContainer. The following functions are provided for interacting with the StackContainer: back - Selects and shows the previous child widget. forward - Selects and shows the next child widget. getNextSibling - Returns a reference to the next child widget. getPreviousSibling - Returns a reference to the previous child widget. selectChild - Takes a reference to the child widget to select and show.   Here is the slightly abbreviated markup for the test shown above (test_StackContainer.html): <div id="myStackContainer" dojoType="dijit.layout.StackContainer" style="width: 90%; border: 1px solid #9b9b9b; height: 20em; margin: 0.5em 0 0.5em 0; padding: 0.5em;"> <p id="page1" dojoType="dijit.layout.ContentPane" title= "page 1">IT WAS the best of times, ....</p> <p id="page2" dojoType="dijit.layout.ContentPane" title= "page 2">There were a king with a large jaw ...</p> <p id="page3" dojoType="dijit.layout.ContentPane" title= "page 3">It was the year of Our Lord one thousand seven hundred and seventy- five. .../p></div> The StackContainer also publishes topics on certain events which can be caught using the messaging system. The topics are: [widgetId]-addChild [widgetId]-removeChild [widgetId]-selectChild [widgetId]-containerKeyPress Where [widgetId] is the id of this widget. So if you had a StackContainer defined in the following manner: <div id="myStackContainer" dojoType="dijit.layout.StackContainer">...</div> You can use the following code to listen to events from your StackContainer: dojo.subscribe("myStackContainer-addChild", this, function(arg){ var child = arg[0]; var index = arg[1];}); Compare with the following code from the StackContainer class itself: addChild: function(/*Widget*/ child, /*Integer?*/ insertIndex) { // summary: Adds a widget to the stack this.inherited(arguments); if(this._started) { // in case the tab titles have overflowed from one line // to two lines this.layout(); dojo.publish(this.id+"-addChild", [child, insertIndex]); // if this is the first child, then select it if(!this.selectedChildWidget) { this.selectChild(child); } } }, Also declared in the class file for the StackContainer is the dijit.layout.StackController. This is a sample implementation of a separate widget which presents user controls for stepping forward, backward, and so on in the widget stack. What differentiates this widget from the Tabs in the TabContainer, for example, is that the widget is completely separate and uses the message bus to listen to events from the StackContainer. You can use it as-is, or subclass it as a base for you own controllers. But naturally, you can build whatever you want and connect the events to the forward() and back() function on the StackContainer. It's interesting to note that at the end of the files that define StackContainer, the _Widget base class for all widgets is extended in the following way: //These arguments can be specified for the children of a//StackContainer.//Since any widget can be specified as a StackContainer child,//mix them into the base widget class. (This is a hack, but it's//effective.)dojo.extend(dijit._Widget, {//title: String//Title of this widget.Used by TabContainer to the name the tab, etc.title: "",//selected: Boolean//Is this child currently selected?selected: false,//closable: Boolean//True if user can close (destroy) this child, such as//(for example) clicking the X on the tab.closable: false, //true if user can close this tab paneonClose: function(){//summary: Callback if someone tries to close the child, child//will be closed if func returns true return true; }}); This means that all child widgets inside a StackContainer (or Tab or AccordionContainer) can define the above properties, which will be respected and used accordingly. However, since the properties are applied to the _Widget superclass they are of course now generic to all widgets, even those not used inside any containers at all. The most commonly used property is the closable property, which adds a close icon to the widget and title, which defines a title for the tab. A lot of Dijits respond to keypress events, according to WAI rules. Let's look at the code that is responsible for managing key events in StackContainer and all its descendants: onkeypress: function(/*Event*/ e){ //summary: //Handle keystrokes on the page list, for advancing to next/previous button //and closing the current page if the page is closable. if(this.disabled || e.altKey ){ return; } var forward = null; if(e.ctrlKey || !e._djpage){ var k = dojo.keys; switch(e.charOrCode){ case k.LEFT_ARROW: case k.UP_ARROW: if(!e._djpage){ forward = false; } break; case k.PAGE_UP: if(e.ctrlKey){ forward = false; } break; case k.RIGHT_ARROW: case k.DOWN_ARROW: if(!e._djpage){ forward = true; } break; case k.PAGE_DOWN: if(e.ctrlKey){ forward = true; } break; case k.DELETE: if(this._currentChild.closable) { this.onCloseButtonClick(this._currentChild); } dojo.stopEvent(e); break; default: if(e.ctrlKey){ if(e.charOrCode == k.TAB) { this.adjacent(!.shiftKey).onClick(); dojo.stopEvent(e); } else if(e.charOrCode == "w") { if(this._currentChild.closable) { this.onCloseButtonClick(this._currentChild); } dojo.stopEvent(e); // avoid browser tab closing. } } } // handle page navigation if(forward !== null) { this.adjacent(forward).onClick(); dojo.stopEvent(e); } }}, The code is a very good example on how to handle key press events in Dojo in its own right, but for our purposes we can summarize in the following way: If UP, LEFT, or SHIFT+TAB is pressed, forward is set to false, and the last block of code will use that as an argument to the adjacent function which returns the prior child widget if false and the next child widget if true. In this case, the former. If DOWN, RIGHT, or TAB is pressed, forward will be set to true, which will declare the next child widget to be activated and shown. If DELETE or w is pressed and the current child widget is closable, it will be destroyed. TabContainer The TabContainer, which derives from StackContainer, organizes all its children into tabs, which are shown one at a time. As you can see in the picture below, the TabContainer can also manage hierarchical versions of itself. The TabContainer takes an argument property called tabPosition, which controls where the tab icons are displayed for each tab. Possible values are "top", "bottom", "left-h", "right-h", with "top" as default. There are no special functions provided for TabContainer, which adds very little logic to that provided from the StackContainer superclass. AccordionContainer The AccorionContainer shows a horizontal bar for each added child widget, which represents its collapsed state. The bar acts as a tab and also holds the title defined for the child widget. When the bar is clicked, an animation hides the current widget, and also animates in the widget whose bar was clicked. The abbreviated code for the test case above (test_accordionContainer.html) is here: <div dojoType="dijit.layout.AccordionContainer" style="width: 400px; height: 300px; overflow: hidden"> <div dojoType="dijit.layout.AccordionPane" title="a"> Hello World </div> <div dojoType="dijit.layout.AccordionPane" title="b"> <p> Nunc consequat nisi ... </p> <p> Sed arcu magna... </p> </div> <div dojoType="dijit.layout.AccordionPane" title="c"> <p>The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.</p> </div></div>  A funny thing about the AccordionContainer is that it requires not any old widget as a child node, but its own AccordionPane, as you see in the code above. However, the AccordionPane has ContentPane as superclass, and defines itself slightly differently due to the special looks of an accordion. Also, the AccordionPane does not currently support nested Layout widgets, even though single-level widgets are supported. BorderContainer The BorderContainer has replaced the functionality of both LayoutContainer and SplitContainer. Note that the outermost BorderContainer widget does not carry any layout information. This is instead delegated to each individual widget. As each child gets added to the BorderContainer, the layout is recalculated. Using the BorderContainer is a very good alternative to using CSS-based "tableless tables". For using the BorderContainer, you don't need any other rules, and the Container recalculates positioning automatically, without the need for additional CSS rules (except for the height/width case below) each time you add an element or widget to the area. Since BorderContainer widget replaces both SplitContainer and LayoutContainer, it both lets its child widgets declare where they are in relation to each other. Optionally, add resizing splitter between children. Also, instead of optionally declaring one child as "client", one child must now always be declared as "center". For some reason, the child widget now use region, instead of layoutAlign, so a child widget which would have been defined like this in LayoutContainer: <div dojoType="dijit.layout.ContentPane" layoutAlign="top">...</div> is now defined like this instead: <div dojoType="dijit.layout.ContentPane" region="top">...</div> All "side" widgets must define a width, in style, by CSS class or otherwise, and the same applies for top/bottom widgets, but with height. Center widgets must not declare either height or width, since they use whatever is left over from the other widgets. You can also use leading and trailing instead of right and left. The only difference is that when you change locale to a region that has text going from right to left (like Arabic and many others), this will arrange the widgets appropriate to the locale. The BorderContainer also takes an optional design property, which defines if the BorderContainer is a headline or sidebar. The headline is the default and looks like the picture below. headline means that the top and bottom widgets extend the full length of the container, whereas sidebar means the the right and left (or leading and trailing) widgets extend top to bottom. The sizeShare attribute for the ContentPanes used in the SplitContainer is deprecated in BorderContainer. All ContentPanes sizes are defined using regular techniques (direct stylin, classes, and so on). From the BorderContainer test located in dijit/tests/layout/test_BorderContainer_nested.html, we find the following layout: The (abbreviated) source code for the example is here: <div dojoType="dijit.layout.BorderContainer" style="border: 2px solid black; width: 90%; height: 500px; padding: 10px;"> <div dojoType="dijit.layout.ContentPane" region="left" style="background-color: #acb386; width: 100px;"> left </div> <div dojoType="dijit.layout.ContentPane" region="right" style="background-color: #acb386; width: 100px;"> right </div> <div dojoType="dijit.layout.ContentPane" region="top" style="background-color: #b39b86; height: 100px;"> top bar </div> <div dojoType="dijit.layout.ContentPane" region="bottom" style="background-color: #b39b86; height: 100px;"> bottom bar </div> <div dojoType="dijit.layout.ContentPane" region="center" style="background-color: #f5ffbf; padding: 0px;"> <div dojoType="dijit.layout.BorderContainer" design="sidebar" style="border: 2px solid black; height: 300px;"> <div dojoType="dijit.layout.ContentPane" region="left" style="background-color: #acb386; width: 100px;"> left </div> <div dojoType="dijit.layout.ContentPane" region="right" style="background-color: #acb386; width: 100px;"> right </div> <div dojoType="dijit.layout.ContentPane" region="top" style="background-color: #b39b86; height: 100px;"> top bar </div> <div dojoType="dijit.layout.ContentPane" region="bottom" style="background-color: #b39b86; height: 100px;"> bottom bar </div> <div dojoType="dijit.layout.ContentPane" region="center" style="background-color: #f5ffbf; padding: 10px;"> main panel with <a href="http://www.dojotoolkit.org/"> a link</a>.<br /> (to check we're copying children around properly). <br /> <select dojoType="dijit.form.FilteringSelect"> <option value="1">foo</option> <option value="2">bar</option> <option value="3">baz</option> </select> Here's some text that comes AFTER the combo box. </div> </div> </div></div> You see here the recurring theme of using ContentPanes inside Containers. Also, the innermost "center" ContentPane wraps a new BorderContainer which has its own internal top/left layout widgets. Depending on what kind of application you are building, the BorderContainer might be a good starting point. Since you already know that you can change and reload the contents of individual ContentPanes, you are left with a layout in which each element can function as a lightweight Iframe with none of the negative side effects. DragPane The DragPane is a very simple idea. You have a very large area of elements to display, and want to let the user 'drag' the underlying pane around using the mouse. The DragPane can be used in instances where you have a lot of pictures to present. It can also be used to present text or other widgets that are too numerous to fit in your current designated area of screen real estate. The only property of DragPane is invert, which if set to true, inverts the axis of the drag of the mouse. Example: <div class="hugetext" id="container" invert="false" dojoType="dojox.layout.DragPane"> <p style="color:#666; padding:8px; margin:0;"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. In porta. Etiam mattis libero nec ante. Nam porta lacus eu ligula. Cras mauris. Suspendisse vel augue. Vivamus aliquam orci ut eros. Nunc eleifend sagittis turpis. purus purus in nibh. Phasellus in nunc. </p></div>
Read more
  • 0
  • 0
  • 2569

article-image-working-javascript-drupal-6-part-1
Packt
15 Oct 2009
11 min read
Save for later

Working with JavaScript in Drupal 6: Part 1

Packt
15 Oct 2009
11 min read
How Drupal handles JavaScript How is JavaScript typically used? Mostly, it is used to provide additional functionality to a web page, which is usually delivered to a web browser as an HTML document. The browser receives the HTML from the server and then begins the process of displaying the page. During this parsing and rendering process, the browser may request additional resources from the server such as images, CSS, or Flash. It then incorporates these elements into the document displayed to the user. In this process, there are two ways that JavaScript code can be sent from the server to the browser. First, the code can be placed directly inside the HTML. This is done by inserting code inside the <script> and </script> tags: <script type="text/javascript">alert('hello world');</script> This is called including the script inline. Second, the code can be loaded separately from the rest of the HTML. Again, this is usually done using the <script> and </script> tags. However, instead of putting the code between the tags, we use the src attribute to instruct the browser to retrieve an additional document from the server. <script type="text/javascript" src="some/script.js"></script> In this example, src="some/script.js" points the browser to an additional script file stored on the same server as the HTML document in which this script tag is embedded. So, if the HTML is located at http://example.com/index.html, the browser will request the script file using the URL http://example.com/some/script.js. The </script> tag is required When XML was first standardized, it introduced a shorthand notation for writing tags that have no content. Instead of writing <p></p>, one could simply write <p/>. While this notation is supported by all modern mainstream browsers, it cannot be used for <script></script> tags. Some browsers do not recognize <script/> and expect that any <script> tag will be accompanied by a closing </script> tag even if there is no content between the tags. If we were developing static HTML files, we would simply write HTML pages that include <script></script> tags anytime we needed to add some JavaScript to the page. But we're using Drupal, not static HTML, and the process for adding JavaScript in this environment is done differently. Where Drupal JavaScript comes from? As with most web content management systems, Drupal generates HTML dynamically. This is done through interactions between the Drupal core, modules, and the theme system. A single request might involve several different modules. Each module is responsible for providing information for a specific portion of the resulting page. The theme system is used to transform that information from PHP data structures into HTML fragments, and then compose a full HTML document. But this raises some interesting questions: What part of Drupal should be responsible for deciding what JavaScript is needed for a page? And where will this JavaScript come from? In some cases, it makes sense for the Drupal core to handle JavaScript. It could automatically include JavaScript in cases where scripts are clearly needed. JavaScript can also be used to modify the look and feel of a site. In that case, the script is really functioning as a component of a theme. It would be best to include the script as a part of a theme. JavaScript can also provide functional improvements, especially when used with AJAX and related technologies. These features can be used to make more powerful modules. In that case, it makes sense to include the script as a part of a module. So which one is the best: modules, themes, or core? Rather than deciding on your behalf, Drupal developers have made it possible to incorporate JavaScript into all three: The Drupal core handles including the core JavaScript support as needed. The Drupal and jQuery libraries are included automatically when necessary. When theme developers needs to add some JavaScript, they can do so within the theme. There is no need to tamper with the core, or to accompany a theme with a module. Finally, module developers can add JavaScript directly to a module. In this way, modules can provide advanced JavaScript functionality without requiring modification of the theme. In this article we will add scripts to themes and modules. As we get started, we will begin with a theme. Module or theme? How do you decide whether your script ought to go in a theme or in a module? Here's a basic guideline. If the script provides functionality specific to the layout details of a theme, it should be included in a theme. If the script provides general behavior that should work regardless of the theme, then it should be included in a module. Sometimes it is hard to determine when a script belongs to a theme and when it should to be placed in a module. In fact, the script we create here will be one such a case. We are going to create a script that provides a printer-friendly version of a page's main content. Once we have the script, we will attach it to a theme. Of course, if we want to provide this functionality across themes, we might instead create a module to house the script. We will start out simply with a JavaScript-enabled theme. Project overview: printer-friendly page content The JavaScript that we will write creates a pop-up printer-friendly window, and automatically launches the print dialog. This is usually launched from File | Print in your browser's menu. Once we write the script, we will incorporate it into a theme, and add a special printing feature to the page(s) displayed with that theme. As we walk through this process, we will also create our first theme. (Technically, it will be a subtheme derived from the Bluemarine theme.) By the end of this project, you should know how to create Drupal-friendly JavaScript files. You will also know how to create themes and add scripts to them. The first step in the process is to write the JavaScript. The printer script Our script will fetch the main content of a page and then open a new window, populating that window's document with the main content of the page. From there, it will open the browser's print dialog, prompting the user to print the document. Since this is our first script, we will keep it simple. The code will be very basic, employing the sort of classical procedural JavaScript that web developers have been using since the mid-1990's. But don't expect this to be the norm. To minimize clutter and maximize the reusability of our code, we will store this new script in its own script file. The file will be named printer_tool.js: // $Id$/*** Add printer-friendly tool to page.*/var PrinterTool = {};PrinterTool.windowSettings = 'toolbar=no,location=no,' +'status=no,menu=no,scrollbars=yes,width=650,height=400';/*** Open a printer-friendly page and prompt for printing.* @param tagID* The ID of the tag that contains the material that should* be printed.*/PrinterTool.print = function (tagID) {var target = document.getElementById(tagID);var title = document.title;if(!target || target.childNodes.length === 0) {alert("Nothing to Print");return;}var content = target.innerHTML;var text = '<html><head><title>' +title +'</title><body>' +content +'</body></html>';printerWindow = window.open('', '', PrinterTool.windowSettings);printerWindow.document.open();printerWindow.document.write(text);printerWindow.document.close();printerWindow.print();}; First, let's talk about some of the structural aspects of the code. Drupal coding standards In general, well-formatted code is considered a mark of professionalism. In an open source project such as Drupal, where many people are likely to view and contribute to the code, enforced coding standards can make reading and understanding what the code does easier. When contributing code to the Drupal project, developers adhere to a Drupal coding standard (http://drupal.org/coding-standards). Add-on modules and themes are expected to abide by these rules. It is advised that you follow the Drupal standards even in code that you do no anticipate submitting to the Drupal project. Along with keeping your code stylistically similar to Drupal's, it will also help you develop good coding habits for those occasions when you do contribute something to the community. For the most part, the official Drupal coding standards are focused on the PHP code. But many of these rules are readily applicable to JavaScript as well. Here are a few important standards: Every file should have a comment near the top that has the contents $Id$. This is a placeholder for the version control system to insert version information. Drupal uses CVS (Concurrent Versioning System) for source code versioning. Each time a file is checked into CVS, it will replace $Id$ with information about the current version of the software. To learn more about CVS, visit http://www.nongnu.org/cvs/. Indenting should be done with two spaces (and no tabs). This keeps the code compact, but still clear. Comments should be used wherever necessary. Doxygen-style documentation blocks (/** ... */) should be used to comment files and functions. Any complex or potentially confusing code should be commented with // or /* ... */. Comments should be written in sentences with punctuation. Control structure keywords (if, else, for, switch, and so on) should appear at the beginning of a line, and be followed by a single space (if (), not if()). Here's an example: if (a) {// Put code here.}else if (b) {// Put code here.}else {// Put code here.} Operators (+, =, *, &&, ||, and so on) should have a single space on each side, for example: 1 + 2. The exception to this rule is the member operator (.), which is used to access a property of an object. There should be no spaces surrounding these. Example: window.document (never window . document). Stylistic differences between PHP and JavaScript Not all PHP coding standards apply to JavaScript. PHP variables and function names are declared in all lower case with underscores (_) to separate words. JavaScript typically follows different conventions. JavaScript variables and functions are named using camel case (sometimes called StudlyCaps). For a variable or function, the first word is all lower case. Any subsequent words in the variable or function name are capitalized. Underscores are not used to separate words. Here are some examples: var myNewVariable = "Hello World";function helloWorld() { alert(myNewVariable);} While this convention is employed throughout the Drupal JavaScript code, there is currently no hard-and-fast set of JavaScript-specific coding conventions. The working draft, which covers most of the important recommendations, can be found at http://drupal.org/node/260140. Here is a summary of the more important (and widely followed) conventions: Variables should always be declared with the var keyword. This can go a long way towards making the scope of variables explicit. JavaScript has a particularly broad notion of scope. Functions inherit the scope of their parent context, which means a parent's variables are available to the children. Using var makes it easier to visually identify the scoping of a variable. It also helps to avoid ambiguous cases which may lead to hard-to-diagnose bugs or issues. Statements should always end with a semicolon (;). This includes statements that assign functions, for example, myFunction = function() {};. Our print function, defined earlier, exhibits this behavior. Why do we require trailing semicolons? In JavaScript, placing semicolons at the end of statements is considered optional. Without semicolons, the script interpreter is responsible for determining where the statement ends. It usually uses line endings to help determine this. However, explicitly using semicolons can be helpful. For example, JavaScript can be compressed by removing whitespace and line endings. For this to work, every line must end with a semicolon. When an anonymous function is declared, there should be a space between  the function and the parentheses, for example, function () {}, not function() {}. This preserves the whitespace that would be there in in a non-anonymous function declaration (function myFunction() {}). There are other conventions, many of which you will see here. But the ones mentioned here cover the most frequently needed. With coding standards behind us, let's take a look at the beginning of the printer_tool.js file.
Read more
  • 0
  • 0
  • 2577

article-image-layout-dojo-part-2
Packt
15 Oct 2009
12 min read
Save for later

Layout in Dojo: Part 2

Packt
15 Oct 2009
12 min read
GridContainer There are a lot of sites available that let you add a lot of rss feeds and assorted widgets to a personal page, and which then also let you arrange them by dragging the widgets themselves around the page. One of the most known examples is iGoogle, Google's personal homepage for users with a staggering amount of widgets that are easy to move around. This functionality is called a GridContainer in Dojo. If you're not familiar with the concept and have never used a service which lets you rearrange widgets, it works like this: The GridContainer defines a number of different columns, called zones. Each column can contain any number of child widgets, including other containers (like AccordionContainer or BorderContainer). Each child widget becomes draggable and can be dragged into a new position within its own column, or dragged to a new position in another column. As the widget gets dragged, it uses a semi-transparent 'avatar'. As the widget gets dragged, possible target drop zones open up and close themselves dynamically under the cursor, until the widget is dropped on one of them. When a widget is dropped, the target column automatically rearranges itself to make the new widget fit. Here is an example from test_GridContainer.html in /dojox/layout/tests/. This is what the GridContainer looks like from the beginning: It has three columns (zones) defined which contain a number of child widgets. One of them is a Calendar widget, which is then dragged to the second column from its original position in the third: Note the new target area being offered by the second column. This will be closed again if we continue to move the cursor over to the first column. Also, in the example above, transparency of 1.0 (none) is added to the avatar, which looks normal. Finally, the widget is dropped onto the second column, both the source and target column arrange their widgets according to whether one has been added or removed. The implications of this is that it becomes very simple to create highly dynamical interfaces. Some examples might be: An internal "dashboard" for management or other groups in the company which needs rearrangeable views on different data sources. Portlets done right. Using dojox.charting to create different diagrammatic views on data sources read from the server, letting the user create new diagrams and rearranging them in patterns or groups meaningful to the current viewer. A simple front-end for a CMS-system, where the editor widget is used to enter text, and the user can add, delete or change paragraphs as well as dragging them around and rearranging their order. An example of how to create a GridContainer using markup (abbreviated) is as follows: <div id="GC1" dojoType="dojox.layout.GridContainer" nbZones="3" opacity="0.7" allowAutoScroll="true" hasResizableColumns="false" withHandles="true" acceptTypes="dijit.layout.ContentPane, dijit.TitlePane, dijit.ColorPalette, dijit._Calendar"><div dojoType="dijit.layout.ContentPane" class="cpane" label="Content Pane">Content Pane n?1 !</div><div dojoType="dijit.TitlePane" title="Ergo">Non ergo erunt homines deliciis ...</div><div dojoType="dijit.layout.ContentPane" class="cpane" label="Content Pane">Content Pane n?2 !</div><div dojoType="dijit.layout.ContentPane" title="Intellectum">Intellectum est enim mihi quidem in multis, et maxime in me ipso, sed paulo ante in omnibus, cum M....</div><div dojoType="dijit.layout.ContentPane" class="cpane" label="Content Pane">Content Pane n?3 !</div><div dojoType="dijit.layout.ContentPane" class="cpane" label="Content Pane">Content Pane n?4 !</div><div dojoType="dijit._Calendar"></div></div> The GridContainer wraps all of its contents.These are not added is not added in a hierarchical manner, but instead all widgets are declared inside the GridContainer element. When the first column's height is filled, the next widget in the list gets added to the next column, and so on. This is a quite unusual method of layout, and we might see some changes to this mode of layout since the GridContainer is very much beta [2008]. The properties for the GridContainer are the following: //i18n: Object//Contain i18n ressources.i18n: null,//isAutoOrganized: Boolean://Define auto organisation of children into the grid container.isAutoOrganized : true,//isRightFixed: Boolean//Define if the right border has a fixed size.isRightFixed:false,//isLeftFixed: Boolean//Define if the left border has a fixed size.isLeftFixed:false,//hasResizableColumns: Boolean//Allow or not resizing of columns by a grip handle.hasResizableColumns:true,//nbZones: Integer//The number of dropped zones.nbZones:1,//opacity: Integer//Define the opacity of the DnD Avatar.opacity:1,//minColWidth: Integer//Minimum column width in percentage.minColWidth: 20,//minChildWidth: Integer//Minimun children with in pixel (only used for IE6 that doesn't//handle min-width css propertyminChildWidth : 150,//acceptTypes: Array//The gridcontainer will only accept the children that fit to//the types.//In order to do that, the child must have a widgetType or a//dndType attribute corresponding to the accepted type.acceptTypes: [],//mode: String//location to add columns, must be set to left or right(default)mode: "right",//allowAutoScroll: Boolean//auto-scrolling enable inside the GridContainerallowAutoScroll: false,//timeDisplayPopup: Integer//display time of popup in milisecondstimeDisplayPopup: 1500,//isOffset: Boolean//if true : Let the mouse to its original location when moving//(allow to specify it proper offset)//if false : Current behavior, mouse in the upper left corner of//the widgetisOffset: false,//offsetDrag: Object//Allow to specify its own offset (x and y) onl when Parameter//isOffset is trueoffsetDrag : {}, ////withHandles: Boolean//Specify if there is a specific drag handle on widgetswithHandles: false,//handleClasses: Array//Array of classes of nodes that will act as drag handleshandleClasses : [], The property isAutoOrganized, which is set to true by default, can be set to false, which will leave holes in your source columns, and require you to manage the space in the target columns yourself. The opacity variable is the opacity for the 'avatar' of the dragged widget, where 1 is completely solid, and 0 is completely transparent. The hasResizableColumns variable also adds SplitContainer/BorderContainer splitters between columns, so that the user can change the size ratio between columns. The minColWidt/minChildWidth variables manage the minimum widths of columns and child widgets in relation to resizing events. The AcceptTypes variable is an important property, which lets you define which classes you allow to be dropped on a column. In the above example code, that string is set to dijit.layout.ContentPane, dijit.TitlePane, dijit.ColorPalette, dijit._Calendar. This makes it impossible to drop an AccordionContainer on a column. The reason for this is that certain things would want to be fixed, like status bars or menus, but still inside one of the columns. The withHandles variable can be set to true if you want each widget to get a visible 'drag handle' appended to it. RadioGroup The source code of dojox.layout.RadioGroup admits that it probably is poorly named, because it has little to do with radio buttons or groups of them, per se, even if this was probably the case when it was conceived. The RadioGroup extends the StackContainer, doing something you probably had ideas about the first time you saw it – adding flashy animations when changing which child container is shown. One example of how to use StackContainer and its derivatives is an information box for a list of friends. Each information box is created as a ContentPane which loads its content from a URL. As the user clicks on or hovers over the next friend on a nearby list, an event is triggered to show the next item (ContentPane) in the stack. Enter the RadioGroup, which defines its own set of buttons that mirror the ContentPanes which it wraps. The unit test dojox/layout/tests/test_RadioGroup.html defines a small RadioGroup in the following way: <div dojoType="dojox.layout.RadioGroup" style="width:300px; height:300px; float:left;" hasButtons="true"><div dojoType="dijit.layout.ContentPane" title="Dojo" class="dojoPane" style="width:300px; height:300px; "></div><div dojoType="dijit.layout.ContentPane" title="Dijit" class="dijitPane" style="width:300px; height:300px; "></div><div dojoType="dijit.layout.ContentPane" title="Dojox" class="dojoxPane" style="width:300px; height:300px; "></div></div> As you can see, it does not take much space. In the test, the ContentPanes are filled with only the logos for the different parts of Dojo, defined as background images by CSS classes. The RadioGroup iterates over each child ContentPane, and creates a "hover button" for it, which is connected to an event handler which manages the transition, so if you don' t have any specific styling for your page and just want to get a quick mock-up done, the RadioGroup is very easy to work with. The default RadioGroup works very much like its parent class, StackContainer, mostly providing a simple wrapper that generates mouseover buttons. In the same file that defines the basic RadioGroup, there are two more widgets: RadioGroupFade and RadioGroupSlide. These have exactly the same kind of markup as their parent class, RadioGroup. RadioGroupFade looks like this in its entirety: dojo.declare("dojox.layout.RadioGroupFade", dojox.layout.RadioGroup, { // summary: An extension on a stock RadioGroup, that fades the //panes. _hideChild: function(page){ // summary: hide the specified child widget dojo.fadeOut({ node:page.domNode, duration:this.duration, onEnd: dojo.hitch(this,"inherited", arguments) }).play(); }, _showChild: function(page){ // summary: show the specified child widget this.inherited(arguments); dojo.style(page.domNode,"opacity",0); dojo.fadeIn({ node:page.domNode, duration:this.duration }).play(); }}); As you can see, all it does is override two functions from RadioGroup which manage how to show and hide child nodes upon transitions. The basic idea is to use the integral Dojo animations fadeIn and fadeOut for the effects. The other class, RadioGroupSlide, is a little bit longer, but not by much. It goes beyond basic animations and uses a specific easing function. In the beginning of its definition is this variable: // easing: Function// A hook to override the default easing of the pane slides.easing: "dojo.fx.easing.backOut", Later on, in the overridden _hide and _showChild functions, this variable is used when creating a standalone animation: ...this._anim = dojo.animateProperty({ node:page.domNode, properties: { left: 0, top: 0 }, duration: this.duration, easing: this.easing, onEnd: dojo.hitch(page,function(){ if(this.onShow){ this.onShow(); } if(this._loadCheck){ this._loadCheck(); } })});this._anim.play();   What this means is that it is very simple to change (once again) what kind of animation is used when hiding the current child and showing next, which can be very usable. Also, you can see that it is very simple to create your own subclass widget out of RadioGroup which can use custom actions when child nodes are changed. ResizeHandle The ResizeHandle tucks a resize handle, as the name implies, into the corner of an existing element or widget. The element which defines the resize handle itself need not be a child element or even adjacent to the element which is to receive the handle. Instead the id of the target element is defined as an argument to the ResizeHandle as shown here: <div dojoType="dijit.layout.ContentPane" title="Test window" style="width: 300px; height: 200px; padding:10px; border: 1px solid #dedede; position: relative; background: white;" id="testWindow"> ...<div id="hand1" dojoType="dojox.layout.ResizeHandle" targetId="testWindow"></div> </div> In this example, a simple ContentPane is defined first, with some custom styling to make it stand out a little bit. Further on in the same pages comes a ResizeHandle definition which sets the targetId property of the newly created ResizeHandle to that of the ContentPane ('testWindow'). The definition of the ResizeHandle class shows some predictable goodies along with one or two surprises: //targetContainer: DomNode//over-ride targetId and attch this handle directly to a//reference of a DomNodetargetContainer: null,//resizeAxis: String//one of: x|y|xy limit resizing to a single axis, default to xy ...resizeAxis: "xy",//activeResize: Boolean//if true, node will size realtime with mouse movement,//if false, node will create virtual node, and only resize target//on mouseUp.activeResize: false,//activeResizeClass: String//css class applied to virtual resize node.activeResizeClass: 'dojoxResizeHandleClone',//animateSizing: Boolean//only applicable if activeResize = false. onMouseup, animate the//node to the new size.animateSizing: true,//animateMethod: String//one of "chain" or "combine" ... visual effect only.combine will "scale"//node to size, "chain" will alter width, then heightanimateMethod: 'chain',//animateDuration: Integer//time in MS to run sizing animation. if animateMethod="chain",//total animation playtime is 2*animateDuration.animateDuration: 225,//minHeight: Integer//smallest height in px resized node can beminHeight: 100,//minWidth: Integer//smallest width in px resize node can beminWidth: 100, As could be expected, it is simple to change if the resizing is animated during mouse move or afterwards (activeResize: true/false). If afterwards, the animateDuration declares in milliseconds the length of the animation. A very useful property is the ability to lock the resizing action to just one of the two axes. The resizeAxis property defaults to xy, but can be set to only x or only y as well. Both restricts resizing to only one axis and also changes the resize cursor to show correct feedback to which axis is 'active' at the moment. If you at any point want to remove the handle, calling destroy() on it will remove it from the target node without any repercussions.
Read more
  • 0
  • 0
  • 2183
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 $15.99/month. Cancel anytime
article-image-creating-better-selling-experience-drupal-e-commerce
Packt
14 Oct 2009
5 min read
Save for later

Creating a Better Selling Experience with Drupal e-Commerce

Packt
14 Oct 2009
5 min read
Doug is an avid dinosaur and model enthusiast, and runs his own shop and museum selling model dinosaurs and offering information and facts on various dinosaurs. For the purpose of this article, we will create an e-commerce website named 'Doug's Dinos!' for Doug and his business. Making Things Easier Although Doug's store is relatively simple for his customers to use, it is missing three key features that would make their time on the website easier, these are: An overview of the shopping cart Search features Ability to auto-create user accounts At the moment, without a search feature the only way for users to find products is by manually browsing through the website and stumbling across a product they like. Adding a Shopping Cart We can add a shopping cart to our theme so that customers can continue browsing the website but still know how much is in their shopping cart, and easily get to it later. To add this block, we need to go to the Blocks section, which is under Site Building within the Administer area. Within the Blocks section, we need to ensure we have all our themes selected (or do this for each theme we are using) and then change the Region of the Shopping cart to the left sidebar. Once we click on the Save blocks button, the shopping cart block is displayed in our theme: Adding Search Capabilities Doug tested the website with a few friends and family members, and their main issue with it was the difficulty in finding products they wanted. The first thing we need to do is install the Search module, which is grouped under the Core - optional section of Modules in the Administer area. With the module installed, we now need to enable the Search feature from the Blocks section; otherwise the search box won't be displayed on the website. We can select this feature by going to Administer | Site Building | Blocks, then set it up in the same way as for the shopping cart and save the settings. We now have a search box on our website under the header but above the main menu! Let's try searching for one of our products, for instance T-Rex. Notice something? No results found! This seems quite strange as we have a product with T-Rex in the name, so why didn't we get any results? The reason for this is that Drupal has not yet been indexed. Drupal uses a cron job to create the index of the site. Without the indexing done Search options cannot work. The Search settings under Administer | Site configuration allow us to specify how many pages are indexed per "cron run" and allow us to set the site to be re-indexed. Cron JobsA cron job is a setting on your web host's server (if you have cPanel hosting, it is available under "crontab") that performs tasks at specific times. Drupal has a special page that performs various tasks; this can be called by a cron job so that it regularly opens the page and runs the tasks. This setting depends on having set up a cron job to periodically call the cron.php file. For more information on setting up cron jobs, you should contact your web host. Typically it involves a crontab setting in your hosting control panel such as cPanel. We can manually run the cron task, by opening the cron.php file in our web browser. In this case we just open: http://www.dougsdinos.com/cron.php. Once we have opened this page, let's try searching for T-Rex again. This time we will get some results! Customers will now be able to find products and other content on Doug's website much more easily! Auto-Creating User Accounts If a customer is not a user on our site, we can automatically create a user account for them once they have placed their order; this saves the inconvenience of using an anonymous purchase policy where the user has to log in or register, but it gives the user the added convenience of having their details saved for future orders. This is something Doug wants to enable to make things easier for regular customers on this site. The first thing we need to do is install the module. The module is called EC Useracc and is listed in the E-Commerce Uncategorized group of modules. Now under E-Commerce configuration we have a new option called User Account; let's take a look at it. This has the following settings: Confirmation e-mail Welcome mail Days to confirm expiry The Confirmation e-mail is to see if the customer wants to create a user account; this email expires after the number of days set in the Days to confirmation expiry setting has passed, and the Welcome mail is the email sent when the account is created. These emails can be configured on the Mail page. These settings don't actually enable the feature though; we have installed the module and looked at the global settings, but to actually get it to work we need to set how we would like each product to work in relation to this module. If we go to edit any product, there is a new section, which was not there previously, called User account provision; this is what we need to change. As Doug wants this feature enabled, we need to check the option Create an account for the user when this product is purchased. The other option, Block the user's account when this product expires, relates to using recurring billing in products (mainly non-tangible products i.e. services) such as a customer support contract or a magazine subscription.
Read more
  • 0
  • 0
  • 1037

article-image-anatomy-typo3-extension
Packt
14 Oct 2009
8 min read
Save for later

Anatomy of TYPO3 Extension

Packt
14 Oct 2009
8 min read
TYPO3 Extension Categories All TYPO3 extensions are classified into several predefined categories. These categories do not actually differentiate the extensions. They are more like hints for users about extension functionality. Often, it is difficult for the developer to decide which category an extension should belong to. The same extension can provide PHP code that fits into many categories. An extension can contain Frontend (FE) plugins, Backend (BE) modules, static data, and services, all at once. While it is not always the best solution to make such a monster extension, sometimes it is necessary. In this case, the extension author should choose the category that best fits the extension's purpose. For example, if an extension provides a reservation system for website visitors, it is probably FE related, even if it includes a BE module for viewing registrations. If an extension provides a service to log in users, it is most likely a service extension, even if it logs in FE users. It will be easier to decide where the extension fits after we review all the extension categories in this article. Choosing a category for an extension is mandatory. While the TYPO3 Extension Manager can still display extensions without a proper category, this may change and such extensions may be removed from TER (TYPO3 Extension Repository) in the future. The extension category is visible in several places. Firstly, extensions are sorted and grouped by category in the Extension Manager. Secondly, when an extension is clicked in the Extension Manager, its category is displayed in the extension details. If an extension's category is changed from one to another, it does not affect extension functionality. The Extension Manager will show the extension in a different category. So, categories are truly just hints for the user. They do not have any significant meaning in TYPO3. So, why do we care and talk about them? We do so because it is one of those things that make a good extension. If an extension developer starts making a new extension, they should do it properly from the very beginning. And one of the first things to do properly is to decide where an extension belongs. So, let's look into the various extension categories in more detail. Category: Frontend Extensions that belong to the Frontend category provide functionality related to the FE. It does not mean that they generate website output. Typically, extensions from the FE category extend FE functionality in other ways. For example, they can transform links from standard /index.php?id=12345 to /news/new-typo3-bookis-out.htm. Or, they can filter output and clean it up, compress, add or remove HTML comments, and so on. Often, these extensions use one or more hooks in the FE classes. For example, TSFE has hooks to process submitted data, or to post‑filter content (and many others). Examples of FE extensions are source_optimization and realurl. Category: Frontend plugins Frontend plugins is possibly the most popular extension category. Extensions from this category typically generate content for the website. They provide new content objects, or extend existing types of content objects. Typical examples of extensions from the Frontend plugins category are tt_news, comments, ratings, etc. Category: Backend Extensions from the Backend category provide additional functionality for TYPO3 Backend. Often, they are not seen inside TYPO3 BE, but they still do some work. Examples of such extensions are various debugging extensions (such as rlmp_ filedevlog) and extensions that add or change the pop-up menu in the BE (such as extra_page_cm_options system extension). This category is rarely used because extensions belonging to it are very special. Category: Backend module Extensions from this category provide additional modules for TYPO3 BE. Typical examples are system extensions such as beuser (provides Tools | Users module) or tstemplate (provides Web | Template module). Category: Services Services extend core TYPO3 functionality. Most known and most popular service extensions are authentication services. TYPO3 Extension Repository contains extensions to authenticate TYPO3 users over phpBB, vBulletine, or LDAP user databases. Services are somewhat special and will not be covered in this article. Extension developers who are interested in the development of services should consult appropriate documentation on the typo3.org website. Category: Examples Extensions from this category provide examples. There are not many, and are typically meant for beginners or for those who want to learn a specific feature of TYPO3, or features that another TYPO3 extension provides. Category: Templates Extensions from this category provide templates. Most often, they have preformatted HTML and CSS files in order to use them with the templateautoparser extension or map with TemplaVoila. Sometimes, they also contain TypoScript templates, for example, tmpl_andreas01 and tmpl_andreas09 extensions. Once installed, they provide pre‑mapped TemplaVoila templates for any website, making it easy to have a website up and running within minutes. Category: Documentation Documentation extensions provide TYPO3 documentation. Normally, TYPO3 extensions contain documentation within themselves, though sometimes, a document is too big to be shipped with extensions. In such cases, it is stored separately. There is an unofficial convention to start an extension key for such extensions with the doc_ prefix (that is, doc_indexed_search). Category: Miscellaneous Everything else that does not fit into any other category goes here; typical examples are skins. But do not put your extension here if you just cannot decide where it fits. In all probability, it should go into one of the other categories, not into Miscellaneous. Extension Files TYPO3 extensions consist of several files. Some of these files have predefined names, and serve a predefined purpose. Others provide code or data but also follow certain naming conventions. We will review all the predefined files in this article and see what purpose they serve. We will look into the files according to their logical grouping. While reading this section, you can take any extension from the typo3conf/ext/ directory at your TYPO3 installation and check the contents of each discussed file. Some files may be missing if the extension does not use them. There is only one file which is mandatory for any TYPO3 extension, ext_emconf.php. We will start examining files starting from this one. Common Files All files from this group have predefined names, and TYPO3 expects to find certain information in them. Hacking these files to serve another purpose or to have a different format usually results in incompatibility with other extensions or TYPO3 itself. While it may work in one installation, it may fail in others. So, avoid doing anything non-standard with these files. ext_emconf.php This is the only required file for any TYPO3 extension. And this is the only file that should be modified with great care. If it is corrupt, TYPO3 will not load any extension. This file contains information on the TYPO3 Extension Manager. This information tells the Extension Manager what the extension does, provides, requires, and conflicts with. It also contains a checksum for each file in the extension. This checksum is updated automatically when the extension is sent to TER (TYPO3 Extension Repository). The server administrator can easily check if anyone has hijacked the extension files by looking into the extension details in the Extension Manager. The modified files are shown in red. Here is a tip. If you (as an extension developer) send your own extension directly to the customer (bypassing TER upload), or plan to use it on your own server, always update the ext_emconf.php file using the Backup/Delete function of the Extension Manager. This will ensure that TYPO3 shows up-to-date data in the Extension Manager. Here is an example of a ext_emconf.php file from the smoothuploader extension: <?php ############################################################# # Extension Manager/Repository config file for ext: ↵ # "smoothuploader" # Auto generated 29-02-2008 12:36 # Manual updates: # Only the data in the array - anything else is removed by ↵ # next write. # "version" and "dependencies" must not be touched! ############################################################# $EM_CONF[$_EXTKEY] = array( 'title' => 'SmoothGallery Uploader', 'description' => 'Uploads images to SmoothGallery', 'category' => 'plugin', 'author' => 'Dmitry Dulepov [Netcreators]', 'author_email' => '[email protected]', 'shy' => '', 'dependencies' => 'rgsmoothgallery', 'conflicts' => '', 'priority' => '', 'module' => '', 'state' => 'beta', 'internal' => '', 'uploadfolder' => 0, 'createDirs' => '', 'modify_tables' => 'tx_rgsmoothgallery_image', 'clearCacheOnLoad' => 0, 'lockType' => '', 'author_company' => 'Netcreators BV', 'version' => '0.3.0', 'constraints' => array( 'depends' => array( 'rgsmoothgallery' => '1.1.1-', ), 'conflicts' => array( ), 'suggests' => array( ), ), '_md5_values_when_last_written' => 'a:12:{s:9:...;}', 'suggests' => array( ), ); ?> The variable _md5_values_when_last_written is shortened in the listing above.
Read more
  • 0
  • 0
  • 1854

article-image-testing-your-jboss-drools-business-rules-using-unit-testing
Packt
14 Oct 2009
5 min read
Save for later

Testing your JBoss Drools Business Rules using Unit Testing

Packt
14 Oct 2009
5 min read
What is unit testing? A good enterprise computer system should be built as if it was made of Lego bricks. Your rules are only a piece of the puzzle. You'll need to go back to the Lego box to get pieces that talk to the database, make web pages, talk to other systems that you may have in your company (or organization), and so on. Just as Lego bricks can be taken apart and put together in many different ways, the components in a well-designed system should be reusable in many different systems. Before you use any of these components (or 'bricks') in your system, you will want to be sure that they work. For Lego bricks this is easy—you can just make sure that none of the studs are broken. For components this is a bit harder—often, you can neither see them, nor do you have any idea whether their inputs and outputs are correct. Unit testing makes sure that all of the component pieces of your application work, before you even assemble them. You can unit test manually, but just like FIT requirements testing, you're going to 'forget' to do it sooner or later. Fortunately, there is a tool to automate your unit tests known as Junit (for Java; there are also versions for many other languages, such as .Net). Like Drools and FIT, Junit is open source. Therefore, we can use it on our project without much difficulty. Junit is integrated into the JBoss IDE and is also pretty much an industry standard, so it's easy to find more information on it. A good starting point is the project's home page at http://www.Junit.org. The following points can help you to decide when to use unit testing, and when to use the other forms of testing that we talked about: If you're most comfortable using Guvnor, then use the test scenarios within Guvnor. As you'll see shortly, they're very close to unit tests. If the majority of your work involves detailing and signing off against the requirement documents, then you should consider using FIT for Rules. If you're most comfortable using Java, or some other programming language, then you're probably using (J)unit tests already—and we can apply these unit tests to rule testing. In reality, your testing is likely to be a mix of two or three of these options. Why unit test? An important point to note is that you've already carried out unit testing in the rules that we wrote earlier. OK, it was manual unit testing, but we still checked that our block of rules produced the outcome that we expected. All we're talking about here is automating the process. Unit testing also has the advantage of documenting the code because it gives a working example of how to call the rules. It also makes your rules and code more reusable. You've just proved (in your unit test) that you can call your code on a standalone basis, which is an important first step for somebody else to be able to use it again in the future. You do want your rules to be reused, don't you? Unit testing the Chocolate Shipments sample As luck would have it, our Chocolate Shipments example also contains a unit test. This is called DroolsUnitTest.java, and it can be found in the test/java/net/firstpartners/chap7 folder. Running the Junit test is similar to running the samples. In the JBoss IDE Navigator or package explorer, we select DroolsUnitTest.java, right-click on it, and then select Run as | Junit test from the shortcut menu. All being well, you should see some messages appear on the console. We're going to ignore the console messages; after all, we're meant to be automating our testing, not manually reading the console. The really interesting bit should appear in the IDE— the Junit test result, similar to the screenshot shown below. If everything is OK, we should see the green bar displayed—success! We've run only one unit test, so the output is fairly simple. From top to bottom we have: the time it took to run the test; the number of errors and failures (both zero—we'll explain the difference shortly, but having none of them is a good thing), the green bar (success!), and a summary of the unit tests that we've just run (DroolsUnitTest). If you were running this test prior to deploying to production, all you need to know is that the green bar means that everything is working as intended. It's a lot easier than inspecting the code line by line. However, as this is the first time that we're using a unit test, we're going to step through the tests line by line. A lot of our Junit test is similar to MultipleRulesExample.java. For example, the unit test uses the same RuleRunner file to load and call the rules. In addition, the Junit test also has some automated checks (asserts) that give us the green bar when they pass, which we saw in the previous screenshot.
Read more
  • 0
  • 0
  • 3240

article-image-audio-fields-drupal
Packt
14 Oct 2009
5 min read
Save for later

Audio Fields in Drupal

Packt
14 Oct 2009
5 min read
FileField remixed If you haven't examined FileField, you'll have to do so by downloading the FileField module from http://drupal.org/project/filefield and enable it on the Modules administration page (by browsing to Administer | Site building | Modules, at /admin/build/modules). Now create a new content type named Album by going to Administer | Content management | Content types | Add content type (at /admin/content/types/add). We'll next add a FileField to this by editing the new Album type and selecting the Add field tab (at /admin/content/types/album/add_field). Call it Song, select the File for the Field type, press Continue, and press Continue again (leaving the Widget type as File Upload). In the Permitted upload file extensions, enter mp3 for now. If you wish, you may enter a new File path as well such as audio. Uploaded files would then be saved to that path. Note that you have access to the Token module's features here. So, for instance you may enter something like audio/[user-raw], which will replace [user-raw] with the username of the node's creator: Finally, select Unlimited for the Number of values, since we'll allow a single album to contain many songs. We'll also check the Required checkbox so that each album will hold at least one song. Finally, we will ensure that the Default listed value is Listed, and that we select the Enforce Default radio button for How should the list value be handled? This will force a node to always list files when displayed. We need to list our files, although we plan ultimately to control display of an album's songs in the player: Now we can add an album node with a few songs by going to Create content | Album (at /node/add/album). Uploading is simple. At this point, we only have a link displayed for our files. Our next task is to create an inline player for the audio. One possibility would be to override the theme function. However, we have other tools available that will make our job easier and even ensure cross-browser compatibility, better accessibility, and valid HTML: jQuery Media to the rescue The jQuery Media plug-in, written by Mike Alsup at http://www.malsup.com/jquery/media/, is a perfect solution. It will convert any link to media into the browser-specific code required for displaying the media. The jQuery Media module is a configurable wrapper for this plug-in. We'll also need a media player. For this exercise, we'll again use the JW FLV Media Player developed by Jeroen Wijering. This excellent player is free for non-commercial use, and has a very inexpensive licensing fee for other uses. First, download that player from http://jeroenwijering.com/ and install the player.swf file somewhere in your site's directory tree. If you install it in the site's www root folder, the module will work with little extra configuration. But you can install it in the files directory, your theme folder, or another convenient place if you need it for your environment. Just remember where you put it for future reference. Next, download and enable the jQuery Media module from http://drupal.org/project/jquery_media. You may wish to also install the jQ module from http://drupal.org/project/jq, which consolidates jQuery plug-ins installed on your site. The configuration is simple. You'll just need to enter the filepath of your media player, which can be different than the Flash Video player entered earlier, if desired. Go to the jQuery Media Administration page by browsing to Administer | Site configuration | jQuery Media Administration (at /admin/settings/jquery_media). Open the Default players (within Extra settings) and enter the filepath of your media player in the MP3 Player (mp3Player) text field: Now just check the Album box in Node types, and set the width and height within Default settings. In most cases, you would be done and the audio would be displayed automatically with no further configuration. However, we're assuming you plan to use this module in conjunction with videos, which may have already set a width and height. That means we'll need to do some more customization. Note: You do not need to do any of this, unless you have video and audio files on the site both using jQuery Media. We need to change the class of our field and add a new invocation script. However, we don't want to affect the class of our existing video files. So add the following somewhere in the phptemplate_preprocess_filefield_file function, creating that function if necessary. (If you haven't already done that, then create function phptemplate_preprocess_filefield_file(&$variables) in template.php. $node = node_load($file['nid']); if ($node->type == 'album') { $variables['classes'] = 'filefield-file-song'; if (module_exists('jquery_media')) { jquery_media_add(array('media class' => '.filefield-file-song a', 'media height' => 20, 'media width' => 200)); } } else { $variables['classes'] = 'filefield-file'; } Then you'll need to change a line in filefield_file.tpl.php. (If you haven't already created that file, create it in your theme directory, and copy the code from the theme_filefield_file function that is found in /sites/all/modules/filefield/filefield_formater.inc.) The original line in question reads as follows: return '<div class="filefield-file clear-block">'. $icon . l($file['filename'], $url) .'</div>'; However, we can rewrite that line to read: <div id="filefield-file-file-<?php print $id; ?>" class="filefield-file clear-block" <?php print $style; ?> > In either case, simply replace class="filefield-file clear-block" with class=" clear-block".
Read more
  • 0
  • 0
  • 1592
article-image-content-editing-and-management-open-souce-cms
Packt
14 Oct 2009
11 min read
Save for later

Content Editing and Management in an Open Souce CMS

Packt
14 Oct 2009
11 min read
There are exciting things ahead in this article, so let's get started. Adding content to our site Adding, updating, and deleting page content is at the heart of a CMS. We will use the Joomla! content management system for our examples in this article. Joomla! is a very popular and powerful CMS. Let's see how we can manage content with Joomla!. Time for action-adding a page Log in to the administration section of Joomla!. It is generally athttp://yoursite.com/joomla/administrator/. Click on the large icon that says Add New Article. We want to create a page about Surya Namaskara, or Sun Salutation, one of the most popular yoga postures. Enter Surya Namaskara in the Title field, and Sun Salutation in the Alias field. We have already created a few sections and categories in Joomla!. Select Posturesas Section, and Featured as Category from the drop downs. The Word-like area below is a content editor. It is also known as the WYSIWYG (What You See Is What You Get) editor. Type in the following text in the area that looks like a white page. We took this text from Wikipedia, but you can type a statement of your choice. Surya Namaskara or Sun Salutation (lit. "salute to the sun"), is a common sequence of Hatha yoga asanas. Its origins lie in a worship of Surya, the Hindu solar deity. Don't see a Word-like editor? If you don't see a Word-like text editor, you may be missing some browser plug-ins. Your browser may warn you of missing plug-ins. In such a case, go ahead and install the missing plug-ins. If it still does not work, go toSite | Global Configuration | Site | Site Settings | Default WYSIWYG Editor and select TinyMCE or XStandard. You can also configure the editor per user from User Manager. Press Enter after the first paragraph. Add two more sentences like this: Surya Namaskara is an excellent exercise for the whole body. Mastering this asana will help you stay fit forever. "Asana" is the Sanskrit word for posture. Yoga postures are called Asanas. We want to highlight that Surya Namaskara is an excellent exercise for the whole body. Select that portion of text and click on the B icon to make it bold. You will immediately see the result in the editing window. At this stage, your editing window will look like this. If you want to write additional text, go ahead and add it. Click on the large Save icon at the top right of the page when you are done. Now our content is saved. Click on the Preview link in the Joomla! menu bar and you will see the content on the site's home page. Here's how it will look: What just happened? We used Joomla! to create our first content page. We added a page title, an alias, and the section and category this page belongs to. We then used a Word-like editor to enter text for our page. We emphasized keywords by making them bold. This was done by selecting the keywords, and clicking on the B icon button in the toolbar. Notice that we can use this editor to apply a variety of other formatting to selected text. This kind of text editor is called aWYSIWYG editor. What is WYSIWYG? Why is it important?  WYSIWYG (pronounced 'wize,wig) is an acronym for What You See Is What You Get.The Word-like content editor we saw is WYSIWYG because our page looks the same in the editor as it does on the site. The fonts, formatting, colors, and alignments—all work consistently between the editing interface and the actual site.  Most CMSs come with a WYSIWYG editor. Such editors make it very easy for authors to add content and the formatting style that they like. These formatting options look and behave in a way similar to Microsoft Word or OpenOffice Writer. But the complexity of options provided may vary between CMSs. The following image shows the WYSIWYG editor toolbars of Joomla! (top) and WordPress (bottom). As you see, WordPress offers a simpler editor, but with lesser options. An amateur user will find it easier to work with an editor with fewer choices. As a matter of fact, WordPress's editor toolbar shows only the first row of options by default. You can enable a second row by clicking on the last button in first row: Show / Hide Kitchen Sink. On the other hand, Joomla! comes ready with all options visible. This is useful for a professional who wants better control over content formatting. Evaluate how important is it for you to have a WYSIWYG editor. Also, see if the CMS comes with it by default, or you have to add it via a plug-in or extension. For example, Drupal does not have a WYSIWYG editor module by default; but you can easily add it via a module. This also means some CMSs may not have a WYSIWYG editor. So, if there is no WYSIWYG editor, how do you add content? Well, if your content does not require a fancy format, you can live with simple textual content. Else, you can always use HTML. Surya Namaskara or Sun Salutation (lit. "salute to the sun"), is a common sequence of Hatha yoga asanas. Its origins lie in a worship of Surya, the Hindu solar deity. Do I need to learn HTML?  HTML is the language to layout and format web site pages. If you know HTML, it will be easier to manage your CMS. If HTML is not an option, a WYSIWYG editor can be really helpful. Here are some links for learning the basics of HTML:http://www.html.net/tutorials/html/http://www.w3schools.com/html/DEFAULT.asp Adding images We have added the basic content to our page. Now, we will try to include some pictures in our page. Images add a lot of meaning to the content, apart from adding a decorative value. Let's add an image to our page now. Time for action-adding images If you are not already logged in to the Joomla! administration, log in now. Click on Site in the main menu. That should open a submenu of site management options. Click on Media Manager. You will see previews of current images in Joomla!. Click on the stories folder to go into it. You will now see images within this folder. Let's create a new folder here to store images of different asanas/postures. In the Create Folder text box near the top right side, type in asanas and click on the button. This should create a new folder within stories. Click on it to move inside. We can now upload an image here. Click within the text box of the Upload File section at the page end. This will bring up a dialog window to select a file you want to upload. We want to upload an image for Surya Namaskara. Select an image of your choice. Now click on the Start Upload button.                                               File uploading requires correct permissions on the server To upload files to your site, you require correct permissions on yourserver. In technical terms, this is called making a folder world-writable or changing mode to 777. You can change folder permissions using an FTPapplication, or your site's control panel. Technically, it's sufficient to give a 666permission—read-and-write permission to the owner, group, and others—butnormally everyone gives a 777 permission, including execute permission for allthree. Here's a screenshot of setting these permissions using FireFTP, an FTPextension for the Firefox browser. The file upload operation may take a few seconds to complete, depending on image size. Once the image is uploaded, you will see its thumbnail in the list. Upload more images if you want to. Finally, your folder may look like this. We are now ready to insert an image in our page. Select Content  Article Manager  from the main menu. Click on the Surya Namaskara page to edit it. Inside our WYSIWYG editor, keep your cursor where you want to insert the image. Click on the Image button below the WYSIWYG editor. A window will open up with a thumbnail list of images available. Click on the b we created earlier. Click and select an image you want to insert. Add a description and title. Click on the Insert button at the top right. That will insert our image into the content area. Re-size it using the handles on the corners if you wish. Here's how it will look: Congratulations! You have successfully added an image to our page. What just happened?  We uploaded an image from our computer and added it to a page. In the process, we learned about the Media Manager, creating folders, and uploading files to Joomla!. We also learned how to select images to use on a page and even saw image insertion options.  Adding an image involved multiple activities. We had to first add it to the Media Manager.Because this was the first time we were adding an image, we also created a new folder. It was as simple as typing in a name and clicking a button.  We added images within folders since it will help us manage the images better. Once we add an image to the Media Manager, we can use that image on as many pages as we want. The Image button on the content editing screen allows us to select images to use on that page. It also helps us to add captions and correctly align inserted images with the text. You can also upload images using that image selection window itself.We took the Media Manager route to learn more. You can also upload images using that image selection window itself.We took the Media Manager route to learn more. Have a go hero-image formatting options  We have learned enough about inserting images to content now. It is time we try out something else. Once you insert an image, click on it, and then click on the small photo icon in the WYSIWYG editor's toolbar. Go ahead and try out different image properties, different alignment options, spacing, caption, and alternative text. See how the result changes in the preview.                                                       Don't let your images sink your site!                                                     Make sure your images are optimized and sized for web usage. Avoid changing the width and height via image properties. If you want to show a smaller image than the one you uploaded, resize it using photo editing software and use that new version. Large images take longer to load and can make your site slow.                                                      Have a go hero-adding a video  Our Yoga site may also require videos. Look around and find how a video can be added to the page.  Completed? Alright! We have now looked at how to edit a page and insert images/videos into it. Let's see the other options we have in editing and maintaining site content.
Read more
  • 0
  • 0
  • 985

article-image-implementing-document-management-alfresco-3-part2
Packt
14 Oct 2009
4 min read
Save for later

Implementing Document Management in Alfresco 3- part2

Packt
14 Oct 2009
4 min read
Library services Library services are common document management functions for controlling the users through permissions, for creating multiple instances of a document(versioning), and for providing users with access into a document to make the changes (checking-in or checking-out). Versioning You might have more than one person who can edit a document. What if somebody edits a document and removes a useful piece of information? Well, you can make use of the versioning features of Alfresco to resolve such issues. Versioning allows the history of previous versions of a content to be kept. The content needs to be Versionable, in order for versions to be kept. You can enable versioning in four different ways: Individually: To enable versioning for an individual content object item, go to the View Details page and click on the Allow Versioning link. The next screenshot illustrates how to enable versioning on an individual content item. Using Smart Spaces: A business rule can be set for a space to allow versioning of all of the content or selected content within that space. By Type: By default, versioning is disabled for all of the content types in the Alfresco content model. Versioning can be enabled for a specific content type, irrespective of the location of the content. Globally: Alfresco can be configured globally to enable versioning for all content throughout the site. Enable versioning for sample file that you have already uploaded to the system. Go to the Intranet > Marketing Communications > Switch to open source ECM > 02_Drafts space and view the details of Alfresco_CIGNEX.doc file. Click on the Allow Versioning link to enable versioning, as shown in the following screenshot. You will immediately notice that a version with a version number of 1.0 is created. At the time of writing this article (Alfresco version 3.1), reverting back to an older version of the content is not supported. There is a plan to support this feature in future releases of Alfresco. The workaround is to download the older version and upload it again as the current version. For a checked out content, the version is updated when the content is checked in. The version number is incremented from the version number of the content object that was checked out. Auto Versioning Auto versioning can be enabled by editing the content properties and selecting the Auto Version checkbox. If auto versioning is enabled, then each Save of the content results in an incremented version number, when the content is edited directly from the repository. Each Update (upload) of the content also results in a new version (with an incremented version number) being created. If auto versioning is not enabled, then the version number is incremented only when the content is checked in. Check In and Check Out By using the versioning feature, you can ensure that all of the changes made to a document are saved. You might have more than one person who can edit a document. What if two people edit a document at once, and you get into a mess with two new versions? To resolve this issue, you'll need to use the library services. Library services provide the ability to check out a document, reserving it for one user to edit, while others can only access the document in read-only mode. Once the necessary changes have been made to the document, the user checks in the document, and can either replace the original, or create a new version of the original. Check Out locks the item and creates a working copy that can be edited (both the content and the details). Check In replaces the original item with the working copy, and releases the lock.
Read more
  • 0
  • 0
  • 1498

article-image-creating-your-first-web-page-using-expressionengine-part-1
Packt
14 Oct 2009
8 min read
Save for later

Creating Your First Web Page Using ExpressionEngine: Part 1

Packt
14 Oct 2009
8 min read
Toast for Sale! To demonstrate the power of ExpressionEngine, we are going to use a fictitious business as an example throughout this article. Our website is in the business of selling toast (heated bread with melted butter) online. With this example, we will be able to explore many of the nuances of building a complete website with ExpressionEngine. Though unlikely that we would really want to sell toast over the internet, the concepts of our example should be transferable to any website. In this article, we want to introduce the world to our business, so we are going to create a 'News from the President' webpage. This will allow the President of our company to communicate to customers and investors the latest goings-on in his business. Inside the Control Panel When you first log into the control panel, there are lots of options. Let us take a quick tour of the control panel. First, we will need to log into ExpressionEngine. If you are using XAMPP to follow along with this article, go to http://localhost/admin.php or http://localhost/system/index.php to log in. It is assumed that you are using XAMPP with http://localhost/ addresses. If you are following along on an actual website, substitute http://localhost/ for your website domain (for example, http://www.example.com/). It is required to move the login page to the root of our website to mask the location of our system directory The first page we see is the CP Home. We can return to this page anytime by selecting CP Home from the menu at the top-right of the screen, above the main menu. In the left column, we have EllisLab News Feed. Below, we have Most Recent Weblog Entries as well as any Recent Comments or trackbacks visitors may have left. In our case, our site is brand new, so there will be no recent comments or trackbacks, and only 1 recent weblog entry (Getting Started with ExpressionEngine). Clicking on the link will take you directly to that entry. On the right, there is a Bulletin Board (a way for you to pass messages to other members of your control panel), the Site Statistics and a Notepad (we can write anything here, and it will be available every time we log-in). Across the top is the main menu bar, and at the top-right are links to your website (My Site), this page (CP Home), the ExpressionEngine user-guide (User Guide), and to log-out (Log-out). The Publish and Edit links in the main menu bar are where you can create new entries and edit existing entries. The Templates link is where we can create new templates and edit existing templates. We will spend most of our time in these sections. The Communicate tab is where we can manage bulk-emails to our website members. At this time we do not have any members to email (other than ourselves), but as our site grows larger, this feature can be a useful communication/marketing tool. Be careful to avoid sending unsolicited bulk emails (or spam) using this feature. In many countries, there are laws governing what can or cannot be done. In the United States, commercial emails must meet very specific guidelines set by the Federal Trade Commission (http://www.ftc.gov/spam/). The Modules tab is where we can manage all the modules that come with ExpressionEngine, as well as optional third-party modules that we may wish to install. We can download additional modules from http://expressionengine.com/downloads/addons/category/modules/. The My Account tab is where we can edit our login preferences, including our username and password. We can also edit the look and feel of the control panel home page from this screen, as well as send private messages to other members. Much of this page is irrelevant when we are the only member of the site (as we are right now). The Admin tab is where most of the configuration of ExpressionEngine takes place, and we will spend a lot of time here. By default, most of the ExpressionEngine settings are already properly set, but feel free to browse and explore all the options that are available. Full documentation on each of the options is available at http://expressionengine.com/docs/cp/admin/index.html. This concludes our brief tour of ExpressionEngine. Now we are going to delve into one of the most important parts of the control panel—templates. Templates and URLs The basic concept in ExpressionEngine is that of a template. Go to any ExpressionEngine-powered website and you will undoubtedly be looking at a template. Templates are what the outside world sees. At its most basic, a template in ExpressionEngine is a HTML (or CSS or JavaScript) file. If we wanted to, we could use a template exactly like a HTML file, without any problems. We could create an entire website without ever using any other part of ExpressionEngine. However, we can take templates a lot further than that. By using ExpressionEngine tags inside our templates, we can take advantage of all the features of ExpressionEngine and combine it with all the flexibility that HTML and CSS offers in terms of layout and design. We are not limited to pre-defined 'cookie-cutter' templates that have been carefully adapted to work with ExpressionEngine. This is why ExpressionEngine is very popular with website designers. On the flip side, this is also why there is such a learning curve with ExpressionEngine. There is no point-and-click interface to change the look and feel of your website; you have to have some experience with HTML to get the most out of it. Let us take a closer look at templates and how they relate to URLs: If you are not already logged in, log into ExpressionEngine at either http://localhost/admin.php or http://www.example.com/admin.php. Click on the Templates button on the top of the screen. Templates are stored in groups. There is no 'right' way to group templates—some sites have all their templates in a single group and other sites have lots of template groups. We are going to create a new template group for each section of our website. ExpressionEngine does come pre-installed with two template groups: the site template group and the search template group. As a new user, it is best not to delete these template groups in case you want to refer to them later. In the next screen we can give our template group a name; let us use toast. There is an option to Duplicate an Existing Template Group which copies all the templates from one template group into our new template group. This can be useful if we are creating one template group that will work very similarly to the one that we already created, but as this is our first template group, we are going to start from scratch. Checking the box Make the index template in this group your site's home page? means that visitors will see the toast website in place of the ExpressionEngine example site. If you are using the XAMPP test server, go ahead and check this box. Hit Submit to create the template group. We will be returned to the Template Management screen. A message will appear saying Template Group Created, and the new template will appear in the box of groups on the left-hand side. Left-click on the New Template group in the Choose Group box on the left-hand side. Each template group comes with an initial template, called index. Remembering that a template is like an HTML file, a template group is like a directory on our server. The index template is the equivalent of the index.html file—when a visitor visits our template group, the index template is displayed first. For that reason, the index template cannot be renamed or deleted. Let us edit the index template to see what it does. Click on the word index. A template is essentially just text (although it usually contains HTML, CSS, or ExpressionEngine code). When we first create a template, there is no text, and therefore all we see is an empty white box. Let us write something in the box to demonstrate how templates are seen by visitors. Type in a sentence and click Update and Finished. Just like HTML files and directories, templates and template groups relate directly to the URL that visitors see. In the URL http://www.example.com/index.php/toast/index, the index.php is what distinguishes this as an ExpressionEngine page. Then comes the template group name, in our case called toast. Finally, we have the template name, in this case index. Go to the previous URL (with or without the index.php as appropriate, for example, http://www.example.com/toast/index or http://localhost/toast/index) and the template we just edited should appear. Now try typing the template group without specifying which template to load. The index template is always returned. What happens if we do not specify the template group, and just go to our base domain (http://localhost/ or http://www.example.com/)? In this case, the toast template of the default template group is returned. The default template group is indicated on the templates screen with an * before the template group name and underneath the list of template groups.
Read more
  • 0
  • 0
  • 3898
article-image-creating-your-first-web-page-using-expressionengine-part-2
Packt
14 Oct 2009
7 min read
Save for later

Creating Your First Web Page Using ExpressionEngine: Part 2

Packt
14 Oct 2009
7 min read
Viewing Our First Entry Now one question remains: where do we have to go to see our entry? The answer is that our entry is not yet on our website. That is because the entry does not appear in a template and everything on an ExpressionEngine website must go into a template before it can be viewed. Follow these instructions to point a template to our new weblog. Click on Templates in the menu bar. Select Create a New Template Group, and call the New Template Group to be news. Leave all the other options at their default and click Submit. Select the news template group, and then click on the index template to edit it. To include a weblog in a template, we use a tag. A tag is a unique ExpressionEngine piece of code that is used in templates to include extra functionality. In this case, we want to include a weblog, so we need a weblog tag. A tag has two parts: variables and parameters. Parameters are always part of the opening tag whereas variables are used between the opening tag and the closing tag. In the news/index template we will add in the weblog tag as well as some standard HTML code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html > <head> <title>News from the President</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Toast for Sale!</h1> <h2>News from the President</h2> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> {summary} {body} {extended} {/exp:weblog:entries} </body> </html> The indentation helps to demarcate related sections and therefore make the code more readable, but is certainly not required. Click Update and Finished to save our updates. The difference between Update and Update and Finished is that Update will keep you in the template editing screen so that you can continue to make further edits, whereas Update and Finished returns you to the main templates screen. Now view the news template at http://localhost/news or www.example.com/news to see how it looks. It should look like the following screenshot. Notice how the {title} has been changed to reflect the actual title of our entry (and so has {summary} and {body}). What happens if we post two entries? Let us try it and see! Back in the control panel, select Publish | Toast News and write a second entry with a different title, URL title, and so forth. Hit Submit, and then visit http://localhost/news or http://www.example.com/news to see what happens. It should look like as follows: For our final enhancement, let us edit the template to include variables for the author name and the date of the entry. To do this, add the highlighted code as shown next: <body> <h1>Toast for Sale!</h1> <h2>News from the President</h2> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> {summary} {body} {extended} <p class="footnote">Written by {author} on {entry_date format="%F %j%S"}</p> {/exp:weblog:entries} </body> {author} is a variable that returns the name of the person who was logged in when the entry was created. {entry_date} is a variable that displays the date that the entry was written on. format is a parameter of the entry_date variable that is used to specify how the date should be formatted. %F is the month of the year spelled out; %j is the day of the month; and %S is the suffix (for example, nd or th). So %F %j%S is rendered as 'February 7th'. For a complete list of date formats, visit http://expressionengine.com/docs/templates/ date_variable_formatting.html.   Revisit http://localhost/news or http://www.example.com/news, and you can now see the author name underneath both entries. Make Our Weblog Pretty Using CSS Our weblog, whilst functional, is not exactly the prettiest on the web. We will spruce it up with some more HTML and CSS. This section will not introduce any new ExpressionEngine features but will demonstrate how to incorporate standard CSS into our templates. An understanding of HTML and CSS will be invaluable as we develop our ExpressionEngine site. Please note that this article can only demonstrate the basics of using HTML with CSS in an ExpressionEngine website. If you are already familiar with using HTML and CSS, then you will only need to go through the section in the first part (Creating and Linking to a Styling Template) to create the CSS template and link to it from the HTML template. Creating and Linking to a Styling Template As with a more conventional HTML/CSS website, our CSS code will be separated out from our HTML code, and placed in its own template (or file). This requires creating a new CSS template and modifying our existing template to identify the main styling elements, as well as to link to the CSS template. First, let us go back into our news template and add the following code (highlighted). The trick with writing HTML with CSS is to identify the main sections of the HTML code using the <div> tag. <body> <div id="header"> <h1>Toast for Sale!</h1> <h2>News from the President</h2> </div> <div id="content"> {exp:weblog:entries weblog="toastnews"} <h3>{title}</h3> <div class="contentinner"> {summary} {body} {extended} </div> <p class="footnote">Written by {author} on {entry_date format="%F %j%S"}</p> {/exp:weblog:entries} </div> </body> Here we have identified three sections using the <div> tag. We have encapsulated our website title in a header section. We have wrapped up all of our ExpressionEngine entries into a content section. Finally, we have created a contentinner section that contains just the text for each ExpressionEngine entry, but does not include the title. Also note that footnote is a section. What is the difference between an id and a class in our <div> tags? A section defined with an id only appears once on a page. In our case, the header only appears once, so we can use the id. A section defined with a class may appear multiple times. As the contentinner section will appear on the page for each entry present there, we have used a class for this section. Next, we want to create a CSS template that tells us what to do with these sections. To do this, go back to the main Templates page, select the toast template group, and then select New Template. Call the new template toast_css. Under Template Type select CSS Stylesheet instead of Web Page. Leave the Default Template Data as None – create an empty template and hit Submit. Before we start editing our new CSS template, we must be sure to tell the HTML template about it. Select to edit the index template in the news template group. Insert the following highlighted commands between the <head> and </head> tags to tell the HTML template where the CSS template is. <head> <title>News from the President</title> <link rel='stylesheet' type='text/css' media='all' href='{path=toast/toast_css}' /> <style type='text/css' media='screen'>@import "{path=toast/toast_css}";</style> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> </head>
Read more
  • 0
  • 0
  • 1315

article-image-enhancing-user-experience-wordpress-27part-1
Packt
14 Oct 2009
6 min read
Save for later

Enhancing User Experience with WordPress 2.7(Part 1)

Packt
14 Oct 2009
6 min read
As a blogger, I read loads of blog posts every day, on many different blogs. Very often, I'm scared to see how many blogs have a non user-friendly interface. How often does it happen that you can't click on the logo to go back to the blog homepage, or can't find what you're looking for by using the search engine? It is a well known fact that in blogging the content is king, but a nice, user friendly interface makes your blog look a lot more professional, and much easier to navigate. In this article, I'll show you what can be done for enhancing user experience and making your blog a better place. Replacing the Next and Previous links by a paginator When a web site, or blog, publishes lots of articles on a single page, the list can quickly become very long and hard to read. To solve this problem, paginations were created. Pagination allows displaying 10 articles (for example) on a page. If the user wants, then he or she can go to the next page, or click on a page number to directly go to the related page. I definitely don't understand why WordPress still doesn't have a built-in pagination system. Instead, at the bottom of each page you'll find a Next link to go to the next page, and a Previous link to go back. This works fine when you're on page two and would like to go to page three, but what if you're on page one, and remember a very interesting article which was located on page eight? Are you going to browse page per page until you find your article? The answer is yes, because you don't have the choice. You can't jump from page one to page eight. In this recipe, I'll show you how to integrate a pagination plugin in your WordPress blog theme. One very good point of this recipe is that the plugin file is embedded in your theme, so if you're a theme designer, you can distribute a theme which has a built-in pagination system. Getting ready To execute this recipe you need to grab a copy of the WP-PageNavi plugin, which can be found at http://wordpress.org/extend/plugins/wp-pagenavi/. I have used version 2.40 of the Wp-PageNavi plugin in this example. Once you have downloaded it, unzip the zip file but don't install the plugin yet. How to do it Open the WP-PageNavi directory and copy the following files into your WordPress theme directory (For example, http://www.yourblog.com/wp-content/ theme/yourtheme). wp-pagenavi.php wp-pagenavi.css Once done, edit the index.php file. You can do the same with other files, such as categories.php or search.php as well. Find the following code (or similar) in your index.php file: <div class="navigation"> <div class="alignleft"><?php next_posts_link('Previous entries') ?></div> <div class="alignright"><?php previous_posts_link('Next entries') ?></div></div> Replace that with the following code: <?php include('wp-pagenavi.php'); if(function_exists('wp_pagenavi')) { wp_pagenavi(); } ?> Save the index.php file. If you visit your blog now, you'll see that nothing has changed. This is because we have to call a function in the wp-pagenavi.php file. Open this file and find the following code (line 61): function wp_pagenavi($before = '', $after = '') {global $wpdb, $wp_query; We have to call the pagenavi_init() function, so let's do this in the following way: function wp_pagenavi($before = '', $after = '') {global $wpdb, $wp_query;pagenavi_init(); //Calling the pagenavi_init() function Now, save the file and refresh your blog. The pagination is now displayed! This is great news, but the pagination doesn't look good. To solve this problem, you simply have to integrate the wp-pagenavi.css file that you copied earlier in your theme directory. To do so, open the header.php file from your theme and paste the following line between the <head> and </head> tags: <link rel="stylesheet" href="<?php echo TEMPLATEPATH.'/pagenavi. css';?>" type="text/css" media="screen" /> Visit your blog homepage one more time. The pagination looks a lot better. You may have to edit the wp-pagenavi.css file in order to make your pagination look and feel ft your blog style. How it works In this recipe, you have discovered a very useful technique that I often use on my blogs, or in the themes that I distribute—the integration of a WordPress plugin into a theme. When the plugin is integrated into your theme as I have shown you in this example, there's no activation process needed. All of the work is done directly from the theme. The WP-PageNavi plugin itself works by using two values—the number of posts to be displayed per page and the first post to be displayed. Then, it executes the relevant query to WordPress database to get the posts. The pagination bar is calculated by using the total number of posts from your blog, and then dividing this value by the number of posts per page. One good point of this technique is that the plugin is integrated in your blog and you can redistribute the theme if you want. The end user will not have to install or configure anything. Highlighting searched text in search results I must admit that I'm not a big fan of the WordPress built-in search engine. One of its weakest features is the fact that searched text aren't highlighted in the results, so the visitor is unable to see the searched text in the context of your article. Getting ready Luckily, there's a nice hack using regular expressions to automatically highlight searched text in search results. This code has been created by Joost de Valk who blogs at www.yoast.com. How to do it This useful code is definitely easy to use on your own blog: Open your search.php file and find the following: echo $title; Replace it with the following code: <?php $title = get_the_title(); $keys= explode(" ",$s); $title = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt"></strong>',$title);?> Save the search.php file and open the style.css file. Append the following line to it: strong.search-excerpt { background: yellow; } You're done. Now, the searched text will be highlighted in your search results. How it works This code is using PHP regular expressions to find the searched terms in the text returned by WordPress. When an occurrence has been found, it is wrapped in a <strong> HTML element. Then, I simply used CSS to define a yellow background to this element.
Read more
  • 0
  • 0
  • 1596