When the admin changes(Add/Remove) roles of the user, how to get assigned and removed roles of that user? There are more than 20 user roles(Editor,approver,new admin..) in the  project. Whenever the admin assign/delete the role to user then the user should be notified with email. Email should say Hey Prabhakar You have been assinged to following roles or you have been removed from following roles.

Implement hook_user_presave:

/**
 * Implements hook_user_presave()
 */
function yourModuleName_user_presave(&$edit, $account, $category){
  foreach ($account->roles as $role_id => $val) {
    $user_roles_existing[] = $role_id;
  }
  foreach ($edit['roles'] as $role_id => $val) {
    // $edit['roles'] contains all roles ids as key and selected role id as val. If not selected then value is 0
    // ex. $edit['roles'] = array(5=>5, 6=>0) here role id 5 selected
    if ((int) $val > 0) {
      $user_roles_form[] = $role_id;
    }
  }
  $user_roles_new = array_diff($user_roles_form, $user_roles_existing);
  $user_roles_removed = array_diff($user_roles_existing, $user_roles_form);
  //roles added
  if (count($user_roles_new) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing new roles count' . count($user_roles_new));
  }
  //roles removed
  if (count($user_roles_removed) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing Removed roles count' . count($user_roles_removed));
  }
}


Privatemsg Module and custom timestamp By default the Privatemsg Module has three timestamp displays for various lengths the message has been sent. After a certain point the listed 'time' changes.

What I want to do is append the next timestamp to the end of the current one. This way it remains the details of minutes and date posted as time moves forward.

Example: after 24hrs, instead of it just saying 'Oct 8' I want it to say 'oct 8 12:45' and after a year '2014 oct 8 12:45'

I think I found the code in the module where timestamps are printing, I just can't figure out how to add to it.

function privatemsg_date_formats() {
  $formats = array('g:i a', 'H:i', 'M j', 'j M', 'm/d/y', 'd/m/y', 'j/n/y', 'n/j/y');
  $types = array_keys(privatemsg_date_format_types());
  $date_formats = array();
  foreach ($types as $type) {
    foreach ($formats as $format) {
      $date_formats[] = array(
        'type' => $type,
        'format' => $format,
        'locales' => array(),
      );
    }
  }
  return $date_formats;
}

function privatemsg_date_format_types() {
  return array(
    'privatemsg_current_day' => t('Privatemsg: Current day'),
    'privatemsg_current_year' => t('Privatemsg: Current year'),
    'privatemsg_years' => t('Privatemsg: Other years'),
  );
}

function privatemsg_format_date($timestamp) {
  if ($timestamp > ((int)(REQUEST_TIME / 3600)) * 3600) {
    return t('@interval ago', array('@interval' => format_interval(abs(REQUEST_TIME - $timestamp), 1)));
  }
  if ($timestamp > ((int)(REQUEST_TIME / 86400)) * 86400) {
    return format_date($timestamp, 'privatemsg_current_day');
  }
  if ($timestamp > mktime(0, 0, 0, 1, 0, date('Y'))) {
    return format_date($timestamp, 'privatemsg_current_year');
  }
  return format_date($timestamp, 'privatemsg_years');
}

Add these two date formats (in admin/config/regional/date-time/formats):

M d H:i

Y M d H:i

After that choose above created date formats (in admin/config/regional/date-time)
in

Privatemsg: Current year & Privatemsg: Other years  respectively.

Day     ---     ---
d   Day of the month, 2 digits with leading zeros   01 to 31
D   A textual representation of a day, three letters    Mon through Sun
j   Day of the month without leading zeros  1 to 31
l (lowercase 'L')   A full textual representation of the day of the week    Sunday through Saturday
N   ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)     1 (for Monday) through 7 (for Sunday)
S   English ordinal suffix for the day of the month, 2 characters   st, nd, rd or th. Works well with j
w   Numeric representation of the day of the week   0 (for Sunday) through 6 (for Saturday)
z   The day of the year (starting from 0)   0 through 365
Week    ---     ---
W   ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)     Example: 42 (the 42nd week in the year)
Month   ---     ---
F   A full textual representation of a month, such as January or March  January through December
m   Numeric representation of a month, with leading zeros   01 through 12
M   A short textual representation of a month, three letters    Jan through Dec
n   Numeric representation of a month, without leading zeros    1 through 12
t   Number of days in the given month   28 through 31
Year    ---     ---
L   Whether it's a leap year    1 if it is a leap year, 0 otherwise.
o   ISO-8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)    Examples: 1999 or 2003
Y   A full numeric representation of a year, 4 digits   Examples: 1999 or 2003
y   A two digit representation of a year    Examples: 99 or 03
Time    ---     ---
a   Lowercase Ante meridiem and Post meridiem   am or pm
A   Uppercase Ante meridiem and Post meridiem   AM or PM
B   Swatch Internet time    000 through 999
g   12-hour format of an hour without leading zeros     1 through 12
G   24-hour format of an hour without leading zeros     0 through 23
h   12-hour format of an hour with leading zeros    01 through 12
H   24-hour format of an hour with leading zeros    00 through 23
i   Minutes with leading zeros  00 to 59
s   Seconds, with leading zeros     00 through 59
u   Microseconds (added in PHP 5.2.2). Note that date() will always generate 000000 since it takes an integer parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds.    Example: 654321
Timezone    ---     ---
e   Timezone identifier (added in PHP 5.1.0)    Examples: UTC, GMT, Atlantic/Azores
I (capital i)   Whether or not the date is in daylight saving time  1 if Daylight Saving Time, 0 otherwise.
O   Difference to Greenwich time (GMT) in hours     Example: +0200
P   Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)    Example: +02:00
T   Timezone abbreviation   Examples: EST, MDT ...
Z   Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.  -43200 through 50400
Full Date/Time  ---     ---
c   ISO 8601 date (added in PHP 5)  2004-02-12T15:19:21+00:00
r   » RFC 2822 formatted date   Example: Thu, 21 Dec 2000 16:01:07 +0200
U   Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

and you can used :
$date = date("character");


Organic groups automatic audience selection I am working with organic groups. Within each group, permitted users are allowed to create their own pages.

What my problem is that I need to set the audience for a new page automatically as the group the user is currently in.
This is so that the user cannot manually change the group the post should go into but instead it's automatically and permanently set ( unless an administrator changes it ).

Does anyone know of a way that I might accomplish that?

You can use the prepopulate module to pass the group's gid to the node add form.
For example, the link will looks something like this:

node/add/discussion?edit[group_audience][und]=4

You could then hide the group selection box with css so the user cannot change it.
For a more robust solution you would code a form hook. Here is an example.

With Drupal 7, you don't need the Prepopulate module.

You can just use this node/add/blog?og_group_ref=1 where 1 is the group ID.


How to make user.html.twig template for two different pages (users)? I want to make user.html.twig template for user ID1 is not such as to all other users. How to?

I tried this code in MYTHEME.theme file:

function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  if ($user = \Drupal::routeMatch()->getParameter('users')) {
    // For make files, like:
    // page--user--[id].html.twig
    $suggestions[] = 'page__user__' . $user->uid();
  }
}

But template page--user--1.html.twig or page--user--%.html.twig don't work. Cache is clear.

Platon, you appear to be mixing up the template for the user itself (user.html.twig) and the overall page template (page.html.twig).

If you want to override the user template then you need to implement hook_theme_suggestions_HOOK where "HOOK" is "user" which is the theme hook you are overriding.

Here is an example of what that code would look like if you were using Bartik (but of course in practice you should be using your own subtheme rather than hacking core):

function bartik_theme_suggestions_user_alter(array &$suggestions, array $variables) {
  $suggestions[] =  'user__' . $variables['elements']['#user']->id();
  return $suggestions;
}

In "themename.theme" file use below template suggestion hook

function themename_theme_suggestions_user_alter(array &$suggestions, array $variables) {
    if($currentUserID == 10){
        $suggestions[] =  'user__info';
    }
    elseif($currentUserID == 12){
        $suggestions[] =  'user__profile';
    }
  return $suggestions;
}

and create two new files "user--info.html.twig" and "user--profile.html.twig" under 'themename/templates/page/' directory and copy the content of "user.html.twig" and paste into it


Password request redirect to another page I click on forgot password page

it redirect me to http://example.com/user/password which is fine

now when i enter email id . it redirect me to

"http//example.com/user */. I want it to redirect another page

http://example.com/request-access

Any idea?

Thanks

You can add your own submit handler to the form :

function CUSTOM_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_reset') {
    $form['#submit'][] = 'CUSTOM_form_submit';
  }
}

function CUSTOM_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'request-access';
}

If you want to close all the sessions after reset password, you can play with Rules and hybridauth modules.

Steps:

Install the module and configure it.
Add a rule "Logout after password update" or whatever name you want to give here.
Select event "After updating an existing user account" .
Once you select an event you will have to add conditions and actions based on which your rule works. Add a condition "Execute php code".
Now a page will get opened where you can add your one liner php code.

return $account_unchanged->pass != $account->pass;

save it and go back to your rules page.

Add an action "Destroy session" and you are done.


Drupal Commerce: how to add "Middle name" field to the "Address" pane? Currently for "Address" pane (field named "commerce_customer_address") available two options:

1) Name (First name, Last name)
2) Name (single line)

In my country middle name is very important. How to add this as separated field from custom module?

To Rayan: By the way, does it make sense to include this option in the Commerce core?

You can add the field under store -> customer profiles -> profile types -> Billing Information -> Manage Fields (Or go to admin/commerce/customer-profiles/types/billing/fields)

You can add any additional fields there. You can't add any fields directly to customer_commerce_address, but if you add any fields under the Billing Information they will show up during checkout.

You should use the Extra Fields Checkout Pane module.


Why does the favicon sometimes not show up and generate "page not found" errors, and other times does show up As the question implies, on occasion Drupal's log is showing that the favicon is not found. Indeed, it does not show in the browser tab or address bar. At other times, even within the same surfing session, it does show up.

Why does it do this and how can I prevent it so that the favicon will always show?

I am using version Drupal 7.22. with a custom subtheme and an admin theme (Stark).

My favicon is set in the subtheme theme configuration at sites/default/files/images/favicon.ico and that is located there as I have checked via FTP.

The log shows the browser is looking in example.com/favicon.ico.

The custom subtheme I use has <link rel="shortcut icon" href="http://example.com/sites/default/files/images/favicon.ico"; type="image/vnd.microsoft.icon" /> in the source code and the admin theme (Stark) uses <link type="image/vnd.microsoft.icon" href="http://example.com/misc/favicon.ico"; rel="shortcut icon"> and this file also exists in that location (not actually using example.com, of course).

Drupal is using clean URLs.

The web server is Apache on Debian Linux.

Thank you.

Some browsers search for favicon under http://example.com/favicon.ico without checking. But they are minority now.

Most respect:

<link rel="icon" href="http://example.com/img/icon.png">

as described by W3C.

If your site tries to use <link> approach but fails on some pages, like admin pages rendered using different template, and you do not have favicon.ico in default location, you will get exactly described effects.

If browser is looking for  http://example.com/favicon.ico when you have proper <link rel="shortcut icon"> it is a browser problem, not yours. It means browser (or at least that part of it's code) is outdated, unless it looked under correct URI first and got another error, but then you would see two errors in log, one for right place, second for outdated one. In Mozilla's queue there is a number of reports about improper favicon detection by FireFox - in example this one. It shows how even modern browsers can sometimes fall back to old methods.

You can try https://www.drupal.org/project/favicon
It to make requests to http://example.com/favicon.ico forward to the actual site's true favicon.


how to Remove "Add new Content" from the Main page I have a front page in which blocks and some contents (ie story) were displayed.
These stories were marked as "Promoted to front page"; later, I unchecked them.
These stories are now gone, yet the blocks were present.

Now I have the following content on my front page:

"No front page content has been created yet.

Add new content"

How do I remove this content or text?

Just add this code to the page.tpl.php or page--front.tpl.php on Drupal 7.

find

<?php print render($page['content']); ?>

and replace with below code.

<?php  if(drupal_is_front_page())
                {
                    unset($page['content']['system_main']['default_message']);
            }
        print render($page['content']);
    ?>

And i believe you surely get all blocks or contents you posted on page.

and to remove page title on page like

Welcome to "website name"

find this code on page.tpl.php or page--front.tpl.php

<?php if ($title): ?>
<?php  print $title; ?>

<?php endif; ?>

and you can remove this code or else just make a comment over.

Just edit to /modules/node/node.module, look for $default_message line (around line 2621) and change 'No front page content has been created yet' to simply ''.


how to see which user has assigned a content_profile content type? I´m using the module
http://drupal.org/project/content_profile
for drupal 6

I want to make a view where I show all the users and a link to their content profile,
or even display some views from their profile..

Can´t seem to be able to do that, I don´t know where to pick the relation between the users and the content type

Currently my view is of the Usuer type..not Node..
I can handle PHP with customfield if I have to..don´t know where to start

According to the code of the content profile module (I didn't test this) you can use views relations between profile nodes (ordinary cck node types) and users.

I'm not sure whether you have to base your view on the cck node type for the profile or users. But with one of these you should get an option to add the other side as a relation and then use fields of the user and the profile in the same view.

In your view, in fields add User: Name

Tick "Output this field as a link" and set users/[name] in the "Link path" field


How can I change the search form placeholder value? How can I change the search form placeholder value? I can change the value of it in my .theme file, but I want it to be also translatable.

What is the correct way of doing this?

You don't alter a TranslatableMarkup object: You replace it with another TranslatableMarkup object you obtain from t('The new placeholder') or
new TranslatableMarkup('The new placeholder') (or a method returning a TranslatableMarkup object).

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['title'] = t('The new placeholder');
}

The result of this code is the following (on Google Chrome running on OS X El Capitan).

What you are showing is not the placeholder, but the input title. To change the placeholder of a form element, you should use code similar to the following one.

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

Using this code, you get the following result.

This worked for me:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id == 'search_form') {

    $form['basic']['keys']['#title'] = 'Your Title';
  }
}


How do I pass a checkbox value to a Webform through URL? When I click a webform link, I want one of the checkbox checked. I've set already set up the default value for that checkbox as %get[foo] in Webform.

I tried:

a href="node/34?foo=checked"

a href="node/34?foo=selected"

a href="node/34?foo=1"

a href="node/34?foo[]=1"

Am I missing something?

Webform provides this functionality by itself.

Define in your checkbox field a default value:

%get[customkey]

The url will be:

http://example.com/node/1?customkey=one,two

This feature is not directly available on Webform module. You've to implement some code to prefill the form fields.

A simple method is to write some JS which reads the URL parameters and set the values to the corresponding fields.

There are many ways to implement this code. This is an example of JavaScript code:

var current_url = window.location.href;
if (current_url.indexOf('foo=') > 0){
  $('#field-id').val(current_url.substr(current_url.indexOf('foo=') + 4));
}

At first the script get the current url and if the "foo" parameter is found, then the value will be loaded and used to set the #field-id value. #field-id is the id of the input field on the webform. 4 is the length of "foo=".

If you have many parameters you can use

  current_url.split("&")

method which returns an array with all the parameters.


How to convert a Drupal website to standalone exe file? I'm trying to convert my Drupal website to a standalone .exe file. I tried some popular applications like ZZEE PHPExe or ExeOutputPHP, ZZEE PHPExe returns the error that /includes/boostrap.inc is not found in the output directory, while I copied that folder in there. The ExeOutputPHP errors File not Found and nothing else! it doesn't even tell me what file is not found!

Any suggestion to convert Drupal website to standalone exe file?

You should generate a static copy of your site first.

For that you can either use a module like the static module, or just "copy" your entire site with wget or curl.

So for example you can do something like this :

wget -p --convert-links http://localhost/ -P ~/site_static_copy

(This assumes that you're accessing your localhost with http://localhost/ and that you want to copy under your ~/site_static_copy directory )

Once you've done that you'll be able to package the copy with the tools you mention.

I will suggest you to create the profile for your site and then you just need to install it all the time whenever you needed.


How load only some node fields? entity.query service is very handy when it comes to finding nodes with specific field values. Unfortunately all it returns are entity IDs and revision IDs.

In case in which result set is big it's really inefficient to load whole nodes if only data from specific fields is needed.

In D7 it was possible for example to use field_attach_load() function which (thankfully) has been removed in D8, as detailed in Fields are no longer handled individually and are bound to an entity type. The problem is that Drupal change log references loadFieldItems() and doLoadFieldItems() of FieldableEntityStorageControllerBase class neither of which exists in current release of D8.

What is the Drupal 8 way of loading data for specific node fields only?

I did some profiling with a query of 100,000 nodes, fetching the field myfield from all nodes of type mybundle.

Good: A dynamic query with addField()

$connection = \Drupal::database();
$query = $connection->select('node__field_myfield');
$query->condition('node__field_myfield.bundle', 'mybundle');
$query->addField('node__field_myfield', 'field_myfield_value');
$result = $query->execute();
$values = $result->fetchAll();

This runs in about 250 milliseconds.

Bad: An entity query with loadMultiple()

$query = \Drupal::entityQuery('node');
$query->condition('type', 'mybundle');
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$values = [];
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);
foreach($nodes as $node) {
  $values[] = $node->get('field_myfield')->getValue();
}

This took 3 minutes after a few repeated attempts when the cache was fully built. After a cache rebuild, it took more than half an hour.

Please create View/Reference/Block/Attachment with selected field. And Call that using contextual filter.

For example :
http://localhost/project/admin/structure/views/view/view_machine_name/edit/your_block

            $nameshipped = 'view_machine_name'; // please check the url
            $viewshipped = views_get_view($nameshipped);
            $display_id_shipped = 'your_block';
            $viewshipped->set_display($display_id_shipped);
            //$viewshipped->set_arguments(array($all_con_id)); // if we need to use contextual filter.
            echo $html = $viewshipped->render();

Please use the above code where you want to implement.


Disable CkEditor to body field of a content type I enabled the CkEditor module, which is affecting all the text-area fields with summary and input format. How can I exclude the CkEditor for some fields?

The problem you experienced with configuring the field is that in core there is no option to select the allowed text formats. When this module is installed

https://www.drupal.org/project/allowed_formats

you can select the text format that is available for a specific field and then you can choose in the settings of the text format whether to use ckeditor or not.

There is work going on to put this in core: https://www.drupal.org/node/784672

If you are using CK editor then go to

  /admin/settings/ckeditor/edit/Default

to change the setting for the default profile, under visibility settings select include and enter the text aread ids for which you want the editor to be enabled.

And as the blog help says entering

  blog@.edit-body - matches all fields of type "blog" called
  edit-body, on any page.
  node/add/.edit-user-* - matches fields starting with "edit-user-" on
  pages starting with "node/add/


How to create a 'most popular content' view? I'd like to get a view block listing the most viewed articles.

What are the options to do that with drupal 8?

Note: I have activated the core module named 'statistics' and configured 'Increment a counter each time content is viewed.' But I cannot select that field for sorting in Views.

After activating the "Statistics" core module and checking the "Count content views" option in /admin/config/system/statistics, as you mention, you can select "Total views" as sort criteria (see screenshot).

After enable Statistics module, creating your view and visiting some pages on a different session,  make sure you run cron and clear cache to view an updated list.


How to hide/remove a specific menu heading tittle I have created a menu using Superfish containing the following items: "Menu 1," "Menu 2," "Menu 3," and "Contact."

When I click on each menu, the heading title is displayed. I want to hide the contact menu title. i was trying to hide it from the block but each menu doesn't have a block title.

How can I hide only the "Contact" menu heading title?

You should:

select the Structure->Blocks menu;
from the blocks list, click on "configure" next to your menu block;
specify <none> as block title.

It works

.is-active:before {
   font-family: FontAwesome;
   content: "\f015";
}

This doesn't work
display:none


Webform translation while keeping single node I want to translate a Webform. I know it's very easy to achieve if there are separate Webform nodes for each language but I don't want to do that, I want to keep a single node.

I have already tried the Webform Localization module:

As per the readme of this module, it says to keep a single node enable
"localization by string translation" fieldset in the form settings

Which I have done.

I have also refreshed the i18n_string, as suggested in module readme.

Issue here is, even with above settings when I click on translate tab of the Webform node, it creates new node.

So are there any other settings I'm missing or this module is not working as its currently in under development.

The method in the documentation is working:

Go to the Webform Form settings at node/1/webform/configure
Check "localization by string translation" and "Expose webform
component strings suitable for translation."
If dealing with an existing webform, then go to Go to Configuration -> Translate interface -> Strings
Enable "Webform localization" checkbox (this is important)
And Refresh Strings
Then you will be able to see the string in Configuration -> Translate interface -> Translate

At least this works for me.

If you have "localization by string translation" then it will create additional nodes each with their own title, path etc, but they will share a single webform.  Use the translate tab just to change the node title etc, but to translate elements in the webform, go to /admin/config/regional/translate/translate and search of each field label etc in turn.


Cannot fetch form_state['values'] of text field from dynamically created Ajax fields I have a custom form with dynamically generated fields. I am unable to fetch values from these fields using form_state['values']. Code is attached below. I have been struggling with this since two days, but have not found anything that can fix the issue. Please help!!!

function oulta_seller_create_search_agent_form_second($form, &$form_state) {

$form['#tree'] = TRUE;

$form['names_fieldset'] = array(
  '#type' => 'fieldset',
  '#title' => t('People coming to the picnic'),
  '#prefix' => '
',
  '#suffix' => '
',
);

if (empty($form_state['num_names'])) {
  $form_state['num_names'] = 1;
}
for ($i = 0; $i < $form_state['num_names']; $i++) {
  $form['names_fieldset']['name'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
);
if(!empty($form_state['values'][$i]) &&  ($form_state['values'][$i] !='')) {
drupal_set_message($form_state['values'][$i]);//<-- This statement never gets executed. Also cannot fetch the value of $form_state['values'][$i]
}

}
 $form['names_fieldset']['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('ajax_example_add_more_add_one'),
  '#ajax' => array(
  'callback' => 'ajax_example_add_more_callback',
  'wrapper' => 'names-fieldset-wrapper',
),
);
if ($form_state['num_names'] > 1) {
  $form['names_fieldset']['remove_name'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#submit' => array('ajax_example_add_more_remove_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
  ),
);
}
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
);

return $form;
}

function ajax_example_add_more_add_one($form, &$form_state) {
 $form_state['num_names']++;
 $form_state['rebuild'] = TRUE;
}

function ajax_example_add_more_callback($form, $form_state) {
 return $form['names_fieldset'];
}

function ajax_example_add_more_remove_one($form, &$form_state) {
 if ($form_state['num_names'] > 1) {
   $form_state['num_names']--;
 }
 $form_state['rebuild'] = TRUE;
}

You have used $form_state['num_names'] instead of $form_state['values']['num_names'].

Please try to update and see.


Contextual filter with multiple entity reference fields Troubles with displaying content in a sidebar block with a View.
Actually, the website is in Dutch, so I'll replace the names of Content Types with something easier, like A, B, C, D.

I have 4 entity types: A, B, C, and D. These are articles referencing each other. So, a node for entity type A on the screen, has additional relevant information in B, C, and D.
While the node from entity type A is on the screen, I want to display the links to the different nodes in B, C and D in a sidebar block.

So in each entity type, I have Entity Reference fields, for example a node from type A has fields  refB and refC and refD.

All working fine, with the links being correctly displayed within the node display, and I can jump between content from each entity type using the Entity Reference fields.

So, for the sidebar block, I created a  View that contains the refB and refC and refD fields, and added a relationship (just for refB initially, to reference the content in entity type B), and a contextual filter on the Nid, getting the value from "Entity from URL".

Nothing gets displayed in the block however.
When I remove the contextual filter, all possible values for the entity reference fields are displayed.  So either I'm getting everything or nothing, but not the relevant entity reference fields from the node in entity type A only.

Articles on this subject explain the Relations and Contextual Filter configuration, but can't get it right apparently.

I think it's because you did not select a Relationship in your field.

Example: Title field (By the way, field_test is my entity ref field name)

Also make sure your contextual filter does not have a relationship

Solved the problem already.   Apparently I was making this too complex.
Created a new view, just adding the refA, refB, refC and refD entity fields.
Then a contextual filter with Nid as  "Content ID from URL"

And that's it, working fine.
No relationships required apparently.  Because the Entity reference already contains the "relationship info".

I think a Relationship is only required if one wants to match nodes on specific content in fields ?

So in this case, no relationship link required.


How to detect which module creates session? I am trying to achive Varnish HIT for anonymous user but get only MISSes.

It seems that my Drupal 7 site somehow starts new session for every anonymous user which opens even main page of the site. I want to detect which module makes session to start?

Unless you have a strong suspicion on a particular module or a small number of modules that could be creating a session, finding the 'culprit' module could be too tiresome.

I would suggest searching for the 'cookie name' instead of a string like '_SESSION' as a more accurate and a faster way.

Say if the cookie name is 'PLAY_ACTIVE_ACCOUNT' (real example from site play.google.com), you could navigate to the parent directory of your contrib module and do a grep -iRn PLAY_ACTIVE_ACCOUNT * to find the filename and line number of where this session cookie is being set. And then disable the module or take other action.

You can discover the name of your cookie by using your browser. In chrome you could do this by typing chrome://settings/content in a new tab and then clicking on the button 'All cookies and site data'. And then typing in the name of your site domain (like I have used play.google.com for example)

You'll need to look into the database to get the module name from the session cookie.


Domain Access force node redirect to proper domain Using Domain Access with Drupal 6, I am encountering an issue in the following scenario:

I set up a node published to a sub site, say:

subsite.com/node-x

If I browse to:

mainsite.com/node-x

I would like it to redirect to:

subsite.com/node-x

However, it just renders the content on the main site domain (which the search engines would pick up as duplicate content).

Any idea how I can configure the sites to redirect to the site on which the node is published? I attempted to use Global Redirect to redirect from the main site to the full url  on the sub site but Drupal told me that I was redirecting something to itself. Are web server redirects my only option?

There is a special module for that: https://www.drupal.org/project/domain_path_rewrite.

The idea is to check the request path before the page load and to make a redirect to the proper domain if needed. Something like:

/**
 * Implements hook_init().
 */
function domain_path_rewrite_init() {
  if ($domain_path = _domain_path_rewrite_domain_path(current_path())) {
    global $_domain;

    if (!($_domain['domain_id'] == $domain_path['domain_id'] && request_path() == $domain_path['path'])) {
      drupal_goto($domain_path['url'], array(), 301);
    }
  }
}

I believe Domain 301 Redirect mixed with domain source will do what you are after.

  The Domain 301 Redirect module allows sites to 301 redirect to a
  domain that is marked as the main domain. This means you can have all
  subdomains and other domains pointing to the site 301 redirect to a
  domain that you choose as the main domain. This provides great SEO
  benefit.


drupal_render() and formBuilder's getForm What exactly is the best way to accomplish this? I can pass the $form object returned from getForm to drupal_render() and get the correct themed output fragment but the API docs say this function will be deprecated in D9 and to use the renderer service instead.

When I use:

\Drupal::service('renderer')->render($form)

I get

  You have requested a non-existent service "renderer". Did you mean one of these: "render_html_renderer", "html_fragment_renderer",
  "html_page_renderer"?

When I use:

\Drupal::service('render_html_renderer')->render($form)

I get a valid object with a protected content() method, which contains the string, but I can't seem to find any valid public functions to access this.

I can normally use the route builder to point to a form controller that I've created but, in this instance, I just want to pull an existing form, get the HTML content, and display it - hopefully as a variable in a preprocess function. I don't necessarily want to create a block, since I probably won't be reusing it.

What is the best way to do this? Keep using drupal_render() until D9? Can somebody point me in the right direction?

There are almost no reasons to manually call drupal_render(), you can use/return render arrays almost anywhere, controllers, blocks and also in twig templates.

If you do $variables['form'] = $your_form;in preprocess, then {{ form }} in your template should just work.

Try using renderRoot() instead of render(), e.g.

\Drupal::service('renderer')->renderRoot($form)

  Renders final HTML given a structured array tree.


commerce feeds product import not showing up I imported a file with 5 fields UPC-> SKU(Unique), Product Description -> Title, Unit Price -> Price Amount and 2 custom fields for wood type and knife number the import process says it created 21 products and I can find these products through phpmyadmin in various places including commerce_product, commerce_product_revision.

There are also a number of entries of type commerce_product in the field_revision_field_product_category table where as the types of my already created content are node in the same table. They all have a price of 0  but are not showing up in the product listing.

I'm using commerce kickstart 2.0, commerce feeds 1.3, feeds 2.0 alpha 7 and have feeds tamper 1.0 beta 4.
I have run cron and flushed all caches.

I tried this in a fresh install of Commerce Kickstart but the products are still not showing up in the view products screen.

I also created a barebones Drupal 7 install with commerce and feeds/commerce feeds and other required modules and the products seem to be created just fine.

Yesterday on #drupal-commerce in IRC, someone had a similar question. It appears that the "title" module may be interfering with commerce_feeds. Try disabling the "title" module and see if that helps your import woes.

It seems Bojan Zivanovic is right. I don't see anything about a second importer to create the nodes. You'll need two importers and need to specify what gets added to the product (variation) and what gets added to the node (content type).


Generating  with the form API I  have a heavily themed form to integrate, whose structure is shown below. I am just about there for the most part except for the submit.

 <form action="#">
   <fieldset>
     <legend>Authentification</legend>
       Courriel*
       <input type="text" name="email" id="email">
       Mot de passe*
       <input type="password" name="password" id="password" class="last">
       Forgot password?
       <button type="submit" class="clearfix">Login</button>
   </fieldset>
 </form>

I have tried many different combinations, turns out button_type has no effect on core. So I used this hack, hoping it would fix my issue. Alas, it only changes the 'type' attribute (obviously), and not the element itself. The button type can hold other elements, in this case the span is needed to hold a background image, it needs to be in a span to stretch as the text in the button is dynamic.

Does anyone have a clue as to how I can generate the following line of markup using the form API?

<button type="submit" class="clearfix">Login</button>

As an addition, just in case someone runs into the same trouble as I did - when using the #markup or #prefix/#suffix trick on a form's actions group, the submit callback function won't be called at all, unless a submit type element is present. My workaround was like this:

$form['actions']['submit'] = array
(
    '#type' => 'submit',
    '#value' => '',
    '#attributes' => array( 'style' => array( 'display: none' )), // hide the input field
    '#submit' => array( 'my_callback_for_the_form_submit' ),
    '#prefix' => '<button type="submit" class="btn btn-primary">Add <i class="fa fa-plus-square-o">',
    '#suffix' => '</i></button>',
);

That way you can use custom HTML for submit action groups.

More correct way is:

$form['submit'] = array(
  '#type' => 'button',
  '#value' => 'Login',
);

It produces valid HTML like this:

<button value="&lt;span&gt;Login&lt;/span&gt;" type="submit">
    Login
</button>

...and this method doesn't brake autocomplete and other features.


Form submit handler not working I'm developing a pretty basic module catalog_request that creates a form. I'm replacing the form's default submit button <input ..type="submit" /> with a <button ...>click</button> using following in form definition.

function catalog_request_form($form, &$form_state) {

    /**
     * form fields here
     */

    $form['fieldset_submit']['the_submit_button'] = array(
       '#type' => 'markup',
       '#prefix' => '<button class="btn submit">',
       '#markup' => 'Send Request...',
       '#suffix' => '</button>',
    );

    /* ... */
}

and have defined other two form related functions

function catalog_request_form_validate($form, &$form_state) {
    drupal_set_message(t('The form was validated'));
}

function catalog_request_form_submit($form, &$form_state) {
    die('submitted');
    //drupal_set_message(t('The form was submitted'));
}

The problem

My submit function catalog_request_form_submit isn't being called. I've read numerous articles online but none resolved my issue. Following didn't work

Adding '#submit' => 'catalog_request_form_submit', to
the_submit_button key
Adding '$form['#submit'] => 'catalog_request_form_submit'; to end
of catalog_request_form function
Adding '$form['#submit'][] => 'catalog_request_form_submit'; to
end of catalog_request_form function

I've read that adding something along the lines of $form['actions']['#submit'][] = 'custom_function'; could solve the problem but I'm not sure how to adapt it for my form.

I know that having '#type' => 'submit' for the submit button makes the form work but I want a button tag.

My problem is exactly When altering the submit button, the form does not work but it doesn't have a solution (only an answer that ignores the question's point)

P.S. I do not develop for drupal frequently so I might be missing something very obvious.

Any help will be greatly appreciated. thanks

In order to add another submit handler you have to add something to hook_form_alter(): check for your particular form ID, and then add a submit handler in one of the following ways:

OPTION 1:

To add a submit handler that is called as the next callback after processing the default submit handler callback you can use this:

function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    $form['actions']['submit']['#submit'][] = 'mymodule_whatever_function';
  }
}

OPTION 2:

If OPTION 1 is not working for you, replace the third line with this:

form['#submit'][1] = 'mymodule_whatever_function';

This will add a second submit handler, or replace the second one with yours if there is already more than one.

OPTION 3:

To remove the default submit handler completely (so that "nothing will happen" on submit, or so that you can replace it with your own), use code like this:

function mymodule_form_alter(&$form, &$form_state) {
  if ($form_id == 'form-id-of-your-form') {
    unset($form["actions"]['submit']);
  }
}

If you are rendering your form using form--anyformname.tpl.php template file then make sure in that template file you are rendering these three thing at the end:

    <div>
    <?php print render($form['form_id']); ?>
    <?php print render($form['form_build_id']);?>
    <?php print render($form['form_token']); ?>
    </div>


Prefill taxonomy term reference field while in term page I have a content type A with a required term reference field (vocabulary: category, widget: radios). I would like to accomplish the following:

In every term page (of this specific vobaulary) i will have an "add type A" link.
When the node/add form appears (upon clicking on this link) i want the value of taxonomy term reference field to already be chosen as the category term which corresponds to the specific term page. Ideally i would like the above and also to dissapear this field from the form.

Any help?

There is a module for this and it's called Entity reference prepopulate.

When you define the field for the content type, you can set a default. Then you can use the Fields Permissions module to restrict access to the field the the admin role. If the user does not possess the required role, they will not have access to the field on the edit form.


How to hide default "N/A" option for checkboxes? I have a "gender" (checkbox) option that I want to show on the user profile page (but not on the registration page).
The options are "Male" (default) and "Female". Since I don't make the field required it is showing the "N/A" option. Drupal does this by design.

If I make the field required the "N/A" option will go away but then it will automatically show on the registration page which I don't want.

I was trying to hide it with CSS but I cannot see a way to just hide that checkbox and "N/A" text:

<input id="edit-field-gender-und-none" class="form-radio" type="radio" value="_none" name="field_gender[und]">
N/A

<input id="edit-field-gender-und-0" class="form-radio" type="radio" checked="checked" value="0" name="field_gender[und]">
Male

<input id="edit-field-gender-und-1" class="form-radio" type="radio" value="1" name="field_gender[und]">
Female

Help! ;-)

You can use jQuery to accomplish this

$("#edit-field-gender-und-none").remove();

One of the interesting Features of Drupal 7 is the Field API. Prior to Drupal 6, to make a custom field the Core Profile Module and Content Profile Modules are used. Now in Drupal 7 we can make any custom field to appear in User Registration Form. When Adding Custom Fields Such as Gender usually we use Radio Button Input. However there is a small Problem with the core module as it displays the third option N/A in the input. To Remove the N/A option the field needs to be set as mandatory. To Remove this option there is another way. Go to modules/field/modules/options/options.module and comment the the code $properties['empty_option'] = ‘option_none’ as shown below under buttons.

case ‘buttons’:
$properties = array(
‘filter_xss’ => TRUE,
);
// Add a ‘none’ option for non-required radio buttons.
if (!$required && !$multiple) {
//$properties['empty_option'] = ‘option_none’;
}
break;

case ‘onoff’:
$properties = array(
‘filter_xss’ => TRUE,
);
break;
}

However the proper way to achieve it would be to override this function in custom module. But for a quick fix we can also follow this method. [blog]: http://yamafm.wordpress.com/ "click here for updates"


How to link the file icon to the file and to hide the filename? I have uploaded files to be displayed in a table together with some other informations (title, tags etc). One row of this table the filename which links to the downloadable file. Next to the filename a file icon is displayed be daefault, which isn't linked.

That's how it looks now:

I want the filename to be hidden and the file icon linked to the downloadable file.

What functions would I have to override to make that happen? Or what other way may exist?

The problem with generic file display is that icon is not linkable, therefor a CSS solution is useless.

So in order to make the icon linkable you need to create another file display formate or alter theme_file_link

My solution is to add additional display formate, code as follow:

/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
    'mymodule_link_icon' => array(
      'label' => t('Linkable icon'),
      'field types' => array('file'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {

    case 'mymodule_link_icon':

      foreach ($items as $delta => $item) {

        $file = (object) $item;

        $url = file_create_url($file->uri);

        $icon_directory = variable_get('file_icon_directory', drupal_get_path('module', 'file') . '/icons');

        $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

        $options['attributes']['title'] = check_plain($file->filename);

        $options['html'] = TRUE;

        $link_icon = '' . l($icon, $url, $options) . '';

        $element[$delta] = $element[$delta] = array('#markup' => $link_icon);
      }

      break;
  }

  return $element;
}

After you implement the above code in a module and enable it, make sure to change field formatter option in your view to Linkable icon

Edit file  file.module in path /modules/file

Returns HTML for an image with an appropriate icon for the given file.

  @param $variables
  An associative array containing:
  -file: A file object for which to make an icon.

  icon_directory: (optional) A path to a directory of icons to be used for files. Defaults to the value of the "file_icon_directory" variable.

  alt: (optional) The alternative text to represent the icon in text-based browsers. Defaults to an empty string.

  @ingroup themeable

function theme_file_icon($variables) {
  $file = $variables['file'];
  $alt = $variables['alt'];
  $icon_directory = $variables['icon_directory'];

  $mime = check_plain($file->filemime);
  $icon_url = file_icon_url($file, $icon_directory);
  $url = file_create_url($file->uri); /*Thêm đường dẫn file */
  return ''; /* Thêm link vào icon */
}

Then using css to hide the filename.
Thanks Mahyar Farshi for share.


Change image style in view depending on node type I have a view which shows a list of nodes of two different node types. Both have an image field.

Now I would like to have the image style to be different for the two node types.

I can't use hook_views_pre_render(), because then I would change the image style for all the nodes displayed. I also think I can't use a tpl.php file, because then I already have a URL, and can't retrieve another image style URL based on that that URL. Another option would be to define the image field twice in the view, and hide one depending on the node type, but I wouldn't know how to do that.

I'm using Drupal 7.

Any idea I overlooked?

Here is a better way to format your image or check out this post http://drupal.org/node/958726

$hero_image = array(
  'style_name' => 'case_study_teaser',
  'path' => $image['uri'],
  'width' => '',
  'height' => '',
  'alt' => $image['alt'],
  'title' => $image['title'],
  );
print theme('image_style',$hero_image);

If you only have a few images and the file size is small you could resize them with css. Not the most elegant solution but a quick one ;-)


Remove colons from Drupal form fields/labels How can I remove the : from appearing after every label in forms made with the Drupal Form API?

Create your own implementation of theme_form_element().
The offending semicolon is in $t('!title: !required', ...), and would need to be removed in both locations.

Not the easiest thing to change, but at least it's possible without hacking core!

You can try this also, works for me in drupal 7.

Drop this in the body of your version of 'page.tpl.php' in your template folder.

<?php
    drupal_add_js(
      'jQuery(document).ready(function () {
        var labels = jQuery(".field-label");
        jQuery.each(labels, function() {
          this.innerHTML = this.innerHTML.replace(":", "");
        });
      });',
      'inline');
  ?>


Ajax error while uploading or removing file through managed file I am getting following error while using managed file through my custom form.

  "An Ajax HTTP request terminated abnormally."

Also, I updated my jquery version to latest using jquery_update module. Still no any benefit.

Any idea on how to solve it?

EDIT:

Code

  $form['path_image'] = array(
    '#title' => t('Image'),
    '#type' => 'managed_file',
    '#description' => t('The uploaded image will be displayed on the page unless it is marked as "removed".'),
    '#default_value' => $current_image,
    '#upload_location' => 'public://subpage_banner/',
  );

MaxRequestLen sometimes gets lowered as a result of server/module updates. Also, adding modules that add to the request length can also introduce this problem. This is why disabling modules can sometimes "fix" the problem.

See http://drupal.org/node/1015938#comment-7412202 for a solution that involves updating your vhost file, eg:

<IfModule mod_fcgid.c>
  # 50MB
  MaxRequestLen 52430000
</IfModule>

Or try switching from FastCGI to mod_php or php-fpm (if you're using FastCGI).

It's a jquery_update issue. Check with lower version of jquery.


custom block tpl with custom module I have created a block-custom.tpl.php, the following is the code inside:

Hello World

Subject:<?php print $block->subject ?>

Content:<?php print $block->content ?>

My custom module code:

        function custom_block_info() {
          $blocks['my-block-id'] = array(
            'info' => t('Block Name'),
          );
          return $blocks;
        }

        /**
         * Implementation of hook_block_view().
         */
        function custom_block_view($delta='') {
          $block = array();
          switch ($delta) {
            case 'my-block-id':
              $block['subject'] = t('Block Name');
              $block['content'] = custom_contents();
              break;
          }
          return $block;
        }

        /**
         * custom html block
         * @return string
         */
        function custom_contents() {
          return '

              Hello World, this is a example custom Block

          ';
        }

I placed the tpl file in /module/block/ directory

I followed the tutorial of the following web page (I know it is for Drupal 6)
http://eureka.ykyuen.info/2010/11/11/drupal-customize-block-template-file/

Of course, the result is nothing, anything I am missing? How to override the block.tpl.php?

You have to put your code into an custom module. Creating Drupal 7.x modules should get you going. You should never change code of core. This will be lost (or at least causes tidious manual work) the next time you update drupal.

I think you may losing a hook:

function custom_theme(){

}


Why would single-use (harcoded) tokens not validate in the Message module, when the dynamic version does? In the Message module, why does the following dynamic token validate nicely [message:field-message-content:body] but the single-use (harcdoded) token does not @{message:field-message-content:body}

Basically changing [token] to @{token} doesn't work.

Note: I know I have to create a new message and just can't change the template on the fly to back-propagate existing messages.

For reference from the module's readme.txt:

  Tokens

  "Dynamic" tokens   When defining a message type, it is possible to use Drupal tokens in any of the   message fields, in order to inject
  certain content into the field on the fly.   E.g. Entering the string
  "[current-date:short]" to the message text will   display the current
  request time instead of the token.   E.g. [message:user:mail] will be
  replaced with the message author's username   (When displaying the
  message).   If the message has fields (e.g field_node_ref), its
  contents will accessible   by the token system as well under
  [message:field_node_ref].   (For instance:
  [message:field_node_ref:title]).   This relies on "Entity token"
  module that ships with Entity API.   Enabling "Token" module is also
  recommened, as it provides more tokens   and shows a token browser in
  the message type creation page.
  "Single use" tokens   The single-use tokens are similiar to the dynamic tokens, excepet they're   being replaced by their content as
  the message is created; Meaning this   content will not get updated if
  it's reference gets changed.   E.g. "@{message:user:name}" - Will be
  replaced by the message author's name   (When creating the message).
  You can use this for example when you know the user's name is not
  going   to change, so there is no reason for re-checking all the time
  the user   name -- hardcoding it makes more sense.

Note: There is nothing in the error logs. Essentially when I use the dynamic token, it works and if I change it to a hardcoded token, then it doesn't. Basically changing [token] to @{token} it no longer works. I know I have to create a new message and just can't change the template too.

Provided you're using Rules to send the message, i'll suggest you to manually save the message entity after having set all required fields but right before sending the message.

Single Use token are evaluated at save time.

"Single use" tokens may saved to database one time and not be changed when update relate entity,while  "Dynamic" tokens was replace when theme the message.


Zen header 'site name' + links issue I'm using a Zen sub theme, and I've placed the main menu block into the header.

I would like to place the links to the right of the site name, but they only sit underneath. I've tried playing with the CSS styles that control the menu block, without success.

Is there a special trick of Zen's quirk I'm missing?

I am new to coding so anyone should feel free to correct are add to this.

Your theme is placing the content on a page using a file called page.tpl.php. It may be found in your subtheme folder or in the parent them folder. This file is responsible for assembling the HTML code that actually displays your page.  The file is a text file and is easy to open and edit (not as easy to understand if you are not familiar with HTML and PHP.  I am using Fusion themes, so there may be some difference, but if you search for 'menu' you will find the part of the template that generates the menu.  There you will probably find a HTML command to 'clear' or a Class definition that will include the clear command.  This command is telling the browser to push further content in the region, such as your block, to the next row.  To change this you will need to make an override page.tpl.php file (copy the parent theme file into your subtheme directory and remove the command. If the command is in the CSS file, you will have to alter the CSS file containing the class definition.

I do not recommend doing this if you are not yet familiar with coding in Drupal (do a bit of research first).  Good luck.


Alter weather block behaviour? In the weather module, if a user has not configured a custom weather block, the block does not display:

/**
 * Implement hook_block_view().
 */
function weather_block_view($delta = '') {
  global $user;
  module_load_include('inc', 'weather', 'weather.common');
  $block = array();
  // Handle the 'system_NUMBER' type of blocks
  if (strpos($delta, '_') === FALSE) {
    $display_type = $delta;
  }
  else {
    list($display_type, $display_number) = explode('_', $delta);
  }
  $forecast_days = (int) variable_get('weather_forecast_days', '2');
  switch ($display_type) {
    case 'user':
      if (weather_access_userblock()) {
        // Show the user's custom weather block, if there is already
        // a place configured. Otherwise, do not show the block.
        $places = weather_get_places_in_use('user', $user->uid);
        if (!$places) {
          return;
        }
        ...
        [from weather.module]

Is there a way of displaying a 'Please set your weather location' link, instead of nothing at all, without applying a patch to the module?

Thanks.

Use the hook_block_view_MODULE_DELTA_alter in your custom module to display text if user has not configured the custom location.you can access the current user object from global $user if you want to perform any operation on it.

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function demo_wipe_block_view_weather_user_alter(&$data, $block) {
//Check here that whether user has configured or not.
  if(!is_array($data)) {
    $data['subject'] = t('Blah Blah Blah!');
    $data['content'] = t('Blah Blah Blah! link');
  }
}

P.S. : I have tested it on php 5.5.3

I think you should also specify this as a feature request in the module issue queue to set default whether location(that should be in admin configuration) on user whether block if user has not configured the block yet.

Enable PHP Filter module.
Create custom block, add on textarea "Please set your weather location" link , set title to "Weather".
Set PHP visibility for block next code:

global $user;
$places = weather_get_places_in_use('user', $user->uid);
return !$places;

Move block position to under Weather block.
So when user doesn't set Weather, he will see set location link block, otherwise, he will see Weather block. No hacks :)


Organizing common functions/classes Currently I have a common.module for storing common functions.  This file is getting way to long and I'd like to start breaking it up by similar functionality or by class:

common.inc
common.query.inc
common.taxonomy.inc
Node.php
etc...

I thought I could add files[] entries to my common.info file but this doesn't seem to source these files.

I need these files to be always sourced: on any page load, on full drupal bootstrap, and on update.php.

In your .module file add the following to the very top of the module (just after the opening <?php tag):

module_load_include('inc', 'common', 'common.query');
module_load_include('inc', 'common', 'common.taxonomy');

For your reference:

module_load_include();

EDIT

Seeing as how you're not going to be needing these on cached pages, then putting them in hook_init() is much better practice.

Like the following:

function common_init() {
  module_load_include('inc', 'common', 'common.query');
  module_load_include('inc', 'common', 'common.taxonomy');
}

You can split out class definitions into separate files and then use files[] to cache those class definitions. That's what files[] does.

On top of that you could have a common.module file that minimally implements hook_help(), and would require_once() all the files you want. This is of course not the best way to go; consumers should require_once() the files on their own, for only the files they need.

Also if you're trying to use an external library, you might consider taking a look at the Libraries module.

EDIT: Uh, didn't see that it was tagged 6. :-) Drupal 6 doesn't support files[] in the .info file at all.


Views module doesn't call hook_node_view() when set to display fields I use Drupal 7 with Views and want to override some node field output in a view (namely change its Title to something I want). To accomplish that I set the view to display Fields and not Context or Rendered Entity and select Title and Body from the list of fields. And here is where the problem lies:

I have a (homemade) module that makes use of hook_node_view() hook to modify Body and Teaser text. When I display article body as a Field in the Views this hook for some strange reason is not called (on Context and Rendered Entity all works correctly). So I need a way to either:

override Title output while NOT setting my view to display Fields, or
find a way to call hook_node_view() while setting my view to display Fields.

Is there a way to do it?

Upd: provided a screenshot showing that hook_node_view() is not called on teaser when setting Show to Fields (left pane) but called when setting Show to Content (right pane):

screenshot showing that hook_node_view is called on teaser when setting Show to Content and is not called when setting Show to Fields http://ari-linn.nightmail.ru/views_and_hook_node_view.jpg

Upd 2: Okay, I did some Drupal colonoscopy and it even works though I can't say whether it is the right way to do things (probably not). I found out that when you render context Drupal apparently thinks you want to render a normal node but when you render fields Drupal is at a loss and doesn't think you're dealing with nodes anymore. Thus it doesn't fire any node hooks including hook_node_view(). If anyone still needs to run their functionality of hook_node_view($node, $view_mode, $langcode) they can use hook_views_pre_render(&$view) though access to node $view_mode and $langcode will be gone.

In case people out there are interested how I override node titles in taxonomy views, here is the scenario. My task was to override node Title with the value of another field, SortKey, and do it only in taxonomy views. I'm happy with "Britney Spears" node title at the main page but when it comes to taxonomy I want her to display "Spears, Britney".

I personally thought it to be tiresome and bothersome to deal with fields (they mess up all my CSS) and found a hack in Views 7.x-3.3: if you set Show parameter in your view to Fields and select Material:Rendered Material AND any other field (you can exclude it from display, just make sure Rendered Material is not the only field you load) you'll get a neat and tidy Node object at $view->result->_field_data. I fail to explain how it is so but it's there, and you can bend it to your needs, and what is even better Drupal will think you're rendering a node and fire all node hooks on it. I pray though that Views coders won't remove this wonderful hack in later versions ruining my code.

Here is the code:

/*
* Changes MYARTICLETYPE title to sortkey on taxonomy views pre-render
*/
function MYMODULE_views_pre_render(&$view)
{
    if($view->name == 'taxonomy_term')
    {
        foreach($view->result as $i => $value)
        {
            $node = &$value->_field_data['nid']['entity']; //it's a real node, yes.
            if($node->type == 'MYARTICLETYPE') //override titles only for this type
            {
                $node->title = $node->field_sort_key['und'][0]['value'];
            }
        }
    }
}

The title of your question is.

  Views module doesn't call hook_node_view() when set to display fields

That is working as intended. The reason is that it's not a node that's being rendered, but just a bunch of fields and attributes that belong to a node that is being rendered.

One way of fixing hook_node_view not being called, would be to actually render the nodes.

If the problem is that the field is not rendered as you which, the best way of dealing with that, would be to alter the rendering of the fields, instead of trying to make Drupal act like you're rendering a node when in fact you're not.

The easiest, cleanest and most flexible way to do that, would be to create some custom field formatters for the fields in question. Field formatters are like theme functions for the fields, and you can in views select which field formatter to use when you want to render a field. It requires some work, but gives great flexibility. That would make your hook_node_view obsolete as you can use field formatters when fields are rendered under the manage display tab in the field settings interface.

in view you can overide field output (settings from view) and  to call hook_node_view you have to display teaser of full content or any other display of the node

to override the field you can check this image


Where can we store 3rd party application passwords? I've written a Drupal 8 custom module that communicates with 3rd party APIs which need authentication. I have an application username and password for those APIs which I need to store somewhere. I can think of the following two ways to achieve that.

I can store the credentials in the Drupal database as configuration. But the password then becomes visible in plain text to all the site admins, and we don't want all the site admins to see the password (I also am aware that we can set up roles and permissions, so we can disable access to a particular configuration for all the site admins, but still the password is saved in plain text in the database).
I can also store the credentials in the settings.php file.

Is there any other way we can store these credentials? What is the best, secure and preferred way to store 3rd party account credentials in Drupal 8?

Yes, if you're looking for a Drupal-centric solution, the Key module might provide what you're looking for. It supports pulling your stored secrets from a few different locations:

Config
File
Environment Variable
3rd party services

As far a best, there's really no one-size-fits-all answer. It depends on your data storage requirements and what you're protecting (e.g. an API key for a medical records REST API should have heavy restrictions whereas a Slack webhook is pretty low risk).

If you're wanting a scalable solution, you might want to consider one of the many 3rd party services that provide secret management.

What about creating a specific permission 'view users password' and give it only to specified user's role 'super admin'? And disable this permission for basic 'administrator' role?

Then your users may store 3rd party app passwords in specified fields and your admins won't see it.


Drupal 7 and PageSpeed The Apache module PageSpeed provides various optimizations for HTML, JavaScript and such, which is great.

However, some of its features are redundant with Drupal's own aggregation and optimization methods. So has anyone tested which filters would be useful for a typical Drupal 7 website and which would be useless due to Drupal already providing support for it?

This is the PageSpeed section from my .htaccess:

<IfModule pagespeed_module>
    ModPagespeed on
    ModPagespeedEnableFilters extend_cache
    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters combine_css
    ModPagespeedEnableFilters move_css_to_head
    ModPagespeedEnableFilters remove_comments
    ModPagespeedEnableFilters inline_css
    ModPagespeedEnableFilters rewrite_javascript
    ModPagespeedEnableFilters insert_img_dimensions
    ModPagespeedEnableFilters rewrite_images
    ModPagespeedEnableFilters rewrite_css
</IfModule>

Whilst there is a little overlap with the js and css compression, I'm not seeing any negative results. I've set Drupal 7 to aggregate and compress CSS and JS.

The site isn't particularly high traffic though.

Here is my htaccess setup:

# -----------------------------------------------------------------------
# Enable keep-alive for faster pagespeed:
# -----------------------------------------------------------------------
<ifModule mod_headers.c>
    Header set Connection keep-alive
</ifModule>

# -----------------------------------------------------------------------
# Expire caching
# -----------------------------------------------------------------------
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType application/x-font-woff "access plus 1 year"
    ExpiresByType application/x-font-woff2 "access plus 1 year"
    ExpiresByType application/x-font-ttf  "access plus 1 year"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresDefault "access plus 2 days"
</IfModule>

# -----------------------------------------------------------------------
# Cache Headers
# -----------------------------------------------------------------------
<ifmodule mod_headers.c>
  # Cache specified files for 31 days
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  # Cache HTML files for a couple hours
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  # Cache PDFs for a day
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  # Cache Javascripts for 31 days
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</ifmodule>

# -----------------------------------------------------------------------
# Defining MIME types to ensure the web server actually knows about them.
# -----------------------------------------------------------------------
<IfModule mod_mime.c>
    AddType text/css .css
    AddType application/javascript .js
    AddType application/x-javascript .js
    AddType text/html .html .htm
    AddType text/richtext .rtf .rtx
    AddType image/svg+xml .svg .svgz
    AddType text/plain .txt
    AddType text/xsd .xsd
    AddType text/xsl .xsl
    AddType text/xml .xml
    AddType video/asf .asf .asx .wax .wmv .wmx
    AddType video/avi .avi
    AddType image/bmp .bmp
    AddType application/java .class
    AddType video/divx .divx
    AddType application/msword .doc .docx
    AddType application/x-msdownload .exe
    AddType image/gif .gif
    AddType application/x-gzip .gz .gzip
    AddType image/x-icon .ico
    AddType image/jpeg .jpg .jpeg .jpe
    AddType application/vnd.ms-access .mdb
    AddType audio/midi .mid .midi
    AddType video/quicktime .mov .qt
    AddType audio/mpeg .mp3 .m4a
    AddType video/mp4 .mp4 .m4v
    AddType video/mpeg .mpeg .mpg .mpe
    AddType application/vnd.ms-project .mpp
    AddType application/vnd.oasis.opendocument.database .odb
    AddType application/vnd.oasis.opendocument.chart .odc
    AddType application/vnd.oasis.opendocument.formula .odf
    AddType application/vnd.oasis.opendocument.graphics .odg
    AddType application/vnd.oasis.opendocument.presentation .odp
    AddType application/vnd.oasis.opendocument.spreadsheet .ods
    AddType application/vnd.oasis.opendocument.text .odt
    AddType audio/ogg .ogg
    AddType application/pdf .pdf
    AddType image/png .png
    AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx
    AddType audio/x-realaudio .ra .ram
    AddType application/x-shockwave-flash .swf
    AddType application/x-tar .tar
    AddType image/tiff .tif .tiff
    AddType audio/wav .wav
    AddType audio/wma .wma
    AddType application/vnd.ms-write .wri
    AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw
    AddType application/zip .zip
    AddEncoding gzip svgz
    #AddEncoding gzip js
    #AddEncoding gzip  css
</Ifmodule>

# -----------------------------------------------------------------------
# Compressing output.
# -----------------------------------------------------------------------
<IfModule mod_deflate.c>
    # Enable compression
    SetOutputFilter DEFLATE

    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|png|jpg|jpeg)$ no-gzip dont-vary
    Header append Vary User-Agent env=!dont-vary
</IfModule>

# -----------------------------------------------------------------------
#  PageSpeed. - TESTED with Mediacenter
# -----------------------------------------------------------------------
<IfModule pagespeed_module>

    # Turn on mod_pagespeed. To completely disable mod_pagespeed, you
    # can set this to "off".
    ModPagespeed on

    # Direct Apache to send all HTML output to the mod_pagespeed
    # output handler.
    AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html

    ModPagespeedLowercaseHtmlNames on
    ModPagespeedEnableFilters extend_cache
    ModPagespeedEnableFilters insert_dns_prefetch
    ModPagespeedEnableFilters add_head
    ModPagespeedEnableFilters add_instrumentation
    ModPagespeedEnableFilters make_google_analytics_async
    #ModPagespeedEnableFilters make_show_ads_async
    ModPagespeedEnableFilters flatten_css_imports

#
# Text / HTML
#

    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters convert_meta_tags
    ModPagespeedEnableFilters remove_comments
    ModPagespeedEnableFilters collapse_whitespace
    ModPagespeedEnableFilters elide_attributes
    ModPagespeedEnableFilters trim_urls
    ModPagespeedEnableFilters pedantic

#
# JavaScript
#

    ModPagespeedEnableFilters combine_javascript
    #ModPagespeedEnableFilters canonicalize_javascript_libraries
    ModPagespeedEnableFilters rewrite_javascript
    ModPagespeedEnableFilters defer_javascript
    ModPagespeedEnableFilters inline_javascript

#
# CSS
#

    ModPagespeedEnableFilters rewrite_css
    ModPagespeedEnableFilters combine_css
    ModPagespeedEnableFilters move_css_to_head
    ModPagespeedEnableFilters inline_css
    ModPagespeedEnableFilters inline_import_to_link
    ModPagespeedEnableFilters move_css_above_scripts

#
# Images
#

    ModPagespeedEnableFilters inline_preview_images
    ModPagespeedEnableFilters insert_img_dimensions
    ModPagespeedEnableFilters rewrite_images
    ModPagespeedEnableFilters convert_gif_to_png
    ModPagespeedEnableFilters recompress_images
    ModPagespeedEnableFilters recompress_jpeg
    ModPagespeedEnableFilters recompress_png
    ModPagespeedEnableFilters convert_jpeg_to_progressive
    ModPagespeedEnableFilters resize_mobile_images
    ModPagespeedEnableFilters sprite_images
    ModPagespeedEnableFilters lazyload_images
    ModPagespeedEnableFilters local_storage_cache
    ModPagespeedJpegRecompressionQuality 100
    #ModPagespeedEnableFilters responsive_images
    ModPagespeedEnableFilters resize_images

    # Disallow problematic files:
    #ModPagespeedDisallow "*/respond.js"
    #ModPagespeedDisallow "*/lightbox.js*"

</IfModule>