Sunday, April 16, 2017

only show translated menu items into current language (Drupal 8)

function MY_THEME_preprocess_menu(&$variables) {
  if ($variables['menu_name'] == 'brancott-header-menu') {
   $language = Drupal::languageManager()->getCurrentLanguage()->getId();

    foreach ($variables['items'] as $key => &$item) {
      $menuLinkEntity = sapient_brancott_load_link_entity_by_link($item['original_link']);
      if ($menuLinkEntity != NULL) {
        $languages = $menuLinkEntity->getTranslationLanguages();
        // Remove links which is not translated to current language.
        if (!array_key_exists($language, $languages)) {
          unset($variables['items'][$key]);
          continue;
        }
      }
   
    foreach ($variables['items'][$key]['below'] as $key_child => &$item_child) {
      $menuLinkEntity = sapient_brancott_load_link_entity_by_link($item_child['original_link']);
      if ($menuLinkEntity != NULL) {
        $languages = $menuLinkEntity->getTranslationLanguages();
        // Remove links which is not translated to current language.
        if (!array_key_exists($language, $languages)) {
          unset($variables['items'][$key]['below'][$key_child]);
        }
      }
    }

    }
  }
}

function MY_THEME_load_link_entity_by_link(MenuLinkInterface $menuLinkContentPlugin) {
  $entity = NULL;

  if ($menuLinkContentPlugin instanceof MenuLinkContent) {
    list($entity_type, $uuid) = explode(':', $menuLinkContentPlugin->getPluginId(), 2);
    $entity = \Drupal::entityManager()->loadEntityByUuid($entity_type, $uuid);
  }
  return $entity;
}

Wednesday, October 12, 2016

Symfony components in Drupal 8.x

The following are the Symfony components that are going to power the Drupal 8 core to a major extent:
  • HttpKernel and HttpFoundation – These are responsible for streamlining the process of converting a Request into a Response with the help of EventDispatcher. Drupal 8 being moved to Symfony was driven by Web Services and Content Core Initiative (WSCCI) in a motive to transform Drupal from a first-class CMS to a first-class REST server with first-class CMS running on top of it. This initiative is intended to allow Drupal to use web services to offer its content with reduced complexity; considering this as a long term vision, Drupal will be more flexible, robust and easily maintainable CMS.
  • EventDispatcher – Implements the Mediator pattern (that uses encapsulation) in a simple and effective manner especially where code inheritance doesn’t work out, making the application highly extensible. It is more effective in situations where you tend to maintain and/or refactor a program consisting of a huge number of classes due to the fact that it makes the communication amongst the classes quite simple and easy.
  • ClassLoader – Provides tools that autoload classes and caches their location. PHP uses the autoloading mechanism to delegate the loading of a file that defines the class in situations where you reference a class that has not been required or included yet. Symfony comes with autoloaders like PSR-0 Class Loader and MapClassLoader. Implementing theClassLoader component will make Drupal module developers carefree especially when it comes to implementingmodule_load_include and other dependencies. Moreover, it allows developers easy calling of classes during run-time.
  • YAML – It parses YAML strings and converts them to PHP arrays and vice versa. This format has been especially designed to hold configuration related information, while being as expressive as XML files and as readable as INI files. It serves as an integral component of Drupal’s CMI (Configuration Management Initiative) that allows our modules to initially define their default configuration settings and later allows the site builder to override the same as-and-when instructed to. This concept of Drupal 8’s CMI which is powered by YAML is a replacement for Features contributed Drupal module which proves to be a robust concept as far as migrating and deploying across environments is concerned.
  • Routing – Allows us to load all routes, and dumps a URL matcher or generator specific to these routes. This also means that it maps an HTTP request to a set of configuration variables. As far as Drupal 8 and above versions are concerned, we define our module’s routes in a YAML configuration file, each of them set to trigger a specific action that has been defined in our module’s classes.
  • DependencyInjection – Primarily used to standardize and centralize the way objects are constructed in our application. Symfony’s DependencyInjection component has been incorporated in Drupal 8 in an intention to write code in such a way that classes can be reused and unit-tested wherever applicable and desired.
  • Twig – Drupal 8 has adopted the Twig template engine. This is of interest to the themers who will probably never think of any other option again for as long as they’re working on Drupal themes. Twig was developed by Fabien Potencier, who also developed the Symfony project, and was fine tuned for integration into Drupal 8.
  • Process – Helps execute commands in sub-processes using the command-line interface. Drupal 8 will use this to handle all activities that are command-line in nature.
  • Serializer – It is used to transform objects into a specific format (eg. XML, YAML, JSON, etc.) and vice versa. To understand it better, let us look at the following schema that a Serializer component follows:
    Additionally, we can use it to accomplish a number of jobs, ranging from configuration to node and entity creation that should be delivered by a REST endpoint.
  • Validator – Helps Drupal validate values. For example: validating form submission, validating entities within Drupal, etc. To accomplish its job, it uses Doctrine Annotations (discussed in Out-of-the-box third party components section).
  • Translation – Provides a standard set of tools to load translation files, generate translated strings as output, and use the generated outcome.
Courtesy :  https://www.sitepoint.com/symfony-drupal-8/

Wednesday, December 2, 2015

Bulk Content Import Drupal 7 (Feeds Module)

Required modules:
Set up CSV:
Prepare the Excel file that you will convert to CSV - open up Excel and in the first row add the headers. Feeds importer requires a global ID to uniquely identify nodes. So the first column should contain this unique identifier. Name this column "guid". The other column headers can be anything you like. For example, if you want to import a list of files with title; you can name your columns filename, title, description etc. The column headers do not have to match content type fields.
Add data to the Excel file:
  • guid: make sure each row has a unique number.
  • filename: You will have to upload all the files you want to migrate, into your Drupal root directory. So put all your files in a directory called import-uploads and upload them to your Drupal root. Make sure that the filenames have the path from your Drupal root. So each filename should have "import-uploads/" prepended. E.g. "import-uploads/file1.pdf", "import-uploads/file2.avi", etc.
  • title/description: should have text, make sure that your title is less than 256 characters.
Save as CSV - save the Excel file in CSV format - make sure to quote all cells. Otherwise you will run into errors if any of the text (e.g. description) contains commas.
Set up Feeds Importer:
  • Navigate to Structure -> Feeds Importer -> Add Importer.
  • Give your importer a meaningful name like "bulk file upload" and click Submit.
On the next screen follow these directions:
  • Basic Settings: leave as is, no changes needed.
  • Fetched: click "change" and select the "File Upload" option and click save.
  • Fetched Fileupload: click settings, make sure to add all the file extentions you want to add, e.g. pdf, wav, doc, docx etc.
  • Parser: click "change", select the "CSV Parser" option and save.
  • CSV Parser: leave as is.
  • Processor: leave as is (Node Processor).
  • Node Processor: click settings, select "Replace existing node" for "Update exisiting node", select the Content Type you want to use for this import. You may choose to use an existing user as the author.
  • Click Save.
  • Node Processor Mapping: This is where you will map your CSV file headers to the Content Type fields. One by one, add the column headers of the CSV file to the mapping and choose the appropriate Content Type field to map to.
  • Click Save.
Run the import:

  • Navigate to Structure -> Feeds Importer, and click on the "import" link.
  • Click on the Bulk File Upload link.
  • Upload your CSV file into your sites/default/files folder.
  • Upload your import-upload folder, containing all the files to be imported into your Drupal root.
  • Enter your CSV file's name in the File text field.
  • Click on the Import Button.

Thursday, September 17, 2015

How to add extra fields to user profile in Drupal?

Step 1. - Create custom module -For Example My custom module name is extra_user_profile
Folder Name - extra_user_profile
Files - extra_user_profile.nfo, extra_user_profile.module, extra_user_profile.install

Step 2.
extra_user_profile.nfo file:-
name = Extra User Profile
description = Add new field in user profile
core = 7.x
version = "7.x-2.5"
core = "7.x"

Step 3.
extra_user_profile.module file:-
<?php

Step 4.
extra_user_profile.install file:-
<?php

/**
 * Implementation of hook_enable().
 */
function extra_user_profile_enable() {
  // Check if our field is not already created.
  if (!field_info_field('field_nickname')) {
    $field = array(
        'field_name' => 'field_nickname', 
        'type' => 'text', 
    );
    field_create_field($field);

    // Create the instance on the bundle.
    $instance = array(
        'field_name' => 'field_nickname', 
        'entity_type' => 'user', 
        'label' => 'Nick Name', 
        'bundle' => 'user',
        'required' => TRUE,
        'settings' => array(
            'user_register_form' => 1,
        ),
        'widget' => array(
            'type' => 'textfield',
            'weight' => '1',
        ), 
    );
    field_create_instance($instance);
  }
}

Step 5 Enable Module

Now Nickname field is available in User profile page
Enjoy....!!!!

Monday, June 23, 2014

PHP explode() Function

Definition and Usage

The explode() function breaks a string into an array.
Note: The "separator" parameter cannot be an empty string.
Note: This function is binary-safe.

Example

Break a string into an array:
<?php
$str = "My name is KC Verma";
print_r (explode(" ",$str));
?>

Result -
Array ([0] => My [1]=>name [2]=> is [3]=> KC [4] => Verma)

Syntax

explode(separator,string,limit)

ParameterDescription
separatorRequired. Specifies where to break the string
stringRequired. The string to split
limitOptional. Specifies the number of array elements to return.Possible values:
  • Greater than 0 - Returns an array with a maximum of limit element(s)
  • Less than 0 - Returns an array except for the last -limit elements()
  • 0 - Returns an array with one element

Entities (Major difference between Drupal 6 and Drupal 7)

Entities

Maybe you've heard of "entities" in Drupal 7, wondered what they were, and wanted to learn the underlying concepts. Leveraging the Entity API lets you create more lightweight and flexible solutions.
The Drupal community often compares site building through configuration to a favorite childhood toy: LEGO bricks. We can build Entity types, which can make Bundles, to which we can add Fieldsand then create Entities. This article explains the relationships between Entity types > Bundles > Fields > Entities. This was one of the most important changes of Drupal 7, and brought components from some well-loved contributed modules -- such as CCK -- into the core system.
The illustration below shows some examples of Entity types included with Drupal 7, with some example entities:
entity types and some entities
Let’s take a closer look at these concepts. It’s sort of a chicken-and-egg thing, one doesn’t exist without the other.

Entity types

In earlier versions of Drupal, the field system was only used on content types. Now, thanks to the Entity API, we can add fields to other things, like comments. Fieldable entities make Drupal eminently flexible. An entity type is a useful abstraction to group together fields. Let’s consider some examples of entity types:
  • Nodes (content)
  • Comments
  • Taxonomy terms
  • User profiles
You can also build new kinds of entity types where the options above don't suit your needs. For more information, read further about using the hook_entity_info and extension by Entity API:entity_crud_hook_entity_info.

Bundles

Bundles are an implementation of an entity type to which fields can be attached. You can consider bundles as subtypes of an entity type. With content nodes (an entity type), for example, you can generate bundles (subtypes) like articles, blog posts, or products. Not all entity types have bundles, however. For example, users do not have separate bundles (subtypes). For the entity types that do allow bundles, you can create as many bundles (subtypes) as you want. Then, using the Field system, you can add different fields to each bundle. Examples include a file download field on Basic Pages and a subtitle field on Articles.

Fields

A field is a reusable piece of content. In technical terms, each field is a primitive data type, with custom validators and widgets for editing and formatters for display. You can read further for a developer's guide to using the Drupal 7 Fields API.
What's important to know as it relates to Entities is that Fields can be added to any of the bundles (or entity types) to help organize their data. Say, for example, you create a content type with an unstructured text field and use HTML to structure parts of it, like a summary section, or prices. That would make it more difficult, then, to control how these were displayed, or to make connections between different types of related content. This is where using fields is essential.

Entity

An entity would be one instance of a particular entity type such as a comment, taxonomy term or user profile or a bundle such as a blog post, article or product.
You can use entity_load to load any entity. Note, however, that the core does not provide a save or delete function, but thanks to Entity API module the missing pieces are added (entity_create(), entity_save(), entity_delete(), entity_view() and entity_access()).

Putting this in Object-Oriented Design/Programming terms...

If you come from an OOD/P background and are trying to better understand what these key D7 concepts are, the following suggested mapping might help (albeit not strictly true from a purist’s perspective) :-
  • An entity type is a base class
  • bundle is an extended class
  • field is a class memberpropertyvariable or field instance (depending on your naming preference)
  • An entity is an object or instance of a base or extended class
All these four OOD/P concepts are special in that they are serialisable (stored - e.g. to a database or file). Serialisation takes place via the Entity API.

So what’s the big deal?

If you’re familiar with Drupal 6 and new to Drupal 7, this will sound like great news. In Drupal 6 and before, users and comments didn't have the same power that nodes (content) had. They couldn't have translations, fields, versioning, and so on. It also meant that systems such as Views, which relied on controlling the selection and listing of fields didn’t work as well with comments and users. Some experimentation was done with modules that turned comments or users into nodes. However, this meant that all the additional information in the node object was added to comments.
Instead, the community created this abstraction based on what was common between these different models of entity types. In this way, the Entity API allows for more lightweight and flexible solutions. There are many entity-aware modules, and more being developed with Drupal 7, which make it easier to relate content together, and gain a more flexible architecture.

Entity API module

The project Entity API extends the entity API of Drupal core in order to provide a unified way to deal with entities and their properties. Additionally, it provides an entity CRUD controller, which helps in simplifying the creation of new entity types.
Learn more about using the Entity API in your projects.


Monday, October 21, 2013

What's New in Drupal 7

New Minimum System Requirements:

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

Security:

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

Usability:

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

Database:

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

Several Performance Improvements Implemented

Documentation:

  • Hook API documentation now included in Drupal core.

News aggregator:

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

Search:

  • Added support for language-aware searches.

Testing:

  • Added test framework and tests.

Theme system:

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

File handling:

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

Image handling:

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

Better Support for Multisite Installations

Added RDF support

Better support for search engine optimization and web linking

Added ability to add custom fields

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

Installer can be run from the command line

JavaScript changes

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

Improved node access control system

Task handling

  • Improved handling of long-running tasks.

only show translated menu items into current language (Drupal 8)

function MY_THEME_preprocess_menu(&$variables) {   if ($variables['menu_name'] == 'brancott-header-menu') {    $langu...