Friday, December 30, 2011

Creating Blocks using Dynamic (Coding) way

 Creating Blocks using Dynamic (Coding) way:

function modulename_block($op='list',$delta=array(),$edit=array()) {
    global $base_path;
    switch ($op) {

        case 'list':
            $blocks[0]['info'] = t('Block name 1');
            $blocks[1]['info'] = t('Block name 2');
            return $blocks;
            break;
        case 'view':
            switch ($delta) {
                case 0:
                    $blocks['subject'] = t('');
                    $blocks['content'] = drupal_get_form('reset_form');
                  break;
                case 1:
                    $blocks['subject'] = t('');
                    $blocks['content'] = drupal_get_form('login_form'); 
                  break;
                }
      return $blocks;
    break;
    }   
}

function reset_form(){
     $form['pass'] = array(
    '#type' => 'textfield',
    '#title' => t('Password'),
    '#maxlength' => 15,
  );
  $form['conform_pass'] = array(
    '#type' => 'password',
    '#title' => t('ConformPassword'),
    '#maxlength' => 15,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  ); 
  return $form;
}

function login_form(){
  $form['mailid'] = array(
    '#type' => 'textfield',
    '#title' => t('Mail Id'),
    '#maxlength' => 15,
  );
  $form['password'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 15,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  ); 
  return $form;
}

After creating the block,assign it to the proper region.

drupal_write_record

drupal_write_record:

Save a record to the database based upon the schema.
Default values are filled in for missing items, and 'serial' (auto increment) types are filled in with IDs.

Parameters

$table The name of the table; this must exist in schema API.
$object The object to write. This is a reference, as defaults according to the schema may be filled in on the object, as well as ID on the serial type(s). Both array an object types may be passed.
$update If this is an update, specify the primary keys' field names. It is the caller's responsibility to know if a record for this object already exists in the database. If there is only 1 key, you may pass a simple string.

Return value

Failure to write a record will return FALSE. Otherwise SAVED_NEW or SAVED_UPDATED is returned depending on the operation performed. The $object parameter contains values for any serial fields defined by the $table. For example, $object->nid will be populated after inserting a new node.

Example:

$result_array = array_slice($form_state['values'],0,2);
drupal_write_record('tbl_eng_braz',$result_array); 

tbl_eng_braz - table name
$result_array - Sliced array  of the form values to be stored in to the "tbl_eng_braz" table.Only 2 fields are there in the form,so we should create the table with 2 fields and give the name for the fields as per the form.
 

Friday, December 16, 2011

For printing out strings, there are echo, print and printf. Explain the differences

For printing out strings, there are echo, print and printf. Explain the differences:

echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like: 

 <?php echo 'Welcome ', 'to', ' ', 'phpndrupal Blog!'; ?>
 
and it will output the string "Welcome to phpndrupal Blog!" print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf  is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

Wednesday, November 23, 2011

Creating and Displaying Primary and Secondary Links

Creating and Displaying Primary and Secondary Links:
Create the Primary and Secondary links from the drupal admin end by,
Administer->Site Building->Menus->Primary Links or Secondary Links->Add item
There give the path that your primary that redirects to,next give title in the second field then give weight if u need.Then save it.Create more like this and print this in page.tpl.php or in your Header.php block using this code,

For Primary Links
<?php
 if (isset($primary_links)) {
 print theme('links', $primary_links, array('class' => 'links', 'id' => 'navlist'))
 } 
?> 
For Secondary Links
<?php
if (isset($secondary_links)) { 
print theme('links', $secondary_links, array('class' => 'links', 'id' => 'subnavlist'))
}
?>
 

To Create Header Block for a Site

To Create Header Block for a Site:

If you are creating a site with the header that will come all the pages.Then we can use this method for that thing,create a block as Header then define it in page.tpl.php

Create a block in the name of Header and use this code to print the header in your top of the page.tpl file.Then only you will get that header in all those pages,

               <?php
                    $block = module_invoke('block', 'block', 'view', 1(block id));
                    print $block['content'];
                ?>

How to open the Primary Liks or Secondary Links in New Tab

How to open the Primary Liks or Secondary Links in New Tab:

Give this code inside your template.php file,
For Example,your primary menu item class is menu-1 and its locate inside a <li class="menu1"><a href="<?php $base_path();?>contact_us"></a></li> tag then,
you should do like this,

drupal_add_js ('$(document).ready(function(){$("li.menu-1 a").click(function() {     window.open(this.href); return false; }    ); 
}

Setting Different Page Design for a Content Type

Setting Different Page Design for a Content Type:

If we want to create different page design for your content,then you need to create a content type and below that content you need to create the contents.Then if we need to create a tpl file for that content type.
For Example if you are creating a Content Type as "right",then you need to create a tpl like page-node-right.tpl.php.
After Creating the Content Type and tpl File,you should do this finally inside phptemplate_preprocess_page in your template file,

function phptemplate_preprocess_page(&$variables) {

    if ($variables['node']->type == "right") {
        $variables['template_files'][] = "page-node-" . $variables['node']->type;
    }

}

Setting Browser Title for Each Pages

Setting Browser Title for Each Pages: 

While Creating a page or node in a site,we should give the browser title,
for that we need to give this code inside the phptemplate_preprocess_page function in template.php.
for Example if your page is Contact Us and the url is contact_us,you need to write the code like this,

function phptemplate_preprocess_page(&$variables) {
   
    $path = drupal_get_path_alias($_GET['q']);
   
    if($path == 'contact_us'){
       $variables['head_title'] = 'Your Project Name - Contact Us';
     }

}

Friday, October 21, 2011

Java Script Validation for Text Field

Java Script Validation for Text Field:
First we need to declare the Regular Expression for the Alphabetic validation like this,

var alphabetic = /^[a-zA-Z ]+$/;

Then we need to store our field value as a variable like this,

var fname=$('#edit-firstName').val(); 

Now we need to check whether the entered content is alphabetical or not,It will accept only alphabets..

if((fname == '') || (!alphabetic.test(fname))){
        errorCount = 1;
         error+= "You must supply a
alphabetic value for the 'FullName' field of this form.";
    }  


Creating a Different layout for our Site

Creating a Different layout for our Site:
1.At first we need to create a content type as "layout" and save it.

2.After creating the content type,keep this coding in the top of the template file,

function yourthemename_preprocess_page(&$variables) {
    if ($variables['node']->type == "layout") {
        $variables['template_files'][] = "page-node-" . $variables['node']->type;
    }
}

3.Then create a tpl as,page-node-layout.tpl.php.

4.In that tpl you can able to create a diff structure for the different layout from the old

5.Then print the content that you want to display in that layout like this,


<?php print $content;?>


6.After creating the tpl,create the contents under the "layout" content type


7.Now you will get the different kind of layout from old layout.There your contents will display.


***Different layout in the sense,with header or footer or both or just a content page without header,footer,left & right side blocks.


Thursday, October 13, 2011

Writing .install files (Drupal 6.x)

 Writing .install files (Drupal 6.x):

A .install file is run the first time a module is enabled, and is used to run setup procedures as required by the module. The most common task is creating database tables and fields. The .install file does not have any special syntax. It is merely a PHP file with a different extension.
.install files are also used to perform updates when a new version of a module needs it.

Instructions

Install instructions are enclosed in a _install() function. This hook will be called when the module is first enabled. Any number of functions can reside here, but the most typical use is to create the necessary tables for your module.
As of Drupal 6.x the database tables are created using the Schema API .
The Schema API allows modules to declare their database tables in a structured array (similar to the Form API) and provides API functions for creating, dropping, and changing tables, columns, keys, and indexes.

A sample schema data structure (taken from the Schema Api Documentation)

As an example, here is an excerpt of the schema definition for Drupal's 'node' table:

<?php
$schema
['node'] = array(
   
'description' => t('The base table for nodes.'),
   
'fields' => array(
     
'nid' => array(
       
'description' => t('The primary identifier for a node.'),
       
'type' => 'serial',
       
'unsigned' => TRUE,
       
'not null' => TRUE),
     
'vid' => array(
       
'description' => t('The current {node_revisions}.vid version identifier.'),
       
'type' => 'int',
       
'unsigned' => TRUE,
       
'not null' => TRUE,
       
'default' => 0),
     
'type' => array(
       
'description' => t('The {node_type} of this node.'),
       
'type' => 'varchar',
       
'length' => 32,
       
'not null' => TRUE,
       
'default' => ''),
     
'title' => array(
       
'description' => t('The title of this node, always treated a non-markup plain text.'),
       
'type' => 'varchar',
       
'length' => 255,
       
'not null' => TRUE,
       
'default' => ''),
      ),
   
'indexes' => array(
     
'node_changed'        => array('changed'),
     
'node_created'        => array('created'),
      ),
   
'unique keys' => array(
     
'nid_vid' => array('nid', 'vid'),
     
'vid'     => array('vid')
      ),
   
'primary key' => array('nid'),
    );
?>
 
In this excerpt, the table 'node' has four fields (table columns) named 'nid', 'vid', 'type', and 'title'. Each field specifies its type ('serial', 'int', or 'varchar' in this example) and some additional optional parameters, including a description.
The table's primary key is the single field 'nid'. There are two unique keys: first named 'vid' on the field 'vid' and second called 'nid_vid' on fields 'nid' and 'vid'. Two indexes, one named 'node_changed' on field 'changed' and one named 'node_created' on the field 'created'.

Creating tables: hook_schema and .install files

For the Schema API to manage a module's tables, the module must have a .install file that implements hook_schema() (note: in a pre-release version, hook_schema() was in a .schema file but that is no longer used.) For example, mymodule's mymodule.install file might contain:

<?phpfunction mymodule_schema() {
 
$schema['mytable1'] = array(
    
// specification for mytable1
 
);
 
$schema['mytable2'] = array(
    
// specification for mytable2
 
);
  return
$schema;
}

function
mymodule_install() {
 
// Create my tables.
 
drupal_install_schema('mymodule');
}

function
mymodule_uninstall() {
 
// Drop my tables.
 
drupal_uninstall_schema('mymodule');
}
?>
 
Updating your schema for new versions works just as it has since Drupal 4.7, using a hook_update_n() function. Suppose you add a new column called 'newcol' to mytable1. First, be sure to update your schema structure in mymodule_schema() so that newly created tables get the new column. Then, add an update function to mymodule.install:

<?phpfunction mymodule_update_1() {
 
$ret = array();
 
db_add_field($ret, 'mytable1', 'newcol', array('type' => 'int'));
  return
$ret;?>
 
There is also a module available called as Schema Module which provides additional Schema-related functionality not provided by the core Schema API that is useful for module developers. Currently, this includes:
  • Schema documentation: hyperlinked display of the schema's embedded documentation explaining what each table and field is for.
  • Schema structure generation: the module examines the live database and creates Schema API data structures for all tables that match the live database.
  • Schema comparison: the module compares the live database structure with the schema structure declared by all enabled modules, reporting on any missing or incorrect tables.

Writing .info files (Drupal 6.x)

Overview

Drupal uses .info files (aka, "dot info files") to store metadata about themes and modules.
For modules, the .info file is used:
  • for rendering information on the Drupal Web GUI administration pages;
  • for providing criteria to control module activation and deactivation;
  • for notifying Drupal about the existence of a module;
  • for general administrative purposes in other contexts.
This file is required for the system to recognize the presence of a module.
The following is a sample .info file:

name = "Example module"
description = "Gives an example of a module."
core = 6.x
package = Views
dependencies[] = views
dependencies[] = panels
 
The .info file should have the same name as the .module file and reside in the same directory. For example, if your module is named example.module then your .info file should be named example.info.
This file is in standard .ini file format, which places items in key/value pairs separated by an equal sign. You may include the value in quotes. Quoted values may contain newlines.

description = "Fred's crazy, crazy module; use with care!"
 
.info files may contain comments. The comment character is the semi-colon and denotes a comment at the beginning of a line. CVS Ids used to be placed at the head of info files using a semicolon, but now that Drupal.org has moved to git they are no longer included.
The .info file can contain the following fields:
name (Required)
The displayed name of your module. It should follow the Drupal capitalization standard: only the first letter of the first word is capitalized ("Example module", not "example module" or "Example Module"). Spaces are allowed as the name is used mainly for the display purposes.

name = "Forum"
description (Required)
A short, preferably one line description that will tell the administrator what this module does on the module administration page. Remember, overly long descriptions can make this page difficult to work with, so please try to be concise. This field is limited to 255 characters.

description = "Enables threaded discussions about general topics."
core (Required)
The version of Drupal that your module is for. For Drupal 6 this would be 6.x, Drupal 7 would be 7.x, etc. Note that modules cannot specify the specific version of a branch of Drupal. 6.x is correct 6.2 is not.

core = 6.x
dependencies (Optional)
An array of other modules that your module requires. If these modules are not present, your module can not be enabled. If these modules are present but not enabled, the administrator will be prompted with a list of additional modules to enable and may choose to enable the required modules as well, or cancel at that point.

The string value of each dependency must be the module filename (excluding ".module") and should be written in lowercase like the examples below. Spaces are not allowed.

dependencies[] = taxonomy
dependencies[] = comment
package (Optional)
If your module comes with other modules or is meant to be used exclusively with other modules, enter the name of the package here. If left blank, the module will be listed as 'Other'. In general, this field should only be used by large multi-module packages, or by modules meant to extend these packages, such as CCK, Views, E-Commerce, Organic Groups and the like. All other modules should leave this blank. As a guideline, four or more modules that depend on each other (or all on a single module) make a good candidate for a package. Fewer probably do not. The exception to this rule is the "Development" package, which should be used for any modules which are code development tool modules (Devel, Coder, Module Builder...).

If used, the package string is used to group modules together on the module administration display; the string should therefore be the heading you would like your modules to appear under, and it needs to be consistent (in spelling and capitalization) in all .info files in which it appears. It should not use punctuation and it should follow the Drupal capitalization standard as noted above.

package = Views

Suggested examples of appropriate items for the package field:
  • Access control
  • Audio
  • Bot
  • CCK
  • Chat
  • E-Commerce
  • Event
  • Feed parser
  • Organic groups
  • Performance and scalability
  • Station
  • Video
  • Views
  • Voting (if it uses/requires VotingAPI)
  • Location
php (Optional)
As of version 6.x, module and themes may specify a minimum PHP version that they require. They may do so by adding a line similar to the following to their .info file:

php = 5.1

That specifies that the module/theme will not work with a version of PHP earlier than 5.1. That is useful if the module makes use of features added in later versions of PHP (improved XML handling, object iterators, JSON, etc.). If no version is specified, it is assumed to be the same as the required PHP version for Drupal core. Modules should generally not specify a required version unless they specifically need a higher later version of PHP than is required by core. See the PHP Manual for further details on PHP version strings.
hidden (Optional)
As of version 6.20, modules may specify that they should not be visible on the modules page by adding hidden = TRUE. This is commonly used with testing modules used with SimpleTest where end-users should never enable the testing modules. Can also be used with feature modules, made with the module Features.
version (Discouraged)
The version string will be added by drupal.org when a release is created and a tarball packaged. However, if your module is not being hosted on the drupal.org infrastructure, you can give your module whatever version string makes sense.

Users getting their modules directly from git will not have a version string, since the .info files checked into git do not define a version. These users are encouraged to use the Git deploy module to provide accurate version strings for the admin/build/modules page for modules in directories checked out directly from git.

Because Drupal core uses a slightly different packaging process than contributed modules, the core modules have a version line predefined. This is an exception to the rule, not the model for contributed modules.
project (Discouraged, packaging use only)
Module maintainers should not use this at all. The packaging script on drupal.org will automatically place a string here to identify what project the module came from. This is primarily for the Update status module, so that Drupal installations can monitor versions of installed packages and notify administrators when new versions are available.
For more information on info file formatting, see the drupal_parse_info_file() documentation.

Troubleshooting

I added the core = 6.x line, but my module still says "This version is incompatible with the 6.x version of Drupal core" on the modules page. What gives?
Be aware that the "dependencies" format changed between Drupal 5.x and 6.x.

Wrong:
name = Example
description = Example description
; 5.x dependency format.
dependencies = foo bar
core = 6.x
 
Correct:
name = Example
description = Example description
; Note the [], and that each of the dependencies is on its own line.
dependencies[] = foo
dependencies[] = bar
core = 6.x

Description and Accents

If you need to use accents, use ASCII characters. It is the only way to prevent truncating this field in the database and still have accents in the description. You cannot use utf8_encode in there.

Tuesday, October 11, 2011

How to Implement ORM on PHP5

How to Implement ORM on PHP5:

ORM (Object-relational mapping) programming is the best way to improve your PHP skill. There are many ORM framework in the market. However, CakePHP, Symfony and Doctrine are the best in the crowd. ORM layer in a PHP framework can use “objects” stored in a database behave like actual objects from a programming perspective. For example, creating a new “mobile” stored in the database could involve a call to $mobile->new(). ORM brings data closer to a programming paradigm. It is the manipulation of object rather than the data.

ORM works one level above actual database operations. During the use of ORM layer, you don’t need to write SQL queries. It is taken care of, although an understanding of how to is always helpful. ORM works based on MVC structure. Symfony is possible the most robust ORM layer. However, CakePHP‘s ORM layer is not far away. Doctrine is also quite competitive, in providing ORM. There are many other frameworks. Of course, you can to do experiments on their ORM.  Finally, ORM provides many fundamental advantage over raw SQL.  It massively simplifies the interactions with your database and eliminate the chore of hand written SQL for common operations. During programming, most of the time you will be using code generators or mapping files to manipulate your tables.

Typical ORM Conventions:
To get the most value out of the ORM library, you should adhere to the conventions outlined below. Moreover, it is possible to override these default conventions via ORM object properties.
  • Table names are plural, e.g. users .
  • Model names are singular (e.g. user)
  • Each table should have an auto_incrementing column named ‘id’ as its primary key)
  • Foreign keys should be named using the ‘modelname_id’ (e.g. user_id)
  • Pivot tables should use the parent table names in alphabetical order in the form table1_table2. For example: If you have a many-to-many relationship between users and roles tables, the join table should be named roles_users.
ORM Relations:
The ORM library supports the following relationships in your model:
  • hasOne for one-to-one relationships
  • hasMany for the parent side of a one-to-many relationship
  • belongsTo for the child side of a one-to-many or one-to-one relationship
ORM Coding (Example):
Using code generators (like cake bake),  you easily generate codes for ORM. But discussion purpose some examples are given below:

Example:
Step 1: Create the Database on MySQL

CREATE TABLE `xyzs` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` varchar( 60 ) NOT NULL ,
`address` varchar( 260 ) NOT NULL ,
`email` varchar( 60 ) NOT NULL
);
CREATE TABLE `pqrs` (
`id` int( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`code` varchar( 40 ) NOT NULL ,
`title` varchar( 40 ) NOT NULL ,
`description` text NOT NULL ,
`xyz_id` int( 11 ) NOT NULL
)

Step 2: Define Models
Create the Xyz model using the following code (/app/models/xyzs.php):
<?php
class Xyz extends AppModel
{
var $name = ‘Xyz’;
var $hasMany = ‘Pqr’;
}
?>

Create the Pqr  model (/app/models/books.php):
<?php
class Pqr extends AppModel
{ var $name = ‘Pqr’;
var $belongsTo = ‘Xyz’;
}
?>

Step 3: Define the Controllers
Create a controller for the Xyz model with the following code: (/app/controllers/xyzs_controller.php):
<?php
class XyzsController extends AppController {
var $name = ‘Xyzs’;
function index() {
$this->Xyz->recursive = 1;
$authors = $this->Xyz->find(‘all’);
$this->set(‘xyzs’, $xyzs);
}
}
?>

Create the controller for the Pqr  model (/app/controllers/books_controller.php):
<?php
class PqrsController extends AppController {
var $name = ‘Pqrs’;
function index() {
$this->Pqr->recursive = 1;
$authors = $this->Pqr->find(‘all’);
$this->set(‘pqrs’, $pqrs);
}
}
?>

Step 4: Define the Views
The view file for the action for both the tables should be like this: (index.ctp):
<?php foreach($xyzs as $xyz): ?>
<h2><?php echo $xyz['Xyz']['name'] ?></h2>
<hr />
<h3>List of PQR(s):</h3>
<ul>
<?php foreach($xyz['Pqr'] as $book): ?>
<li><?php echo $pqr['code'] ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>

When to use GET or POST?

Explain when to use GET or POST. Provide example for both the ways.

Both GET and POST are used to collect data from a form. However, when security is desired $_POST should be used. When the $_ POST variable is used, all variables used are NOT displayed in the URL. Also, they have no restrictions to the length of the variables. GET should be used when the interaction with the form is more like a question. For e.g. firing a query etc. POST should be used more often when the interaction is more like an order or the interaction changes the state of the resource.

POST Example:
Name:Sridar
Age:22

On clicking submit the URL resembles to: http://www.mysamplesite.com/sample.php
The sample.php file can be used for catching the form data using $_POST
Hello <?php echo $_POST["name"]; ?>.
You are <?php echo $_POST["age"]; ?> years old!

GET Example:
Name:Sridar
Age:22

On clicking submit the URL resembles to : http://www.mysamplesite.com/sample.php?name=Sridar&age=22
The sample.php file can be used for catching the form data using $_GET
Hello <?php echo $_GET["name"]; ?>.
You are <?php echo $_GET["age"]; ?> years old!

 

Changing FilePermission and Ownership using PHP's chmod() function

Changing FilePermission and Ownership using PHP's chmod() function:

Chmod() is used for changing permissions on a file.

Syntax:
Chmod(file, mode)

Mode here specifies the permissions as follows:

* The first number is always zero
* The second number specifies permissions for the owner
* The third number specifies permissions for the owner's user group
* The fourth number specifies permissions for everybody else


Possible values (to set multiple permissions, add up the following numbers)

* 1 = execute permissions
* 2 = write permissions
* 4 = read permissions


Example:

// everything for owner, read for owner's group
chmod("test.txt",0740);


Difference between PHP4 and PHP5 && Type Juggling in php

Difference between PHP4 and PHP5:

There are several differences between PHP4 and PHP5.
1.Unified constructor and Destructor.
2.Exception has been introduced.
3.New error level named E_STRICT has been introduced.
4.Now we can define full method definitions for an abstract class.
4.Within a class we can define class constants.
5.we can use the final keyword to indicate that a method cannot be overridden by a child

Added features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.

Type Juggling in PHP:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)

If the last two examples above seem odd, see String conversion to numbers.
If you wish to change the type of a variable, see settype().
If you would like to test any of the examples in this section, you can use the var_dump() function.
Note: The behavior of an automatic conversion to array is currently undefined.

Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a? The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:

Tuesday, October 4, 2011

HTML Escape Characters for Drupal

Table of HTML Escape Characters
Decimal Value (&#DV;) Escape Character Output
0 - 031 None Nothing
032 &sp; or &blank; Blank
033 &excl; !
034 &quot; "
035 &num; #
036 &dollar; $
037 &percnt; %
038 &amp; &
039 &apos; '
040 &lpar; (
041 &rpar; )
042 &ast; *
043 &plus; +
044 &comma; ,
045 &hyphen; or − or &dash; -
046 &period; .
047 &sol; /
048-057 = digits 0-9
058 &colon; :
059 &semi; ;
060 < <
061 &equals; =
062 > >
063 &quest; ?
064 &commat; @
065 - 090 = letters A - Z
091 &lsqb; [
092 &bsol; \
093 &rsqb; ]
094 ˆ or &caret; ^
095 &lowbar; _
096 None (grave accent/back apostrophe) `
097 - 122 = letters a - z
123 &lcub; {
124 &verbar; |
125 &rcub; }
126 &tilde; or &sim; ~
127 None (delete) None
128 - 159 = unused (MS specific)
160 &nbsp; non-breaking space
161 &iexcl; ¡
162 &cent; ¢
163 &pound; £
164 &curren; ¤
165 &yen; ¥
166 &brvbar; or &brkbar; ¦
167 &sect; §
168 &uml; or &die; ¨
169 &copy; ©
170 &ordf; ª
171 &laquo; «
172 &not; ¬
173 &shy; (soft hyphen) None
174 &reg; ®
175 &macr; or &hibar; ¯
176 &deg; °
177 &plusmn; ±
178 &sup2; ²
179 &sup3; ³
180 &acute; ´
181 &micro; µ
182 &para;
183 &middot; ·
184 &cedil; ¸
185 &sup1; ¹
186 &ordm; º
187 &raquo; »
188 &frac14; ¼
189 &frac12; or &half; ½
190 &frac34; ¾
191 &iquest; ¿

How to interact with Drupal search system ?

There are three ways to interact with the search system:

1.Specifically for searching nodes, you can implement nodeapi('update index') and nodeapi('search result'). However, note that the search system already indexes all visible output of a node, i.e. everything displayed normally by hook_view() and hook_nodeapi('view'). This is usually sufficient. You should only use this mechanism if you want additional, non-visible data to be indexed.

2.Implement hook_search(). This will create a search tab for your module on the /search page with a simple keyword search form. You may optionally implement hook_search_item() to customize the display of your results.

3.Implement hook_update_index(). This allows your module to use Drupal's HTML indexing mechanism for searching full text efficiently.
If your module needs to provide a more complicated search form, then you need to implement it yourself without hook_search(). In that case, you should define it as a local task (tab) under the /search page (e.g. /search/mymodule) so that users can easily find it.

Friday, September 30, 2011

Adding Jquery for the Contact Us Form

So as each jquery file, in template.php you can add the js file with:

<?php
drupal_add_js
(path_to_theme(). '/jquery.contact.js'); ?>
 
In our JS File, jquery.contact.js, we add a function to the submit function, which checks whether all fields are filled up, if not it alerts some messages

if (Drupal.jsEnabled) {
  $(document).ready(function() {
  $('form#contact-mail-page').submit(function () {
    //if one of this fields as nothing in print out that the form is not ready yet
    //  if ready the field is send
    if ($('#contact-mail-page #edit-name').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet", ['@name'] = Drupal.t("name")]);
      return false;
    }
    else if ($('#contact-mail-page #edit-subject').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet"), ['@name'] = Drupal.t("subject")]);
      return false;
    }
    else if ($('#contact-mail-page #edit-mail').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet"), ['@name'] = Drupal.t("mail")]);
      return false;
    }
    else if ($('#contact-mail-page #edit-message').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet"), ['@name'] = Drupal.t("message")]);
      return false;
    }
    else {
      return true;
    }
  });
});
}

Thursday, September 29, 2011

Managing JavaScript in Drupal 7

Drupal 7 has introduced several new techniques that allow you far greater flexibility and control in the scripts you can have on your Drupal site's pages.

Weighted JavaScript

drupal_add_js() now allows you to add a weight value to each script you’re adding so you can completely control the order in which the script tags appear:
- JS_LIBRARY: Any libraries, settings, or jQuery plugins.
- JS_DEFAULT: Any module-layer JavaScript.
- JS_THEME: Any theme-layer JavaScript
Example:
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

Adding JavaScript in the module's .info file

You can now add Javascript in the module's .info file if it should be added on every page. This allows Javascript to be aggregated in an optimal way, and is the preferred method of adding Javascript that most visitors will need on a typical site visit:
scripts[] = somescript.js

External JavaScript

drupal_add_js() now allows you to add external scripts.
Example:
drupal_add_js('http://example.com/example.js', 'external');

Overriding JavaScript

hook_js_alter() allows you to modify the path referenced by one of the scripts added by core or another module. An obvious example is if you want to use a newer version of jQuery than what comes with core:
function hook_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js'; // Swap out jQuery to use an updated version of the library
}

JavaScript Libraries

There is now a standard way of adding collections of JavaScript and CSS, such as jQuery plugins. If you have a set of JavaScript and/or CSS that could be considered a package, provide it as a library to other modules by implementing hook_library(), and include it it in your own pages either by using #attached['library'] or drupal_add_library(). This is the preferred way to deal with JavaScript and CSS which might be used by other modules.
Modules define libraries which can be added when needed. For example, system.module defines the Vertical Tabs library, which includes one js file and one css file:
function system_library() {
  ...
  // Vertical Tabs.
  $libraries['vertical-tabs'] = array(
    'title' => 'Vertical Tabs',
    'website' => 'http://drupal.org/node/323112',
    'version' => '1.0',
    'js' => array(
      'misc/vertical-tabs.js' => array(),
    ),
    'css' => array(
      'misc/vertical-tabs.css' => array(),
    ),
  );
  ...
  return $libraries;
}

The library gets added when it's needed, through a call to drupal_add_library:
function theme_vertical_tabs($variables) {
  $element = $variables['element'];
  // Add required JavaScript and Stylesheet.
  drupal_add_library('system', 'vertical-tabs');

  return '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
}

Prefer drupal_add_library() and always use it for core JavaScript files

drupal_add_js() should not be used for JavaScript which is already included in a library (as all core JavaScript libraries are). Use drupal_add_library() instead.

Using jQuery

jQuery is now namespaced to avoid conflicts with other Javascript libraries such as Prototype. All your code that expects to use jQuery as $ should be wrapped in an outer context like so.
(function ($) {
  // All your code here
}(jQuery));

If you don't, you may see the error Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function or similar.

Behaviors

Behavior handling has changed again in Drupal7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler.
Instead of the settings being a global object, settings are now passed to your handlers directly, after the context.
These changes, besides namespaced jQuery, mean basic module code should go from
something like this in Drupal 6:
Drupal.behaviors.exampleModule = function (context) {
   $('.example', context).click(function () {
    $(this).next('ul').toggle('show');
  });
}
To something like this in Drupal 7:
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

}(jQuery));

AJAX Forms in Drupal 7

<?php/**
* AJAX-enabled select element causes replacement of a set of checkboxes
* based on the selection.
*/
//the AJAX-enabled element is a select, $form['howmany_select'], which causes replacement of the HTML ID 'checkboxes-div' (named in #ajax['wrapper']), which is a wrapper around a the fieldset $form['checkboxes_fieldset']:

function ajax_example_autocheckboxes($form, &$form_state) {

 
$default = !empty($form_state['values']['howmany']) ? $form_state['values']['howmany'] : 1;

 
$form['howmany_select'] = array(
   
'#title' => t('How many checkboxes do you want?'),
   
'#type' => 'select',
   
'#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
   
'#default_value' => $default,
   
'#ajax' => array(
     
'callback' => 'ajax_example_autocheckboxes_callback',
     
'wrapper' => 'checkboxes-div',
     
'method' => 'replace',
     
'effect' => 'fade',
    ),

  );


 
$form['checkboxes_fieldset'] = array(
   
'#title' => t("Generated Checkboxes"),
   
// The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
   
'#prefix' => '<div id="checkboxes-div">',
   
'#suffix' => '</div>',
   
'#type' => 'fieldset',
   
'#description' => t('This is where we get automatically generated checkboxes'),
  );

When the 'howmany_select' element is changed, a background request is issued to the server requesting that the form be rebuilt. After the form is rebuilt, using the changed 'howmany' field as input on how to rebuild it, the callback is called:

  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
  for (
$i=1; $i<=$num_checkboxes; $i++) {
   
$form['checkboxes_fieldset']["checkbox$i"] = array(
     
'#type' => 'checkbox',
     
'#title' => "Checkbox $i",
    );
  }

 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit'),
  );

  return
$form;
}
/**
* Callback element needs only select the portion of the form to be updated.
* Since #ajax['callback'] return can be HTML or a renderable array (or an
* array of commands), we can just return a piece of the form.
*/
function ajax_example_autocheckboxes_callback($form, $form_state) {
  return
$form['checkboxes_fieldset'];
}
?>
The callback in this case (and in many cases) just selects the portion of the form which is to be replaced on the HTML page and returns it. That portion of the form is later rendered and returned to the page, where it replaces the #ajax['wrapper'] which was provided.
That's AJAX forms in a nutshell. A form element with the #ajax property submits a background request to the server when it is triggered by a click or change. The form gets rebuilt (on the server) by the form-builder function, and then the callback named in #ajax['callback'] is called, which selects the portion of the form to return for replacement on the original page.

Simple Form API Example

<?php
//Menu Hook
function formcreation_menu() {
$items = array();
$items['formcreation/new_form'] = array(
    'title' => t('New form'),
      'page callback' => 'drupal_get_form',
    'page arguments' => array('create_form'),
    'access arguments' => array('access content'),
    'description' => t('New form'),
    'type' => MENU_CALLBACK,
);
return $items;
}
// Menu Callback
function create_form($form_state) {
$form['personal_details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Personal Details'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
);
$form['personal_details']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    //'#required' => TRUE,
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
);
$form['personal_details']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    //'#required' => TRUE,
    '#description' => "Please enter your last name.",
    '#size' => 20,
    '#maxlength' => 20,
);

$form ['personal_details']['year_of_birth'] = array(
    '#type' => 'textfield',
    '#title' => "Year of birth",
    '#description' => 'Format is "YYYY"',
    '#size' => 10,
    '#maxlength' => 4,
);
//Adding more fields for the form
if (isset($form_state['storage']['other_details'])) {
      $form['personal_details1'] = array(
        '#type' => 'fieldset',
        '#title' => t('More Details...'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
      );
      $form['personal_details1']['age'] = array(
        '#type' => 'textfield',
        '#title' => t('Age'),
        '#description' => "Please enter your Age.",
        '#size' => 3,
        '#maxlength' => 3,
        '#default_value' => $form_state['values']['age'],
      );
      $form['personal_details1']['sex'] = array(
        '#type' => 'textfield',
        '#title' => t('Sex'),
          '#description' => "Please enter your Sex.",
          '#size' => 6,
        '#maxlength' => 6,
        '#default_value' => $form_state['values']['sex'],
      );
      $form['personal_details1']['city'] = array(
        '#type' => 'textfield',
        '#title' => "City",
        '#description' => 'Please enter your City.',
          '#size' => 20,
        '#maxlength' => 20,
        '#default_value' => $form_state['values']['city'],
      );
    }
   
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
);
//Reset the form, Hook;
$form['clear'] = array(
    '#type' => 'submit',
    '#value' => 'Clear',
    '#validate' => array('create_form_clear'),
  );
  //Adding more fields, Hook;
if (empty($form_state['storage']['other_details'])) { 
      $form['other_details'] = array(
        '#type' => 'submit',
        '#value' => 'Add Some more Details',
        '#validate' => array('create_form_other_details'),
      );
    }
return $form;
}
//Form validation
function create_form_validate($form, &$form_state) {
    $year_of_birth = $form_state['values']['year_of_birth'];
    $first_name = $form_state['values']['first'];
    $last_name = $form_state['values']['last'];
        if (!$first_name) {
            form_set_error('first', 'Please enter your first name.');
        }
        if (!$last_name) {
            form_set_error('last', 'Please enter your last name.');
        }
        if ($year_of_birth == '') {
        form_set_error('year_of_birth', 'Kindly enter the year of Birth');
        }else if($year_of_birth < 1900 || $year_of_birth > 2000){
        form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
        }
//validation for the extra fields that added newly
    if ($form_state['storage']['other_details']) {
        $age = $form_state['values']['age'];
        $sex = $form_state['values']['sex'];
        $city = $form_state['values']['city'];
        if (!$age) {
            form_set_error('age', 'Please enter your Age.');
        }
        if (!$sex) {
            form_set_error('sex', 'Please enter your Sex.');
        }
        if (!$city) {
            form_set_error('city', 'Please enter your City.');
        }
    }
}
//Adding more fields Menu Callback
function create_form_other_details($form, &$form_state) {
    $form_state['storage']['other_details'] = TRUE;
    $form_state['rebuild'] = TRUE;
}
//Reset the form Callback
function create_form_clear($form, &$form_state) {
    unset ($form_state['values']); 
    unset ($form_state['storage']);
    $form_state['rebuild'] = TRUE;
}
//Form Submit
function create_form_submit($form, &$form_state) {
unset($form_state['storage']);
drupal_set_message(t('The form has been submitted.'));
}

?>

Wednesday, September 28, 2011

Drupal Awards, Logo's and Banners

Awards

The following is a list of awards that Drupal has won, in chronological order:

2011

2010

2009

2008

2007

  • Webware 100
    http://drupal.org/node/152770
  • Packt Publishing Open Source CMS Awards:
    Best Overall Open Source CMS (1st place)
    Best PHP Open Source Content Management System (2nd place)
    Best Open Source Social Networking Content Management System (2nd place tie)

2006

  • Packt Publishing Open Source CMS Awards:
    Best Overall Open Source CMS (2nd place)

 

Banners and Community Logos

For special events and holidays special banners are often created. These are often featured on the Drupal.org front page.
A template for these logos is available in Paint Shop Pro and Photoshop format (note the Photoshop mask layer needs to be applied manually).

What's New in Drupal

What's New in Drupal 7

Drupal 7 is released. Download the full release version.
Here is a summary of changes introduced to Drupal 7. You can also see the complete Drupal change log.

New Minimum System Requirements:

This is not a complete list of requirements. Please read the complete list of requirements.
  • Database: MySQL 5.0.15 or PostgreSQL 8.3
  • PHP Version 5.2 or higher
  • PHP Memory: 40M - 64M

Security:

  • More secure implementation for scheduled tasks (cron.php).
  • More secure password system.
  • More secure log-in system.
  • Modules can be updated via the web.

Usability:

  • Administrative links to edit existing page elements are now available on each web page, without having to go to an administration page first.
  • Improved support for integration of WYSIWYG editors.
  • Added more drag-and-drop for administrative tasks.
  • Permissions now have the ability to handle more meta-data (permissions now have a description).
  • User 1 created as part of the installation process.
  • Added features to the default install profile (tagging on the Article content type).
  • Setting up automated task runs (cron) can now be achieved via Drupal's configuration alone, without having to install any scripts on the web server.
  • Redesigned password strength validator to make it kinder and gentler, and clearer.
  • Renamed "input formats" to "text formats".
  • Added support for default text formats to be assigned on a per-role basis.
  • Moved text format permissions to the main permissions page
  • Added "vertical tabs", a reusable interface component that features automatic summaries and increases usability.
  • Improved time zone support
  • Removed per-user themes: Contributed modules with similar functionality are available.
  • Added new "Shortcuts" module to allow user to create their own menu for the pages they visit the most.

Database:

  • Added query builders for INSERT, UPDATE, DELETE, MERGE, and SELECT queries.
  • Support for master/slave replication, transactions, multi-insert queries,delayed inserts, and other features.
  • Added support for the SQLite database engine.
  • Default to InnoDB engine, rather than MyISAM, on MySQL when available for greater scalability and data integrity.

Several Performance Improvements Implemented

Documentation:

  • Hook API documentation now included in Drupal core.

News aggregator:

  • Added OPML import functionality for RSS feeds.
  • Added feed update options.

Search:

  • Added support for language-aware searches.

Testing:

  • Added test framework and tests.

Theme system:

  • Removed the Bluemarine, Chameleon and Pushbutton themes. These themes live on as contributed themes
  • Added "Bartik" theme as the default user interface theme.
  • Added "Seven" theme as the default administration interface theme.
  • Added "Stark" theme to make analyzing Drupal's default HTML and CSS easier.

File handling:

  • Files are now first class Drupal objects with file_load(), file_save(),
    and file_validate() functions and corresponding hooks.
  • Files use PHP stream wrappers to enable support for both public and private files and to support pluggable storage mechanisms and access to remote resources (e.g. S3 storage or Flickr photos).
  • Added a field specifically for uploading files, previously provided by
    the contributed module FileField.

Image handling:

  • Improved image handling, including better support for add-on image
    libraries.
  • Added a field specifically for uploading images, previously provided by the contributed module ImageField.

Better Support for Multisite Installations

Added RDF support

Better support for search engine optimization and web linking

Added ability to add custom fields

  • Provides most of the features of the former Content Construction Kit (CCK) module.
  • Custom data fields may be attached to nodes, users, comments and taxonomy terms.
  • Node bodies and teasers are now fields instead of being a hard-coded property of node objects.
  • Fields are translatable.

Installer can be run from the command line

JavaScript changes

  • Upgraded the core JavaScript library to jQuery version 1.4.2.
  • Upgraded the jQuery Forms library to 2.36.
  • Added jQuery UI 1.8, which allows improvements to Drupal's user experience.

Improved node access control system

Task handling

  • Improved handling of long-running tasks.