Friday, September 11, 2015

How to build custom entity in drupal ?

For a traditional php/zend/codeignitor  programmer the logic behind developing any stuff is to create db tables with some form , save these content into db table and show these data on view parsing through controller .
How to do this custom module / programming stuff in drupal ?
Let us take entity api example step by step


Entities are a great way to organize your data in Drupal. If you are familiar with nodes, taxonomy terms, comments or users, you should also know that since Drupal 7, these have been entities. Another important aspect about them is that they are fieldable via the Field API.
In this tutorial I will show you how you can define your own custom entity type and get started working with it. Why would one want to do this instead of using nodes? Because although they are great, nodes can sometimes be overkill. There is a lot of functionality you may not need such as revisions or commenting.
For example we will define our own custom entity type called Insurance to represent simple information we have about our projects (title, price and deadline)(title,price,tenaure ). Then we will look at a few things about working with the entities of this type.
  dditionally, you need the Entity API contrib module enabled on your site and set as a dependency to your custom module. The Entity API module is very powerful when working with entities as it provides a lot of functionality that the Drupal core lacks.

Defining our own Drupal entity type

The first thing we need to do to create a new entity type is to declare its schema definition. That is, write the code that will generate the database table for the entity data. In my demo.install file I have the following code:
/**
 * Implements hook_schema().
 */
function demo_schema() {

  $schema = array();

  $schema['demo_insurance'] = array(
    'description' => 'The base table for the Project entity',
    'fields' => array(
      'id' => array(
        'description' => 'Primary key of the Project entity',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'name' => array(
        'description' => 'Policy name.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
      ),
      'price' => array(
        'description' => 'Insurance price.',
        'type' => 'text',
        'size' => 'big',
        'not null' => FALSE,
        'default' => NULL
      ),
      'tanure' => array(
        'description' => 'Insurance tanure.',
        'type' => 'int',
        'length' => 11,
        'not null' => FALSE,
      ),
    ),
    'primary key' => array('id'),
  );

  return $schema;
}
This is a simple implementation of hook_schema() through which we create a demo_projects table that has 4 columns: id, name, description and deadline, the first representing the primary key. Nothing big.
The next thing we need to do is implement hook_entity_info(). There are a lot of options we can specify in this hook, but here are the most basic and required ones (this goes in the demo.module file):
/**
 * Implements hook_entity_info().
 */
function demo_entity_info() {

  $info = array();

  $info['insurance'] = array(
    'label' => t('insurance'),
    'base table' => 'demo_insurance',
    'entity keys' => array(
      'id' => 'id',
      'label' => 'name',
    ),
    'module' => 'demo',
  );

  return $info;
}
With this hook we return a new key in the $info array that represents the entity machine name. Inside this array we specify the options (we will add more in the course of this tutorial). For now, we will stick tolabel (human readable name of the entity type), base table that stores the entity data, entity keyswhich are the properties that act as identifiers for the entities and module that specifies which module defines the entity type. The last one is not mandatory but recommended.
And with this we have registered our own basic entity type with Drupal. To test out if it works, enable the module for the first time and check if the table was created in the database. Then populate it with a few rows to have something to work with:
INSERT INTO `demo_insurance` (`id`, `name`, `price`, `tanure`)
VALUES
    (1, 'Summer House', '10000', '120m'),
    (2, 'Winter House', '25000', '60m');
Finally, register a path with Drupal (any path for testing only) using hook_menu() and paste the following in its callback function:
$projects = entity_load('insurance', array(1, 2));
dpm($projects);
return 'Some string';
First, we use the entity_load() function to load the project entities with the IDs of 1 and 2 and then we print them to the screen using the Devel dpm() function (so make sure Devel is enabled on your site for testing). And don’t forget that the callback function for the page needs to return something otherwise it won’t build.
Now if you navigate to that page you’ll see in Krumo the data from the 2 entities in the database.
Alternatively, you can use the EntityFieldQuery class to query for the new entities by any property you want (not just the id). For more information about how this works you can check out this Sitepoint tutorialthat will get you started.

Entity class and controller

Unfortunately, Drupal core does not come with too many helper functions to work with entities (entity_load() is pretty much the only one). However, the Entity API module fills this gap.
In order to make use of its functionality, we need to alter the entity info we declared earlier and specify the PHP classes that can be used to work with the entities. For now, we’ll add 2 more keys to the array keyedproject inside our hook_entity_info() declaration:
...

'entity class' => 'Entity',
'controller class' => 'EntityAPIController',

...
The first one is the base class provided by Entity API that will offer some wrapping functionality for the entities. This class is declared in the entity.inc file of the module and if you look inside, you’ll notice that many of its methods call the methods of another (controller) class. This is the class we specified for the controller class key.
The EntityAPIController class (found in entity.controller.inc file of the module) offers some sensible defaults for working with the entities. It extends the default Drupal coreDrupalDefaultEntityController class and it is responsible – among many other things – for performing CRUD operations.
Both of these classes can be extended in your custom module to adjust functionality (like querying, loading or displaying the entities). We will see how to do this in a minute.
But first, I want to show you how to save a new entity. Currently, in my database I have 2 records with the ids 1 and 2. I want to adjust the code we wrote in the test page callback above to create a new entity with the id of 3 if one doesn’t already exist. It can look something like this:
 $projects = entity_load('insurance', array(1, 2, 3));

 if (!isset($projects[3])) {
   $entity = entity_create('insurance', array('id' => 3));
   $entity->name = t('accidental policy');
   $entity->price= t('5000');
$entity->tanure= t('60m');
$entity->save(); } dpm($projects); return 'Some string';
As you can see, now we try to load 3 project entities and check for the existence of the third. If it doesn’t exist, we use the entity_create() helper function provided by Entity API, set the properties to some random values and then use the save() method on the entity to persist it to the database. This method is provided by the Entity class and its job is to call the save() method on the controller class we defined above. And that method will perform the logic necessary to persist the entity. But all this happens behind the scenes and we don’t have to worry about it.
If you reload that page, you should see only 2 returned project entities, but if loaded a second time, there should be 3.

Overriding the entity classes

The last thing I want to show you in this part of the tutorial is how to display your entities. For this, we will stick to the page callback function we’ve been working with and have it render a list of our entities.
The first thing we need to do is override the buildContent() method of the defaultEntityAPIController class. The reason is that the controller cannot make assumptions about our data so we need to provide some information about how to display it. First, let’s declare our controller class that extends the previous one:
/**
 * Extending the EntityAPIController for the Project entity.
 */
class ProjectEntityController extends EntityAPIController {

}
I chose the class name ProjectEntityController and you need to make sure that you replace with this name the value you set for the controller class key in the hook_entity_info()implementation. Don’t forget.
Inside of this class, we can copy the method name from the original one and have it return the same its parent would:
public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {

$build = parent::buildContent($entity, $view_mode, $langcode, $content);

// Our additions to the $build render array

return $build;

}
As such, there are no new changes. But now we can add our own data to the returned value of this method which is nothing more than a Drupal render array. So for example we can write this right before we return the $build array:
$build['price'] = array(
  '#type' => 'markup',
  '#markup' => check_plain($entity->description),
  '#prefix' => '<div class="project-description">',
  '#suffix' => '</div>',
);
$build['tanure'] = array(
  '#type' => 'markup',
  '#markup' => date('d F, Y', check_plain($entity->deadline)),
  '#prefix' => '<p>Deadline: ',
  '#suffix' => '</p>',
);
We are basically adding two new items to the array. The first one will wrap the description with a<div class="project-description"> and the second will output a formatted date in between paragraph tags. This is basic Drupal theming so brush up on that if you don’t understand what’s going on here. But you will notice that the project name is missing. That will be rendered automatically by Drupal because we specified it as the label in the entity keys of the hook_entity_info() implementation.
The final step is to go to our page callback function and make it display our entities. A quick way of doing that (just for demonstration purposes):
$projects = entity_load('project', array(1, 2, 3));

$list = entity_view('project', $projects);

$output = array();

foreach ($list['project'] as $project) {
  $output[] = drupal_render($project);
}

return implode($output);
As before, we first load our entities with the respective ids. Then, we run them through theentity_view() helper function that will end up calling the buildContent() method we just overrode. This function returns a list of render arrays for each entity. We render each one and store the result in the$output array that we then implode and return.
You can refresh the page and you should see a listing of all the entities you loaded. Make sure you clear the caches so that the changes become visible.

  Welcome back to the second part of this tutorial in which we explore the world of custom entities in Drupal. If you haven’t already, I strongly recommend you read the first installment, but let’s do a short recap nonetheless.

In the previous article we’ve defined the schema for our entity type and registered it with Drupal. We’ve also overridden the EntityAPIController to build up the display for our entities.
In this part of the tutorial we will continue and talk about a few other cool things we can do with entities in Drupal. First, we’ll quickly set up the pages where we can display the individual project entities. Next, we will build a straightforward but very powerful admin interface to manage them. Then, we will make our entity type fieldable so we can add fields through the UI. And finally, we’ll expose it to Views so we can create proper listings of project entities.
If you want, you can follow along with the source code from the first branch of the Git repository, or take a peek into the second branch which contains all the code we will cover today.

Individual entity pages

The first thing we’ll do is create the pages for displaying individual project entities. We’ll start by adding a new item to our hook_menu() implementation:
  $items['project/%'] = array(
    'title' => 'Project',
    'page callback' => 'demo_view_project',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );
We are registering a path (project/id) and a callback function (demo_view_project()) to which we pass the wildcard URL argument (the ID of the project). As for access, anybody with theaccess content permission can see the page.
Next, let’s write the said callback function (keep in mind this is a simple example just for demonstration purposes):
/**
 * Callback function for displaying the individual project page
 */
function demo_view_project($id) {

  $projects = entity_load('project', array($id));
  $project = $projects[$id];

  drupal_set_title($project->name);
  $output = entity_view('project', array($project));

  return $output;

}
This is again very simple: we load the entity with the ID passed from the URL, we set the title of the page, run the entity object through entity_view() and return it as page output. We’ve covered these Entity API concepts last time when we listed our projects. You can now clear the cache and navigate toproject/1 and you should see the project with the ID of 1. If you see the project name twice, don’t worry, this will become clear in the next section when we let Drupal know which one is the default URI callback for the project entities.

Admin user interface

Now that we can display the individual entities, let’s leverage the power of the Entity API module to set up a quick admin user interface to manage them. There are a few simple steps we need to take for this.
First, let’s edit our hook_entity_info() implementation for our entity type and add the following (I’ll explain everything after):
...

'access callback' => 'demo_access_callback',
'uri callback' => 'entity_class_uri',
'admin ui' => array(
  'path' => 'admin/projects',
  'controller class' => 'EntityDefaultUIController',
),

...
And replace this line:
'entity class' => 'Entity',
With this:
'entity class' => 'ProjectEntity', 
With these modification, we do 4 things:
  1. We specify an access callback function for the entity type. We’ll need this for the admin UI and we’ll declare the callback function in a minute.
  2. We set the uri callback to the default one provided by the entity class (I will come back to this at point 4).
  3. We set the admin ui information: path to the UI page and the controller class that will handle it.EntityDefaultUIController is the default UI class that comes with Entity API and it is declared in the entity.ui.inc file.
  4. We change the name of the entity class for this entity type to one that does not exist yet. We will create it now by extending the previous one so that we can override its defaultUri() method:
    /**
     * Project entity class extending the Entity class
     */
    class ProjectEntity extends Entity {
    
      /**
       * Change the default URI from default/id to project/id
       */
      protected function defaultUri() {
        return array('path' => 'project/' . $this->identifier());
      }
    
    }
    
As you can see, we are basically changing that path to the individual project entity returned by this class method. When the time comes, I will point out why this was handy but this will be the default one I mentioned at point 2. Now let’s quickly also declare our access callback function mentioned at point 1:
/**
 * Access callback for project entities.
 */
function demo_access_callback($op, $project = NULL, $account = NULL) {
  if ($op == 'view' || $op == 'update' || $op == 'create' || $op == 'delete') {
    return TRUE;
  }
  else {
    return FALSE;
  }
}
As you can see, this is not much of an access callback function as it returns true for everything. Here you will normally perform proper access checks but for our demonstration purposes it works just fine.
Now there is one last thing we need to do to make use of our admin interface: declare a simple add/edit form for the project entity and its submit handler:
/**
 * Form definition for adding / editing a project.
 */
function project_form($form, &$form_state, $project = NULL) {

  $form['name'] = array(
    '#title' => t('Project name'),
    '#type' => 'textfield',
    '#default_value' => isset($project->name) ? $project->name : '',
    '#required' => TRUE,
  );

  $form['description'] = array(
    '#title' => t('Project description'),
    '#type' => 'textarea',
    '#default_value' => isset($project->description) ? $project->description : '',
    '#required' => TRUE,
  );

  $form['deadline'] = array(
    '#title' => t('Project deadline'),
    '#type' => 'textfield',
    '#default_value' => isset($project->deadline) ? $project->deadline : '',
    '#required' => TRUE,
  );  

  $form['submit'] = array(
    '#type' => 'submit', 
    '#value' => isset($project->id) ? t('Update project') : t('Save project'),
    '#weight' => 50,
  );

  return $form;
}

/**
 * Submit handler for the project add/edit form.
 */
function project_form_submit($form, &$form_state) {
  $project = entity_ui_form_submit_build_entity($form, $form_state);
  $project->save();
  drupal_set_message(t('The project: @name has been saved.', array('@name' => $project->name)));
  $form_state['redirect'] = 'admin/projects';
}

in this way we can create   entire different set of module with different table  and save data in it. 

Wednesday, September 9, 2015

Deployment Processes available with drupal 7

Deployment is one of the panic areas for high traffic website.

Some of best deployment process Deploy module with Features module.
In its simplest terms, deployment is when you release changes to your website from your local environment to your live site. In professional environments, you are likely to have multiple stages before live, such as QA and staging. Each of these stages require deployment for each release.

The Deploy module can be used to export any entities that support UUID into Features. This can be useful for install profiles and distributions to provide default/demo content, or for circumstances in which a piece of content straddles the line between pure content and configuration.
To export content with Deploy:
  • Install Deploy along with the Features Module. The Services module and it's setup steps are not required if you are not going to be using Deploy to sync content from one Drupal site to another, and only want to be able to export into Features.
  • Go to admin/structure/deploy/plans/add to create a new Deployment Plan.
  • Select your desired aggregation method (See Basic usage of Deploy for info on the different methods available for adding content to a deployment plan).
  • Check the Fetch only checkbox. Not only will we not be needing a deployment processor or service endpoint, but the entities added to the Deployment Plan will not actually be exposed in the Features UI unless "Fetch only" is set!
  • Go to admin/structure/features/create
  • Under Deployment (deploy_plans), select the component for the deployment plan you created
  • Under UUID Entities (uuid_entities), you will have a component matching the name of your deployment plan. Select it as well
  • Note that selecting these components will not automatically provide dependencies such as content types, fields, modules, etc. Be sure to select any other dependencies you may need. If you're bringing the content to a site with similar/same configuration, or have your dependencies covered with a separate feature, you're fine to export just the Deployment Plan and its related UUID Entities component.
The entity type you are exporting will need to be supported for UUID in order for it to be exportable. The Entity UUID project aims to add support for any non-core entities. To add UUID support specifically for Commerce entities, check out Commerce UUID
Alternative Method:
UUID Features Integration module provides a simple way to export content to Features, but it mostly supports core entities. Using Deploy, the entity just needs to have UUID support to be exportable. If you're just needing core entities like nodes or taxonomy terms, this method may be simpler as it does not really require extra configuration.

contact me - anshul.udapure@gmail.com
9009902877

Data migration in drupal

Contact me - anshul.udapure@gmail.com
9009902877

Data migration with Feed and related module

This post is a short how-to on importing data from multiple fields of a comma separated value (CSV) file into one multi-value field using the Drupal Feeds Tamper.
Chances are you have been in a situation where you need to import some data into a Drupal site. The data was provided to you in a CSV file. Because you are smart and know better than to spend your client’s money writing your own code for this, you grab the Feeds module which conveniently includes a CSV parser.
All is well until you need to merge the content of multiple sources (eg: “cells”) into one target (eg: “field”). This might be the case if you have a List field where multiple options can be checked.
For each of these names we want all of the certifications to be passed to a single field:
View of our list field widget
This is where Feeds Tamper shines. Here’s how you do it:
1. Go to your feed processor mapping page and map all three sources to the one target:
View of our Source / Target mapping
2. Go to the Tamper tab (if you are using the dev version) or to the Feeds Tamper link above the mapping table (if you are using the beta-3 version) and add a plugin for the last of your 3 sources (in our example certification_three).
3. Select the Rewrite plugin and use the tokens to rewrite the input to include all of your sources separated by a comma and save.
A view of the configuration of our Rewrite plugin.
4. Add a second plugin: Explode. Make sure that the string separator is the same as the one you have used in the Rewrite plugin. Save.
5. Run your import et voilà!
A couple of gotchas: there seems to be some cases where this module misbehaves. In the example I just described, each of the certifications is numbered by a string. Using an integer (eg: certification1, certification2) made the Rewrite plugin fail. Indeed instead of the value the token represents, you will get the label of the token itself.

Set Up Multiple drupal website with same code base



Hi Freinds.As web world growing many organizations need multiple website to promote there business.Sometime it is not easy to get SEO rank of contents through one domain . Associated and content related domain is required .
So Organizations created multiple website.But it lead to some more back end web work to maintain these multiple websites.  The solution drupal comes with multiple website can be set up with one code base.

How to Set Up Multiple drupal website

Multi-sites is a Drupal feature that makes managing many websites easier.
The idea with multi-sites is that you can use a single codebase for more than one website. When you update that single codebase, you update all of your Drupal sites. Each site can still have its own theme, modules and content.
With multi-sites you can have many sites with one database, or many sites with different databases.  In this tutorial we will chose to have multiple sites, each with their own database.
We're going to set up one core installation, and share those files with two sub-sites. Each sub-site will share those files but have its own URL and its own database. In this tutorial I'm going to set up two sub-sites with different URLs:
  • Master site: http://emotiongift.com
  • Sub-site 1: http://flowersallindia.com
  • Sub-site 2: http://mumbaicakes.com
Setting up multi-sites is not an easy task for beginners. To make it easier, we're going to show you how to use your hosting account with cPanel to get this done more easily. If you aren't using a commercial host with cPanel, your setup process will be slightly different.

Step 1. Choose your master domain name

Your first step is to hoose the URL that will host your main site. As we mentioned, in this example, our main URL will be http://emotiongift.com.
 
This doesn't have to be an important URL. Unless you decide you want it to, this one won't be used by anyone but you. It's only going to hold the master copy of your Drupal installation. 
 
It is worth nothing however that this site might be visible if one of your sub-sites fails. So it would be a good idea if your master site had a page with your contact information and a message.

Step 2. Start out by creating databases for all the sub-sites

  • Go to MySQL in cPanel or use the database wizard to create databases for each site you want to add.
  • Be sure to add database users with full privileges to each database. If you want to maximise security, create a new database user for each database. In the example below, I named the databases the same as the URLs. This is recommended on a live site, but it does makes it easy for me to refer to them in the tutorial.
tutuploadsmedia_1332372657629.png
 

Step 3. Install Drupal in your master URL directory

  • Install Drupal in your /public_html/ directory.
  • Visit the URL (in this case http://easywebupdate.com) and step through the Drupal installation.
  • Use the master database connection information when the install script asks for it.
tutuploadsmedia_1332354346780.png

Step 4. Create a sub-folder for each sub-site.

  • Create a folder under public_html/sites/subsite.com. Substitute the URL you are going to use.
tutuploadsmedia_1332373988030.png
  • Create one folder for each sub-site.
  • Now copy default.settings.php to each one.
  • CHMOD those files to 644 if they aren't already.
  • If you are doing multi-sites for Drupal 6, you should also create an additional folder called "files" and make sure it's CHMOD 755.
tutuploadsmedia_1332374012859.png

Step 5. Upload or copy default.settings.php to the new folders

You now need to add default.settings.php to your new folders. The image below shows how file structure looks in Filezilla that makes it a little more obvious.
  • If it is Drupal 6, create a files directory with the path sites/domain.com/files/. You don't need this extra directory here for Drupal 7.
  • Copy or upload default.settings.php to the folder.
  • Rename it to settings.php.
tutuploadsmedia_1332374565075.png
We are now finished with the Drupal master site. The next part is more complicated because we have to make sure the domain names are correct. Luckily cPanel can do this easily for beginners. We'll show you that method first. There is a manual method, but it involves making changes in Apache files and this is probably beyond beginner-intermediate skills required of this tutorial.

Step 6. Return to cPanel

  • On the main cPanel dashboard, find the Domains section and click Parked Domains.
tutuploadsmedia_1332375283418.png
 

Step 7. Add the domain

  • Park the domains on top of the master domain.
  • When you park a domain, the domain needs to be pointed at the DNS servers for your hosting account. If you don't know how to do this, the proper place to get information is from the domain name registrar. If you don't know who your registrar is, you get that information your hosting company.
tutuploadsmedia_1332375638592.png

Step 8. Go to your browser and visit the URL

tutuploadsmedia_1332375936533.png
  • In your browser address bar, type the url to your second or third site.
  • Install Drupal by following the prompts.

Step 9. Connect to the proper database

tutuploadsmedia_1332376154830.png
  • When prompted, enter the database information for this specific site.

Result

tutuploadsmedia_1332376922412.png
Three sites, each with their own theme, each with their own modules, all on the same hosting account. To create another site, I just repeat the process. Using cPanel's parking feature, I was able to avoid the need to make changes to Apache, and the need to make symbolic links or redirects in the .htaccess file.
There is another way to do it that is almost as simple, but if you want to try it you will learn a little more since it involves creating a symbolic link. We'll give you the code to paste into your site and walk you through it.

Option 2: Quick ways to set up Drupal multi-sites with cPanel Sub-Domains

Go through Steps 1 through 3 of this tutorial. Everything is the same up to that point. In Step 4 you take a slight detour and so Option 2 starts from that point on.

Option 2, Step 4: Create directories for each domain with the convention subdomain.domain.com

tutuploadsmedia_1332378791796.png
  • Create folders for each site you want to create.
  • Create the folder names with this convention subdomain.domain.com.
  • Upload or copy default.settings.php to each directory.
  • Change the name of each copy to settings.php.
  • Return to cPanel home.

Option 2, Step 5: Create subdomains

tutuploadsmedia_1332382035356.png
  • Go to the Domains section and click Subdomains.
tutuploadsmedia_1332382168695.png
The correct directory structure is pictured below:
  1. The directories created by cPanel.
  2. The directories created by you.
tutuploadsmedia_1332382407419.png
 

Option 2, Step 6: Write a simple php script to create a symlink

In a script editor create a file called mysymlink.php and put the following code into it.
 <?php
symlink( '/home/cPanel_User_Name/public_html/', 'subdomain' ); ?>
In my case the file would look like this
 <?php
symlink('/home/myuserdirectory/public_html/','edandrea');
symlink('/home/myuserdirectory/public_html/','edsparty');
?> 

Option 2, Step 7: Upload the symlink script to the main directory

To run it go to your browser address bar and type in your url and the name of the file.
http://example.com/mysymlink.php
If all goes well you will see a completely blank page. If you made a mistake in the file you will see error messages.
tutuploadsmedia_1332383456174.png

Option 2, Step 8: Add redirection to your .htaccess file

  • Open your .htaccess file in a script editor
  • Find the line # RewriteBase/ and remove the # sing.
  • Add the following line and save the changes
 RedirectMatch 301 ^/subdomain/(.*)$ http://subdomain.yoursite.com $1 
Here's what my .htaccess looked like when finished:
 RewriteBase / RedirectMatch 301 ^/edandrea/(.*)$ http://edandrea.easywebupdate.com/$1 RedirectMatch 301 ^/edsparty/(.*)$http://edsparty.easywebupdate.com/$1 
This redirection will make it so the site can be accessed in two ways.
http://easywebupdate.com/edsparty and http://edsparty.easywebupdate.com will both be redirected to the same site.

Option 2, Step 9: Visit your subdomain and complete the installation

If you did everything right, you can visit your subdomain and you will now be asked to install Drupal in your subdomain.

More on Drupal Multi-sites

What you've seen in this tutorial is just the beginning of the possibilities with Drupal Multi-Sites. There are many optional ways to arrange the code and the data:
  • Multiple domains or vhosts using different databases.
  • Multiple domains using the same database.
  • Multi-site setup using a single Drupal instance.
  • Same codebase, completely different content and users.
One security concernt to note is that Drupal's multi-site feature is normally used in situations where the administrators for all of the sites are highly trusted. The reason is that anyone with full administrative privileges on a Drupal site can execute arbitrary PHP code on that site through various means, even without FTP access to the site. That arbitrary PHP code could be used from one site to affect another site if the two sites are in the same HTTP document root and share the same Drupal codebase. For more information:http://drupal.org/node/476544 and http://drupal.org/node/1244642.

Sunday, August 7, 2011

Custom drupal module drupal 6 , drupal 7, drupal 8 - Check differences

Drupal follows the modular structure.Features of drupal can be extended and implemented by adding a module in it without touching drupal core script.

Steps to make drupal module drupal 6

1) Make a new file with name module_name.info (it contain following )
; $Id$
name = Test Module
description = Allows users to implement new features.
core = 6.x
package = Drupal Development

It has few line which contain information about module like module name, description of module , drupal version it supports, and package you want to keep this module
2) Make one installation directory . If you want to add some mysql table in
module than need of this file
It contain few installation function
a) function table_name_install(){
drupal_install_schema('table_name');
}
b) uninstall function , when module will uninstall than it delete table from
database
function annotate_uninstall() {
drupal_uninstall_schema('table_name');
}
c) Implementation of hook_schema()
function module_name_schema() {
$schema['test_description'] = array(
'description' => t('Stores node test_description that users write.'),
'fields' => array(
'nid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => t('The {node}.nid to which the test_description applies.'),
),
'uid' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
'description' => t('The {user}.uid of the user who created the test_description.')
),
'note' => array(
'description' => t('The text of the test description.'),
'type' => 'text',
'not null' => TRUE,
'size' => 'big'
),
'primary key' => array(
'nid', 'uid'
),
);


return $schema;
}

3) create another file with name module_name.module
We need to read this first before making a new module
http://api.drupal.org/api/drupal/includes--module.inc/group/hooks/6
here it is a list of available drupal hooks

Allow modules to interact with the Drupal core.

Drupal's module system is based on the concept of "hooks". A hook is a PHP function that is named foo_bar(), where "foo" is the name of the module (whose filename is thus foo.module) and "bar" is the name of the hook. Each hook has a defined set of parameters and a specified result type.

To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.

Now view the hook_menu which enable the menu in drupal
function module_name_menu() {
$items['admin/settings/annotate'] = array(
'title' => 'Annotation settings',
'description' => 'description of module menu',
'page callback' => 'drupal_get_form',// will set the drupal form which will be implemented later
'page arguments' => array('module_name_admin_settings'),
'access arguments' => array('administer site configuration'),
'type' => MENU_NORMAL_ITEM,
'file' => 'module_name.admin.inc',
);

return $items;
}


Steps to make drupal module drupal 7

Create Custom Module

In your modules directory (sites/all/modules) create a folder for your module. For this example our module will be called anshulblockmodule, so we would create the directory sites/all/modules/anshulblockmodule. Your module can be called whatever you like, just make sure that when following this tutorial your replace "myblockmodule" with your modules name.

1. Create a .info file

All modules in Drupal require a .info file to let Drupal know that our module exists, what it's name is, as well as other information about our module. In your module folder (sites/all/modules/anshulblockmodule), create a file named anshulblockmodule.info. In myblockmodule.info enter the following:

name = AsnhulBlockModule 
description = Tutorial Modules for beginners 
package = Tutorial Modules 
core = 7.x 

The Explanation

This is how the above breaks down:
  • name is the human readable name of your module. This is required for all modules, It is shown on the modules administration page.
  • description is a short message explaining what this module does. This is also visible on the modules administration page.
  • core describes which version of Drupal this module works with. This is required and should be "7.x" for all Drupal 7 modules.
  • package is optional, but I recommend it. The main purpose of this is to define what category to list the module in on the module admin page.
There are other variables you can define in this file, but these are the main four I put in all modules I create. For more information on module .info files check out Writing module.info files.

2. Create a .module file

There are two files which every module must have. First is the .info file, which we already created. The second is the .module file. Despite the file's extension it is really a PHP script. This file is evaluated every time Drupal a Drupal page is load. The main purpose of this file is to define functions which implement hooks. Hooks are evaluated during different Drupal events and can be called by Drupal itself or other custom modules. (For further reading on hooks: Hooks 101)
For our module we will create a new file in our module's directory (sites/all/modules/anshulblockmodule) called anshulblockmodule.module. This file will implement two hooks, one to let Drupal know that we are defining a new block, and one to let Drupal know what the block's content is. The file will contain the following: 
<?php
/**
 * Declare what blocks are provided by this module.
 * Implements hook_block_info().
 */
function anshulblockmodule_block_info(){
    $block['static_content'] = array(
        'info' => t('Drupal tutorial'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function anshulblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'static_content'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = t('lorem ipsum sit');

        //Define the block content.
        $block['content'] = t('lorem ipsum ').(strtotime("2015-10-21")-time()).t(' seconds.');
    }

    return $block;
}

 In this way can create custom block and can put anywhere in template.

It is very useful to fetch any content as block content from drupal instead od creating views everytime. it increase the performance of drupal website. you can set the cache_Get and cache_Set method for caching. we will those example later.