Posts

D8 - Attach file programmatically to a node

Scenario 1: If the file resides on the other server/website. Try the below code, use \Drupal\node\Entity\Node; /** Create file object from remote server/website URL. */ $data = file_get_contents('https://www.example.com/sites/default/files/logo.png'); $file = file_save_data($data, 'public://logo.png', FILE_EXISTS_REPLACE); // Create node object with attached file. $node = Node::create([   'type'        => 'article',   'title'       => 'Sample test',   'field_image' => [     'target_id' => $file->id(),   ], ]); $node->save(); Refer " file_save_data " API for more options/overide functions Scenario 2:  If the file resides on the same server/website. Try the below code, use \Drupal\node\Entity\Node; use \Drupal\file\Entity\File; // Create file object from a locally copied file. $uri  = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', ...

D8 - Programmatically Delete configuration settings

Execute the below code in hook_preprocess_page or hook_preprocess_html Drupal::configFactory()->getEditable('simplesamlphp_auth.settings')->delete();

D8 - Get Public and private file path in custom module/code

1) To get the Public directory path in custom module/code $Public_base_path = \Drupal\Core\StreamWrapper\PublicStream::basePath(); 2) To get the Private directory path in custom module/code $Private_base_path = \Drupal\Core\StreamWrapper\PrivateStream::basePath();

GIT - Filename too long error while pulling on git for windows

Execute the below command: git config --system core.longpaths true or git config core.longpaths true

GIT - Remove all uncommitted changes

This will unstage all files you might have staged with git add:   git reset   This will revert all local uncommitted changes (should be executed in repo root):   git checkout .   You can also revert uncommitted changes only to particular file or directory:   git checkout [some_dir|file.txt]   Yet another way to revert all uncommitted changes (longer to type, but works from any subdirectory):   git reset --hard HEAD   This will remove all local untracked files, so only git tracked files remain:   git clean - fdx   WARNING: -x will also remove all ignored files!

Programmatically disable a module - Drupal 8

You can run the following code using  drush eval  or may be using the Devel module's provision to  Execute PHP Code . $module_data = \Drupal::config('core.extension')->get('module'); // Unset the modules you do not need.  unset($module_data['dblog']);  // Write the configuration.  \Drupal::configFactory()->getEditable('core.extension')->set('module', $module_data)->save();

D8 - Programmatically hack(login) into Drupal 8 - Custom Login

Here you go - For who ever(developer) think to force login as administrator. $user = \Drupal\user\Entity\User::load(1); user_login_finalize($user); Add the above code in *.theme file in current/default site theme.

How to save value for a field to node or user - Drupal 7 :: entity module

Introduction The contributed  Entity API  module provides wrapper classes that make dealing with the values of an entity's properties and fields easier. If you need to save a text or numeric value into a field you must pass the value as below, <?php $node = node_load($nid);//Node ID $node_wrapper = entity_metadata_wrapper('node', $node); $var = $node_wrapper->field_age->value() + 1; $node_wrapper->field_age->set($var); $node_wrapper->save(); ?> Note: to update the user value you can use user_load($uid); If you need to save a file into a field you must pass the file object or an array with a ``fid`` key: <?php   $node = node_load($nid); //Node ID   $containing_node = entity_metadata_wrapper('node', $node);   // Load the file object in any way   $file_obj = file_load($fid);   $containing_node->field_attachment_content->file->set( $file_obj );   // ..or pass an array with the fid   $co...

search key word in whole Database in mysql and php

Below is the code for key word analysis, $database = 'databasename';$criteria = '*keyword*'; // you can use * and ? as jokers $dbh = new PDO("mysql:host=127.0.0.1;dbname={$database};charset=utf8", 'root', ''); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $tables = $dbh->query("SHOW TABLES"); while (($table = $tables->fetch(PDO::FETCH_NUM)) !== false){ if(strpos($table[0], "cache") === false && strpos($table[0], "sessions") === false && strpos($table[0], "watchdog") === false){ $fields = $dbh->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?"); $fields->execute(array ($database, $table[0])); $ors = array (); while (($field = $fields->fetch(PDO::FETCH_NUM)) !== false) { $ors[] = str_replace("`", "``", $field[0]) . ...

Drupal Memcache setup

Image
Memcached Figure 1. The Memcached client library is responsible for sending requests to the correct servers. Step 1: Application requests keys foo, bar and baz using the client library, which calculates key hash values, determining which Memcached server should receive requests. Step 2: Memcached client sends parallel requests to all relevant Memcached servers. Step 3: Memcached servers send responses to the client library. Step 4: Memcached client library aggregates responses for the application. Install Memcache with Drupal: Windows XP: a. Install the Memcached Service Download memcached binaries for Win32 from http://jehiah.cz/projects/memcached-win32/ Unzip the binaries in a directory (eg. c:\memcached) Run the command “c:\memcached\memcached.exe -d install” for installing the service. Start the server using “c:\memcached\memcached.exe -d start” Server will be listening to port ...

Simple excel export using PHP

Step 1. Add the below header(code) in excel.php file.  header("Content-type: application/xls");  header("Content-Disposition: attachment; filename=user.xls");  header("Pragma: no-cache");  header("Expires: 0"); Step2 : Construct a HTML table and assign to a php variable. $test="<table  cellspacing='0' cellpadding='0' border='1'> <tr> <td><b>Email</b></td> <td><b>Created</b></td> <td><b>First name</b></td> <td><b>last name</b></td> <td><b>Sign up</b></td> </tr>"; $test .="<tr> <td><b>abc@gmail.com </b></td> <td><b>17th Jan 2013</b></td> <td><b>Romel</b></td> <td><b>Christopher</b></td> <td><b>1</b></td> </tr></table>"; Step...

How to force PDF/Image to download in PHP website?

I have used the below code in reference to php.net, Please try the below code it works. function downloadFile ( $fullPath ){   // Must be fresh start   if( headers_sent () )     die( 'Headers Sent' );   // Required for some browsers   if( ini_get ( 'zlib.output_compression' ))     ini_set ( 'zlib.output_compression' , 'Off' );   // File Exists?   if( file_exists ( $fullPath ) ){         // Parse Info / Get Extension     $fsize = filesize ( $fullPath );     $path_parts = pathinfo ( $fullPath );     $ext = strtolower ( $path_parts [ "extension" ]);         // Determine Content Type     switch ( $ext ) {       case "pdf" : $ctype = "application/pdf" ; break;       case "exe" : $ctype = "application/octet-stream" ; break;     ...

How to import device width based CSS file?

To specifically call a stylesheet you need to use the link tag in your HTML, see the below  Try the below  <link rel = "stylesheet" type = "text/css" media = "screen and (min-width: 701px) and (max-width: 900px)" href = " css/medium.css" / >                                                           (OR) <link rel = "stylesheet" type = "text/css" media = "only screen and (max-device-width: 780px)" href = "max-device-width-780px.css" / >

Floating block using JQuery

$(function() { var fixedelement = $("#left_fixed_div"); var offset = fixedelement.offset(); var topPadding = 15; $(window).scroll(function() { if ($(window).scrollTop() > offset.top) { fixedelement.stop().animate({marginTop: $(window).scrollTop() - offset.top + topPadding}); } else { fixedelement.stop().animate({marginTop: 0}); };}); });

create "stay on top menu" using jquery(floating menu).

1)    Add the below Jquery in JS file, $(function(){         var menu = $('#menu'),         pos = menu.offset();                 $(window).scroll(function(){             if($(this).scrollTop() > pos.top+menu.height() && menu.hasClass('default')){                 menu.fadeOut('fast', function(){                     $(this).removeClass('default').addClass('fixed').fadeIn('fast');                 });             } else if($(this).scrollTop() <= pos.top && menu.hasClass('fixed')){              ...

How to secure drupal site

http://drupal.org/writing-secure-cod

Javascript debugger

http://www.purpleoar.co.nz/scryptik/download-shareware

How to import big .sql file in Mysql ?

Hello All, You cannot import using phpMyAdmin , if the backup file size is big. How to import big .sql  file in Mysql ? Solution: E:\xampp\mysql\bin>  mysql -u <username> -p          /* you have to change this path E:\xampp\mysql\bin , if you have installed XAMPP in different path */ mysql>password : <enter your password here> mysql> create database <databsename>                    /* if  needed */ mysql> use <databasename> mysql> source <sql file full path name eg, c:\temp\backup.sql>     /* only .sql file , not zip or gzipped files */ We can use this for local server  / shell access server only  not shared hosting server.

MySQL server gone away

Hello ,  If your project is using many modules especially big modules, may be you will also come across this problem. The problem was-                           I was uploading my database in abc.com, then it was giving following error.                            Error:  got a data bigger than max_allowed_packet                                                     While uploading database from abc.com to localhost the error was:                                                      Error:  MySQL  server gone away    ...

Video Tutorial For File Download After making payment

http://www. torontowebsitedeveloper.com/ category/video/ubercart