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

How-To Tutorials - Web Development

1802 Articles
article-image-testing-students-knowledge-using-moodle-modules
Packt
03 Jun 2010
11 min read
Save for later

Testing Students' Knowledge using Moodle Modules

Packt
03 Jun 2010
11 min read
(For more resources on Moodle, see here.) There are a number of tools in Moodle to find out the students' depth of understanding—some formal and some informal. There are also some tools that allow the students to assist themselves in their own knowledge consolidation. We will now investigate these tools in more detail. Implementing a glossary The glossary is a well known and commonly used module in Moodle, but it may not always be used as the effective teaching and learning tool that it can be. Given the jargon-rich nature of design and technology, it is also an important glue for the whole subject area. Checking the settings The key options here relate to the functioning of the glossary and how you use it as a teaching and learning tool. The first thing that needs to be done is to check the overall settings for the module in the administration section of the site. The settings are divided into three key areas: Default settings for the glossary module Settings for the entries in the glossary Format of the display styles The previous settings can be found on the administration panel in the Site Administration | Modules | Activities | Glossary section. Default settings The first section determines which functions of the glossary are generally available to the users of the module on the site. In the previous screenshot, the main options relate to the linking functions and comments on the entries themselves. For example, do you want to allow students to comment on the glossary entries? For a subject such as DT, you might wish to allow students to add their own understanding of terms. In some cases, there may be regional terms for some things which are different from the "formal" definition of a term, such as the term used for certain woodworking tools. As woodworking is an ancient craft, there are many different local terms to describe some of the equipments used. The glossary would then reinforce the social nature of the design as a part of a teaching method. Preventing duplicate entries As you can see in the previous screenshot, the default setting here would be to not allow duplicate entries in the glossary—although it can be enabled to perhaps show the nuances in a term or allow the term to be defined in another language, if your school has a partner school in another country. In some instances, you might have a definition that is the accepted definition, but also one that students might come across such as a building term. Likewise, you might have a definition relating to a usage as opposed to how a manufacturer might determine an item. Allowing duplication gives students a sense of how terms change, depending on how they are used and by whom. Allowing comments Allowing comments on the entries is useful for students to build up an internal dialog whereby they may be able to add examples of best practice to the definitions in the glossary relating to their on-the-job work experience. This is useful because students who had previously worked in a company and gained some experience of the job can leave a historical record to help the students who have just started the course or work. Automatically linking comments The linking of the glossary terms is useful if you use a consistent approach throughout your course design; in particular, if you use the Compose a web page function under Add a resource, as discussed earlier, rather than uploading the proprietary word-processed files, then Moodle will be able to link the terms through the database. However, please bear in mind that the linking function will add some load to your server and may not be appropriate in all cases, such as when using a server on a shared system. Linking definitions throughout the site allows students to have a better understanding of all the elements, as they work through them and when they forget some key terms. However, you need to remember that this links across an entire site and some definitions may clash across curriculum subjects. Therefore, there is a need for the duplicate entries. The ability to create a glossary for all the users on a site is only available to site administrators. Entry level default settings The following screenshot shows the options that are available for the entries, which are added to the glossaries. If enabled, the options shown in the following screenshot will automatically be enabled when the entries are made. Users still have the choice to disable the options like the automatic linking shown as follows: Again, you can link terms in the course to the glossary definitions, and if necessary, make the terms case sensitive. The case-sensitive option as well as the matching of whole words allows some fine tuning of the glossary. For example, you may make an entry for a law, which is HAM. If you enable the case-sensitive option on this entry, then a link will be created in the database when the specific term HAM is entered on a page in the course and not for every instance of hammer. This may be more useful with younger students when it is important for them to learn the key terms, but perhaps not so with older students. You can now save the settings you have chosen. If the changes have been applied for you by your site administrator, you can move directly to your course to begin using a glossary. Creating a glossary Once you or the site administrator have set up the module in the way that is most appropriate for your institution, teachers can then begin to apply them to their courses. We are assuming here that you have other subject areas on your Moodle site, therefore, we will focus on the course-level entries, but the principles are same. Enabling the glossary For this example, we will add a glossary of terms to our construction-based course. Younger students may be unfamiliar with this subject in many cases and they will, therefore, have a greater need for some ways of understanding the wealth of the terms. The same is true for Food Technology or Resistant Materials, but it is more likely that they would have at least encountered food-based products or materials in their lives. It is less likely that they had been involved in the construction of their environment or have working knowledge of these key terms. As with all the modules, the first action is to enable editing on the course to activate the activities drop-down menu. This requires clicking the button that follows: This will then show the activities menu from which you can select the glossary module Glossary from one of the many Add an activity' drop down menus, as shown in the following screenshot, to create a new glossary activity module. Editing the glossary Once enabled, added, or created, you can then name the glossary and determine some of the functionality you want in it to be available. Like all the other modules, these are related to time and display elements. The following screenshot shows some of the key settings such as the type of glossary and the display format. Most of these settings were determined at the site level, such as allowing duplicate entries or comments, but they can be changed by the staff as required. The key point here is that we make one glossary—a main glossary for the course. We make all the subsequent glossaries secondary, which means that we can export the terms into this main one, but this is the overall glossary for the course. We might have secondary glossaries for the human aspects of construction or health and safety, as opposed to the material elements for example. As this is a very graphical subject, we have enabled the display to be like an encyclopedia. This will allow staff and students to add images and video files to explain the terms they are defining in a better way. Rating entries If you are going to use the glossary in a more formal way, it would be useful to allow the students to rate the entries, so that they can peer assess each other's terms. If you set each student a number of terms to define as a homework exercise, you can allow the students to research and populate the glossary and for the other students to award marks. This makes the terms far more dynamic and real for the students. You might also invite your contacts from local companies to rate the students' definitions and give them feedback to help develop their understanding on a deeper level. This is enabled through the grading option, as shown in the following screenshot: The glossary can now be saved. Adding entries (categories) When we are adding entries, the first real requirement is to create some categories in which you can organize the terms. A category in this instance is a group of terms such as tools or techniques. If we had created one Moodle course to cover all the DT subjects, we might have a main glossary for DT and secondary glossaries for Food and Construction. This makes it more organized as well as making it easier to search for items. In this example, we are creating some glossary items relating to the term 'carpentry'. We need to create an overall category for this area. This is achieved by first adding a new category item by clicking on the Browse by category tab and then on Edit categories, as shown in the following screenshot: This will open the dialog window to create a new category for this glossary, as shown in the following screenshot: If you select to link the category, this whole sub-section will be revealed by a hyperlink to this term, which could be useful for newer students. Adding entries If the course you are managing incorporates all of the DT subjects, then you may wish to create a main glossary for DT and secondary glossaries for Food or Resistant Materials and so on. In this example, we have a course for Construction and the Built Environment, which is the main glossary. We are going to create categories to group the terms in the glossary for areas such as carpentry or electrical. With the categories set, it is now possible to add and organize the definitions for your course. This can be managed entirely by the staff or can be an exercise that allows student participation, such as a homework exercise as mentioned earlier. In this example, we are building up a definition for a particular woodworking joint. Once we have set the name and basic details, we can then categorize the entry and add some keywords for searches, as shown in the following screenshot: The entry can now be viewed by students as well as rated and commented upon. In the following instance, the student has not only rated the entry, but also added a comment with a link to a website they have found, which further illustrates the particular woodworking joint. Students could also embed a video stream from a video site, which would also help to explain the process more clearly. This level of collaborative learning is immensely powerful with this type of kinesthetic information. Students can now add their own entries as part of a homework routine or teaching strategy. As shown in the following screenshot, items added to the glossary are linked to other pages through the database. The terms are highlighted by Moodle and clicking on them will take users to the glossary page, which defines them. In this example, the word 'wood' is highlighted in green. When you click on this link, it will open the corresponding entry for wood in the glossary, as shown in the following screenshot. Mapping their minds Many aspects of design require students to sketch out their ideas in a graphical form in order to get to grips with the complexity and the various components. These sketches could be scanned and uploaded as formal assignments, but they could also be incorporated into the Moodle site through the use of an add-on called Mindmap. This is a third-party module that allows the students to map out their ideas using a basic interface and permits them to link and label the items on a screen. It can be saved by them in their area and can be viewed by the staff for guidance and support. The Mindmap module can be found at: http://moodle.org/mod/data/view.php?d=13&rid=1628&filter=1 Once the module has been installed, it is added to a course in a similar way as we add any other module, by turning the editing on. After choosing the drop-down activities menu, you can then add theMindmap module, as shown in the following screenshot: This will activate the dialog to set up the name and settings for the Mindmap module for the course.
Read more
  • 0
  • 0
  • 1398

article-image-using-javascript-effects-joomla-15
Packt
03 Jun 2010
7 min read
Save for later

Using Javascript effects with Joomla! 1.5

Packt
03 Jun 2010
7 min read
(Read more interesting articles on Joomla! 1.5 here.) Using JavaScript effects Joomla! includes mootools—a powerful compact JavaScript framework. Mootools enables us to do many things, but it is used extensively in Joomla! to create client-side effects. Some of these, such as the accordion, are accessible through Joomla! classes. Others require special attention. In some instances it may be necessary to manually add the mootools library to the document. We can do this using the JHTML behavior.mootools type: JHTML::_('behavior.mootools'); JPane A pane is an XHTML area that holds more than one set of information. There are two different types of panes: Tabs: Tabs provides a typical tabbed area with tabs to the top that are used to select different panes. Sliders: Sliders, based on the mootools accordion, are vertical selections of headings above panels that can be expanded and contracted. We use the JPane class to implement panes. This example demonstrates a basic tabular pane with two panels: $pane =& JPane::getInstance('Tabs');echo $pane->startPane('myPane');{ echo $pane->startPanel('Panel 1', 'panel1'); echo "This is Panel 1"; echo $pane->endPanel(); echo $pane->startPanel('Panel 2', 'panel2'); echo "This is Panel 2"; echo $pane->endPanel();}echo $pane->endPane(); There are essentially two elements to a pane: the pane itself and the panels within the pane. We use the methods startPane() and endPane() to signify the start and end of the pane. When we use startPane() we must provide one string parameter, which is a unique identifier used to identify the pane. Panels are always created internally to a pane and use the methods startPanel() and endPanel(). We must provide the startPanel() method with two parameters, the name, which appears on the tab, and the panel ID. The following is a screenshot of the pane created from the previous code: Had we wanted to create a slider pane instead of a tab pane when we used the getInstance() method, we would need to have supplied the parameter Sliders instead of Tabs. This is a screenshot of the same pane as a slider: Panes are used extensively in Joomla! As a general rule, tabs are used for settings and sliders are used for parameters. Tooltips Tool tips are small boxes with useful information in them that appear in response to onmouseover events. They are used extensively in forms to provide more information about fields and their contents. Tooltips can be extremely helpful to users by providing small helpful hints such as what value should be put into a field or what is the purpose of a field. It takes a small amount of code to implement but adds a lot of value for our users. So how do we add a tooltip? We use JHTML to render tips easily. There are two types that we use: behavior.tooltip is used to import the necessary JavaScript to enable tooltips to work and it does not return anything. We only ever need to call this type once in a page. tooltip is used to render a tooltip in relation to an image or a piece of text. There are six parameters associated with tooltip, of which five are optional. We will explore the more common uses of these parameters. The most basic usage of tooltip returns a small information icon that onmouseover displays as a tooltip; as this example demonstrates: echo JHTML::_('tooltip', $tooltip); The next parameter allows us to define a title that is displayed at the top of the tooltip: echo JHTML::_('tooltip', $tooltip, $title); The next parameter allows us to select an image from the includes/js/ThemeOffice directory. This example uses the warning.png image: echo JHTML::_('tooltip', $tooltip, $title, 'warning.png'); The next obvious leap is to use text instead of an image and that is just what the next parameter allows us to do: echo JHTML::_('tooltip', $tooltip, $title, null, $text); There are some additional parameters that relate to using hypertext links. A full description of these is available in Appendix E, Joomla! HTML Library. We can modify the appearance of tooltips using CSS. There are three style classes that we can use: .tool-tip, .tool-title, and .tool-text. The tooltip is encapsulated by the .tool-tip class, and the .tool-title and .tool-text styles relate to the title and the content. This code demonstrates how we can add some CSS to the document to override the default tooltip CSS: // prepare the cSS$css = '/* Tooltips */.tool-tip{ min-width: 100px; opacity: 0.8; filter: alpha(opacity=80); -moz-opacity: 0.8;}.tool-title{ text-align: center;}.tool-text { font-style: italic;}';// add the CSS to the document$doc =& JFactory::getDocument();$doc->addStyleDeclaration($css); Let's add tooltips to our com_boxoffice/views/revue/tmpl/default.php layout file. The first step is to enable tooltips by adding behavior.tooltip to the beginning of our layout file as follows: <?php // No direct access defined('_JEXEC') or die('Restricted access'); // Enable tooltips JHTML::_('behavior.tooltip');?> This should be placed at the beginning as illustrated. This adds the mootool JavaScript class Tips to our document and adds the following JavaScript code to the document heading: <script type="text/javascript"> window.addEvent('domready', function(){ var JTooltips = new Tips($$('.hasTip'), { maxTitleChars: 50, fixed: false}); });</script> Next, we identify those elements that we wish to have a tooltip enabled for. There are two documented ways to implement a tooltip. We will create both for the movie title to illustrate: <tr> <td width="100" align="right" class="key"> <span class="editlinktip hasTip" title="::<?php echo JText::_('TIP_001');?>"> <label for="title"> <?php echo JText::_('Movie Title'); ?>: </label> </span> </td> <td> <input class="inputbox" type="text" name="title" id="title" size="25" value="<?php echo $this->revue->title;?>" /> <?php echo JHTML::_('tooltip', JText::_('TIP_001')); ?> </td></tr> The first approach wraps the label with a <span> that has two CSS classes declared editlinktip and hasTip, and a title attribute. The title attribute is a two part string with the parts separated by double colons; the first part is the tooltip title and the second is the tooltip text. Both methods will produce similar results. There are a few differences that you should keep in mind. The first approach displays the tip when you hover over the spanned element (in this case the label field). The second approach will generate a small icon next to the input field; the tip will appear when you move your mouse over the icon. You can duplicate the results of the first approach using the tooltip method with the following code: <?php $label = '<label for ="title">' . JText::_('Movie Title') . '</label>'echo JHTML::_('tooltip', JText::_('TIP_001'), '', '', $label);?> Note that the tip text is passed through JText with a key from our translation file. Here are the entries for our tips: # Tip TextTIP_001=Enter the film title.TIP_002=Choose the MPAA film rating.TIP_003=Provide a brief impression of the film.TIP_004=Enter the name of the reviewer.TIP_005=Enter 1-5 asterisks (*) for overall quality of the film.TIP_006=Enter the date of the review (mm/dd/yyyy).TIP_007=Do you wish to publish this revue? In the end the method you choose to implement tooltips is largely a personal preference.
Read more
  • 0
  • 0
  • 1812

article-image-easily-modifying-page-joomla-15
Packt
02 Jun 2010
17 min read
Save for later

Easily modifying a page with Joomla! 1.5

Packt
02 Jun 2010
17 min read
(Read more interesting articles on Joomla!1.5 here.) Application message queue You may have noticed that when we raise a notice or a warning, a bar appears across the top of the page containing the notice or warning message. These messages are part of the application message queue. The application message queue is a message stack that is displayed the next time the application renders an HTML view. This means that we can queue messages in one request but not show them until a later request. There are three core message types: message, notice, and error. The next screenshot depicts how each of the different types of application message is rendered: We use the application enqueueMessage() method to add a message to the queue. This example demonstrates how we would add all of the messages shown in the previous screenshot to the message queue: $mainframe->enqueueMessage('A message type message');$mainframe->enqueueMessage('A notice type message', 'notice');$mainframe->enqueueMessage('An error type message', 'error'); The first parameter is the message that we want to add and the second parameter is the message type; the default is message. It is uncommon to add notice or error messages this way; normally we will use JError::raiseNotice() and JError::raiseWarning() respectively. This means that we will, in most cases, use one parameter with the enqueueMessage() method. It is possible however, to add messages of our own custom types. This is an example of how we would add a message of type bespoke: $mainframe->enqueueMessage('A bespoke type message', 'bespoke'); Custom type messages will render in the same format as message type messages. Imagine we want to use the bespoke message type to render messages but not display them. This could be useful for debugging purposes. This example demonstrates how we can add a CSS Declaration to the document, using the methods described earlier to modify the way in which the bespoke messages are displayed: $css = '/* Bespoke Error Messages */#system-message dt.bespoke{display: none;}dl#system-message dd.bespoke ul{ color: #30A427; border-top: 3px solid #94CA8D; border-bottom: 3px solid #94CA8D; background: #C8DEC7 url(notice-bespoke.png) 4px 4px no-repeat;}';$doc =& JFactory::getDocument();$doc->addStyleDeclaration($css); Now when bespoke messages are rendered, they will appear like this: Redirecting the browser Redirection allows us to redirect the browser to a new location. Joomla! provides us with some easy ways in which to redirect the browser. Joomla! redirects are implemented using HTTP 301 redirect response codes. In the event that response headers have already been sent, JavaScript will be used to redirect the browser. The most common time to redirect a browser is after a form has been submitted. There are a number of reasons why we might want to do this, such as the following: Redirecting after form submission prevents forms from being submitted multiple times when the browser is refreshed We can redirect to different locations depending on the submitted data Redirecting to another view reduces the amount of development required for each task in the controller There are many scenarios where the use of a redirect is common. The following list identifies some of these: Canceling editing an existing item Copying items Creating new items and updating existing items Deleting items Publishing or unpublishing items Updating item ordering Imagine a user submits a form that is used to create a new record in a database table. The first thing we need to do when we receive a request of this type is to validate the form contents. This next data flow diagram describes the logic that we could implement: The No route passes the invalid input to the session. We do this so that when we redirect the user to the input form we can repopulate the form with the invalid input. If we do not do this the user will have to complete the entire form again. We may choose to omit the Pass invalid input to user session process as the core components do. It is normal to include JavaScript to validate forms before they are submitted, and since the majority of users will have JavaScript support enabled, this may be a good approach to use. Note that omitting this process is not the same as omitting form validation. We must never depend on JavaScript or other client-side mechanisms for data validation. A good approach is to initially develop forms without client-side validation while ensuring that we properly handle invalid data with server-side scripts. As a quick aside, a good way to validate form contents is to use a JTable subclass check() method. If we place failed input into the session, we might want to put it in its own namespace. This makes it easier to remove the data later and helps prevent naming conflicts. The next example demonstrates how we might add the field value of myField to the myForm session namespace: // get the session$session =& JFactory::getSession();// get the raw value of myField$myFieldValue = JRequest::getString('myField', '', 'POST', JREQUEST_ALLOWRAW);// add the value to the session namespace myForm$session->set('myField', $myFieldValue, 'myForm') When we come to display the form we can retrieve the data from the session using the get() method. Once we have retrieved the data we must remember to remove the data from the session, otherwise it will be displayed every time we view the form (unless we use another flag as an indicator). We can remove data items from the myForm namespace using the clear() method: // get the session$session =& JFactory::getSession();// Remove the myField$session->clear('myField', 'myForm'); The final thing we do in the No route is to redirect the user back to the input form. When we do this, we must add some messages to the application queue to explain to the user why the input has been rejected. The Yes route adds a new record to the database and then redirects the user to the newly created item. As with the No route, it is normal to queue a message that will say that the new item has been successfully saved, or something to that effect. There are essentially two ways to redirect. The first is to use the application redirect() method. It is unusual to use this mechanism unless we are developing a component without the use of the Joomla! MVC classes. This example demonstrates how we use the application method: $mainframe->redirect('index.php?option=com_boxoffice'); This will redirect the user's browser to index.php?option=com_boxoffice. There are two additional optional parameters that we can provide when using this method. These are used to queue a message. This example redirects us, as per the previous example, and queues a notice type message that will be displayed after the redirect has successfully completed: $mainframe->redirect('index.php?option=com_boxoffice','Some Message', 'notice'); The final parameter, the message type, defaults to message. The application redirect() method immediately queues the message, redirects the user's browser, and ends the application. The more common mechanism for implementing redirects is to use the JController setRedirect() method. We generally use this from within a controller method that handles a task, but because the method is public we can use it outside of the controller. This example, assuming we are within a JController subclass method, will set the controller redirect to index.php?option=com_boxoffice: $this->setRedirect('index.php?option=com_boxoffice'); As with the application redirect() method, there are two additional optional parameters that we can provide when using this method. These are used to queue a message. This example sets the controller redirect, as per the previous example, and queues a notice type message that will be displayed after the redirect has successfully completed: $this->setRedirect('index.php?option=com_boxoffice', 'Some Message','notice'); Unlike the application redirect() method, this method does not immediately queue the optional message, redirect the user's browser, and end the application.To do this we must use the JController redirect() method. It is normal, in components that use redirects, to execute the controller redirect() method after the controller has executed a given task. This is normally done in the root component file, as this example demonstrates: $controller = new BoxofficeController();$controller->execute(JRequest::getCmd('task'));$controller->redirect(); Component XML metadata files and menu parameters When we create menu items, if a component has a selection of views and layouts, we can choose which view and which layout we want to use. We can create an XML metadata file for each view and layout. In these files we can describe the view or layout and we can define extra parameters for the menu item specific to the specified layout. Our component frontend has a single view with two layouts: default.php and list.php. The next figure describes the folder structure we would expect to find in the views folder (for simplicity, only the files and folders that we are discussing are included in the figure): When an administrator creates a link to this view, the options displayed will not give any information beyond the names of the folders and files described above, as the next screenshot demonstrates: The first element of this list that we will customize is the view name, Revue. To do this we must create a file in the revue folder called metadata.xml. This example customizes the name and description of the revue view: ?xml version="1.0" encoding="utf-8"?><metadata> <view title="Movie Revues"> <message> <![CDATA[Movie Revues]]> </message> </view></metadata> Now if an administrator were to view the list of menu item types, Revue would be replaced with the text Movie Revues as defined in the view tag title attribute. The description, defined in the message tag, is displayed when the mouse cursor is over the view name. The next task is to customize the definitions of the layouts, default.php and list.php. Layout XML metadata files are located in the tmpl folder and are named the same as the corresponding layout template file. For example, the XML metadata file for default.php would be named default.xml. So we need to add the files default.xml and list.xml to the tmpl folder. Within a layout XML metadata file, there are two main tags in which we are interested: layout and state. Here is an example of a XML metadata file <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Individual Revue"> <message> <![CDATA[Individual movie revue.]]> </message> </layout> <state> <name>Individual Revue</name> <description>Individual movie revue.</description> </state></metadata> And here is the list.xml file: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> </state></metadata> At first glance it may seem odd that we appear to be duplicating information in the layout and state tags. However, the layout tag includes information that is displayed in the menu item type list (essentially an overview). The state tag includes information that is displayed during the creation of a menu item that uses the layout. There are occasions when a more detailed description is required when we come to define a menu item. For example, we may want to warn the user that they must fill in a specific menu parameter. We will discuss menu parameters in a moment. Assuming we created the default.xml and list.xml files as shown previously, our menu item type list would now appear as follows: Now that we know how to modify the names and descriptions of views and layouts, we can investigate how to define custom menu parameters. There are many different types of parameter that we can define. Before you continue, you might want to familiarize yourself with this list of parameter types because we will be using them in the examples. A complete description of these parameters is available in Appendix B, Parameters (Core Elements): category editors filelist folderlist helpsites hidden imagelist languages list menu menuitem password radio section spacer sql text textarea timezones Menu parameters can be considered as being grouped into several categories: System Component State URL Advanced The System parameters are predefined by Joomla! (held in the administrator/components/com_menus/models/metadata/component.xml file). These parameters are used to encourage standardization of some common component parameters. System parameters are shown under the heading Parameters (System); we cannot prevent these parameters from being displayed. The Component parameters are those parameters that are defined in the component's config.xml file. Note that changing these parameters when creating a new menu item only affects the menu item, not the entire component. In essence, this is a form of overriding. This form of overriding is not always desirable; it is possible to prevent the component parameters from being shown when creating or editing a menu item. To do this we add the attribute menu to the root tag (config) of the component config.xml file and set the value of the attribute to hide: The remaining parameter groups—State, URL, and Advanced—are defined on a per layout basis in the layout XML metadata files inside the state tag. These are the groups in which we are most interested. The State parameters are located in a tag called params. In this example, which builds on our list.xml file, we add two parameters: a text field named revue_heading and a radio option named show_heading: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> <params> <param type="radio" name="show_heading" label="Show Heading" description="Display heading above revues." default="0"> <option value="0">Hide</option> <option value="1">Show</option> </param> <param type="text" name="revue_heading" label="Revue Heading" description="Heading to display above the revues." default="Box Office Revues" /> </params> </state></metadata> When an administrator creates a new menu item for this layout, these two parameters will be displayed under the heading Parameters (Basic). The parameters are not presented under a State heading, because State and URL parameters are consolidated into one section. URL parameters always appear above State parameters. We define URL parameters in much the same way, only this time we place them in a tag named url. The URL parameters are automatically appended to the URI; this means that we can access these parameters using JRequest. These parameters are of particular use when we are creating a layout that is used to display a single item that is retrieved using a unique ID. If we use these parameters to define an ID that is retrieved from a table, we should consider using the often overlooked sql parameter type. The following example builds on the previous example, and adds the URL parameter id, which is extracted from the #__boxoffice_revues table: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> <url> <param type="sql" name="id" label="Revue:" description="Revue to display" query="SELECT id AS value, title AS id FROM #__boxoffice_revues" /> </url> <params> <param type="radio" name="show_heading" label="Show Heading" description="Display heading above revues." default="0"> <option value="0">Hide</option> <option value="1">Show</option> </param> <param type="text" name="revue_heading" label="Revue Heading" description="Heading to display above the revues." default="Box Office Revues" /> </params> </state></metadata> The query might be slightly confusing if you are not familiar with the sql parameter type. The query must return two fields, value and id. value specifies the value of the parameter and id specifies the identifier displayed in the drop-down box that is displayed when the parameter is rendered. When using the sql parameter type, if applicable, remember to include a WHERE clause to display only published or equivalent items. The Advanced parameters are specifically for defining parameters that are more complex than the State parameters. These parameters are defined in the advanced tag. This example adds an advanced parameter called advanced_setting: <?xml version="1.0" encoding="utf-8"?><metadata> <layout title="Revue List"> <message> <![CDATA[Summary list of revues.]]> </message> </layout> <state> <name>Revue List</name> <description>Summary list of revues.</description> <url> <param type="sql" name="id" label="Revue:" description="Revue to display" query="SELECT id AS value, title AS id FROM #__boxoffice_revues" /> </url> <params> <param type="radio" name="show_heading" label="Show Heading" description="Display heading above revues." default="0"> <option value="0">Hide</option> <option value="1">Show</option> </param> <param type="text" name="revue_heading" label="Revue Heading" description="Heading to display above the revues." default="Box Office Revues" /> </params> <advanced> <param type="radio" name="list_by_cat" label="List by Genre" description="List revues by genre." default="0"> <option value="0">No</option> <option value="1">Yes</option> </param> </advanced> </state></metadata> Advanced parameters will appear under the Parameters Advanced heading. Component parameters, Component Design—will appear under the Parameters (Component) heading. The resultant parameters area for this layout will appear as follows: All name and description elements from the XML metadata files will be translated into the currently selected locale language. When we save a menu item, all of the parameters, except URL parameters, are saved to the params field in the menu item record. This means that we can end up with naming conflicts between our parameters. We must ensure that we do not name any two parameters the same. This includes not using the predefined System parameter names. This list details the System parameter names: page_title show_page_title pageclass_sfx menu_image secure Once we have successfully created the necessary XML, we will be able to access the parameters from within our component using a JParameter object. This is described in the next section.
Read more
  • 0
  • 0
  • 1879

article-image-ajax-implementation-apex
Packt
01 Jun 2010
8 min read
Save for later

AJAX Implementation in APEX

Packt
01 Jun 2010
8 min read
(For more resources on Oracle, see here.) APEX introduced AJAX supports in version 2.0 (the product was called HTML DB back then). The support includes a dedicated AJAX framework that allows us to use AJAX in our APEX applications, and it covers both the client and the server sides. AJAX support on the client side The APEX built-in JavaScript library includes a special JavaScript file with the implementation of the AJAX client-side components. In earlier versions this file was called htmldb_get.js, and in APEX 3.1, it was changed to apex_get_3_1.js. In version 3.1, APEX also started to implement JavaScript namespace in the apex_ns_3_1.js file. Within the file, there is a definition to an apex.ajax namespace. I'm not mentioning the names of these files just for the sake of it. As the AJAX framework is not officially documented within the APEX documentation, these files can be very important and a useful source of information. By default, these files are automatically loaded into every application page as part of the #HEAD# substitution string in the Header section of the page template. This means that, by default, AJAX functionality is available to us on every page of our application, without taking any extra measures. The htmldb_Get object The APEX implementation of AJAX is based on the htmldb_Get object and as we'll see, creating a new instance of htmldb_Get is always the first step in performing an AJAX request. The htmldb_Get constructor function has seven parameters: function htmldb_Get(obj,flow,req,page,instance,proc,queryString) 1—obj The first parameter is a String that can be set to null, a name of a page item (DOM element), or an element ID. Setting this parameter to null will cause the result of the AJAX request to be assigned in a JavaScript variable. We should use this value every time we need to process the AJAX returned result, like in the cases where we return XML or JSON formatted data, or when we are relaying on the returned result, further in our JavaScript code flow. The APEX built-in JavaScript library defines, in the apex_builder.js file, (which is also loaded into every application page, just like apex_ get_3_1.js), a JavaScript global variable called gReturn. You can use this variable and assign it the AJAX returned result. Setting this parameter to the name (ID) of a page item will set the item value property with the result of the AJAX call. You should make sure that the result of the AJAX call matches the nature of the item value property. For example, if you are returning a text string into a text item it will work just fine. However, if you are returning an HTML snippet of code into the same item, you'll most likely not get the result you wanted. Setting this parameter to a DOM element ID, which is not an input item on the page, will set its innerHTML property to the result of the AJAX call. Injecting HTML code, using the innerHTML property, is a cross-browser issue. Moreover, we can't always set innerHTML along the DOM tree. To avoid potential problems, I strongly recommend that you use this option with <div> elements only. 2—flow This parameter represents the application ID. If we are calling htmldb_Get() from an external JavaScript file, this parameter should be set to $v('pFlowId') or its equivalent in version 3.1 or before ($x('pFlowId').value or html_GetElement('pFlowId').value ). This is also the default value, in case this parameter is left null. If we are calling htmldb_Get() as part of an inline JavaScript code we can use the Substitution String notation &APP_ID. (just to remind you that the trailing period is part of the syntax). Less common, but if you are using Oracle Web Toolkit to generate dynamic code (for dynamic content) that includes AJAX, you can also use the bind variable notation :APP_ID. (In this case, the period is just a punctuation mark.) 3—req This String parameter stands for the REQUEST value. Using the keyword APPLICATION_PROCESS with this parameter allows us to name an application level On Demand—PL/SQL Anonymous Block process that will be fired as part of the AJAX server-side processing. For example: 'APPLICATION_PROCESS=demo_code'. This parameter is case sensitive, and as a String, should be enclosed with quotes. If, as part of the AJAX call, we are not invoking an on-demand process, this parameter should be set to null (which is its default value). 4—page This parameter represents an application page ID. The APEX AJAX process allows us to invoke any application page, to run it in the background, on the server side, and then clip portions of the generated HTML code for this page into the AJAX calling page. In these cases, we should set this parameter to the page ID that we want to pull from. The default value of this parameter is 0 (this stands for page 0). However, this value can be problematic at times, especially when page 0 has not been defined on the application, or when there are inconsistencies between the Authorization scheme, or the page Authentication (such as Public and Required Authentication) of page 0 and the AJAX calling page. These inconsistencies can fail the execution of the AJAX process. In cases where you are not pulling information from another page, the safe bet is to set this parameter to the page ID of the AJAX calling page, using $v('pFlowStepId') or its equivalent for versions earlier than 3.1. In the case of an inline code, the &APP_PAGE_ID. Substitution String can also be used. Using the calling page ID as the default value for this parameter can be considered a "good practice" even for upcoming APEX versions, where implementation of page level on-demand process will probably be introduced. I hope you remember that as of version 3.2, we can only define on-demand processes on the application level. 5—instance This parameter represents the APEX session ID, and should almost always be left null (personally, I never encountered the need to set it otherwise). In this case, it will be populated with the result of $v('pInstance') or its earliest versions. 6—proc This String parameter allows us to invoke a stored or packaged procedure on the database as part of the AJAX process. The common behavior of the APEX AJAX framework is to use the application level On Demand PL/SQL Anonymous Block process as the logic of the AJAX server-side component. In this case, the on-demand process is named through the third parameter—req—using the keyword APPLICATION_PROCESS, and this parameter—proc—should be left null. The parameter will be populated with its default value of 'wwv_flow.show'(the single quotes are part of the syntax, as this is a String parameter). However, the APEX AJAX framework also allows us to invoke an external (to APEX) stored (or packaged) procedure as the logic of the AJAX server side. In this case, we can utilize an already existing logic in the database. Moreover, we can benefit from the "regular" advantages of stored procedures, such as a pre-complied code, for better performance, or the option to use wrapped PL/SQL packages, which can protect our business logic better (the APEX on-demand PL/SQL process can be accessed on the database level as clear text). The parameter should be formatted as a URL and can be in the form of a relative URL. In this case, the system will complete the relative URL into a full path URL based on the current window.location.href property. As with all stored or packaged procedures that we wish to use in our APEX application, the user (and in the case of using DAD, the APEX public user) should have the proper privileges on the stored procedure. In case the stored procedure, or the packaged procedure, doesn't have a public synonym defined for it then the procedure name should be qualified with the owner schema. For example, with inline code we can use: '#OWNER#.my_package.my_proc' For external code, you should retrieve the owner and make it available on the page (e.g. assign it to a JavaScript global variable) or define a public synonym for the owner schema and package. 7—queryString This parameter allows us to add parameters to the stored (packaged) procedure that we named in the previous parameter—proc. As we are ultimately dealing with constructing a URL, that will be POSTed to the server, this parameter should take the form of POST parameters in a query string—pairs of name=value, delimited by ampersand (&). Let's assume that my_proc has two parameters: p_arg1 and p_arg2. In this case, the queryString parameter should be set similar to the following: 'p_arg1=Hello&p_arg2=World' As we are talking about components of a URL, the values should be escaped so their code will be a legal URL. You can use the APEX built-in JavaScript function htmldb_Get_escape() to do that. If you are using the req parameter to invoke an APEX on-demand process with your AJAX call, the proc and queryString parameters should be left null. In this case, you can close the htmldb_Get() syntax right after the page parameter. If, on the other hand, you are invoking a stored (packaged) procedure, the req parameter should be set to null.
Read more
  • 0
  • 0
  • 4164

article-image-blogs-and-forums-using-plone-3
Packt
28 May 2010
11 min read
Save for later

Blogs and Forums using Plone 3

Packt
28 May 2010
11 min read
Blogs and forums have much to offer in a school setting. They help faculty and students communicate despite large class sizes. They engage students in conversations with each other. And they provide an easy way for instructors and staff members to build their personal reputations—and, thereby, the reputation of your institution. In this article, we consider how best to build blogs and forums in Plone. Along the way, we cite education-domain examples and point out tips for keeping your site stable and your users smiling. Plone's blogging potential Though Plone wasn't conceived as a blogging platform, its role as a full-fledged content management system gives it all the functionality of a blog and more. With a few well-placed tweaks, it can present an interface that puts users of other blogging packages right at home while letting you easily maintain ties between your blogs and the rest of your site. Generally speaking, blog entries are… Prominently labeled by date and organized in reverse chronological order Tagged by subject Followed by reader comments Syndicated using RSS or other protocols Plone provides all of these, with varying degrees of polish, out of the box: News items make good blog entries, and the built-in News portlet lists the most recent few, in reverse chronological order and with publication dates prominently shown. A more comprehensive, paginated list can easily be made using collections. Categories are a basic implementation of tags. Plone's built-in commenting can work on any content type, News Items included. Every collection has its own RSS feed. Add-on products: free as in puppies In addition to Plone's built-in tools, this article will explore the capabilities of several third-party add-ons. Open-source software is often called "free as in beer" or "free as in freedom". As typical of Plone add-ons, the products we will consider are both. However, they are also "free as in puppies". Who can resist puppies? They are heart-meltingly cute and loads of fun, but it's easy to forget, when their wet little noses are in your face, that they come with responsibility. Likewise, add-ons are free to install and use, but they also bring hidden costs: Products can hold you back. If you depend on one that doesn't support a new version of Plone, you'll face a choice between the product and the Plone upgrade. This situation is most likely at major version boundaries: for example, upgrading from Plone 3.x to Plone 4. Minor upgrades, as from Plone 3.2 to 3.3, should be fairly uneventful. (This was not always true with Plone 2.x, but release numbering has since gotten a dose of sanity.) One place products often fall short is uninstallation. It takes care to craft a quality uninstallation routine; low-quality or prerelease products sometimes fail to uninstall cleanly, leaving bits of themselves scattered throughout your site. They can even prevent your site from displaying any pages at all (often due to leaving remnants in portal_actions), and you may have to repair things by hand through the ZMI or, failing that, through an afternoon of fun with the Python debugger. The moral: even trying a product can be a risk. Test installation and uninstallation on a copy of your site before committing to one, and back up your Data.fs file before installing or uninstalling on production servers. Pace of work varies widely. Reporting a bug against an actively developed product might get you a new release within the week. Hitting a bug in an abandoned one could leave you fixing it yourself or paying someone else to. (Fortunately, there are scads of Plone consultants for hire in the #plone IRC channel and on the plone-users mailing list.) In addition to the above, products that add new content types (like blog entries, for instance) bring a risk of lock-in proportional to the amount of content you create with them. If a product is abandoned by its maintainer or you decide to stop using it for some other reason, you will need to migrate its content into some other type, either by writing custom scripts or by copying and pasting. These considerations are major drivers of this article's recommendations. For each of the top three Plone blogging strategies, we'll outline its capabilities, tick off its pros and cons, and estimate how high-maintenance a puppy it will be. Remember, even though puppies can be some work, a well-chosen and well-trained one becomes a best friend for life. News Items: blogging for the hurried or risk-averse Using news items as blog entries is, in true Extreme Programming style, "the simplest thing that could possibly work". Nonetheless, it's a surprisingly flexible practice and will disappoint only if you need features like pings, trackbacks, and remote editor integration. Here is an example front page of a Plone blog built using only news items, collections, and the built-in portlets: Structure of a news-item blog A blog in Plone can be as simple as a folder full of News Items, further organized into subfolders if necessary. Add a collection showing the most recent News Items to the top-level folder, and set it as its default page. As illustrated below, use an Item Type criterion for the collection to pull in the News Items, and use a Location criterion to exclude those created outside the blog folder: To provide pagination—recommended once the length of listings starts to noticeably impact download or render timetime—use the Limit Search Results option on the collection. One inconsistency is that only the Summary and Tabular Views on collections support pagination; Standard View (which shows the same information) does not. This means that Summary View, which sports a Read more link and is a bit more familiar to most blog users, is typically a good choice. Go easy on the pagination More items displayed per page is better. User tests on prototypes of gap.com's online store have suggested that, at least when selling shirts, more get sold when all are on one big page. Perhaps it's because users are faced with a louder mental "Continue or leave?" when they reach the end of a page. Regardless, it's something to consider when setting page size using a collection's Number of Items setting; you may want to try several different numbers and see how it affects the frequency with which your listing pages show up as "exit pages" in a web analytics package like AWStats. As a starting point, 50 is a sane choice, assuming your listings show only the title and description of each entry (as the built-in views do). The ideal number will be a trade-off between tempting visitors to leave with page breaks and keeping load and render times tolerable.   Finally, make sure to sort the entries by publication date. Set this up on the front-page collection's Criteria tab by selecting Effective Date and reversing the display order: As with all solutions in this article, a blog built on raw News Items can easily handle either single- or multi-author scenarios; just assign rights appropriately on the Sharing tab of the blog folder. News Item pros and cons Unadorned News Items are a great way to get started fast and confer practically zero upgrade risk, since they are maintained as part of Plone itself. However, be aware of these pointy edges you might bang into when using them as blog entries: With the built-in views, logged-out users can't see the authors or the publication dates of entries. Even logged-in users see only the modification dates unless they go digging through the workflow history. Categories applied to a News Item appear on its page, but clicking them takes you to a search for all items (both blog-related and otherwise) having that category. This could be a bug or a feature, depending on your situation. However, the ordering of the search results is unpredictable, and that is definitely unhelpful. The great thing about plain News Items is that there's a forward migration path. QuillsEnabled, which we'll explore later, can be layered atop an existing news-item-based blog with no migrations necessary and removed again if you decide to go back. Thus, a good strategy may be to start simple, with plain news items, and go after more features (and risk) as the need presents itself. Scrawl: a blog with a view One step up from plain News Items is Scrawl, a minimalist blog product that adds only two things: A custom Blog Entry type, which is actually just a copy of News Item. A purpose-built Blog view that can be applied to folders or collections, which are otherwise used just as with raw News Items. Here are both additions in action: Scrawl's Blog Entry isn't quite a verbatim copy of News Item; Scrawl makes a few tweaks: Commenting is turned on for new Blog Entries, without which authors would have to enable it manually each time. The chances of that happening are slim, since it's buried on the Edit → Settings tab, and users seldom stray from the default tab when editing. Blog Entry's default view is a slightly modified version of News Item's: it shows the author's name and the posting date even to unauthenticated users—and in a friendly "Posted by Fred Finster" format. It also adds a Permalink link, lest you forfeit crosslinks from users who know no other way of finding an entry's address. Calm your ringing phone by cloning types Using a custom content type for blog entries—even if it's just a copy of an existing one—has considerable advantages. For one, you can match contributors' vocabulary: assuming contributors think of part of your site as a blog (which they probably will if the word "blog" appears anywhere onscreen), they won't find it obvious to add "news items" there. Adding a "blog entry," on the other hand, lines up naturally with their expectations. This little trick, combined with judicious use of the Add new… → Restrictions… feature to pare down their options, will save hours of your time in training and support calls. A second advantage of a custom type is that it shows separately in Plone's advanced search. Visitors, like contributors, will identify better with the "blog entry" nomenclature. Plus, sometimes it's just plain handy to limit searches to only blogs. This type-cloning technique isn't limited to blog entries; you can clone and rename any content type: just visit portal_types in the ZMI, copy and paste a type, rename it, and edit its Title and Description fields. One commonly cloned type is File. Many contributors, even experts in noncomputer domains, aren't familiar with the word file. Cloning it to create PDF File, Word Document, and so on can go a long way toward making them comfortable using Plone.   Pros and cons of scrawl Scrawl's biggest risk is lock-in: since it uses its own Blog Entry content type to store your entries, uninstalling it leaves them inaccessible. However, because the Blog Entry type is really just the News Item type, a migration script is easy to write: # Turn all Blog Entries in a Plone site into News Items. # # Run by adding a "Script (Python)" in the ZMI (it doesn't matter where) and pasting this in. from Products.CMFCore.utils import getToolByName portal_catalog = getToolByName(context, 'portal_catalog') for brain in portal_catalog(portal_type='Blog Entry'): blog_entry = brain.getObject() # Get the actual blog entry from # the catalog entry. blog_entry.portal_type = 'News Item' # Update the catalog so searches see the new info: blog_entry.reindexObject() The reverse is also true: if you begin by using raw News Items and decide to switch to Scrawl, you'll need the reverse of the above script—just swap 'News Item' and 'Blog Entry'. If you have news items that shouldn't be converted to blog entries, your catalog query will have to be more specific, perhaps adding a path keyword argument, as in portal_catalog(portal_type='News Item', path='/my-plonesite/ blog-folder'). Aside from that, Scrawl is pretty risk-free. Its simplicity makes it unlikely to accumulate showstopping bugs or to break in future versions of Plone, and, if it does, you can always migrate back to news items or, if you have some programming skill, maintain it yourself—it's only 1,000 lines of code.
Read more
  • 0
  • 0
  • 30256

article-image-individual-learning-plan-ilp-moodle-19
Packt
28 May 2010
10 min read
Save for later

Individual Learning Plan (ILP) with Moodle 1.9

Packt
28 May 2010
10 min read
(For more resources on Moodle 1.9, see here.) The ILP module, once installed and activated, allows you to set some quite detailed targets within courses and to fine tune reports to and about students in order to better motivate them in their learning. This type of power means that there are quite a few options associated with the module and you will need to use the ones that are best suited to your needs. There is also the capability to tie the system in with your institution's own Student Information System (SIS) or Management Information System (MIS)) through a database abstraction layer. If you require this level of integration, you will need to discuss this with your network team or the company that provides your Moodle hosting service. In the UK, at least you can discuss this functionality with a Moodle partner that specializes in system integration with MIS. You can find out more about this at http://moodle.com/integration/. The installation process will install two modules: targets and reports, as well as a number of ILP related blocks for your courses such as Personal Learning Plan and Student Information. The modules and blocks that are installed as part of this package have a number of related settings associated with them, which will need to be adjusted at the site administration level. If you are the site administrator, you can do this; if not, you will need to ask the site admin to make the necessary changes. Module settings: Targets and Reports The basic settings required are to be able to set targets and view reports, though there are numerous levels and complexities to this activity. Again, you will need to adjust these as required. The settings are in the site administration panel. You will see two new icons for the ILP modules, as shown in the following screenshot, namely, Report and Target: Each of these new modules has a corresponding settings link. Report options The settings for the report allow you to determine what reports are visible to staff and students, as well as what can be shared between students. Set the visibility and information as required by your particular course or institution. The first block of settings relate to how the reports are viewed and whether or not students are made aware of any interactions on the part of tutors, as shown in the following screenshot: In this case, we are choosing to be able to see the status of each individual student and to send them messages when comments or concerns are posted. However, we have chosen not to show reports just within a course, as we are likely to teach students across the faculty. Therefore, it is more useful to get an overview of how they are working. The concerns we might highlight could be that a student has been missing key practical classes or has not attended their work placement. The second block of settings determines what types of reports you would like to see. It may be that you are only responsible for a certain aspect of a student's learning, in which case you may not enable all of the reporting functions. In this case, we are choosing to see all reports, as shown in the following screenshot. This may be the case if you are a personal tutor for some students and wish to get a detailed overview of their progress and activities, as well as be able to talk to them about any concerns raised by other staff. For example, a student to whom you are a personal tutor might express an interest in Product Design and therefore you might consult with colleagues in this subject area to set key targets for the student to achieve. These targets and achievements can be discussed with the students or with the students and their parents, to make sure that they are working towards their desired goals in technology. We can now save these settings in order to use all of these features on courses that we teach. Target options The settings for the Target module are similar—again the default for course-specific targets is disabled, which makes it easier to see student information across subjects. The main settings here, as shown in the following screenshot, relate to how messages are relayed to students about their targets. For example, there may be a modification to an exam board specification that makes a student's established target not such a high priority. If you are teaching students at a distance and do not see them regularly, then this would be a useful way to notify them of the changes. ILP blocks: Personal Learning Plan (PLP) The block element of ILP has several more settings that allow some customization of the block once initiated on your course page. It is shown under the add blocks menu as the Personal Learning Plan (PLP), showing that it is something that students have more ownership of as they can add targets and concerns themselves. Main options The default settings would be "No", but in this case, we would like the students to be able to see a complete range of information in relation to themselves and their courses in design technology. If the user guide link is set to 1, then it will show a link to the online guide for the module. This might be something to set up once everyone is comfortable with the use of the ILP. Student information block The final settings on the blocks page are for Student Info. The settings here allow you to customize messages and instructions for students in relation to the information they put in the PLP, such as information about themselves that only they or their teacher can see, or shared information that all other students will be able to see. The student can then use this space to fill in information about themselves, which will tie in with their targets and concerns and give a full picture of them for staff and even potential employers. The student's view of this becomes available through the course, though it will also link in through their profile. We will look at this in detail now. The following screenshot shows the student's view of the above settings when initiated: Once these settings under modules and blocks have been saved, staff can now create targets and modify reports, and students can get an overview of their work and learning, as we will see now. Creating targets The first task is to add some targets to your course for your students. The block will link to the area that displays the students so that you can see the targets, but the targets are added as activities. Switch on the edit function and choose a target for a section of your course where it is appropriate. This will be under the activities drop-down menu. The target requires a basic name and a summary of what it is for, as with all other activities. Once it is set, you can then make more specific targets for each student in the group by clicking on the target link from the front of the course. The following screenshot shows the target named Research Skills that we have created: Clicking on this link will open up a menu for all of your students. For each student, there is a link for targets and here you can add or modify targets for the students. Here you can see that a target has been set with a deadline of one month after it is set. You can add comments as it progresses, and the drop-down menu allows you to modify it so that it is either achieved (in which case when, or withdrawn as not achievable). The targets themselves can be general targets that need to be achieved across the range of the student's learning, or they can be tied specifically to a course by checking the Course related option checkbox, as shown in the following screenshot: You can also see that we have the option to tie it to courses that the student is taking. If you are a personal tutor, you can work across the subject range and apply a number of targets. All of these can have a specified deadline. You now need to allow students to see their plans. Accessing personal plans As a teacher, you need to switch on editing for your course. This makes the block visible on the bottom-right margin of your course (assuming that is where you added the block). Choose the Personal Learning Plan block. This will then be added to your course and can be moved to where it is most suited to your layout. The preceding screenshot is the view that you will see as a teacher and will allow you to see and comment on a student's targets and reports as needed, as well as export those reports. The students will have a more restricted view, as shown in the following screenshot: When students will click on the link My PLP, it will open the interface showing them their personal settings as well as any targets, concerns, or reports related to them. The more settings you have enabled on the admin section, the more they will see, so it is down to decide what information they can access. In this case, the student will be able to add some details about themselves for you and their class, but also see how they are faring in terms of targets. This can be used for tutorial sessions so that they can work on improving areas of perceived strengths or weaknesses. In terms of the targets that are set, they can interact with staff through comments so that a clear dialog can be established and hopefully issues can be picked up on as soon as possible. Once you hav e added various targets and worked with students through their concerns and those of other staff, you can then pull it all together through a report. The report can then be used to show their skills and aptitudes in their individual design areas and may show that they have a preference and an aptitude in one area such as resistant materials but not in food. This information can be used to provide clearer information for the students in the courses you design and the examples you use. Summary This article introduced you to a Personal Learning module which allows you and your students to set and evaluate targets and personal goals. This module will help your students reflect on their work and allow you to better guide them in their ideas and practices. Further resources on this subject: Moodle 1.9 Teaching Techniques [book] Moodle 1.9 Math [book] Moodle 1.9: Exploring Design Portfolios [article] Testing Students' Knowledge using Moodle Modules [article] Managing Student Work using Moodle: Part 1 [article] Managing Student Work using Moodle: Part 2 [article] Managing Student Work using Moodle: Part 3 [article]
Read more
  • 0
  • 0
  • 1929
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at $19.99/month. Cancel anytime
article-image-installing-and-configuring-joomla-local-and-remote-servers
Packt
27 May 2010
8 min read
Save for later

Installing and Configuring Joomla! on Local and Remote Servers

Packt
27 May 2010
8 min read
Like every other endeavor in life, there are two ways of installing Joomla!—the easy way and the difficult way. In order to do it the difficult way, you will need to set up your server by yourself before you proceed with the installation. You have the choice of environment to use for your new installation: you may install directly to a live server or you can set up a test environment on your local computer. Minimum system requirements A fully-operational web server (preferably Apache) is required to successfully install and use Joomla!. You also need a database (preferably MySQL) and the server-side scripting language PHP, together with specific modules for MySQL, XML, and Zlib functionality, which are activated within PHP amongst others. Following are the minimum versions of these server components that are required: Software Minimum requirement Recommended Latest options Website PHP 4.3.10 4.4.7 5.x.series http://php.net MySQL 3.23.x or above   5.x series http://dev.mysql.com/downloads/mysql/5.0.html Apache 1.3 or above   2.2 series http://httpd.apache.org Installation on a local computer There are a number of ways to set up a test environment on your own local computer. Most time-pressed developers will install and configure directly onto a live server, but there are good reasons for running your application first on a local development server: Developing your application locally allows you to work on it even if you are not connected to the Internet. The experience that you gain from getting your local server running on a simple installation like WampServer for a machine running Windows, or MAMP for a Mac, will make it easier for you to understand server processes and databases. This knowledge will certainly pay off as you get deeper into Joomla!. The Web is constantly scanned and archived by various search engines, and so will everything that you put on the Web. This information will be around for quite a bit of time and you certainly don't want Google to display your inevitable learning mistakes for the world to see. Installation on WampServer WampServer2 enables you to run Apache, MySQL, and PHP on Windows, and is available for free. You can download it from http://www.wampserver.com. The WampServer2 package comes with the following components already configured to work together: Apache 2.2.11 MySQL 5.1.30 PHP 5.2.8 There are similar packages that already include Joomla! (such as DeveloperSide and WDE). However, note that these may not always have the latest secure version of Joomla!. Therefore, it is better to use WampServer2 and load it with the Joomla! version of your choice. WampServer2 is self-installing. Just double-click on the icon after you've unpacked your zipped download and follow the installation instructions. This gets your development environment ready in just a few minutes. Now let the fun begin! Installing Joomla! 1.5 on localhost Installing Joomla! on localhost can be remarkably straightforward: Download the latest stable release of Joomla!, and unzip the discernible Joomla! 1.5 folder. You will need to use a tool such as WinZip for Windows (http://www.winzip.com) to perform this task. Another free alternative to WinZip is IZArc (http://www.izarc.org/). Locate the directory in which WampServer2 is installed on your computer. This will usually be the root of your computer's main directory (usually C:) and in a folder named wamp. Open it, locate the www folder, and copy your Joomla! 1.5 folder into it. Name the Joomla! folder as per your preference. In the unlikely scenario that you will be installing only one Joomla! test site on your local machine, you may—just for the sake of living to a ripe old age—name it Joomla. Navigate to your computer desktop taskbar tray, click on the WampServer icon, and select the Start All Services option (if this has not yet been selected). Then open your browser and navigate to http://localhost. This will display the main WampServer2 interface and you will see your project, Joomla, listed under Your Projects. However, because Joomla! needs a database to run, you must create the database for our project. Click on the phpMyAdmin link. This will display another interface, this time for phpMyAdmin. Enter the name of your new database in the Create new database field. For the simple reason that we shouldn't live a complicated life, we have given this database the same name (Joomla) as our project and our installation folder. We are now ready to install Joomla!. Joomla! has an automated installation script that automatically populates database tables. The installation script will set the base URL, connect Joomla! to the database, and create tables in the database. Navigate to http://localhost/Joomla and start your installation. You will be presented with a step-by-step guide to the installation in the later pages. Page 1: Choose Language This page asks what language you want to use for the installation. We select English as the language of choice. Click on the Next button to continue with your installation. Page 2: Pre-installation Check Checks are made by the installation script on server configuration. If any of these items are not supported (marked as No), then your system does not meet the minimum requirements for the installation of Joomla!, and you should take the appropriate actions in order to correct the errors. Failing to do so could lead to your Joomla! installation not functioning properly. You are not likely to face this problem on your local installation, and if you do, it can be quickly fixed. Page 3: License The License page is just a page of legalese that the developers of Joomla! really think you must read. It tells you the conditions for use of the free software and also spells out liabilities. Primarily, if the Joomla! installation makes your computer to explode or you start acting funny after you are done with the installation, the suppliers of Joomla! will accept no liability. After correcting any host-specific errors and reading the license, you will be directed to the Database Configuration page. Page 4: Database Configuration On the Database Configuration page, you specify the database where Joomla! will store and retrieve data. Select the type of database from the drop-down list. This will generally be mysql. Also, enter the hostname of the database server that Joomla! will be installed on. This may not necessarily be the same as your web server, so check with your hosting provider if you are not sure. In the present case, it will be localhost. Now enter the MySQL username, password, and database name that you wish to use with Joomla!. These must already exist for the database that you are going to use. We have already determined this when we created the data base. Here are the values for our present project: Host Name: localhost Username: root (unless you have changed it) Password: Leave blank (unless you added a password when you set up your database) Database Name: Joomla (or whatever you have called yours) Table Prefix: If you are installing more than one instance of Joomla! in a single database, then give one of them a prefix (such as jos2_), or else the second instance will not install. Otherwise, you may safely ignore this. Click on the Next button to continue. Page 5: FTP Configuration You can safely omit this step and go on to the next page. But if you do decide to carry out this step, do take notice of the following requirements: As explained on this Joomla! installation page, due to file system permission restrictions on Linux and other Unix systems (and PHP Safe Mode restrictions), an FTP layer is used to handle fi le system manipulation and to enable Joomla! installers. You may enter an FTP username and password with access to the Joomla! root directory. This will be the FTP account that handles all of the file system operations when Joomla! requires FTP access to complete a task. However, for security reasons, if the option is available, you are advised to create a separate FTP user account with access to the Joomla! installation only and not to the entire web server. Page 6: Main Configuration This is where you define your site's public identity. The descriptions of the fields are as follows: Site Name: Enter the name of your Joomla! site. Your E-mail: This will be the e-mail address of the website Super Administrator. Admin Password: Enter a new password and then confirm it, in the appropriate fields. Along with the username admin, this will be the password that you will use to login to the Administrator Control Panel at the end of the installation. Install Sample Data: It is strongly recommended that new Joomla! users install the default sample data. To do this, select this option and click on the button, before proceeding to the next stage. Page 7: Finish That's all! Your installation success screen will be displayed. Congratulations, you are now on your way to becoming a Joomla! Guru. Once the installation script has successfully been completed and you have removed the installation folder, you will be directed to the Joomla! Administration login page—if you want to immediately perform administrative functions on your new site. Otherwise, clicking on the Site icon will direct you to the front page of your site showing all of the sample data—if you have loaded it. That is the most of what you need to know about installing Joomla!.
Read more
  • 0
  • 0
  • 5294

article-image-moodle-19-exploring-design-portfolios
Packt
27 May 2010
9 min read
Save for later

Moodle 1.9: Exploring Design Portfolios

Packt
27 May 2010
9 min read
(For more resources on Moodle 1.9, see here.) Exploring the Exabis portfolio The Exabis portfolio is a third-party add-on that can be placed in your courses to allow students to store and organize their work and allow them to share it with others, for example, external verifiers. The code can be downloaded from the Modules and plugins section at the Moodle website (http://moodle.org/mod/data/view.php?d=13&rid=1142&filter=1). Once the code has been installed, the site administrator will need to check the settings of the block for all users. Site-wide settings The first job, for an administrator, is to make sure the settings meet the institution's needs. These settings are available on the administration panel. You may need your site administrator to adjust these for you if you do not have these permissions. The following screenshot shows the two options available: The settings will be determined by what version you have installed on your system, and in this case, the options relate to how the portfolio looks. The key feature of recent portfolios is the ability to create views that are customized web pages. Most students will be familiar with this activity through social networking sites. Installing the Exabis block into a course To use the Exabis block, you first need to enable editing within the course you are responsible for. To do this, you need to click on the Turn editing on button, as shown in the following screenshot: This will change the view of your course, and a block will now be visible on the right-hand column to add further blocks to your course. The Add button, as shown in the previous screenshot, is a drop-down list and will list all available blocks in alphabetical order. You need to scroll down until you find the Exabis E-Portfolio listing and then click to add this block. Once the block has been added to your course area, you can make some more localized adjustments. In the staff view, there are three options. However, the two lower options merely point to different tabs on the same menu as the MyPortfolio link. Once you open the portfolio, you can see the layout of the block and the functions that it supports, as shown in the following screenshot: The personal information tab The first tab allows students to build up some personal information so that they have a sort of limited resume or CV. Once students click on the Information tab, they will see one button (Edit), which will open an edit window to allow them to add some notes and details. The Categories tab After students have entered some basic information about themselves, they need to organize their material. This is achieved initially by establishing some categories under which the information they gather can be structured. In this example, using the Product Design course, the student may need to create categories for each section they are working with. In the UK, for example, this would be: Materials and Components, Design and Market Influence, and Process and Manufacture. By clicking on the Categories tab, there will, as with the Information tab, be an edit button visible. Clicking on this button will open a window to create the required categories, as shown in the following screenshot: By clicking on the New button, as shown in the previous screenshot, the category will be created and you will then have the choice to add sub-categories or new categories as required. The layout of this edit window is as shown in the following screenshot: These can be further broken down into sub-categories that match the course specification. The process is the same as creating categories, and with each new category created, an additional field appears to add sub-categories, as seen in the previous screenshot. The resulting structure could look similar to the following screenshot, where each part of the specification has a corresponding category and sub-category. These categories will now be available in drop-down menus for the students to add various resources, such as files and notes, as shown in the following screenshot: In the previous screenshot, you can see that students have a drop-down box under Categories, which lists categories and sub-categories for them to link their resources too. Building up the portfolio content Students can now build up their portfolio of evidence and can share this information, if they need to, with staff, other students, or external examiners. The information is organized through the main My Portfolio tab, as shown in the following screenshot: Under this tab, there are sub-tabs that allow the students to link to websites, upload files, and also make notes about some of the material they have gathered. Each of these can now be associated with a category or sub-category to give some clear definition to their research work. The following screenshot shows a student adding some files to a sub-category related to design: In the previous screenshot, students could attach a file which may be some notes they made on a factory visit that they have scanned. Gradually, they can start building up a detailed folder of information and links to other useful resources. The following screenshot shows the MyPortfolio view as a student builds up some of their reference material and notes. Each of the resources is clearly categorized and time stamped and the type of resources is easy to see. Creating views In the release under discussion here (version 3.2.3 release 168) there is a tab to create views. This is still under development and not fully functional, but may well be functional by the time you install it. Clicking on the Views tab will show a button to add a view. Clicking on the Add View button will open an edit window to allow the student to organize their views, as shown in the following screenshot: The views are quite basic at present, but will allow students to build up a portfolio of evidence in an easy and organized way. Sharing their work and thoughts If students would like to share some of their work with each other, then they can via the Views tab. This tab, on the latest version, has a link to allow sharing. Once students enable the sharing function by clicking on the Change link, they can then choose what type of sharing they require and with whom. In the case shown here, the student can elect to share his/her work externally by creating a link to his/her folder from an external or an internal link. The Internal Access option allows them to further specify who can see their portfolio. In this case, they can share it with all of the staff who teach them in the design and technology faculty, or just some of the staff. In this case, when the product design teacher logs in and checks for shared portfolios, they will see this student's work. Importing and exporting portfolios Increasingly with e-portfolios there is the need to be able to take the entire portfolio with the students to other places of study or work. With the Exabis system, there is the ability to export the student's work in a number of formats. The two formats, currently available are Shareable Content Object Reference Module (SCORM) and Extensible Markup Language (XML). Both of these are file structures used to import and export groups of files from web-based systems such as Moodle. The import facility in Exabis will import a SCORM file, which is usually in a zipped format. The options shown for Export/Import are shown in the following screenshot: In both cases shown here, the export will allow students to save their work as a ZIP file, and depending on how they have structured their portfolio, they will have a range of choices regarding what to include in the export. The following screenshot shows the options for a SCORM export. The student, as shown in the previous screenshot, has chosen to save his/her Product Development material in a SCORM file. Clicking on the Create SCORM-File button will open a download dialog window where the student can chose where on his/her computer to save the zipped file. An additional feature shown in the previous Export your portfolio screenshot is the ability to include Moodle assignments in the portfolio of evidence. This would be useful if students take the portfolio to a new job. Clicking on the Import from Moodle-Assignments link results in a screen where students can add their assignments, as shown in the following screenshot: Under the Action column shown in this screenshot, the student can click on the add this file link. Clicking this link will open the MyPortfolio:Add window and the student can link this assignment to a category. The resulting link will then appear in their MyPortfolio: Files view. The assignment itself will be a hyperlink, which will open the word-processed assignment when clicked. Opening the assignment link will create a full URL to where the assignment can be located so that external examiners or employers can also view the work. It allows additional notes to be added by the student, such as follow up comments, as shown in the following screenshot: The additional commentary shows how the student has used the portfolio to track their learning process and to reflect on their earlier work. The whole process is therefore contained in an organized structure that the student controls and can be modified as their greater understanding dictates. Future developments in Exabis As mentioned, the views in this portfolio are not yet fully developed, but the current version is very usable. In order to have more flexibility and functionality, it is necessary to install a more fully featured e-portfolio such as MyStuff, which we will investigate in the next section.
Read more
  • 0
  • 0
  • 3081

article-image-building-news-aggregating-site-joomla
Packt
26 May 2010
3 min read
Save for later

Building a News Aggregating Site in Joomla!

Packt
26 May 2010
3 min read
(For more resources on Joomla!, see here.) The completed news aggregation site will look similar to the example shown in the following screenshot: Build Weird Hap'nins Vaughan Pyre is a very ambitious webpreneur. What he really hopes for is a website that is completely self-maintaining, and on which he can place some Google AdSense blocks. Clicks from the visitors to his site will ensure that he makes lots of money. For this, he needs a site where the content updates regularly with fresh content so that visitors will keep coming back to click on some more Google ads. Vaughan's ultimate objective is to create several of these websites. Template The template chosen is Midnight by BuyHTTP, which is a template that fits the theme of this unique website. Extensions This is, surprisingly, a very simple site to build, and much of the requirements can be actually be achieved by using the native News Feeds component. However, the News Feeds component will only list the title links to the external feed items, whereas what Vaughan wants is that the feeds are pulled into the site as articles. Therefore, we will be using an automatic article generator component. There are several of such components on the Joomla! extensions site, but almost all of them are commercial. Vaughan is a skinflint and will not pay to buy any script, so what we are looking for is free component. That is why we have chosen the following: 4RSS—aggregates RSS feeds and creates articles from them JCron Scheduler—used for cron jobs management and scheduling to simulate cron jobs through the Joomla! frontend interface at preset intervals Indeed, were it not for the fact that Vaughan needs the content to automatically be updated, we needn't use any extension other than the 4RSS component. Other extensions The core module that will be used for this site is: Main Menu module—creates the primary navigation functionality for the site pages Sections and categories New sections and categories will need to be created so that incoming article feeds will be correctly routed according to their description. A new section will be created that we will call Feed. Under this section, we shall have three categories—Bad News, More Bad News, and Weird News. Create a new section We intend to create a section that will be named Feed. In order to do this, perform the following steps: Navigate to the Section Manager from the Control Panel, and then click on the New icon at the top right-hand side, in order to create a new section. On the next page, add the name of the section, and then save your changes. Create new categories To create a new category, perform the following steps: Navigate to the Category Manager page from the Control Panel. On the following page, create a new category in the same way as we created the new section. However, remember to set the Section to Feed.
Read more
  • 0
  • 0
  • 2981

article-image-plone-3-themes
Packt
26 May 2010
9 min read
Save for later

Plone 3 Themes

Packt
26 May 2010
9 min read
(For more resources on Plone, see here.) Plone's stock configuration delivers a great deal of concrete functionality: workflow, security, tagging, and more. However, the people whom you need to win over—like your boss and the public—often form their first impressions of your site based solely on visual design. Replacing the out-of-the-box look of Plone with one tailored to your organization is thus a very important task. Changing the overall look of a Plone site requires more than just the web designer's usual toolkit of HTML and CSS. In this article, we provide an introduction to the additional Zope- and Plone-specific techniques you need. We give an overview of Plone's somewhat complicated theming situation, show how to theme a site in a portable, reusable way, and demonstrate practices that strike a balance among ease, speed, and compatibility with future versions of Plone. Theming is a complex topic, and there are entire books on that topic alone, so we also give plenty of outside references in case your needs extend beyond the basic. An overview of Plone theming Plone themes, also known as skins, are visual designs that can be applied to a site, independent of its content. There are two main ways to create a theme: through the web and via the filesystem. Through-the-web versus filesystem One of the great advantages of Zope (and thus Plone) has historically been the customization power available through its web-based interface. Though there are some holes in this functionality with Plone 3 and 4, you can, for the most part, still point and click your way to a working theme. The advantages of this approach are: Immediate feedback. Iterations are simple. As a result, you're encouraged to test often, bugs turn up early, and bugs caught early are bugs solved easily. Explorability. Though the Zope Management Interface, where most theme work takes place, isn't the best-organized or friendliest environment in the world, it at least offers some semblance of navigable structure. You can find a piece of HTML or CSS you want to customize, click a button, and begin editing. There's less need to think abstractly. Accessibility. Through-the-web theming requires no access to the server's filesystem, so it is usable by people without, for example, Unix command-line experience or the ability to restart Zope. The alternative is theming by developing add-on products, which live on the server's filesystem. The advantages of this are: Better tools. Expressing a theme as files and folders lets you use the entire ecosystem of filesystem-based development tools: proper text editors and version control systems, for example. Ease of re-use. Encapsulating a theme as a product means you can easily make use of it on more than one site, copy it from machine to machine, or share it with the world. Completeness. Some customizations can't yet be done through the Web: for example, moving the search box from the top of the page to the bottom by moving its viewlet into a different viewlet manager. In practice, a filesystem product is usually better, with through-the-web styling used to test changes and to make emergency in-production tweaks between Zope restarts. A load of languages Theming involves several special-purpose languages. Here's the rundown: Language Use in Theming HTML The old standby, Hypertext Markup Language defines the semantic structure of every page. Plone's markup sticks admirably to specifying meaning and avoids visual design. For example, its navigation bars are <ul>s, and its portlets (those omnipresent titled sidebars) are actually definition lists (<dl>s) with the title as the term and the content as the definition. Visual styling is applied almost wholly by CSS. CSS Cascading Stylesheets, another standard tool in the web designer's kit, apply a layer of visual design atop HTML. Because Plone's HTML so assiduously avoids visual design, we can change the look of a Plone site substantially without tampering with markup. TAL Most theming can be done with just CSS, but sometimes, like when adding new element to a page, only HTML changes will do. All HTML in Plone is produced by Template Attribute Language (TAL), a simple XML-based language so named because it nestles entirely within the attributes of XML tags. Like other templating languages, TAL is a more readable alternative to littering program code with bits of hard-coded markup. It is good for inserting content into a page skeleton, repeating portions of a page, and doing other simple presentation logic. More complicated logic is best done in Python modules, where you aren't limited to cramped one-liners. A good introduction to TAL is http://docs.zope.org/zope2/zope2book/ZPT.html. METAL The Macro Expansion for TAL (METAL) language helps combine bits of TAL from different templates to create a single page. http://docs.zope.org/zope2/zope2book/ZPT.html#macros is a good introduction. Python The general-purpose language Zope and Plone are written in. We will write almost no Python in this article, but it often does make an appearance in page templates. It has a much more prominent role in Zope 3-style theming than in Zope 2. ZCML Some parts of theming use the Zope 3 component architecture, a scheme for tying plugins and customizations into a large system like Plone. The Zope Component Markup Language (ZCML) is an XML-based language that specifies where to plug these in. For example, we will use ZCML to tie our theme product to a third-party package that drastically simplifies overriding some templates. GenericSetup XML A variety of XML mini-languages, which show up in your product's profiles folder. These are run by GenericSetup, Plone's installation framework, when your theme product is installed or uninstalled. Don't let theming hold you up Theming is complicated and can be time-consuming the first time through. Don't make the common mistake of letting it hold up work on the rest of your site. Indeed, most information-oriented work—audience analysis, the creation and input of content, information architecture decisions, and development of custom content types—can go on without much thought toward the coat of paint that will eventually go over it. (Likewise, you can change the look of your site later without having to redo all your navigation and content.) The few elements to decide on ahead of time are… Navigation. What is your navigation strategy? Should the theme provide space for main or contextual navigation or for a search field? It can help to have your graphic designer join you for the last few minutes of each information architecture discussion to synchronize expectations. Drawing wireframes is another fast way to get everybody on the same page. For an excellent primer on strategies for organizing your site's content, see Peter Morville's Information Architecture for the World Wide Web. CSS styles. The style menu in Plone's built-in editor is commonly customized to suit the semantic needs of the site at hand. Decide early in the design process what styles will be needed: for example, body text, warning messages, sidebars containing supplementary material, and various levels of headings. It's not necessary to settle on a look for these styles—just to enumerate them and establish their CSS class names. After that, theme and content work can progress in parallel. Prepare your development environment Before we get down the business of creating a theme, make sure you have all the tools and settings in place: Run Zope in foreground mode. When developing, always launch Zope using bin/instance fg rather than bin/instance start. At the cost of a little processor power, this greatly speeds development by… Puting Zope into debug mode. This means it will notice certain changes to the product we're developing without needing to be constantly restarted. In Plone 3.3 and above, this automatically turns on the CSS and JavaScript debug modes as well (explained below). Printing error messages, usually hidden in the event.log file, to the terminal. Plone typically makes a lot of noise when it starts up; that can be ignored. But watch for errors, hidden among the innocuous INFO and DEBUG messages, when you exercise the functionality of your product. Turn on CSS debug mode. With Plone 3.3 or above, you can skip this step, as it's implicitly done when you run Zope in foreground mode. In older versions of Plone, go into the ZMI, then to your Plone site, and finally to portal_css. There, turn on Debug/development mode. This will keep Plone from doing its clever caching, merging, and compression of stylesheets while you're developing them, helping ensure that you always see the latest version of your work. Without CSS debug mode, your CSS changes will take effect only when Zope is restarted. Get Firefox, Firebug, and the Web Developer add-on. Firefox is a nice browser, but what really makes it shine is its third-party plugins. Get the latest version, available from http://www.getfirefox.com/, then grab two vital plugins, Firebug (http://getfirebug.com/) and Web Developer (https://addons.mozilla.org/firefox/addon/60). Turn off caching. In Firefox, show the Web Developer Toolbar (View ? Toolbars ? Web Developer Toolbar), then pull down its Disable menu and select Disable Cache. Together with enabling CSS debug mode, this will ensure that you always see your latest CSS changes. Nothing is more frustrating than spending hours chasing a problem, only to track it down to a stale cache. If you use Firefox for casual browsing, you may not wish to disable caching globally and slow down your surfing. In that case, be sure to use Shift+Command+R (on the Mac) or Shift+Ctrl+R (on other platforms) to force your stylesheets to reload when doing theme work. Begin your theme On-disk theme products can be quite verbose, so we employ a program to generate the skeleton of ours. We'll then make a few clean-ups before moving on to making a visual impact. Install paster and ZopeSkel To generate the empty shell of a theme, we'll use a code generation tool called paster. A set of Zope- and Plone-specific code snippets, called ZopeSkel, extends paster to provide a sort of "madlibs for Plone", churning out skeletal products whose blanks we can fill in. Here's how to get a copy of paster up and running: Some installations of Plone come with paster and ZopeSkel; check the bin folder in your buildout. If paster is in there, you're done; skip to the next section. If not, read on. Install easy_install, a simple Python installer, which we can use to install paster and ZopeSkel. Follow the platform-specific instructions on the easy_install download page: http://pypi.python.org/ pypi/setuptools. Use easy_install to install ZopeSkel, which also automatically installs paster. For example: easy_install ZopeSkel
Read more
  • 0
  • 0
  • 2195
article-image-creating-installing-and-tweaking-your-theme-using-plone-3
Packt
26 May 2010
12 min read
Save for later

Creating, Installing and Tweaking your theme using Plone 3

Packt
26 May 2010
12 min read
(For more resources on Plone here.) We will first inspect a few structural changes and install them, and then finally examine the various components and skin layer items that have been changed, one at a time. Where restarting Zope or rerunning your buildout would be required, this will be noted. About the theme This theme and its design are available for personal and professional use to anyone, and can be freely modified. You can (and should) download the files from https://svn.plone.org/svn/collective/plonetheme.guria/trunk using the following command: svn co https://svn.plone.org/svn/collective/plonetheme.guria/trunk plonetheme.guria Note the space between the words trunk and plonetheme.guria. This theme is intended for installation on Plone 3 web sites. The finished theme should look like the following, but we have work to do to make this happen: This theme was created by me, for use by a charity group in India, called Guria (http://www.guriaindia.org), dedicated to ending human trafficking and prostitution. The finished site is currently in development, and is generously hosted free of charge by the talented folks at Six Feet Up (sixfeetup.com). Additionally, most of the code and lessons learned come courtesy of similar themes created by the staff at ONE/Northwest in Seattle, Washington. The design for this theme was created with the assumption that most of the tasks would need to be present in this theme. In fact, the only task not covered here is the creation of a new viewlet manager. Creation of viewlet managers is discussed at http://plone.org/documentation/how-to/adding-portlet-managers and http://plone.org/documentation/manual/theme-reference/elements/viewletmanager/override. Creating a theme product I created a theme product named plonetheme.guria, using the command line syntax paster create –t plone3_theme, while we were located in the src/ directory of our buildout, as seen next: [bash: /opt/mybuildout/src] paster create -t plone3_theme plonetheme.guriaSelected and implied templates: ZopeSkel#basic_namespace A project with a namespace package ZopeSkel#plone A Plone project ZopeSkel#plone3_theme A Theme for Plone 3.0Variables: egg: plonetheme.guria package: plonethemeguria project: plonetheme.guriaEnter namespace_package (Namespace package (like plonetheme)) ['plonetheme']:Enter package (The package contained namespace package (like example)) ['example']: guriaEnter skinname (The skin selection to be added to 'portal_skins' (like 'My Theme')) ['']: Guria Theme for the Plone Theming BookEnter skinbase (Name of the skin selection from which the new one will be copied) ['Plone Default']:Enter empty_styles (Override default public stylesheets with empty ones?) [True]: FalseEnter include_doc (Include in-line documentation in generated code?) [False]:Enter zope2product (Are you creating a Zope 2 Product?) [True]:Enter version (Version) ['0.1']:Enter description (One-line description of the package) ['An installable theme for Plone 3.0']:Enter long_description (Multi-line description (in reST)) ['']:Enter author (Author name) ['Plone Collective']: Veda WilliamsEnter author_email (Author email) ['product-developers@lists. plone.org']: email@email.comEnter keywords (Space-separated keywords/tags) ['web zope plone theme']:Enter url (URL of homepage) ['http://svn.plone.org/svn/collective/']:Enter license_name (License name) ['GPL']:Enter zip_safe (True/False: if the package can be distributed as a .zip file) [False]:Creating template basic_namespaceCreating directory ./plonetheme.guria[snip] You may wish to generate a new Plone theme product yourself, so that you can compare and contrast the differences between the Guria theme and a vanilla Plone theme. Notice that the full name of the theme is plonetheme.guria, and where an item shows as blank, it defaults to the example value in that step. In other words, the namespace package defaults to plonetheme, because there was no reason to change it. The skinname is set to a single lowercase word out of stylistic preference. It's important to also note that you should not use hyphens or spaces in your theme names, as they will not be recognized by your buildout. We've chosen not to override Plone's default stylesheets, and instead, we want to build on top of Plone's default (and excellent!) stylesheets. I prefer this method mostly because the layout needed for Plone's Contents view and other complex structural pieces are already taken care of by Plone's base stylesheets. It's easier than trying to rebuild those from scratch every time, but this is merely a personal preference. Following the creation of the theme, we register the theme product in our buildout.cfg, using the following syntax [buildout] ...develop = src/plonetheme.guria...[instance]eggs = plonetheme.guria...zcml = plonetheme.guria... If we were using the eggtractor egg, there would be no need to add these lines of code to our buildout.cfg; all we would need to do is rebuild our buildout and it would automatically recognize the new egg. eggtractor can be found at http://pypi.python.org/pypi/buildout.eggtractor, and is documented thoroughly. Assuming we are not using eggtractor, we must rebuild our buildout, as we have altered ZCML code and added a new egg: [bash: /opt/mybuildout/src/] ./bin/buildout This would be a good time to check your vanilla theme product into Subversion, so that you can track back to the original version, if needed. However, since this is an existing theme, there is no need to do so. For the purposes of following along, it might be best if you do not yet install the theme. We want to make some changes first. However, we will point out some caveats along the way, in case you installed the theme prematurely. Altering the theme product's structure Several modifications have been made to the theme product's structure to shorten folder names and change the default behavior. Again, this is mostly a personal preference. Let's take a look at these changes and how they were achieved. Renaming the theme In our theme product, you will see a file named profiles.zcml, located at mybuildout/src/plonetheme.guria/plonetheme/guria/profiles.zcml. The code looks like this: <configure i18n_domain="plonetheme.guria"> <genericsetup:registerProfile name="default" title="Guria Theme for the Plone Theming Book" directory="profiles/default" description='Extension profile for the "Guria Theme for the Plone Theming Book" Plone theme.' provides="Products.GenericSetup.interfaces.EXTENSION" /></configure> If you named your theme in a way that was less descriptive, you could alter the title. Naming your theme product properly is important, because you may have different types of products used for a given web site—for example, a policy product for content that might be used in tandem with your theme product. This text is what you see in the portal_quickinstaller at http://localhost:8080/mysite/portal_quickinstaller/manage_installProductsForm, where mysite is the name of your Plone site. You can also see this name if you install your theme product via Site Setup Add-on Products|, found at http://localhost:8080/mysite/prefs_install_products_form. If you change your XML here, and your theme product is already installed, you'll need to start (or restart) your Zope instance, using: [bash: /opt/mybuildout] ./bin/instance fg Shortening folder names Next, we look at the folder structure of our theme product. The standard Plone 3 theme produces folders with names like plonetheme_guria_custom_images, plonetheme_guria_custom_templates, and plonetheme_guria_styles. While there is nothing wrong with keeping this structure, it can be cumbersome to type or tab through (especially when checking items into Subversion). However, you might want to keep the existing folder names to help you distinguish which items of base Plone you modified. This can make migrations easier. If you choose this route, you probably want to create additional folders for non-base-Plone items. I personally prefer the shorter folder names and don't worry too much about the migration issues. In the case of this theme product, I opted to make the folder names shorter. First, I altered the names of the folders in the skins/ folder to guria_images, guria_styles, and guria_templates. Then, in the theme, go to mybuildout/plonetheme.guria/plonetheme/guria/skins.zcml. The code in this file is altered to appear as follows: <configure i18n_domain="plonetheme.guria"> <!-- File System Directory Views registration --> <cmf:registerDirectory name="guria_images"/> <cmf:registerDirectory name="guria_templates"/> <cmf:registerDirectory name="guria_styles"/></configure> One more step is required here. In plonetheme.guria/plonetheme/guria/profiles/default/skins.xml, the code is changed to read as follows: <?xml version="1.0"?><object name="portal_skins" allow_any="False" cookie_persistence="False" default_skin=" Guria Theme for the Plone Theming Book "> <object name="guria_images" meta_type="Filesystem Directory View" directory="plonetheme.guria:skins/guria_images"/> <object name="guria_templates" meta_type="Filesystem Directory View" directory="plonetheme.guria:skins/guria_templates"/> <object name="guria_styles" meta_type="Filesystem Directory View" directory="plonetheme.guria:skins/guria_styles"/> <skin-path name=" Guria Theme for the Plone Theming Book " based- on="Plone Default"> <layer name="guria_images" insert-after="custom"/> <layer name="guria_templates" insert-after="guria_images"/> <layer name="guria_styles" insert-after="guria_templates"/> </skin-path></object> Basically, the steps are the following:   Rename the folders on the filesystem. Modify the skins.zcml file to change the name of the filesystem directory view (what you see in the portal_skins/properties area of the ZMI). Modify the skins.xml file in the profiles/default folder to match. This alters the basic profile of your theme product. If you wanted to add additional folders and filesystem directory views here (a scripts/ folder, for example), you'd just add code by following the conventions given to you in these files and then create additional folders. Making changes to the ZCML file means that you would need to do a restart of your Zope instance. If you installed your theme product before making the changes to the skin layer names, you might want to inspect the skin layers at http://localhost:8080/mysite/ portal_skins/manage_propertiesForm, to make sure that the correct skin layers are listed. You might even need to reimport the "skins tool" step via portal_setup at http://localhost:8080/mysite/portal_setup/manage_importSteps. Make sure you choose the correct profile first by choosing your theme product's name from the drop-down list at the top of the import page. The theme product's name is the same name as you find in your profiles.zcml file. Adjusting how stylesheets and images are used Next, we remove some of the default behavior given to us by the plone3_theme recipe. In a vanilla theme product, folders named images/ and stylesheets/ are inserted into the plonetheme.guria/plonetheme/guria/browser/ directory. Additionally, a file named main.css is included in the stylesheets/ directory. I chose not to place the theme's images or stylesheets in the browser/ directory, as this is generally unnecessary for most themes. Advanced programmers may wish to expose these items to the browser layer, but this is generally a personal choice and carries with it additional consequences. I deleted the folders mentioned above, as well as the i file. Then, I opened the file named configure.zcml, located at plonetheme.guria/plonetheme/guria/browser/, and removed all of the following boilerplate text: <!-- Viewlets registration --> <!-- Zope 3 browser resources --> <!-- Resource directory for images --> <browser:resourceDirectory name="plonetheme.guria.images" directory="images" layer=".interfaces.IThemeSpecific" /> <!-- Resource directory for stylesheets --> <browser:resourceDirectory name="plonetheme.guria.stylesheets" directory="stylesheets" layer=".interfaces.IThemeSpecific" /> I then removed the highlighted code below fromI then removed the highlighted code below from plonetheme.guria/plonetheme/guria/profiles/default/cssregistry.xml:: <stylesheet title="" id="++resource++plonetheme.guria.stylesheets/main.css" media="screen" rel="stylesheet" rendering="import" cacheable="True" compression="safe" cookable="True" enabled="1" expression=""/> And replaced it with the following: <stylesheet title="" id="guria.css" media="screen" rel="stylesheet" rendering="import" cacheable="True" compression="safe" cookable="True" enabled="1" expression=""/> This, in effect, tells our theme product that we will be using a stylesheet named guria.css (or more correctly, guria.css.dtml, as we'll see in a moment). This stylesheet does not yet exist, so we have to create it. I wanted the option of making use of the DTML behavior provided by Plone, so that I could use certain base properties provided to us via the base_properties.props file (also located in our skins/guria_styles/ folder). DTML essentially allows us to use property-sheet variables and apply changes on a more global scale. The easiest way to create this new stylesheet is to go to your mybuildout/buildout-cache/eggs/Plone[some version number]/Products/CMFPlone/skins/plone_styles/ploneCustom.css and copy the contents of that file into a new stylesheet (named guria.css.dtml) in your theme's guria_styles/ folder (located in the skins/ directory at mybuildout/plonetheme.guria/plonetheme/guria/skins/guria_styles). The important bits of code you want are as follows: /* <dtml-with base_properties> (do not remove this :) *//* <dtml-call "REQUEST.set('portal_url', portal_url())"> (not this either :) *//* DELETE THIS LINE AND PUT YOUR CUSTOM STUFF HERE */ /* </dtml-with> */ Again, we would need to restart our Zope at this point, as we have modified our ZCML. If we had already installed our theme product, we'd also have to import our cssregistry.xml file via portal_setup in the ZMI, to capture the new GenericSetup profile settings. However, we have not yet installed the product, so we do not need to worry about this.
Read more
  • 0
  • 0
  • 4702

article-image-scaling-your-application-across-nodes-spring-pythons-remoting
Packt
24 May 2010
5 min read
Save for later

Scaling your Application Across Nodes with Spring Python's Remoting

Packt
24 May 2010
5 min read
(For more resources on Spring, see here.) With the explosion of the Internet into e-commerce in recent years, companies are under pressure to support lots of simultaneous customers. With users wanting richer interfaces that perform more business functions, this constantly leads to a need for more computing power than ever before, regardless of being web-based or thick-client. Seeing the slowdown of growth in total CPU horsepower, people are looking to multi-core CPUs, 64-bit chips, or at adding more servers to their enterprise in order to meet their growing needs. Developers face the challenge of designing applications in the simple environment of a desktop scaled back for cost savings. Then they must be able to deploy into multi-core, multi-server environments in order to meet their companies business demands. Different technologies have been developed in order to support this. Different protocols have been drafted to help communicate between nodes. The debate rages on whether talking across the network should be visible in the API or abstracted away. Different technologies to support remotely connecting client process with server processes is under constant development. Introduction to Pyro (Python Remote Objects) Pyro is an open source project (pyro.sourceforge.net) that provides an object oriented form of RPC. As stated on the project's site, it resembles Java's Remote Method Invocation (RMI). It is less similar to CORBA (http://www.corba.org), a technology-neutral wire protocol used to link multiple processes together, because it doesn't require an interface definition language, nor is oriented towards linking different languages together. Pyro supports Python-to-Python communications. Thanks to the power of Jython, it is easy to link Java-to-Python, and vice versa. Python Remote Objects is not to be confused with the Python Robotics open source project (also named Pyro). Pyro is very easy to use out of the box with existing Python applications. The ability to publish services isn't hard to add to existing applications. Pyro uses its own protocol for RPC communication. Fundamentally, a Pyro-based application involves launching a Pyro daemon thread and then registering your server component with this thread. From that point on, the thread along with your server code is in stand-by mode, waiting to process client calls. The next step involves creating a Pyro client proxy that is configured to find the daemon thread, and then forward client calls to the server. From a high level perspective, this is very similar to what Java RMI and CORBA offer. However, thanks to the dynamic nature of Python, the configuration steps are much easier, and there are no requirements to extend any classes or implement any interfaces.. As simple as it is to use Pyro, there is still the requirement to write some minimal code to instantiate your objects and then register them. You must also code up the clients, making them aware of Pyro as well. Since the intent of this article is to dive into using Spring Python, we will skip writing a pure Pyro application. Instead, let's see how to use Spring Python's out-of-the-box Pyro-based components, eliminating the need to write any Pyro glue code. This lets us delegate everything to our IoC container so that it can do all the integration steps by itself. This reduces the cost of making our application distributed to zero. Converting a simple application into a distributed one on the same machine For this example, let's develop a simple service that processes some data and produces a response. Then, we'll convert it to a distributed service. First, let's create a simple service. For this example, let's create one that returns us an array of strings representing the Happy Birthday song with someone's name embedded in it. class Service(object): def happy_birthday(self, name): results = [] for i in range(4): if i == 2: results.append("Happy Birthday Dear %s!" % name) else: results.append("Happy Birthday to you!") return results Our service isn't too elaborate. Instead of printing the data directly to screen, it collects it together and returns it to the caller. This allows us the caller to print it, test it, store it, or do whatever it wants with the result. In the following screen text, we see a simple client taking the results and printing them a little formatting inside the Python shell. As we can see, we have defined a simple service, and can call it directly. In our case, we are simply joining the list together with a newline character, and printing it to the screen. Fetching the service from an IoC container from springpython.config import *from simple_service import *class HappyBirthdayContext(PythonConfig): def __init__(self): PythonConfig.__init__(self) @Object def service(self): return Service() Creating a client to call the service Now let's write a client script that will create an instance of this IoC container, fetch the service, and use it. from springpython.context import *from simple_service_ctx import *if __name__ == "__main__": ctx = ApplicationContext(HappyBirthdayContext()) s = ctx.get_object("service") print "n".join(s.happy_birthday("Greg")) Running this client script neatly creates an instance of our IoC container, fetches the service, and calls it with the same arguments shown earlier.
Read more
  • 0
  • 0
  • 7701

article-image-easily-writing-sql-queries-spring-python
Packt
24 May 2010
9 min read
Save for later

Easily Writing SQL Queries with Spring Python

Packt
24 May 2010
9 min read
(For more resources on Spring, see here.) Many of our applications contain dynamic data that needs to be pulled from and stored within a relational database. Even though key/value based data stores exist, a huge majority of data stores in production are housed in a SQL-based relational database. Given this de facto requirement, it improves developer efficiency if we can focus on the SQL queries themselves, and not spend lots of time writing plumbing code and making every query fault tolerant. The classic SQL issue SQL is a long existing standard that shares a common paradigm for writing queries with many modern programming languages (including Python). The resulting effect is that coding queries by hand is laborious. Let's explore this dilemma by writing a simple SQL query using Python's database API. SQL is a long existing standard that shares a common paradigm for writing queries with many modern programming languages (including Python). The resulting effect is that coding queries by hand is laborious. Let's explore this dilemma by writing a simple SQL query using Python's database API. DROP TABLE IF EXISTS article;CREATE TABLE article ( id serial PRIMARY KEY, title VARCHAR(11), wiki_text VARCHAR(10000));INSERT INTO article(id, title, wiki_textVALUES(1, 'Spring Python Book', 'Welcome to the [http://springpythonbook.com Spring Python] book, where you can learn more about [[Spring Python]].');INSERT INTO article(id, title, wiki_textVALUES(2, 'Spring Python', ''''Spring Python''' takes the concepts of Spring and applies them to world of [http://python.org Python].'); Now, let's write a SQL statement that counts the number of wiki articles in the system using the database's shell. SELECT COUNT(*) FROM ARTICLE Now let's write some Python code that will run the same query on an sqlite3 database using Python's official database API (http://www.python.org/dev/peps/pep-0249). import sqlite3db = sqlite3.connect("/path/to/sqlite3db")cursor = db.cursor()results = Nonetry: try: cursor.execute("SELECT COUNT(*) FROM ARTICLE") results = cursor.fetchall() except Exception, e: print "execute: Trapped %s" % efinally: try: cursor.close() except Exception, e: print "close: Trapped %s, and throwing away" % ereturn results[0][0] That is a considerable block of code to execute such a simple query. Let's examine it in closer detail. First, we connect to the database. For sqlite3, all we needed was a path. Other database engines usually require a username and a password. Next, we create a cursor in which to hold our result set. Then we execute the query. To protect ourselves from any exceptions, we need to wrap this with some exception handlers. After completing the query, we fetch the results. After pulling the results from the result set into a variable, we close the cursor. Finally, we can return our response. Python bundles up the results into an array of tuples. Since we only need one row, and the first column, we do a double index lookup. What is all this code trying to find in the database? The key statement is in a single line. cursor.execute("SELECT COUNT(*) FROM ARTICLE") What if we were writing a script? This would be a lot of work to find one piece of information. Granted, a script that exits quickly could probably skip some of the error handling as well as closing the cursor. But it is still is quite a bit of boiler plate to just get a cursor for running a query. But what if this is part of a long running application? We need to close the cursors after every query to avoid leaking database resources. Large applications also have a lot of different queries we need to maintain. Coding this pattern over and over can sap a development team of its energy. Parameterizing the code This boiler plate block of code is a recurring pattern. Do you think we could parameterize it and make it reusable? We've already identified that the key piece of the SQL statement. Let's try and rewrite it as a function doing just that. import sqlite3def query(sql_statement): db = sqlite3.connect("/path/to/sqlite3db") cursor = db.cursor() results = None try: try: cursor.execute(sql_statement) results = cursor.fetchall() except Exception, e: print "execute: Trapped %s" % efinally: try: cursor.close() except Exception, e: print "close: Trapped %s, and throwing away" % ereturn results[0][0] Our first step nicely parameterizes the SQL statement, but that is not enough. The return statement is hard coded to return the first entry of the first row. For counting articles, what we have written its fine. But this isn't flexible enough for other queries. We need the ability to plug in our own results handler. import sqlite3def query(sql_statement, row_handler): db = sqlite3.connect("/path/to/sqlite3db") cursor = db.cursor() results = None try: try: cursor.execute(sql_statement) results = cursor.fetchall() except Exception, e: print "execute: Trapped %s" % e finally: try: cursor.close() except Exception, e: print "close: Trapped %s, and throwing away" % e return row_handler(results) We can now code a custom handler. def count_handler(results): return results[0][0]query("select COUNT(*) from ARTICLES", count_handler) With this custom results handler, we can now invoke our query function, and feed it both the query and the handler. The only thing left is to handle creating a connection to the database. It is left as an exercise for the reader to wrap the sqlite3 connection code with a factory solution. What we have coded here is essentially the core functionality of DatabaseTemplate. This method of taking an algorithm and parameterizing it for reuse is known as the template pattern. There are some extra checks done to protect the query from SQL injection attacks. Replacing multiple lines of query code with one line of Spring Python Spring Python has a convenient utility class called DatabaseTemplate that greatly simplifies this problem. Let's replace the two lines of import and connect code from the earlier example with some Spring Python setup code. from springpython.database.factory import Sqlite3ConnectionFactoryfrom springpython.database.core import DatabaseTemplateconn_factory = Sqlite3ConnectionFactory("/path/to/sqlite3db")dt = DatabaseTemplate(conn_factory) At first glance, we appear to be taking a step back. We just replaced two lines of earlier code with four lines. However, the next block should improve things significantly. Let's replace the earlier coded query with a call using our instance of return dt.query_for_object("SELECT COUNT(*) FROM ARTICLE") Now we have managed to reduce a complex 14-line block of code into one line of Spring Python code. This makes our Python code appear as simple as the original SQL statement we typed in the database's shell. And it also reduces the noise. The Spring triangle—Portable Service Abstractions From this diagram earlier , as an illustration of the key principles behind Spring Python is being made. The DatabaseTemplate represents a Portable Service Abstraction because: It is portable because it uses Python's standardized API, not tying us to any database vendor. Instead, in our example, we injected in an instance of Sqlite3ConnectionFactory It provides the useful service of easily accessing information stored in a relational database, but letting us focus on the query, not the plumbing code It offers a nice abstraction over Python's low level database API with reduced code noise. This allows us to avoid the cost and risk of writing code to manage cursors and exception handling DatabaseTemplate handles exceptions by catching and holding them, then properly closing the cursor. It then raises it wrapped inside a Spring Python DataAccessException. This way, database resources are properly disposed of without losing the exception stack trace. Using DatabaseTemplate to retrieve objects Our first example showed how we can easily reduce our code volume. But it was really only for a simple case. A really useful operation would be to execute a query, and transform the results into a list of objects. First, let's define a simple object we want to populate with the information retrieved from the database. As shown on the Spring triangle diagram, using simple objects is a core facet to the 'Spring way'. class Article(object): def __init__(self, id=None, title=None, wiki_text=None): self.id = id self.title = title self.wiki_text = wiki_text If we wanted to code this using Python's standard API, our code would be relatively verbose like this: cursor = db.cursor()results = []try: try: cursor.execute("SELECT id, title, wiki_text FROM ARTICLE") temp = cursor.fetchall() for row in temp: results.append( Article(id=temp[0], title=temp[1], wiki_text=temp[2])) except Exception, e: print "execute: Trapped %s" % efinally: try: cursor.close() except Exception, e: print "close: Trapped %s, and throwing away" % ereturn results This isn't that different from the earlier example. The key difference is that instead of assigning fetchall directly to results, we instead iterate over it, generating a list of Article objects. Instead, let's use DatabaseTemplate to cut down on the volume of code return dt.query("SELECT id, title, wiki_text FROM ARTICLE", ArticleMapper()) We aren't done yet. We have to code ArticleMapper, the object class used to iterate over our result set. from springpython.database.core import RowMapperclass ArticleMapper(RowMapper): def map_row(self, row, metadata=None): return Article(id=row[0], title=row[1], wiki_text=row[2]) RowMapper defines a single method: map_row. This method is called for each row of data, and includes not only the information, but also the metadata provided by the database. ArticleMapper can be re-used for every query that performs the same mapping This is slightly different from the parameterized example shown earlier where we defined a row-handling function. Here we define a class that contains the map_row function. But the concept is the same: inject a row-handler to convert the data.
Read more
  • 0
  • 0
  • 4284
article-image-setting-complete-django-e-commerce-store-30-minutes
Packt
21 May 2010
7 min read
Save for later

Setting up a Complete Django E-commerce store in 30 minutes

Packt
21 May 2010
7 min read
In order to demonstrate Django's rapid development potential, we will begin by constructing a simple, but fully-featured, e-commerce store. The goal is to be up and running with a product catalog and products for sale, including a simple payment processing interface, in about half-an-hour. If this seems ambitious, remember that Django offers a lot of built-in shortcuts for the most common web-related development tasks. We will be taking full advantage of these and there will be side discussions of their general use. In addition to building our starter storefront, this article aims to demonstrate some other Django tools and techniques. In this article by Jesse Legg, author of Django 1.2 e-commerce, we will: Create our Django Product model to take advantage of the automatic admin tool Build a flexible but easy to use categorization system, to better organize our catalog of products Utilize Django's generic view framework to expose a quick set of views on our catalog data Finally, create a simple template for selling products through the Google Checkout API (Read more interesting articles on Django 1.2 e-commerce here.) Before we begin, let's take a moment to check our project setup. Our project layout includes two directories: one for files specific to our personal project (settings, URLs, and so on), and the other for our collection of e-commerce Python modules (coleman). This latter location is where the bulk of the code will live. If you have downloaded the source code from the Packt website, the contents of the archive download represents everything in this second location. Designing a product catalog The starting point of our e-commerce application is the product catalog. In the real world, businesses may produce multiple catalogs for mutually exclusive or overlapping subsets of their products. Some examples are: fall and spring catalogs, catalogs based on a genre or sub-category of product such as catalogs for differing kinds of music (for example, rock versus classical), and many other possibilities. In some cases a single catalog may suffice, but allowing for multiple catalogs is a simple enhancement that will add flexibility and robustness to our application. As an example, we will imagine a fictitious food and beverage company, CranStore.com, that specializes in cranberry products: cranberry drinks, food, and desserts. In addition, to promote tourism at their cranberry bog, they sell numerous gift items, including t-shirts, hats, mouse pads, and the like. We will consider this business to illustrate examples as they relate to the online store we are building. We will begin by defining a catalog model called Catalog. The basic model structure will look like this: class Catalog(models.Model): name = models.CharField(max_length=255 slug = models.SlugField(max_length=150) publisher = models.CharField(max_length=300) description = models.TextField() pub_date = models.DateTimeField(default=datetime.now) This is potentially the simplest model we will create. It contains only five, very simple fields. But it is a good starting point for a short discussion about Django model design. Notice that we have not included any relationships to other models here. For example, there is no products ManyToManyField. New Django developers tend to overlook simple design decisions such as the one shown previously, but the ramifications are quite important. The first reason for this design is a purely practical one. Using Django's built-in admin tool can be a pleasure or a burden, depending on the design of your models. If we were to include a products field in the Catalog design, it would be a ManyToManyField represented in the admin as an enormous multiple-select HTML widget. This is practically useless in cases where there could be thousands of possible selections. If, instead, we attach a ForeignKey to Catalog on a Product model (which we will build shortly), we instantly increase the usability of Django's automatic admin tool. Instead of a select-box where we must shift-click to choose multiple products, we have a much simpler HTML drop-down interface with significantly fewer choices. This should ultimately increase the usability of the admin for our users. For example, CranStore.com sells lots of t-shirts during the fall when cranberries are ready to harvest and tourism spikes. They may wish to run a special catalog of touristy products on their website during this time. For the rest of the year, they sell a smaller selection of items online. The developers at CranStore create two catalogs: one is named Fall Collection and the other is called Standard Collection. When creating product information, the marketing team can decide which catalog an individual product belongs to by simply selecting them from the product editing page. This is more intuitive than selecting individual products out of a giant list of all products from the catalog admin page. Secondly, designing the Catalog model this way prevents potential "bloat" from creeping into our models. Imagine that CranStore decides to start printing paper versions of their catalogs and mailing them to a subscriber list. This would be a second potential ManyToManyField on our Catalog model, a field called subscribers. As you can see, this pattern could repeat with each new feature CranStore decides to implement. By keeping models as simple as possible, we prevent all kinds of needless complexity. In addition we also adhere to a basic Django design principle, that of "loose coupling". At the database level, the tables Django generates will be very similar regardless of where our ManyToManyField lives. Usually the only difference will be in the table name. Thus it generally makes more sense to focus on the practical aspects of Django model design. Django's excellent reverse relationship feature also allows a great deal of flexibility when it comes time to using the ORM to access our data. Model design is difficult and planning up-front can pay great dividends later. Ideally, we want to take advantage of the automatic, built-in features that make Django so great. The admin tool is a huge part of this. Anyone who has had to build a CRUD interface by hand so that non-developers can manage content should recognize the power of this feature. In many ways it is Django's "killer app". Creating the product model Finally, let's implement our product model. We will start with a very basic set of fields that represent common and shared properties amongst all the products we're likely to sell. Things like a picture of the item, its name, a short description, and pricing information. class Product(models.Model): name = models.CharField(max_length=300) slug = models.SlugField(max_length=150) description = models.TextField() photo = models.ImageField(upload_to='product_photo', blank=True) manufacturer = models.CharField(max_length=300, blank=True) price_in_dollars = models.DecimalField(max_digits=6, decimal_places=2) Most e-commerce applications will need to capture many additional details about their products. We will add the ability to create arbitrary sets of attributes and add them as details to our products later in this article. For now, let's assume that these six fields are sufficient. A few notes about this model: first, we have used a DecimalField to represent the product's price. Django makes it relatively simple to implement a custom field and such a field may be appropriate here. But for now we'll keep it simple and use a plain and built-in DecimalField to represent currency values. Notice, too, the way we're storing the manufacturer information as a plain CharField. Depending on your application, it may be beneficial to build a Manufacturer model and convert this field to a ForeignKey. Lastly, you may have realized by now that there is no connection to a Catalog model, either by a ForeignKey or ManyToManyField. Earlier we discussed the placement of this field in terms of whether it belonged to the Catalog or in the Product model and decided, for several reasons, that the Product was the better place. We will be adding a ForeignKey to our Product model, but not directly to the Catalog. In order to support categorization of products within a catalog, we will be creating a new model in the next section and using that as the connection point for our products.
Read more
  • 0
  • 0
  • 14411

article-image-user-authentication-codeigniter-17-using-facebook-connect
Packt
21 May 2010
8 min read
Save for later

User Authentication with Codeigniter 1.7 using Facebook Connect

Packt
21 May 2010
8 min read
(Read more interesting articles on CodeIgniter 1.7 Professional Development here.) Registering a Facebook application You need to register a new Facebook Application so that you can get an API key and an Application Secret Key. Head on over to www.facebook.com/developers/ and click on the Set up New Application button in the upper right–hand corner. This process is very similar to setting up a new Twitter application which we covered in the previous article, so I won't bore you with all of the details. Once you've done that, you should have your API key and Application Secret Key. These two things will enable Facebook to recognize your application. Download the Client library When you are on your applications page showing all your applications' information, scroll down the page to see a link to download the Client Library. Once you've downloaded it, simply untar it. There are two folders inside the facebook-platform folder, footprints and php. We are only going to be using the php folder. Open up the php folder; there are two files here that we don't need, facebook_desktop.php and facebook_mobile.php—you can delete them. Finally, we can copy this folder into our application. Place it in the system/application/libraries folder, and then rename the folder to facebook. This helps us to keep our code tidy and properly sorted. Our CodeIgniter Wrapper Before we start coding, we need to know what we need to code in order to make the Facebook Client Library work with our CodeIgniter installation. Our Wrapper library needs to instantiate the Facebook class with our API Key and Secret Application Key. We'll also want it to create a session for the user when they are logged in. If a session is found but the user is not authenticated, we will need to destroy the session. You should create a new file in the system/application/libraries/ folder, called Facebook_connect.php. This is where the Library code given next should be placed. Base class The Base Class for our Facebook Connect Wrapper Library is very simple: <?phprequire_once(APPPATH . 'libraries/facebook/facebook.php');class Facebook_connect{ var $CI; var $connection; var $api_key; var $secret_key; var $user; var $user_id; var $client;}?> The first thing that our Library needs to do is to load the Facebook library—the one we downloaded from facebook.com. We build the path for this by using APPPATH, a constant defined by CodeIgniter to be the path of the application folder. Then, in our Class we have a set of variables. The $CI variable is the variable in which we will store the CodeIgniter super object; this allows us to load CodeIgniter resources (libraries, models, views, and so on) in our library. We'll only be using this to load and use the CodeIgniter Session library, however. The $connection variable will contain the instance of the Facebook class. This will allow us to grab any necessary user data and perform any operations that we like, such as updating a user's status or sending a message to one of their friends. The next few variables are pretty self-explanatory—they will hold our API Key and Secret Key. The $user variable will be used to store all of the information about our user, including general details about the user such as their profile URL and their name. The $user_id variable will be used to store the user ID of our user. Finally, the $client variable is used to store general information about our connection to Facebook, including the username of the user currently using the connection, amongst other things such as server addresses to query for things like photos. Class constructor Our class constructor has to do a few things in order to allow us to authenticate our users using Facebook Connect. Here's the code: function Facebook_connect($data){ $this->CI =& get_instance(); $this->CI->load->library('session'); $this->api_key = $data['api_key']; $this->secret_key = $data['secret_key']; $this->connection = new Facebook($this->api_key, $this->secret_key); $this->client = $this->connection->api_client; $this->user_id = $this->connection->get_loggedin_user(); $this->_session();} The first line in our function should be new to everyone reading this article. The function get_instance() allows us to assign the CodeIgniter super object by reference to a local variable. This allows us to use all of CodeIgniter's syntax for loading libraries, and so on; but instead of using $this->load we would use $this->CI->load. But of course it doesn't just allow us to use the Loader—it allows us to use any CodeIgniter resource, as we normally would inside a Controller or a Model. The next line of code gives us a brilliant example of this: we're loading the session library using the variable $this->CI rather than the usual $this. The next two lines simply set the values of the API key and Secret Application Key into a class variable so that we can reference it throughout the whole class. The $data array is passed into the constructor when we load the library in our Controller. More on that when we get there. Next up, we create a new instance of the Facebook Class (this is contained within the Facebook library that we include before our own class code) and we pass the API Key and Secret Application Key through to the class instance. This is all assigned to the class variable $this->connection, so that we can easily refer to it anywhere in the class. The next two lines are specific parts of the overall Facebook instance. All of the client details and the data that helps us when using the connection are stored in a class variable, in order to make it more accessible. We store the client details in the variable $this->client. The next line of code stores all of the details about the user that were provided to us by the Facebook class. We store this in a class variable for the same reason as storing the client data: it makes it easier to get to. We store this data in $this->user_id. The next line of code calls upon a function inside our class. The underscore at the beginning tells CodeIgniter that we only want to be able to use this function inside this class; so you couldn't use it in a Controller, for example. I'll go over this function shortly. _session(); This function manages the user's CodeIgniter session. Take a look at the following code: function _session(){ $user = $this->CI->session->userdata('facebook_user'); if($user === FALSE && $this->user_id !== NULL) { $profile_data = array('uid','first_name', 'last_name', 'name', 'locale', 'pic_square', 'profile_url'); $info = $this->connection->api_client-> users_getInfo($this->user_id, $profile_data); $user = $info[0]; $this->CI->session->set_userdata('facebook_user', $user); } elseif($user !== FALSE && $this->user_id === NULL) { $this->CI->session->sess_destroy(); } if($user !== FALSE) { $this->user = $user; }} This function initially creates a variable and sets its value to that of the session data from the CodeIgniter session library. Then we go through a check to see if the session is empty and the $this->user_id variable is false. This means that the user has not yet logged in using Facebook Connect. So we create an array of the data that we want to get back from the Facebook class, and then use the function users_getInfo() provided by the class to get the information in the array that we created. Then we store this data into the $user variable and create a new session for the user. The next check that we do is that if the $user variable is not empty, but the $this->user_id variable is empty, then the user is not authenticated on Facebook's side so we should destroy the session. We do this by using a function built in to the Session Library sess_destroy(); Finally, we check to see if the $user variable is not equal to FALSE. If it passes this check, we set the $this->user class variable to that of the local $user variable.
Read more
  • 0
  • 0
  • 2301
Modal Close icon
Modal Close icon