Insightful stories that revolve around technology, culture, and design

All blogs

Topics
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Override existing Configuration entity types - Drupal 8
Category Items

Override existing Configuration entity types - Drupal 8

In this article we take a deeper look into config entity types, why do we need to override config entity types? and whats the best way to override them.
5 min read

Why do we need to override Config Entity Types?

  1. By default, Vocabulary list displays all the vocabularies. In case we want to restrict certain roles from viewing certain vocabularies. Overriding that Class(VocabularyListBuilder) function would be the solution to display specific/no/all vocabularies.
  2. Let's assume we need to specify vocabulary-path for each vocabulary apart from name, title, description, vid etc. In this case we would need to override the default Vocabulary Form of taxonomy_vocabulary config entity type.
  3. Suppose we want to custom access check for views on the basis of role/user/views operation or whatever, we would need to override ViewsAccessControllerhandler of view configEntityType and write our own logic.
  4. Another use case can be, if we want to display all the image fields which use image style being deleted, on confirm text message, we again need to override ImageStyleFlushForm class and redefine getconfirmText function.

In short, to customise and meet our dynamic requirements which may not be supported by config entity type definition as a part of @ConfigEntityType annotations in core or contributed modules, we need to override existing config entity types and write some custom code :).

How can we override Config Entity Types?

Entity types use object based annotation unlike array based annotation which is commonly used. Also, Unlike Content Entity Types where every thing is a field, NOTHING is a field for Configuration Entity type.

Every Drupal config entity type is defined as a particular ConfigEntityType Annotation. Entity controller is completely different from the Controller of MVC pattern. To avoid this confusion in terminology Entity Controllers are termed as handlers, each form related to a particular entity type say taxonomy_vocabulary is declared inside handlers with form key. 

In this article, will take an example of adding custom form elements to config entity type forms to explain this.

In case we need to add a custom element to any of these forms, we need to follow these 2 steps:

I) Set a new handler class specific to that form.

  1. Implement hook_entity_type_alter(array &$entity_types).
  2. Set new handler class as :

$entity_types[{id}]->setHandlerClass('form',
 ['{form_type}' => 'Drupal\my_module\MyModuleForm',
 '....',
 '....'
 ]);


where, id = configEntityType id,  form_type eg: default, reset, delete etc is whichever form we want to override and MyModuleForm is the Class name of new form we'll define in Step II.
Here is the sample code of overriding default form of taxonomy vocabulary.


$entity_types['taxonomy_vocabulary']->setHandlerClass('form',
 ['default' => 'Drupal\my_module\VocabularyForm',
 'reset' => 'Drupal\taxonomy\Form\VocabularyResetForm',
 'delete' => 'Drupal\taxonomy\Form\VocabularyDeleteForm'
 ]);

II) Define the class set in Step I.

  • Extend the actual class of the form we want to add new form elements to. 

use Drupal\taxonomy\VocabularyForm as VocabularyFormBuilderBase;

{this is optional, we need to do this to keep the new class name same as base class i.e VocabularyForm}.


class MyModuleForm extends VocabularyFormBuilderBase 	

OR simply,


class MyModuleForm extends VocabularyForm	


This override is important because we need to inherit functions and form elements defined in the parent class i.e VocabularyForm and also add additional feature i.e form element without disturbing the core code. This is purely OOPs concept of inheritance.

  • We need to override the form function by 
  1. Inheriting the parent elements by parent::form(....) and
  2. Defining the new custom elements as the basic example below:

$form['third_party_settings']['qed42_textfield'] = array(
 '#type' => 'textfield',
 '#title' => t('QED42 Custom Form Element'),
 '#default_value' => $vocabulary->getThirdPartySetting('my_module', 'qed42_textfield', 'Qed42 textfield default value')
);  

Config Entities have by default "getThirdPartySetting()" function { Config entities inherit this function if these extend ConfigEntityBase class which implements ConfigEntityInterface interface which in turn extends ThirdPartySettingsInterface interface}. This thirdParty function allows to set and retrieve a value particularly for a module.

  • Similarly, we can inherit the save function to save the value of newly added form element with Third Party Settings  as :  If the form is set as Tree we need to set value as

$vocabulary->setThirdPartySetting('my_module', 'qed42_textfield', $form_state->getValue('third_party_settings')['qed42_textfield']);		

else :


$vocabulary->setThirdPartySetting('my_module', 'qed42_textfield', $form_state->getValue('qed42_textfield'));		

and of course inherit the parent save function.

  • We can implement the same logic for extending definition of any existing method  AND can also define new functions inside our new Form.

Any Configuration Entity Type (Date format etc) can be overridden similarly, this can be extended to list_builder, access etc.  Apart from overriding, we can also add new flavours of entity controller using the above steps.

REST API Explorations in Drupal 8 - Primer
Category Items

REST API Explorations in Drupal 8 - Primer

Discover how Drupal 8 leverages RESTful architecture for CRUD operations on resources like users. A step-by-step guide to REST API exploration.
5 min read

To explore the RESTful nature of Drupal 8, we will need to enable the following modules:

In Core

  • HAL - Serializes entities using Hypertext Application Language.
  • HTTP Basic Authentication - Provides the HTTP Basic authentication provider.
  • RESTful Web Services - Exposes entities and other resources as RESTful web API
  • Serialization - Provides a service for (de)serializing data to/from formats such as JSON and XML.

Contributed

  • REST UI - Provides a user interface to manage REST resources.

RESTful Resources

Every entity in D8 is a resource, which has an end point. Since, its RESTful, the same end-point is used for CRUD (Create, Read, Update, Delete) operations with different HTTP verbs. Postman is an excellent tool to explore / test RESTful services.  Drupal 8 allows you to selectively choose & enable a REST API. e.g., we can choose to expose only nodes via a REST API & not other entities like users, taxonomy, comments etc.

After enabling REST_UI module we can see list of all RESTful resources at /admin/config/services/rest. In addition to ability to choose the entity one can enable, we can also choose the authentication method per resource & enable specific CRUD operations per resource.

Resource Settings

Let us take a look at what the REST APIs for User entity would be after we save the configuration in the above screenshot.

User

POST


http://domain.com/entity/user?_format=hal_json

{
 "_links": {
   "type": {
     "href": "http://domain.com/rest/type/user/user"
   }
 },
 "name": {
   "value":"testuser"
 },
 "mail":{
   "value":"testuser@mailserver.com"
 },
 "pass":{
   "value":"testpass"
 },
 "status": {
   "value": 1
 }
}

Header


X-CSRF-Token: Get from http://domain.com/rest/session/token
Content-Type: application/hal+json
Accept: application/hal+json
Authorization: Basic (hashed username and password)

Note: Drupal 8 doesn't allow anonymous user to send a POST on user resource. It is already fixed in 8.3.x branch but for now we can pass the credentials of the user who have permission to create users. If you are interested in taking a deeper look at the issue, you can follow https://www.drupal.org/node/2291055.

Response: You will get a user object with "200 OK" response code

PATCH


http://domain.com/user/{uid}?_format=hal_json

{
 "_links": {
   "type": {
     "href": "http://domain.com/rest/type/user/user"
   }
 },
 "pass":[{"existing":"testpass"}],
 "mail":{
   "value":"updatedtestuser@mailserver.com"
 }
}

Note: Now as user have permission to update his own profile so we can pass current user's credentials in authentication header.

Response: You will get "204 No Content" in response code.

GET


http://domain.com/user/{uid}?_format=hal_json

Response: You will get a user object with "200 OK" response code.

DELETE


http://domain.com/user/{uid}?_format=hal_json

Response: You will get "204 No Content" in response code.

RESTful Views and Authentication

Drupal 8 also allows us to export views as a REST service. It allows you to use all the available authentication mechanism in views itself.

JSON API Module

JSON API module provides a new format called "api_json" which is soon becoming the de-facto standard for Javascript Frontend frameworks, If you plan to use completely de-coupled Drupal with frontend framework like Angular / React / Ember then its worth a look. To read more about JSON API you can visit the site.This article assumes you are familiar with what RESTful is & what do we mean when we use the term REST API. Some of you might have already worked with RESTful Web Services module in D7, it exposes all entity types as web services using REST architecture. Drupal 8 out of the box is RESTful with core support. All entities (provided by core + ones created using Entity API) are RESTful resources.

New Module - Referral Discount for Drupal Commerce
Category Items

New Module - Referral Discount for Drupal Commerce

A Drupal module that enables referral-based discounts to drive repeat purchases and user loyalty.
5 min read

One of the popular Growth hacking technique for e-commerce and SaaS businesses is Referrals, which is to leverage your user's network to get new users by offering incentives / discounts. On a recent e-commerce project we had the requirement to create a complete referral system but couldn't find a module that came close to fulfilling the requirements, hence we developed and contributed Commerce Referral Discount. This module allows us to provide a discount credit to an existing user for referring new users. Discounts can be configured for both the referring user and the new user who joins as part of the referral. Lets see a typical flow:

  • User A invites user B to signup on website using a unique invite URL (http://yoursite.com/invite/username).
  • User B visits the site using this URL, and is taken to the registration form to create a new account.
  • User B gets some discount amount (say $5) which he could use on his first purchase.
referral discount on order
  • After user B makes his first purchase, user A gets a discount amount (say $10), which could be used in the next purchase.
  • Both discount amounts are configurable from the admin backend.

Module Configuration:

  • To configure the discount amounts browse to /admin/config/referral-discount
discount amount configuration
  • Configure referral discount on product purchase at Administration » Store settings » Promotions » Discounts:
  • Go to admin/commerce/discounts page.
  • Click on "Add discount" button.
  • Choose discount type : Order discount
  • Choose offer type : Referral Discount
  • Now click on Save discount.
referral discount type
  • Configure Invite/Referral Link block
  • Visibility settings: Show block for authenticated user.

Commerce Referral Discount module provide "Invite/Referral Link" block, which contains unique refer/invite link for authenticated users to share across their friends. 
The module also integrates with views:

  1. It provides a view type 'Commerce Referral Discount' which can be used to list down all the discounts and other data which it stores in the 'commerce_referral_discount' table in database.
  2. It also provides relationship to the user entity, so you can also include the data of Referrer user and Invited user.
Pune Drupal Meetup, May 2016
Category Items

Pune Drupal Meetup, May 2016

Recap of the PDG meet-up at QED42 office, featuring sessions on DrupalCon experiences and service workers. Stay tuned for DrupalCamp Pune 2016 updates!
5 min read

The flavour of this month has been the Drupalcon New Orleans and we decided to keep the momentum going for this PDG meet-up held at the QED42 office.

The first session was given by Rakhi Mandhania on her experience at DrupalCon both as an attendee as well as a Keynote speaker for the Higher Ed Summit. She explained how everyone is concerned with the migration of a large number of websites to Drupal 8 and the lack of rich Drupal talent. DrupalCAP initiative was hailed as a solution to the jarring lack of Drupal literate work force and appreciated all around.


The second session was by Piyuesh Kumar on service workers, the same session both he and Saket kumar presented at New Orleans. He explained that functionalities such as, rich offline experiences, periodic background syncs, push notifications that traditionally require a native application are coming to the web and service workers provides the technical foundation all these features will rely on.

He ended the session with a demo of a working website for DrupalCamp.

The evening was concluded with us deciding the dates for DrupalCamp Pune 2016, which will tentatively take place sometime in late August.

Watch this space for details, coming shortly!
Good day and see you all soon.

Pune Drupal Group Meetup, April 2016
Category Items

Pune Drupal Group Meetup, April 2016

A brief about the discussions during the monthly Pune Drupal Group Meetup.
5 min read

The monthly Pune Drupal Group Meetup for April was hosted by QED42. The second PDG meetup to take place in the month of April, You would assume meeting this often would get tiring for other people but not us! We Drupalers love a good catchup session.

The first session was kicked off by Prashant and Rahul, Interns at QED42 and they spoke on, "Our experience with Drupal." They explained about their journey as new comers to Drupal, from the lenses of both CMS and the community. Their confusion at the beginning, the new tech and softwares they have learned, their experience at Drupalcon Asia and their love for the community. A really enjoyable session peppered with ernest observations and cute cat pictures and a brilliant first time attempt. Bravo boys!

The second session was taken by Arjun Kumar of QED42 on,"Introduction to CMI." With a brief on CMI and the difference from the features land, he concluded with a demo.

Arjun CMI

After a short discussion on the probable date and location for Pune Drupal Camp we broke off for BOF sessions,with Navneet leading the discussion on Acquia certifications and further discussions on CMI.

BOF

With 20 people in attendence we concluded the PDG april meetup with delicious Pahadi Sandwiches in our tummy. Have a great weekend and see you soon!

Pune Drupal Meetup - March 2016
Category Items

Pune Drupal Meetup - March 2016

The monthly Meetup for March was hosted by Rotary International and a session on, Services and dependency injections in Drupal 8"."
5 min read

The monthly meet-up for March was moved from the last friday of the month, which was the good Friday, to the 1st of April and hoped really hard that people didn't think it was an April fools prank. This PDG meetup was hosted by Rotary International thanks to diligence of Dipak Yadav who works there. It is always fun when the meetup is hosted in different locations because we get to explore different parts of Pune and see new faces.

With 25 members in attendence, the meetup was kicked off by Dipak giving us an informative talk about Rotary International and the work they do.

Introduction of Rotary International

The speaker for the evening was Sushil Hanwate of Axelerant and he spoke on,“ Services and dependency injections in Drupal 8.”

Session

The session ended after a short Q&A, we broke off into smaller groups for BOF sessions. Saket headed the BOF for Service workers and the second group discussed about the Drupal 8 Module development.

Once we were done with technical talks, we were served one of the best Kachoris we have tasted :). While we happily munched on the snacks, we decided on the preliminary team members for the upcoming Pune Drupal Camp.

Though the meetups are being held regularly we still need to figure a way of involving newer members into the community and one of the way that is possible is if we get more people volunteering to host the meetups. Kudos to Rotary for hosting us, if you are a Pune based company / group who would like to host the next meetup then please get in touch via comments. 

Our next PDG meetup is scheduled for the 29th of April. Along with a session on,"Experience with Drupal" by Rahul Savaria and Prashant Kumar from QED42, we shall also be planning and discussing further about the upcoming Pune Drupal Camp.
Dont forget to RSVP, See you soon!

First Time Customer Discount using Drupal Commerce
Category Items

First Time Customer Discount using Drupal Commerce

Attract new customers to your e-commerce site with first-time purchase incentives. Learn how to offer discounts or special deals using Drupal Commerce.
5 min read

E-commerce has become a way of life for most of us and with so many ecommerce portals competing it becomes important to attract new customers to your site.

A way to attract the new customers is by incentivising their first purchase. E.g. Providing a discount, taking off the shipping charges, providing an extra product for free, etc.

In a recent commerce project we had a this requirement to find out if the purchase being made is the user's first. Searching for a solution online, I came across this sandbox module. The module needed to be published on drupal.org with a little cleanup (code structure and coding standards) [1] [2]. It was promoted to full project : Commerce First Time Customer Discount.

The module provides a couple of ways to identify if the purchase being made by the customer is his/her first:

  1. Using inline condition
  2. Using rules condition

Using inline condition:

Commerce First time Customer Discount can be easily integrated with the Commerce Discount module to check if the purchase is the user’s first. Follow the steps given below to implement it:

  1. Install commerce discount module.
  2. Install Commerce First Time Customer Discount module.
  3. Go to “Store settings” >> “Discounts”(admin/commerce/store/discounts) and click “Add discount”.
  4. Fill in the details for the fields “Admin title”, “Name”, choose the “Discount Type”
  5. Under “Order discount conditions” select “First Time Customer”. The Commerce First Time Customer Discount module provides this option.
  6. Choose the offer type of your choice.
  7. Save!

Your new offer will be now applied to the first purchase that a customer makes. Using commerce discount also enables you to set a date during which this offer will be applicable.

Using rules condition:

Commerce First Time Customer Discount module provides a rule condition to check if this is the first purchase made by the customer. Follow the steps given below to implement discount using the rules module:

  1. Install the Commerce First Time Customer Discount module.
  2. From rules admin section (admin/config/workflow/rules), click to “Add new rule” button. Note: You will have to enable to rules_admin module for this.
  3. Select any event in the “Commerce Order” section. Ex. Before saving a new order.
  4. Add a condition “Users First Order” under the “Commerce Order” section.
  5. Add any action of your choice to the order. The action could be to apply a discount, give away a free product, provide free shipping, etc.
  • [1] : Github issue for proposing the promotion of the module.
  • [2] : drupal.org issue for promoting the sandbox to full project.
We are going to DrupalCon New Orleans!
Category Items

We are going to DrupalCon New Orleans!

QED42 is attending and speaking at Drupalcon New Orleans, 4 of our talks have been selected in various tracks and we are thrilled to meet all the Drupalers. See you there.
5 min read

With around 767 submissions from around the globe DrupalCon New Orleans must have set a new record for an all time high for session submissions at any conference. We can only imagine the plight of track chairs who helped select final ~150 sessions, given the numbers we are absolutely thrilled to announce that three of our talks (Including one in higher ed summit) have been accepted for Drupalcon New Orleans.

Here is a brief of talks at Drupalcon New Orleans May, 2016.

Service Workers Internals:

Saket and Piyuesh will talk about Service Workers on D8 and the promise of offline web. The topic is a build up from series of BoF at Drupalcon Asia where service workers was discussed passionately and pragmatically. It’s not just frontend, necessary backend infrastructure (route caching, url config) needs to be present for service workers to be a reality, hence Saket and Piyuesh ( our frontend and backend leads ) decided to team up on this. You can read more about the tentative agenda at the session synopsis and here are rumours of what to expect in the demo:

  • Config for urls for offline first approach
  • Config for urls for network first approach & fallback to serviceworker cache
  • Static resource caching via service workers
  • Since D8 has placeholders, it would be wise to cache the response of placeholders & render them using service-workers. Background sync can be used to keep pulling in fresh data for the placeholders.

Exploring Drupal 8 Frontend landscape through Polymer :

Saket is back with a session on the utopia of using Drupal 8 as a backend for multiple front end frameworks; this time it’s through Polymer. Webcomponents have had the frontend community wanting, what’s not to desire? Reusable components, shadow DOM, templating and much more all native to the browser. Though webcomponents paints a beautiful feature, Polymer from Google delivers it as a polyfill for the restless. In this talk Saket will talk about what Drupal 8 frontend programming might look like and glitches we might need to resolve for a smooth future.

Higher-ed Summit

Drupal Campus Ambassador Program - A community Initiative:

A wildcard entry into Dries’s keynote and Holly’s closing-note at Drupalcon Asia,  DCAP made its humble beginnings in one of India’s regional events, where business folks were trying to find answers to Drupal talent problems. In spirit of Drupal community’s do-ocracy some of the community members figured a WIN-WIN solution for the problem, that is to take Drupal to colleges and evangelise it professionally. There have been numerous college workshops but DCAP is different in ways that it provides longevity and support to college students and that is exactly what Rakhi will be sharing at Higher-ed summit -- a bit of the history, successes so far and brave new world Drupal will foray into through DCAP. Catch Rakhi in action on May 9 at DrupalCon New Orleans.

QED42 at Drupalcon Asia
Category Items

QED42 at Drupalcon Asia

QED42’s sessions, contributions, and learnings shared at DrupalCon Asia with the global Drupal community.
5 min read

To say that we are excited for Drupalcon Asia would be an understatement. With 36 of QED42 team in attendance, there is nothing we at QED42 love more than a congregation of Drupal lovers and Drupal enthusiasts from all over the world under one roof. We have been busy as elves trying to make it as much fun as possible for everyone (and us).
 

QED42 Sessions at Drupalcons

Art of Debugging and optimising Front End using Chrome Dev Tools: If you have always wanted to know tips,tricks and pointers on front end debugging and optimisation our QED42 guys, Swastik and Saket have you covered. Catch their talk on 02/19/2016 at 16:00 in hall 31, Drupalcon Asia.


Outsource! Really difficult to do it, eh?: Taking her experience as a Project Manager here at QED42, Rakhi Mandhania is giving a talk on outsourcing projects and how to optimize the process. Catch her in action at Drupalcon Asia, on 02/20/2016 from16:00-17:00 in hall 21.

BOFS Proposed by QED42


Bigpipe in Drupal 8: A Birds of a feather by Piyuesh where he will be discussing in detail about pipelining page components with the new Bagpipe Module, including code walk throughs. Take part in it at DrupalCon Asia at 12:45pm-13:45pm on Feb 19, 2016, Seminar Room 12.


Exploring Drupal 8 Frontend landscape through Polymer: Saket is back with a BOF session on the promise of using Drupal 8 as a backend for multiple front end frameworks.He will be concentrating on both about Drupal 8 Front end improvements and web components / Polymer. Come along and volley ideas to and fro with Saket at Drupalcon Asia on Feb 20 at from16:00 to17:00 in Seminar Room 13.

All work and no play makes for a dull Druplar, so come by Booth 11 for some fun activities.


See you soon!

Featured Contributor - Fall 2015
Category Items

Featured Contributor - Fall 2015

At QED42, we value open source contributions. Our inaugural Featured Contributor, Purushotam Kumar, embodies this spirit. Explore PK's remarkable journey from client work to enriching the Drupal community.
5 min read

Open source contributions are one of the key performance indicators at QED42, be it contributing code or participating in various community initiatives; from Developers to Project managers we expect everyone to be active contributors to the communities they interact with. For most of QED42 that translates to (but not limited to) contributing code to Drupal core or contrib and early this year we decided to reward and highlight contributions of one outstanding contributor every 3 months. 

Today I'm proud to announce our first Featured Contributor of the series -  Purushotam Kumar, a 2015 college passout Purshotam or PK as we affectionately call him is a ball of energy in office. Of sharp wit and mopey head of hair, his passion for work shines through his personality. To paraphrase Shakespeare, Though he be little, he is fierce. 

Purushotam kumar -- Featured contributor

Other than being an ace member on client projects, PK has done a tremendous job in getting acquainted with Drupal community and contributing back to it in short span of time. Like most contributors, he started his journey by contributing a module that he custom builf for one of the client projects and after getting git vetted access on 7th Oct, 2015 -- he hasn't looked back. He has contributed to 10+ projects on drupal.org and feels he is just getting started. 

Check out Drupalcon Asia edition of QED42 Times to learn more about his motivations and future plans. 

Drush - drupal productivity messiah
Category Items

Drush - drupal productivity messiah

Discover how Drush can transform your Drupal experience from time-consuming clicks to efficient command-line actions. Save time and boost productivity.
5 min read

Drush is a shell and command line interface for drupal where in you can do 90% of the routine tasks quicker; whether you are maintaining or developing a site. Drush is such an indispensable tool that you can really break down your developer experience in two ages: BD (before Drush) and AD (After Drush). If you were lured by a module in BD age, the drill was something like:

  1. Find the module project page.
  2. Choose the correct module version number.
  3. Download or checkout (CVS) the correct module version.
  4. Place the module directory into your sites/all/modules (or wherever).
  5. Locate the module amidst the long list at admin/build/modules page.
  6. Choose the module and install it.

This experience often made me feel like a click zombie and my development environment and methodologies as a den of time suckage. Really there are more sadistic drills in the drupal verse when you talk about BD. Then came drush, messiah for the click zombies who wanted to mend and do more and they did find happily ever after. The above drill is achieved in 2 steps in AD:

  1. drush dl <module name> ( It will find the correct stable version depending on your site configuration and drupal version or you could specify version num for advance usage. Neat? )
  2. drush en <module name>  ( Would prompt you to enable dependencies if any)

All this at the coziness of your terminal, above is one scenario among many time sucking and boring routines. Drush can do much more, it can empty your cache, it can update your site from command line, it can do releases and hundred other things. So much thanks to ArtoMoshe WeitzmanOwen BartonAdrian Rossouwgreg.1.anderson and other drush contributors for making drush and liberating thousands of click zombies whose life otherwise would have been a lot less productive. 

Essential elements of a social networking site
Category Items

Essential elements of a social networking site

Core features and UX considerations for building a scalable, secure, and engaging social networking platform.
5 min read

Its probably a moot point to suggest that social networking sites are the rage these days. Thanks to the success of facebook, twitter, myspace and orkut, most of the sites now have a strong social component to them. So is the social networking space overcrowded? Maybe, but dont let that discourage you. As we pointed out in a previous blog post there's still a lot of scope here. So what makes a social networking site successful ? What are the key components and features that a social networking site should have. We at qed42 are web dwellers and continuously trying to deconstruct the web and we have the answer for you. The essential elements which you should keep in mind while building a social networking site.

  • Registration Form : Keep your registration form as simple as possible. Broken down to the bare bones a simple email and password field may suffice but you may want to include fields for first and last name.
  • Profile and Feed : Ideally this will be the most viewed page of your website. Apart from the general fields remember to keep fields which will be of interest to other users and which will be in coherence with the general theme of your site. You can check out the profile pages of couchsurfing.org specially in reference to the last point. Here's one. Also as facebook and twitter have proved its a good idea to have a "what are you thinking/doing" feed. Even linkedin has one now. So do some of the other sites like brazen careerist.
  • Easy interaction between users : The success of a social networking site is based on the conversation of its users. So make it easy for users to communicate between each other either actively or even observe what other users and their connections are doing. Also it should be easy to communicate with users of other sites, for example through FBConnect or even their twitter id.
  • UI : Having a simple yet interactive user interface is a must for a successful User Experience. If the UX is good users will return to your site. One of the ways to keep the UI interactive is by using ajax and javascript. Page refresh should also be reduced to as minimum as possible. Some other things to consider are

1. A navigation menu which lets the user access all the elements of the site of which he is a part of.

2. Layouts should be consistent. Header and footer should take no more than 30% of your real estate, if possible may be even less. User should be able to see the content in any resolution. If its not so you may end up in a situation that if the user is at a low resolution, the header occupies 50% of the page and he may need to scroll multiple times.

3. Logo should be the identity of your site and it must be clickable! 

  • Ability to import users from other sites : One of the key reasons why facebook was successful over orkut was that it gave the option to people to import their contacts from gmail and other email providers. This helped in the viral growth of facebook and is one of the major reasons why facebook is what it is.
  • Search : Your site should have the option to search through users, communities etc. Ideally if the user is new you can even suggest him what networks might be interesting to him based on his location or interests

  These are some of the few things which we believe are the ingredients of a successful social networking site. Did we miss out on anything? Let us know in comments or contact us.

Kaal - Drupal 6 theme
Category Items

Kaal - Drupal 6 theme

Discover Kaal, a three-column theme for bloggers with ad integration. Lightweight and browser-compatible, it's perfect for your Drupal 6 website.
5 min read

Kaal is a port of a wordpress theme to drupal. A pro-blogger theme which can have "ads" in the blog. It is a three column theme which you can use for your blog. It uses Blueprint CSS framework. This is a sub theme of drupal's blueprint project. So please download and install the blueprint base theme (follow the install instructions for installing blueprint as base theme) if you chose to install kaal as sub theme. We have also provided an option to download it as a standalone theme. 

Kaal

Features

  • Three column
  • Fixed width
  • It has two sidebars,a AD's sidebar which can be used to display AD's with a right sidebar.
  • Its tableless which makes it light weight.
  • Uses blueprint CSS framework, which takes care of browser compatibility issues.

It has been tested for browser compatibility and it works fine in most of the widely used browsers. You can download the theme here 

This is the first official theme release of QED42, we would be releasing more themes in future and all under GPL. Would love to hear your feedback in comments and suggestions for future theme releases. 

Dont out-spend, out-teach your competition
Category Items

Dont out-spend, out-teach your competition

Why teaching your audience creates stronger brand trust and long-term competitive advantage over spending more.
5 min read

A snippet from a DHH talk on entrepreneurship at Stanford where he emphasises that instead of trying to outspend your competition in advertising, to build a sustainable business you should rather build an audience by educating about your product and your company. A DHH Jewel. You can watch the entire talk here.

Perfection with Sublime Text - Part 1
Category Items

Perfection with Sublime Text - Part 1

Setup and workflow optimization tips for using Sublime Text effectively in front-end development projects.
5 min read

For web developers, the choice of a source code editor isn't one made lightly. If you are going to be coding on a daily basis, and thus productivity is gained or lost here on a grand scale.

But my search for the best code editor stopped with Sublime Text. In the course of the article, I'm going to do my level best to persuade you to switch to Sublime Text 2. For those of you who have already made this smart choice, jump straight to part 2 of this article where we will endeavour to set up the best practices on Sublime Text so that you can have a perfect workflow.

Let me first list out the reasons to switch to Sublime Text 2 if you haven't already -:

  • Compatibility across all modern operating systems - Windows, Linux or Mac
  • Multiple Cursors - Sounds intriguing, doesn't it? We have a detailed explanation below.
  • Vintage Mode for all you Vim Users
  • Lightning fast making it one of the fastest code editors on the web
  • Command palette so that you can touch the mouse as little as possible which is vital if you want to be fast.
  • The vast library at your disposal - Plugins, bundles and packages are readymate and available
  • Did I mention the price? Oh ya, it's completely free. But we do recommend donating to the owner, once you have completely fallen in love with it.

I hope you are convinced already, but if you aren't, read on, as we indulge in the best practices for Sublime Text.

Perfection with Sublime Text - Part 2

In this article we have discussed installing a super-package manager, Sublime shortcuts, code snippets, various libraries at your disposal, and so much more.

By the end of that article, I know you will be like this -: Jumping in happiness.gif

Advanced Services Tutorial
Category Items

Advanced Services Tutorial

Dive deep into creating custom POST services for your Drupal site, complete with authentication, tokens, and cross-site forgery protection.
5 min read

Coming from a Rails background, which is almost built to cater to services and REST API, Drupal was always gonna be tough when it came to services. Our hands were tied, as we knew we had to use Drupal because of the the advantages it offered far outweighed the disadvantages, so we put on a brave face and marched on to tackle services.

In a nutshell, Web Services make it possible for external applications to interact with our application (in this case our Drupal site). These interactions are most commonly reading, creating, updating, and deleting resources. REST is one of the most popular ways of making Web Services work and is the Drupal standard. Making use of these CRUD options is considered making it RESTful. Popular usage of a REST interface is a mobile application that needs to read and write data from your site's database.

There are plenty of tutorials across the web to get you kickstarted on setting up services, and we found this to be relatively easy. One of the best tutorials, I found on the web which spurred me on the way was http://pingv.com/blog/an-introduction-drupal-7-restful-services.

The major problem, I will deal within this tutorial is creating a custom POST driven service, where we will tackle CSRF Token, Cookies etc. 

At the end of the article, I will also be sharing quick tips on working with UUID and integrating it with Services.

Custom POST Service, using cookies and CSRF Token

Submitting a custom form from an external site (or mobile application) to your site. You have services setup in for the site, but can't handle this custom post request. Here are a list of things which needs to happen:

  • Establish a session between mobile application and website so that you can retrieve a cookie which is required for authentication
  • Establish a token so your request can be authenticated, and it knows its not a cross site forgery request
  • Send the data to the endpoint at the site
  • Receive data at the endpoint of the site

Assuming external site is in Drupal, but it really could be anything. If it's a mobile app, it would obviously be something else....This is just so that you get a idea, and can follow. You can execute the code in another local drupal site using devel execute php so that you have an exact idea of what you need to achieve.

In a system config form, 4 variables are saved -: services_username, services_password, services_url, services_endpoint

a) Retreive session cookie


function retrieve_session_cookie() {
  $login_details = drupal_json_encode(array(
      "username"  => variable_get('services_username'),
      "password" => variable_get('services_password')
    )
  );
  $url = variable_get('services_url') . '/' .  variable_get('services_endpoint') . '/user/login';
  $options = array(
    'method' => 'POST',
    'headers' => array('Content-Type' => 'application/json'),
    'data' => $login_details ,
    );
  $result = drupal_json_decode(drupal_http_request($url,$options)->data);
  if ($result == 'Wrong username or password.') {
    drupal_set_message(t('Services Url/Password is not setup for fetching content'), 'error');
    return FALSE;
  } 
  else {
    $sessid = $result["sessid"];
    $session_name = $result["session_name"];
    $cookie = $session_name . '=' . $sessid;
    return $cookie;
  }
}
$cookie = retrieve_session_cookie();
if ($cookie == FALSE) return;

b) Retrieve CSRF token


$token = drupal_http_request(
  variable_get('services_url') . '/' . variable_get('services_endpoint') .'/session/token',
  array(
   'headers' => array('Cookie' => $cookie)
  )
)->data;

c) Sending data to the site


$params = array(
  "title" => $form_state["values"]["title"],
  "question" => $form_state["values"]["question"],
  "name" => $form_state["values"]["name"],
  "email" => $form_state["values"]["email"],
);
$args = array(
  'method' => 'POST',
  'headers' => array('Content-Type' => 'application/json','Cookie' => $cookie, 'X-CSRF-Token' => $token),
  'data' => drupal_json_encode($params),
  'timeout' => 300.0,
);
$result = drupal_http_request(variable_get('services_url') . '/' .  variable_get('services_endpoint') .'/create_question_form/', $args);
if (isset ($result->data)) {
  $result = drupal_json_decode($result->data);
  if ($result["response"] == "Ok" && $result["status"] == "200")
    drupal_set_message(t("Form was submitted successfully"), 'status', FALSE);
  else if ($result["response"] == "Failed")
    drupal_set_message(t("Form was not submitted successfully. Please try after some time."), 'error', FALSE);
}

d) Receiving data at the server


function hook_services_resources() {
  $items = array(
    'create_form' => array(
      'operations' => array(
        'create' => array(
          'help' => 'Creating Form',
          'callback' => '_create_form',
          'access callback' => 'user_access',
          'access arguments' => array('access content'),
          'access arguments append' => FALSE,
          'args' => array(
            array(
              'name' => 'question_details',
              'type' => 'array',
              'description' => 'Question Details',
              'source' => 'data',
              'optional' => FALSE,
            ),
          ),
        ),
      ),
    ),
   );
  return $items;
 }
 
function _create_form($question_details) {
  $new_node = new stdClass();
  $new_node->type = "question";
  $new_node->language = "en";
  $new_node->title = $question_details["title"];
  $new_node->field_question = array("und"=>array(0 => array("value" => $question_details["question"])));
  $new_node->field_user_email = array("und"=>array(0 => array("value" => $question_details["email"])));
  $new_node->field_user_name = array("und"=>array(0 => array("value" => $question_details["name"])));
  $new_node->status = 0;
  $new_node->uid = 1;
  node_save($new_node);
  if ($new_node->nid) {
    return array("response"=>"Ok","status"=>"200");
  }
  else
    return array("response"=>"Failed");
}

As promised few quick tips when integrating services with UUID. 

a) By default the services module, will give you an index of 20 terms when you do /service-endpoint/node. On this view, you only get basic details of the node, language, title, author, uid etc. What you don't get is custom fields like body, tag, category etc. To see the detailed node view, go /service-endpoint/node/nid where nid is the node nid. As promised few quick tips when integrating services with UUID. 

But the catch is this no longer works with UUID. Then on, you have to do /service-endpoint/node/uuid. This applies to everything, /service-endpoint/user/uuid

b) With UUID enabled, CREATE based methods will no longer be accepted. You instead have to do a PUT call on service-endpoint/node/uuid which will create the content if it doesn't exist. In the params, you need to pre-generate a UUID, and pass it in the PUT call, for content to be created with that UUID. Sucks, doesn't it? That's why we resorted to custom calls in our website, rather doing PUT for node creation

Bonus : UUID is not even unique!!! Yes, Universal Unique Identifier does not guarantee unique values. It's the biggest veil ever. If you see the install file in UUID module, uuid.install, you will see in table alterations it adds a 36 character field to many tables, but doesn't add the condition for it to be unique. The explanation is that the chances of having a 36 character being same in a table is 1/36! which is really rare, and its not worth the overhead to check if its unique. Interesting, isn't it?. :-)

With Services, now being integrated into the Drupal Core for D8, it is only going to gain traction in popularity and downloads.. Quoting the founder of Drupal, Dries Buytaert, the future is a RESTFUL Drupal.

Devel Execute PHP Code with Syntax Highlighter
Category Items

Devel Execute PHP Code with Syntax Highlighter

Elevate your Drupal development with Devel's powerful feature - Execute PHP Code. Discover how PHP Execute Extended Tools enhances this tool, offering syntax highlighting and script history.
5 min read

Devel is one of the most powerful modules in Drupal, and it's one of the first modules I end up installing as a developer.

One of the less prominent features of Devel, is the Devel Execute PHP Code, which is available on your site as /devel/php. It provides a text area for entering your PHP code into. Any output (print, print_r, var_dump) is shown in a drupal_set_message.

I often use this interface to experiment with code, run one time scripts, and debug existing functions. Yes, within this block, all drupal functions, and any functions you write on your site can be executed. But it comes with it's fair share of difficulties, and the biggest stumbling block for me, was the lack of a syntax highlighter. There were silly errors you make, which takes forever to debug, and time is always of the essence.

But all this forever changed, when PHP Execute Extended Tools came to my world. This sandbox module is available athttps://drupal.org/sandbox/DizzyC/1905296 and  will change the way you thing about Devel Execute PHP. Quoting from the horse's mouth , PHP Execute Extended Tools is meant to be an extension to Devel's PHP Execute PHP page (/devel/php), and is compatible with Drupal 7.

Devel

 PHP X Tools adds a History section to the devel execute page as well as a Saved Script section. It keeps a history off all scripts executed on the devel/php page so you can rerun or review them at any time. It also adds the ability to save and load custom scripts so you can keep a collection of scripts that you want to be able to load and rerun at any time. (Can be some testing scripts, i

Optionally it integrates with the 'CodeMirror' library (http://codemirror.net/) transforming the plain textarea into a lightweight code editor supporting syntax highlighting, code formatting, code folding, matching brackets, search and replace and some more. 

To be honest, it's this optional integration which gives it all it's fanciness so it's highly recommended. Instructions to install are clearly mentioned in the sandbox project link, and will only take minutes for you to get started.

Code away, and now the semicolon or apostrophe that you forgot, will no longer come back to bite you in the ass. 

Happy Coding!!!

Perfection with Sublime Text - Part 2
Category Items

Perfection with Sublime Text - Part 2

Advanced Sublime Text configuration tips for smoother workflows and higher coding efficiency.
5 min read

Installing Sublime Text

For Linux

Linux 32-bit -:


cd ~
wget http://c758482.r82.cf2.rackcdn.com/Sublime\ Text\ 2.0.1.tar.bz2
tar vxjf Sublime\ Text\ 2.0.1.tar.bz2

Linux 64-bit -:


cd ~wget http://c758482.r82.cf2.rackcdn.com/Sublime Text 2.0.1 x64.tar.bz2
tar vxjf Sublime\ Text\ 2.0.1\ x64.tar.bz2

Customizing on Linux - Desktop Entry and Symbolic Link

Linux Users should do the following to take advantage of Sublime Text by doing the next steps -:


sudo mv Sublime\ Text\ 2 /opt/
sudo ln -s /opt/Sublime\ Text\ 2/sublime_text /usr/bin/sublime
sudo sublime /usr/share/applications/sublime.desktop

For Mac Users, after downloading Sublime Text, all you will need is to create a symlink so that you can use sublime from the terminal


sudo ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" /usr/bin

The last command will open a file called sublime.desktop in sublime, where you need to paste the following


[Desktop Entry]
Version=2.0.1
Name=Sublime Text 2
# Only KDE 4 seems to use GenericName, so we reuse the KDE strings.
# From Ubuntu's language-pack-kde-XX-base packages, version 9.04-20090413.
GenericName=Text Editor
Exec=sublime
Terminal=false
Icon=/opt/Sublime Text 2/Icon/48x48/sublime_text.png
Type=Application
Categories=TextEditor;IDE;Development
X-Ayatana-Desktop-Shortcuts=NewWindow
[NewWindow Shortcut Group]
Name=New Window
Exec=sublime -n
TargetEnvironment=Unity

For Mac OSX

Users should  download the latest package from here -: Sublime Text 2 - Download Open the .dmg file, and then drag the Sublime Text 2 bundle into the Applications folder.

For Windows

Users should download the latest package from here depending on your operating system (32 or 64 bit) -: Sublime Text 2 - Download. Doubleclick on the installer and follow the onscreen instructions.

Mac and Window Users, if you have further queries check this doc out -: Sublime Text Install Doc

Now this is the basic step. But to be super efficient, this is nowhere enough.

Installing Sublime Text Package Manager

Open Sublime Text Editor. Go to View -> Show Console

On Sublime Text 3, now paste the following code in the console

On Sublime Text 2, paste this code in the console

What does this awesome package manager for you? It basically makes package installations a breeze

We can use Sublime’s command palette by accessing the Tools menu, or by pressing Shift + Command + P, on the Mac or Ctrl + Shift + P for Linux and Windows Users. Whether you need to visit a Preferences page, or paste in a snippet, all of that can be accomplished here. It also opens up a list of commands available to the user. Any library that you install will immediately add new commands here.

To install plugins use the following process:

SUPER + SHIFT + P (SUPER = CMD on mac or CTRL on other operating systems) In the dialogue that pops up, type pi followed by the Enter/Return key to select Package Control: Install Package Now type the package install shortcut listed and hit the Enter/Return key again
 

So click Ctrl + Shift + P, and Type in install, which fuzzy searching enables the closest option Package Control : Install Package.

Now through this you can directly install the libraries you need just by searching for what you need.

Sublime Packages you must install -:

But some of these will need extra configuration. Do note that all these have to go in Preferences->Package Settings -> Select Package -> User Settings . Anything saved in Default Settings will be reset.

           
  • Bracket Highlighter -: Like the name states, it highlights the brackets, quotes and html tags. It’s a simple plugin, but helps a lot when working on big code files.
  •        
  • Doc Blockr -: The ability to create PHPDoc style comments. This plugins does it, and not only it works with PHP, but it also supports Javascript, ActionScript, CoffeeScript, Java, Objective C, C and C++.
  •        
  • Sidebar Enhancements -: This plugin extends the sidebar menu, by adding lots of new and useful features like: Move to trash, open in browser, and even copy the content of a file as data:uri base64.
  •        
  • Git
  •        
  • Drupal Snippets
  •        
  • Sublime Lint -: First off, you need this. This plugin is like a IDE itself, it finds errors in your code as you go. It supports dozens of languages, from PHP to Python, Java, etc.. This plugin is not only recommend but it should be mandatory. Now you have to find where the executable of the language are kept. This can be done simply by doing which rubyetc on ubuntu/mac. Go to Preference->Package Settings->Sublime Lint-> Edit User Settings A Word of Warning : Remember this file will always takes input in the form of a json.

<em>
      {"sublimelinter_executable_map": {
      "ruby": "/home/pratik/.rvm/rubies/ruby-2.0.0-p247/bin/ruby",
      "php" : "/usr/bin/php",
      "javascript":"/usr/local/bin/node",
      "css":"/usr/local/bin/node"
    }
  }
</em>
           
  • Gist -: A sublime package to help you create, edit and use Github Gist straight from sublime text. This will also allow you to use any Gists that you fork in Sublime. Which means if you are browsing Gist and find a snippet that you want to use then just fork it and now you can use it in Sublime. You can follow one of the two methods to complete it's configuration -: Go to Terminal 


<em>
    curl -v -u USERNAME -X POST https://api.github.com/authorizations --data "{\"scopes\":[\"gist\"]}"
</em>

where USERNAME is your github username 

OR

Log into github 

Account Settings -> Applications ""Create New Token"" under ""Personal API Access Tokens"" You might want to give the Token a useful name

Edit the settings file (it should open automatically the first time you use a Gist command done through Ctrl + Shift + P) to specify token.


<em>
token"": """"
</em>

You must enter your GitHub token here

  • AlignmentAgain Ctrl + Shift + P, type install, and search for alignment. Now if you are a designer, you would to extend it's settings to meet your need. For eg-: Goto to Preference->Package Settings->Alignment->User Settings

<em>
      "alignment_chars" : ["=","{"]
    }
</em>
  • To use it simply select a block of text and press ctrl+alt+a on Windows and Linux, or cmd+ctrl+a on OS X

Shortcuts to increase efficiency

  • Set Syntax -: Ctr + Shift +P followed by syntax and name of the language. i.e. 'syntax javascript'
  • Copy all selections of a word - : Alt + f3
  • To select word -: Ctrl + D
  • Remove Folder Panel -: Ctrl + K
  • Go to a file -: Ctrl + P
  • Go to a function -: Ctrl + P and begin with @ which displays all function
  • Toggle Full Screen -: F11

Customizing basic settings

Nowdays I am working in Drupal, so I have shown these settings for Drupal Coding standards. A quick Google Search will give you Sublime Text 2 settings for Ruby on Rails, Wordpress, Java or any other language you may be working on. Lets set the encoding, tab size, ruler line, etc right now so that our code will meet the Drupal Coding standards. Paste the following between the squigly brackets in "Settings - User" which you can access from the Preferences menu, you need to add a comma between this and any existing rules but make sure there isn't a comma on the last line:


<em>
  "bold_folder_labels": true,
  "caret_style": "wide",
  "default_line_ending": "unix",
  "draw_white_space": "all",
  "ensure_newline_at_eof_on_save": true,
  "fade_fold_buttons": false,
  "fallback_encoding": "UTF-8",
  "find_selected_text": true,
  "font_options":
  [
  "subpixel_antialias"
  ],
  "highlight_line": true,
  "line_padding_bottom": 1,
  "open_files_in_new_window": false,
  "rulers":
  [
  80
  ],
  "shift_tab_unindent": true,
  "tab_size": 2,
  "translate_tabs_to_spaces": true,
  "trim_automatic_white_space": true,
  "trim_trailing_white_space_on_save": true,
  "use_tab_stops": true,
  "word_separators": "./\\()\"'-:,.;<>~!@#%^&*|+=[]{}`~?"
</em>
Higher-Ed
Healthcare
Non-Profits
DXP
Podcast
BizTech
Open Source
Events
Quality Engineering
Design Process
JavaScript
AI
Drupal
Culture