Revert last commit in GIT

$ git commit -m "Something terribly misguided"          	(1)
$ git reset HEAD~                                       	(2)
<< edit files as necessary >>                           	(3)
$ git add ...                                           	(4)
$ git commit -c ORIG_HEAD                               	(5)
  1. This is what you want to undo
  2. This leaves your working tree (the state of your files on disk) unchanged but undoes the commit and leaves the changes you committed unstaged (so they’ll appear as “Changes not staged for commit” in git status and you’ll need to add them again before committing). If you only want to add more changes to the previous commit, or change the commit message1, you could use git reset –soft HEAD~ instead, which is like git reset HEAD~ but leaves your existing changes staged.
  3. Make corrections to working tree files.
  4. git add anything that you want to include in your new commit.
  5. Commit the changes, reusing the old commit message. reset copied the old head to .git/ORIG_HEAD; commit with -c ORIG_HEAD will open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the -C option.

Drupal Urls

 

DESCRIPTION

CODE

Get route name from current url $variables[‘route_name’] = \Drupal::routeMatch()->getRouteName();
Generate url full path $url = \Drupal\Core\Url::fromUri(“base:/user/$uid”,array(‘absolute’ => TRUE))->toString();node/1 to http://website.com/node/1
Generate url from route \Drupal::url(‘tex.dashboard’)

http://texportal.com/dashboard

To convert url from path given $url = ‘/taxonomy/term/’ . $tid;

$result = \Drupal::service(‘path.alias_manager’)->getAliasByPath($url)

#Alternate method if object is having a function url()

$breadcrumb[‘url’] = $object->url(‘canonical’, [‘absolute’ => TRUE]);

Get URL from Url object $slidersObject[1]->field_read_more[0]->getUrl()->setAbsolute()->toString()

GIT

Table for git commants

ISSUE 

SOLUTION

Initialize git in a project or folder git init
#create a gitignore file to add files that are needed to be not uploaded sudo cp example.gitignore .gitignore
Add all files  git add . OR git add A OR git add all
Set repository git remote add origin https://**********@bitbucket.org/******/*****.git
Commit added file git commit m “initial-commit”
To overwrite last commit message git commit amend message”
Configure user mail and name before performing a commit git config global user.email “*****@4spots.com”

git config global user.name “****”

Push committed work to a repository

P.S: pushing to a branch is always at the risk of the developer

git push origin <branch name>
Push committed work to a new branch in repository git push u origin <branch name>
Pull from repo git pull origin <branch name>
Ignore the current changes in a file

Ignore all current changes

git checkout <filename>

git checkout .

Download all objects and refs from another repository git fetch all
Lists all branches both from local and remote git branch -a
Commit a file only once and leave future changes ignored and revert it back git updateindex assumeunchanged [<file> …]

git updateindex noassumeunchanged [<file> …]

Clone from a particular branch git clone b <branch_name> singlebranch

e.g: https://name4spots@bitbucket.org/team4spots/bib024.git

Fetch a file from another branch git checkout <target_branch_name> <file_name_with_path>

Eg:- git checkout html_branch web/themes/custom/bib/css/style.css

To Change the current origin in an already present git configured folder git remote seturl origin git://new.url.here

or edit .git/config and change the URLs there.

Move existing, uncommitted work to a new branch in Git just create a branch as normal then those changes will be in your new branch.
create a new branch git checkout b <newbranch>
Push a new branch to repo git push u origin <newbranch>
List newly added files between two branches git diff nameonly difffilter=A master bib027299
To list files from only a particular folder git diff nameonly difffilter=A master bib027299 | grep config/sync/
To delete a branch git branch d branch_name

git branch D branch_name //forcefully delete

git push d <remote_name> <branch_name> //delete from repo

To pull from the currently working branch git pull
To push to the currently working branch //git config –global push.default simple

git push 

Adding a twig extension in drupal 8

/**
 * My awesome twig extension.
 */
class MymoduleTwigExtension extends TwigExtension {

  /**
   * {@inheritdoc}
   */
  public function getFunctions() {
    return [
      new Twig_SimpleFunction('url_path', array($this, 'getPathFromUrl'))
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'mymodule_core';
  }

  /**
   * Gets a path from Url object.
   *
   * @param \Drupal\Core\Url $url
   *   The URL object to retrieve the path from.
   *
   * @return string
   *   Path to where the Url object is poiting to.
   */
  public function getPathFromUrl(Url $url) {
    return $url->toString();
  }
}

Render a webform in drupal

$webform = \Drupal::entityTypeManager()->getStorage('webform')->load(webformId);
$view_builder = \Drupal::service('entity_type.manager')->getViewBuilder('webform');
$build = $view_builder->view($webform);

OR

$webform = \Drupal::entityTypeManager()->getStorage('webform')->load(webformId)->getSubmissionForm()

Drupal issues and solutions

ISSUES

SOLUTION

Aggregate css file in server clear cache issue to be resolved Need to set the temp folder in server.
directory /tmp does not exist.

 OR

Not fully protected

Set the tmp folder path to server tmp folder location.

Location in sentora: /var/sentora/temp

Trusted Host Settings -> Not enabled Insert below code in settings.php

$settings[‘trusted_host_patterns’] = array(

  ‘^example\.com$’,

  ‘^www\.example\.com$’,

  ‘^localhost$’,

);

Unable to create :: The TCPDF cache directory, Create tcpdf/cachecahe in the temp folder
PHP OPcode caching -> Not enabled Install opcode from http://php.net/manual/en/opcache.installation.php

Add these lines in php.ini

[opcache]

zend_extension=php_opcache.dll

opcache.enable=1

Update notifications -> Not enabled Enable Update Manager module in backend
Unable To edit super user :: Commonly occured when a site is installed through drush site install. Issue with time zone saved go to DB table user_field_data edit timezone of the user id “1” some valid timezone say “Asia/Kolkata”
Mismatched entity and/or field definitions drush entup
Forgot Admin UserName and Password drush uinf uid

E.g:drush uinf 1

drush upwd username password=newpassword

E.g:drush upwd admin password=abc123

The following module is missing from the file system… drush sqlquery “DELETE FROM key_value WHERE collection=’system.schema’ AND name=’module_name’;”
Changing the sync directory Add the following line in settings.local.php or settings.php

$config_directories[‘sync’] = ‘{path to the desired folder}/’;

Sync uuid when drush is not configured Go to database config table => search for “system.site” 

download the data blob then edit uuid: 

Then replace the uuid with the uuid from the main site (from which site is cloned).

For more Drush Commands Click  For more Drupal Console Commands Click
To generate some sample content for testing purpose, drush genc <number of nodes> <number of comments> types=<content type>

e.g: drush genc 3 0 –types=bank

To import and export configuration to a custom folder drush configimport source=“<folder-path>”

drush configexport destination=“<folder-path>”

Dump database and files drush sql-dump filename E.g:
Dump  database and files
  • mkdir /4spDrive/${PWD##*/}/$(date +”%Y-%m-%d”)
  • drush sql-dump > “/4spDrive/${PWD##*/}/$(date +”%Y-%m-%d”)/${PWD##*/}-$(date +”%Y-%m-%d”).sql”
  • zip -r /4spDrive/${PWD##*/}/$(date +”%Y-%m-%d”)/${PWD##*/}-$(date +”%Y-%m-%d”).zip docroot/sites/default/files/
  • For project inside web folder

zip -r /4spDrive/${PWD##*/}/$(date +”%Y-%m-%d”)/${PWD##*/}-$(date +”%Y-%m-%d”).zip web/sites/default/files/

Import db and files
    • Copy sql and zip file to project root folder
  • drush sql-drop -y; drush sql-cli < path_to_sql.sql
    • Take backup of files if needed
  • sudo mv docroot/sites/default/files docroot/sites/default/files1
  • unzip files.zip
    • Remove backup sudo rm -rf docroot/sites/default/files1
    • Then, git clean -f
Site broken when aggregation is on
  1. Check sites/default/files have full write permission
  2. Check the Temp directory configured and it is having full write permission
  3. If still the site is broken:

Should be a problem with the .htaccess in sites/default/files.

    1. Deactivate all lines in the .htaccess.
    2. Clear the cache it should work.
    3. Turn all htaccess rules back.
    4. Clear the cache it should still work.

(Reference)

List the custom blocks and their corresponding uuids drush sqlq ‘SELECT id,uuid FROM block_content’

Drupal 8 Multisite configuration

  • Install multisite in existing project

    drush site-install --db-url=mysql://root:spots@localhost/bac009_portal --sites-subdir=portal --yes --account-mail="mail@mailss.com" --account-name=superadmin --account-pass=123456 --site-mail="tech@mails.com" --site-name="bac portal"
    
  • Multisite Config export

    1. Get Multisite uri
      drupal debug:multisite
    2. Set config path in settings.php

      /var/www/html/old-bac009-drupal8/web/sites/portal/settings.php
      $config_directories[‘sync’] = ‘../config/sync/portal’;

    3. Get particular site config using uri

      example: portal.localhost
      drupal –uri=portal.localhost config:export
      Config file directory is -> sites->mutisite_folder->files->config

    4. Clear cache multisite

      drupal cr all --uri=portal.localhost

Issues with drupal core upgrade

  1. Frontend Issues

    • Jquery gets upgraded to 3, so many functions wont work also issues arise for bootstrap and owl carousel.
    • Also, a higher version of php is required (It arises while uploading to otherserver)
  2. Update error

    • MySQL Errors occur when upgrading to 8.5.2:
      missing column revision-default ()

      drush sql-query "ALTER TABLE block_content_revision ADD COLUMN revision_default tinyint(5) AFTER revision_log"
    • One error

      drush sql-query "DELETE FROM config WHERE name = ‘system.action.comment_delete_action’;DELETE FROM config WHERE name = ‘views.view.comment’;TRUNCATE TABLE cache_config;"