Friday, February 10, 2012

Theming Views 2 – The Basics


Views 2 provides a well structured theming environment allowing presentation control for each element of your view. And in my humble opinion, it rocks!
Those with no past experience with Views 1 will find Views 2 uses standard PHPTemplate theming techniques. All of your experience theming Drupal can be used with Views.
Views 1 themers starting with Views 2 might be a bit confused at first. I was. The single callback in template.php where everything happened is gone, refactored into a consistent framework of template files. All of the freedom that existed in the single function still exists with the added benefit of a well defined structure.

Overview

Views handles querying the database and organizing the information for display. It creates the output display by converting retrieved data into variables and passing them through a series of templates. Each template handles a different "level" of output creation. The number of templates used to create a view's output depends on the view's type and style, as well as the number of fields involved. These templates exist as files (with a .tpl.php extension), in either the module's or the theme's directory, and follow PHPTemplate's theming conventions.
Generally speaking, the template levels are:
Field:When fields are used in the view ("Row style" = Fields), each field can be themed with a field specific template file. If "Row style" = Node, the node's .tpl.php file is used.
Row:Controls how the individual fields are assembled together into a row. This template isn't used for table styles
Style:Controls how the rows are assembled into the output. For example, in a list view a foreach loop places each row entry into the list entry (<li>) of an unordered list (<ul>).
Display:Controls the other information making up the view such as title, header and footer.
Each level becomes input variables for the next level up. The output of field templates are input variables for the row template, the output for the row template becomes input variables for the style template, and so on. There are also level specific variables available, such as row number. A diagram is available at http://views-help.doc.logrus.com/help/views/analyze-theme.
A template file naming convention is used to make the template highly specific or highly general. Through appropriate naming, a template file can apply to all views, a view of a specific type, or a specific display of a specific view. Where multiple files might apply to a view, the one with the most specific name is used.

Template Files

Each theming level has a default template file. The default templates are located in the theme directory of the Views module. e.g., /root/sites/all/modules/views/theme. These files can provide both a starting point and an example for customization, though their general nature sometimes makes them less useful than one would hope.





Views Module Theme Files
The theme information link on the Views 2 interface shows views theme file information. Each display has slightly different theming information, so make sure the correct display is selected.
Theme Information Link
Clicking the link produces a display pane (shown below). It shows, in bold, the template file used at each level and provides a list of template file names that will override the default templates.
Theme Template Information Pane
When you're ready to theme your view, click the theme information link and decide on the appropriate template file name to use. Generally you'll be theming a particular display of a particular view and will select one of the more specific names, if not the most specific name.
Once you've identified the appropriate level to theme, copy the default template file from the modules/views/theme directory to your theme directory and rename it to your chosen name.
Identifying and Copying a Template File
Pressing the Rescan button in the Information section will refresh the cached information and confirm the file you just copied and renamed has been detected by Views.
You can now modify the template file to your required specifications.
In addition to the recognizing the theme directory as a template file location, Views will also recognize template files in a subdirectory named "views". Placing your views template files in a views subdirectory aids file organization if you have a lot of theme files.

Template Variables

Seeing what's used in the default template code is a good starting place but might not give you an idea of all your options. The default templates are highly generalized, as they must be, and it's sometimes difficult to glean useful information from the variables in the for-each loops. Fortunately there are some simple techniques for displaying available variables.
First, don't ignore the comments at the head of the file. For example, the comments in the row template named views-view-fields.tpl.php tell you how the field objects are structured. But good comments can't tell you the specific name of field related variables.
The most tempting course is to place something like this in your template:
    <?php print print_r(get_defined_vars(), 1?>
Unfortunately, the variables available include the view object, which contains references to itself. The recursion in the resulting output is so long that it's difficult to scan and it can produce memory exceeded errors. A safer approach is using:
  <?php 
     print print_r(array_keys(get_defined_vars()), 1);

    
// Or if you have the developer module installed
    
dsm(array_keys(get_defined_vars())); 

  ?>
Each array key is the name of a variable. e.g., an array key named 'field' appears in the template file as $field. This will give you a safe starting point for exploring variables.
If your view templates has a $fields variable you can repeat this trick to get a list of field names:
    <?php 
    print print_r(array_keys($fields), 1);

    
// Or if you have the developer module installed
     
dsm(array_keys($fields)); 

  ?>
Depending on how you're displaying the information, you may want to wrap the output in a
 tag and use the htmlentities function if the variable contains HTML:
    <?php  print 'htmlentities(print_r($rows1)) . ''; ?>
Since Views 2 uses standard PHPTemplate theming, you can use variable preprocessor functions in template.php. More information of preprocessors: http://drupal.org/node/223430. The hook name is the template file name minus .tpl.php and with hyphens converted to underscores. In the example above where the template file is named views-view-list--comments-recent--page.tpl.php, the preprocessor function for template.php is:
  <?php  function phptemplate_preprocess_views_view_list__comments_recent__page(&$vars) {   // code} ?>
 

Views 1 to Views 2

Some quick differences Views 1 themers might find useful:
  • Theming is now handled by template files, not functions in template.php
  • Views theming is now consistant with the way nodes are themed (i.e., PHPTemplate)
  • Where Views 1 theming provided sample code and naming instructions via the "Theme wizard" tab, Views 2 uses the Information button and default files in views/theme directory
  • The closest equivalent template file to the Views 1 theming function is the "Row style output" template file

Summary

Basic steps for theming a Views 2 view:
  • Use the theme information link to determine your template file starting point and naming options
  • Copy the default template file from modules/views/theme to your theme directory
  • Rename the file with your selected name
  • Press rescan to reload the cache and confirm you've done the copy/rename correctly
  • Read the template file comments and use: 
        <?php 
    print print_r(array_keys(get_defined_vars()), 1);   // Or if you have the developer module installed   dsm(array_keys(get_defined_vars())); 
    ?>
    to find variable names
  • Use a views subdirectory in your theme directory to keep your theme files organized
  • Article taken from http://www.group42.ca/theming_views_2_the_basics
Theming Views 2 – The BasicsSocialTwist Tell-a-Friend

Monday, November 28, 2011

Drupal Bootstrap Database


This is the 3rd article in the series covering DRUPAL v6 bootstrap process. As the bootstrap name implies, this phase covers initializing a connection to a database.

The phase begins by including 'database.inc', which is a database abstraction layer allowing developers to use different database servers with the same code base. One of the functions defined by this library is the db_set_active() function, which is invoked by the bootstrap database phase. This function is used to activate a database used by queries in later phases or during page building and rendering. The function begins by checking if the global variable $db_url is empty. Recall that in the phase #1 - DRUPAL_BOOTSTRAP_CONFIGURATION, this variable is set to the value specified in settings.php unless it is still set to the default string of 'mysql://username:password@localhost/databasename'. In that case, $db_url is simply set to empty string ''. This would indicate a first time installation, and as a result the 'install.inc' file would be included and user redirected to install.php.

Assuming installation had been previously completed, the function proceeds to set $db_conns associative array and initializes a connection to the database specified by the URL. It first determines the connection URL based on the named connection provided to the function as an argument. For the bootstrap phase, no argument is provided and consequently the named connection is set to 'default'. It is interesting to note that an array of connections can be defined in settings.php by defining $db_url as an associative array of key values where the keys are the named connections and the values are the connection URL's. This would be the case where multiple database servers are used to manage content for a site. Drupal expects one of the key values to be named 'default', however. The database type is then extracted from the URL and stored in $db_type global variable. For this example, you can assume that MYSQL is the specified type and therefore 'mysql' would be stored in the variable. Based on the type, the appropriate handler code is then included (again, for this example it would be 'database.mysql.inc'). This file contains the actual code to interface to the specified database.

A connection to the database is then initialized using the handler's db_connect() function using the URL as an argument. This function parses the URL into an array of components (i.e., scheme, host, username, password, and path). It then validates that the specified database type is supported by PHP. Finally, if the given URL contains URL-encoded info, it is then decoded.

A new connection is then opened using the parsed information previously extracted from the URL. If connection to the database was not successful, or if database name not present then Drupal redirects to an error page and terminates.

If everything was successful up until this point, utf8 character encoding support is enabled for this database connection. The connection resource type is then returned to db_set_active() to be assigned to $db_conns static associative array for the specified named connection ('default' for bootstrap phase). The $previous_name variable is set to the name of the previously active connection. In our case this is set to false as there is no previously active connection at this stage of the bootstrap process. The static $active_name is then set to the name of the current connection. Next the global $active_db variable is set with the current connection resource type identifier, which can then be used to execute various DB queries to handle the page request. Finally, the $previous_name variable is returned to the bootstrap function. This return value would be useful for situations where there was a pre-existing DB connection and one wanted to switch to another connection to perform certain actions and then restore the original one once completed. For the bootstrap phase, there shouldn't be a pre-existing connection and the return value is simply discarded.

Until next time.. Stay tuned!
Drupal Bootstrap DatabaseSocialTwist Tell-a-Friend