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.