Saturday 21 May 2016

How to check if current page is frontpage in drupal 8 - drupal_is_front_page drupal 8

How to check if current page is frontpage in drupal 8 

During the Drupal 8 development cycle a path.matcher was introduced which deprecated most procedural functions in path.inc
Drupal 7:
$path_matches = drupal_match_path($path, $patterns);
$is_front = drupal_is_front_page();
Drupal 8:
$path_matches = \Drupal::service('path.matcher')->matchPath($path, $patterns) ;
$is_front = \Drupal::service('path.matcher')->isFrontPage();
 
 
reff links: 
 
https://www.drupal.org/node/2274675 
 
Deprecated by path.matcher service.
https://www.drupal.org/node/2274675

How to check if current path is admin path in drupal 8 ?- path_is_admin druapl 8

if (path_is_admin(current_path())) {
  // Do stuff.
}

To check the path of the current page:
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
to check an arbitrary path, you need to create a Request object and obtain its matching Route:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;

$path = '/node/1';
$request = Request::create($path);

$route_match = \Drupal::service('router.no_access_checks')->matchRequest($request);
$route = $route_match[RouteObjectInterface::ROUTE_OBJECT];
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route); 
 

Drupal 7:
$is_admin = path_is_admin($path);
  Drupal 8:
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute(\Symfony\Component\Routing\Route $route); // In order to get the $route you probably should use the $route_match $route = \Drupal::routeMatch()->getRouteObject(); $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route); * Omit the $path (Drupal 7) or $route (Drupal 8) parameter to check if the current page is an admin page.
 
 
Source : https://api.drupal.org/api/drupal/includes!path.inc/function/path_is_admin/7.x  

Monday 1 February 2016

git patch create new files

Steps to add new files to patch : 

User@AMX-554 /C/xampp/htdocs
$ git clone --branch 8.x-1.x https://git.drupal.org/project/autologout.git
Cloning into 'autologout'...
remote: Counting objects: 1648, done.
remote: Compressing objects: 100% (1179/1179), done.
remote: Total 1648 (delta 982), reused 706 (delta 408) eceiving objects:  96% (1583/1648), 340.00 KiB | 19.00 KiB/s
Receiving objects: 100% (1648/1648), 362.41 KiB | 18.00 KiB/s, done.
Resolving deltas: 100% (982/982), done.
Checking connectivity... done.

User@AMX-554 /C/xampp/htdocs
$ cd autologout/



User@AMX-554 /C/xampp/htdocs/autologout (8.x-1.x)
$ git status
On branch 8.x-1.x
Your branch is up-to-date with 'origin/8.x-1.x'.

nothing to commit, working directory clean

User@AMX-554 /C/xampp/htdocs/autologout (8.x-1.x)

$ git add -N README.txt INSTALL.txt

User@AMX-554 /C/xampp/htdocs/autologout (8.x-1.x)

$ git add -p
warning: LF will be replaced by CRLF in INSTALL.txt.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in README.txt.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in INSTALL.txt.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in INSTALL.txt.
The file will have its original line endings in your working directory.
diff --git a/INSTALL.txt b/INSTALL.txt
index e69de29..7df4980 100644
--- a/INSTALL.txt
+++ b/INSTALL.txt
@@ -0,0 +1,16 @@
+INSTALL.txt file
+================
+$Id: INSTALL.txt,v 1.2 2009/04/17 14:05:51 jvandervort Exp $
+
+1. Place the autologout folder in your drupal/modules folder (or if multisite and this
+  module is meant to be available to just one site in drupal/sites/www.YOURSITE.com/modules)
+
+2. Enable the autologout module at administer > modules
+
+3. Ensure the correct admin users have permissions to administer the autologout module at
+  administer > people > permissions
+
+4. Set-up the module at administer > configure > people > autologout
+
+
+

Stage this hunk [y,n,q,a,d,/,e,?]? y
<stdin>:10: trailing whitespace.
1. Place the autologout folder in your drupal/modules folder (or if multisite and this
<stdin>:19: new blank line at EOF.
+
warning: 2 lines add whitespace errors.

warning: LF will be replaced by CRLF in README.txt.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in README.txt.
The file will have its original line endings in your working directory.
diff --git a/README.txt b/README.txt
index e69de29..2ed76d2 100644
--- a/README.txt
+++ b/README.txt
@@ -0,0 +1,20 @@
+/* $Id:
+
+Description
+===========
+After a given timeout has passed, users are given a configurable session expired prompt. They can reset the timeout, logout, or ignore it in which case they'll be logged out a
fter a the padding time has elapsed. This is all backed up by a server side logout if js is disable or bypassed.
+
+Features
+========
+* Configurable Global timeout and timeout padding. The latter determines how much time a user has to respond to the prompt and when the server side timeout will occur.
+* Configurable messaging.
+* Configurable redirect url, with the destination automatically appended.
+* Configure which roles will be automatically logged out.
+* Configure if a logout will occur on admin pages.
+* Integration with ui.dialog if available. This makes for attractive and more functional dialogs.
+* Configurable timeout based on role
+* Configurable timeout based on User
+* Configurable maximum timeout. Primarily used when a user has permission to change their timeout value, this will be a cap or maximum value they can use.
+* Order of presidence is, user timeout -> lowest role timeout -> global timeout
+* So if a user has a user timeout set, that is their timeout threshold, if none is set the lowest timeout value based on all the roles the user belongs to is used, if none is
set the global timeout is used
+* Roles with the proper permission setting can change their timeout value

Stage this hunk [y,n,q,a,d,/,e,?]? y

User@AMX-554 /C/xampp/htdocs/autologout (8.x-1.x)

$ git diff --cached --binary > add-readme-file-to-module-2658672-2.patch
warning: LF will be replaced by CRLF in INSTALL.txt.
The file will have its original line endings in your working directory.
warning: LF will be replaced by CRLF in README.txt.
The file will have its original line endings in your working directory.

 
Reff links
 
http://stackoverflow.com/questions/14491727/git-add-patch-to-include-new-files 

Tuesday 1 December 2015

Check wether the module exist or not in drupal 8


\Drupal::moduleHandler()->moduleExists("module_name");

How to set/get weight for modules and how to enable module programatically in druapl 8


In Druapl 7 the "system" table will have all the module enable and disable status. In druapl 8
 
Description: 
If you were running any queries against the {system} table, these won't work any more. For example:
Drupal 7:
<?php
  // Enable the admin theme.
  db_update('system')
    ->fields(array('status' => 1))
    ->condition('type', 'theme')
    ->condition('name', 'seven')
    ->execute();
?>

Drupal 8:
<?php
  theme_enable(array('seven'));
?>
 
Enable Module: 
 module_enable(array($module), FALSE); 

 module_enable($module_list, $enable_dependencies = TRUE) 

Reff: http://www.drupalcontrib.org/api/drupal/drupal!core!includes!module.inc/function/module_enable/8

Setting module weights:
Drupal 7:
<?php
  // Set a module's weight.
  db_update('system')
    ->fields(array('weight' => $weight))
    ->condition('name', $mymodule)
    ->execute();
?>
Drupal 8:
<?php
  module_set_weight($mymodule, $weight);
?>
To set a module's weight relative to another, a module_get_weight function is planned.

Source : https://www.drupal.org/node/1813642
 
 

Thursday 26 November 2015

How to log error message in Drupal 8 (watchdog in druapl 8)

hook_watchdog() and watchdog() removed

in drupal 8

In Drupal 8 watchdog has been refactored to an OO, PSR-3 compatible framework.
In the paragraphs below, a "channel" refers to what used to be the $type argument to watchdog(). For logging you would have done with simple watchdog() statements in Drupal 7, look at the example for injecting a specific channel.
The switch to PSR-3 logging has resulted in the following API changes:
  1. hook_watchdog() is gone. For a module to implement a logger, it has to register a service tagged as logger. eg
    services:

      logger.mylog:
        class: Drupal\mylog\Logger\MyLog
        tags:
          - { name: logger }
    This class must implement \Psr\Log\LoggerInterface. like this:
    <?php
    namespace Drupal\mylog\Logger;
    
    use Drupal\Core\Logger\RfcLoggerTrait;
    use Psr\Log\LoggerInterface;
    
    class MyLog implements LoggerInterface {
      use RfcLoggerTrait;
    
      /**
       * {@inheritdoc}
       */
      public function log($level, $message, array $context = array()) {
        // Do stuff
      }
    
    }
    ?>
  2. watchdog($type, $message, $variables, $severity, $link) has been removed in favor of \Drupal::logger($type)->log($severity, $message, $variables)
    D7
    <?php
    // Logs a notice
    watchdog('my_module', $message, array());
    // Logs an error
    watchdog('my_module', $message, array(), WATCHDOG_ERROR);
    ?>

    D8 - procedural
    <?php
    // Logs a notice
    \Drupal::logger('my_module')->notice($message);
    // Logs an error
    \Drupal::logger('my_module')->error($message);
    ?>

    D8 - injecting the whole factory
    services:
      myservice_that_needs_to_log_to_multiple_channels:
        class: Drupal\mymodule\MyService
        arguments: ['@logger.factory']

    <?php
    class MyService {
      public function __construct($factory) {
        $this->loggerFactory = $factory;
      }
    
      public function doStuff() {
        // Logs a notice to "my_module" channel.
        $this->loggerFactory->get('my_module')->notice($message);
         // Logs an error to "my_other_module" channel.
        $this->loggerFactory->get('my_other_module')->error($message);
      }
    }
    ?>
    D8 - injecting a specific channel
    Drupal core registers only one channel in core.services.yml for "system" channel.
    There might be cases where you don't want to inject the whole factory to your class, but just a specific channel.
    In that case you can easily register this channel with something like this:
    services:
      logger.channel.mymodule:
        parent: logger.channel_base
        arguments: ['mymodule']

    And then inject logger.channel.mymodule to your services.
    services:
      myservice_that_needs_specific_channel:
        class: Drupal\mymodule\MyService
        arguments: ['@logger.channel.mymodule']

    <?php
    class MyService {
      public function __construct($logger) {
        $this->logger = $logger;
      }
    
      public function doStuff() {
        // Logs a notice.
        $this->logger->notice($message);
         // Logs an error.
        $this->logger->error($message);
      }
    }
    ?>
  3. WATCHDOG_* constants and watchdog_severity_levels() are removed
    D7
    <?php
    $severity = WATCHDOG_EMERGENCY;
    $severity = WATCHDOG_ALERT;
    $severity = WATCHDOG_CRITICAL;
    $severity = WATCHDOG_ERROR;
    $severity = WATCHDOG_WARNING;
    $severity = WATCHDOG_NOTICE;
    $severity = WATCHDOG_INFO;
    $severity = WATCHDOG_DEBUG;
    $levels = watchdog_severity_levels();
    ?>

    D8
    <?php
    use Drupal\Core\Logger\RfcLogLevel;
    $severity = RfcLogLevel::EMERGENCY;
    $severity = RfcLogLevel::ALERT;
    $severity = RfcLogLevel::CRITICAL;
    $severity = RfcLogLevel::ERROR;
    $severity = RfcLogLevel::WARNING;
    $severity = RfcLogLevel::NOTICE;
    $severity = RfcLogLevel::INFO;
    $severity = RfcLogLevel::DEBUG;
    $levels = RfcLogLevel::getLevels();
    ?>

 Source : https://www.drupal.org/node/2270941 


Friday 30 October 2015

"Error: Invalid form POST data" in ajax login form

 When using ajax login form we are getting the warning "Error: Invalid form POST data" to resolve that we need to implement hook_exit()


/**
 * Implements hook_exit().
 */
function module_exit($destination = NULL) {
  if (arg(0) == 'system' && arg(1) == 'ajax') {
    $is_user_login_form_submission = isset($_POST) && isset($_POST['name']) && isset($_POST['pass']) && isset($_POST['form_build_id']);
    if ($is_user_login_form_submission && user_is_anonymous()) {
      $form_build_id = $_POST['form_build_id'];
      $form_state = form_state_defaults();
      $form_state['values'] = $_POST; // Important!
      $form = form_get_cache($form_build_id, $form_state);

      if (!$form) {
        watchdog(__FUNCTION__, 'User login AJAX form submission failed. Trying again...', array(), WATCHDOG_WARNING);

        $form = drupal_rebuild_form('user_login_form', $form_state);
        $form['#build_id_old'] = $form['#build_id']; // Important!

        // Try form submission again after it is rebuilt above
        $commands[] = ajax_command_update_build_id($form);
        $commands[] = ajax_command_invoke('form#user-login-form', 'trigger', array('submit'));

        print ajax_render($commands);
      }
    }
  }
}

Refference Link

https://www.drupal.org/node/1939254
http://drupal.stackexchange.com/questions/152785/invalid-form-post-data-ajax-for-authenticated-users
http://drupal.stackexchange.com/questions/36830/invalid-form-post-data-in-ajax-login-form