Thursday, 30 May 2019

How to restrict a menu in Drupal 7

Sometimes, we need to restrict a user from accessing a certain page.

You can do it through: hook_menu_alter()

So, if your module name is hello_world, the function should be:

function hello_world_menu_alter(&$items) {
 $items['user/%/edit']['access callback'] = FALSE;
}

Here, we have restricted user from editing profile.

Thursday, 28 March 2019

How to flip font awesome icons

Recently came across a problem with font awesome icons.

We are required to show unlock icon. So, we showed it with:

<i class="fa fa-unlock"></i>

And it showed like:





But, we are supposed to show like:



That is, we need to flip the unlock icon.

So, after some research, found solution.

Add class fa-flip-horizontal to <i>

<i class="fa fa-unlock fa-flip-horizontal"></i>

And the unlock icon is flipped.

Tuesday, 19 March 2019

Drupal 8 uninstall a module programmatically

Drupal 8 does not allow to enable/disable modules like previous version.

You have to completely uninstall a module to get rid of it.

You can install the module be:

<?php
  
\Drupal::service('module_installer')->install(['admin_toolbar']);?>



You can uninstall the module by:

<?php
  
\Drupal::service('module_installer')->uninstall(['admin_toolbar']);?>

Monday, 18 March 2019

Drupal 8: Get User Profile Field Allowed values list


Say, you have a user profile field: field_phone_brand

And you have options:

iPhone|iPhone
Samsung|Samsung
MI|MI
Oppo|Oppo
Vivo|Vivo

And you want to get the allowed values list in a custom module/theme,

$entityManager = \Drupal::service('entity_field.manager');
$fields = $entityManager->getFieldStorageDefinitions('user', 'profile');
$options options_allowed_values($fields[$fieldName]);

If you print:

echo '<pre>';
print_r($options);
echo '</pre>';

You will get:

Array
(
    [iPhone] => iPhone
    [Samsung] => Samsung
    [MI] => MI
    [Oppo] => Oppo
    [Vivo] => Vivo
)

Thursday, 28 February 2019

How to add a class to body Drupal adding a class to “body”

You can use hook_preprocess_html() in your theme's yourtheme.theme file.

Following code will add a body class bdyCls to <body> if certain condition matches.

/**
 * Implement hook_preprocess_html
 */
function yourtheme_preprocess_html(&$html) {
 if ($condition) {
  $html['body_class'] .= 'your-custom-css-class';
 }
}

Wednesday, 27 February 2019

Drupal 8 login a user programatically

Question: How to login a user programmatically in Drupal 8?

Steps:

In your module, create a menu call back

example.externallogin:
  path: '/external/login/{token}'
  defaults:
    _controller: '\Drupal\example\Controller\ExamplesController::externallogin'
    _title: 'Offers'
  requirements:
    _access: 'TRUE'


in your controller,

modules/example/src/Controller/ExamplesController.php,

use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;

public function externallogin($token = NULL) {
$uid = 111; // Can be any valid Drupal's user id.
if(isset($uid)) {
  $user = User::load($uid);
  user_login_finalize($user);
}
return ['#type' => 'markup', '#markup' => $this->t('You are logged in')];
}

And user is logged into Drupal.

Monday, 25 February 2019

Drupal 8 prevent caching of programmatically created block.

I was working on creating a custom block programmatically.

The requirement was to show the file uploaded to a specific node.

The problem was block was caching and showing same value for each node page.

After a lot of Google search for module hooks, theme hooks, I found that there is an inbuilt function in the block definition itself.

getCacheMaxAge()

This function can set cache age to 0 hence disabling to cache the block.

Final code:

<?php
/**
 * @file
 * Contains \Drupal\sample\Plugin\Block\XaiBlock.
 */
namespace Drupal\sample\Plugin\Block;
use Drupal\Core\Block\BlockBase;
//use GuzzleHttp\json_decode;
/**
 * Provides a 'article' block.
 *
 * @Block(
 *   id = "article_block",
 *   admin_label = @Translation("Article"),
 *   category = @Translation("Custom article block sample")
 * )
 */
class ArticleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
public function build() {
$nid = NULL;
$content = NULL;
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// You can get nid and anything else you need from the node object.
$nid = $node->id();
}
if (! empty($nid)) {
$node = \Drupal\node\Entity\Node::load($nid);
$changedVal = $node->get('changed')->getValue();
$changedVal = ! empty($changedVal[0]['value']) ? $changedVal[0]['value'] : '';
if ($changedVal) {
$changedVal = date('d F Y', $changedVal);
}
$content .= '<p class="txt">Last updated ' . $changedVal . '</p>';
}
return array(
'#type' => 'markup',
'#markup' => $content
);
}
/**
     * {@inheritdoc}
     */
    public function getCacheMaxAge() { // <- This function disables block caching.
return 0;
    }
}

How to restrict a menu in Drupal 7

Sometimes, we need to restrict a user from accessing a certain page. You can do it through: hook_menu_alter() So, if your module name i...