Multi-site with two sites sharing the same domain? There is absolutely no problem to have multi sites, where:

domain1.com points to site A
domain2.com points to site B

But I want to have multi-site setup, where:

domain1.com points to site A
domain1.com/blabla points to site B

I was doing everything to solve it, for example using directory structure like that:

domain1.com
domain1.com.blabla

or using file sites.php with content:

$sites = array(
'domain1.com' => 'domain1.com',
'domain1.com' => 'domain1.com.blabla',
);

Nothing works, site 'domain1.com' takes all traffic.

FYI:

I'm using nginx.
I'm using Drupal 7.
I do not want to use the module Domain as I want to have separated databases.

Please help!

I have done this before. Given a generic location / { ... } entry for Nginx which serves domain1.com to make the subdirectory install work I did the following 2 steps. I am not aware of a solution that doesn't involve making a symlink.

Step 1:

In your Nginx configuration:

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            index index.php;
            try_files $uri $uri/ @rewrite;
            expires max;
            # Uncomment to enable naxsi on this location
            # include /etc/nginx/naxsi.rules
    }

    location /blabla {
     try_files $uri $uri/ /blabla/index.php?$args;
    }
    location ~ /blabla/.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
            webuser /usr/share/nginx/html;
    }

Step 2:

Then wherever your docroot is for your site you add an alias with your subfolder name to the main docroot, allowing the path to be valid for Drupal:

$ pwd
/usr/share/nginx/html

user@localhost:/usr/share/nginx/html$ find . -type l -ls
41059    0 lrwxrwxrwx   1 webuser    webuser           21 Sep 25 01:58 ./blabla -> /usr/share/nginx/html

You will still need your sites.php configuration as you have listed. You will need to restart Nginx.


Dynamic theme CSS editing for designer? I am working on a theme with a designer.

A Drupal theme typically stores a style.css on file system which can be access via SFTP, which may not be an easy interface for a designer.

Is it possible to provide a editable theme CSS for designer (something like editing style.css in Wordpress)?

You can try CSS Injector.

Project page says:

  Allows administrators to inject CSS into the page output based on
  configurable rules. It's useful for adding simple CSS tweaks without
  modifying a site's official theme -- for example, a 'nighttime' color
  scheme could be added during certain hours. The CSS is added using
  Drupal's standard drupal_add_css() function and respects page caching,
  etc.


Commerce Import From Ubercart Sales Tax Does anyone have any examples of importing Sales Tax data from Ubercart 2 into Drupal Commerce?

The two systems seem to use -very- different schemas (Ubercart uses separate line items and Commerce attaches tax to the product/line item. I looked at the commerce_migrate_ubercart module and it doesn't even try to handle this.

The problem is that we have historical data where rates have changed over time so it's not accurate to simply recalculate based on current rates.

We could live with simply being able to override the tax on the entire order, but I can't find a hook to override that in the commerce_orders table.

Edit: I could use commerce_tax_rate_apply('state_sales_tax',  $line_item);

     $tax_price = commerce_tax_rate_apply('state_sales_tax',  $line_item);
    // <--- Now what? I don't understand how to apply $tax_price back to the original line item before saving.

     // Save the line item to get its ID.
     commerce_line_item_save($line_item);

Or: After saving the line item, how do I hook into the standard Rules for tax calculation? (Which work fine for new orders.)

The best solution here is a "dumb" migration, one that simply retains the data model of the prior system without trying to shoe horn it into the data model of the new. The reason I changed the tax data model from Ubercart to Commerce is because taxes are actually necessarily tied to the products and services that are being taxes. When we had all taxes added up and stored in a single line item, it's then impossible to do things like refund the taxes collected for one particular product on an order if it's returned. You also cannot generate a very meaningful tax report, though nowadays I'd look to third party systems to do that anyways.

You're going to need to define your own line item type via hook_commerce_line_item_type_info() and then setup your migration to create the line item on migration. I'd call it "Ubercart tax record" or something similar. New taxes going forward should actually become part of the relevant line items when they're calculated.

When you create these tax line items, make sure that you both set the unit price amount / currency code values and update the unit price's components array to match. Look to commerce_product_line_item_populate() around line 1376 where you see the comment about adding the base price to the components array. In your case, you wouldn't use the 'base_price' price component for taxes - you'd either want to define a generic price component type via hook_commerce_price_component_type_info() or if you know the types of the taxes map to price components for tax rates you've defined on the new site, you can use those.


Loading a form from a form include file in a module I have an external form that needs to be loaded inside a template file, used by a block. Right now, i'm a bit confused as to how to load this .inc. Looking at the API docs point to module_load_include() which I've tried with no luck (see example 1, from the template file):

module_load_include('inc', 'example2');
print(render(drupal_get_form("example2_form"))); //Form method in inc file is called "example2_form();

The actual form method is just a few settings for now, once I prove this works...

function example2_form($form, $form_state) {
  $form['fname'] = array(
    '#type' => 'textfield',
    "#attributes" => array(
      'placeholder' => t("First Name"),
    ),
  );

  $form['#validate'][] = "example2_form_validate";
  $form['#submit'][] = "example2_form_submit";

  return $form;
}

I figure the cleanest approach (besides figuring out what could cause the .inc to not load here) is to just drop the form code into the .module, and load the Form array in the blocks hook_block_view(). However, I like to keep stuff clean, so if there's something I'm overlooking here, or how to best do this, it would be cool to know.

File name for the form include is example2.form.inc.

Module_load_include includes the file with extension and filename. Sinds your file is called example2.form.inc and you include the file example2.inc, it doesn't work.

You should be using

Module_load_include('inc', 'example2.form');


Wysiwyg Permissions for Anonymous Users I've installed WYSIWYG for my site editors, but it's also showing up in the comments field box. I don't want my anonymous users to be able to leave comments with the WYSIWYG (but I do want them to comment, with restrictions of course).

I tried looking in People > Permissions and found nothing. I looked through the settings also in Config > WYSIWYG and finally Modules > WYSIWYG.

Anyone know of a way to edit the WYSIWYG permissions?

Sage, edit the content type, go on the COMMENTS FIELDS tab, then click on edit on comment_body.
Make sure you set 'Text processing'  to PLAIN TEXT


how can I hide ShareThis icons from teasers I installed the ShareThis module which works great for me, except I would like to hide the share icons from appearing in teasers. How can I do this?

Thanks

Go to content type's manage display section and select Teaser tab on top right. There you can change the display settings of the teaser.


How to override jQuery from contrib module It's from editable fields that I want to override jQuery from. I tried to simply copy the function in question into my scripts.js and make it work but it obviously doesn't.

I'm sure my custom js file loads because I'm already using other code in it. Now, I just put a console.log statement in the beginning of my copied function that is supposed to fire at every .blur(); but nothing's coming out.

I also checked that my custom js code got loaded after the editable fields code (In case I sound stupid: I don't know how far drupal takes care of it to do this by default.)

this is the function - originally from editablefields - that I would like to override

    (function ($) {
Drupal.behaviors.editablefields_submit = {
console.log('override check');
attach: function (context) {
    $('.editablefield-item').once('editablefield', function() {
      var $this = $(this);

      // There is only one editable field in that form, we can hide the submit
      // button.
      if ($this.find('input[type=text],textarea,select').length == 1) {
        $this.find('input.form-submit').hide();
        $this.find('input[type=text],textarea,select').change(function() {
            console.log('this out of override= ' + $this);
          $this.find('input.form-submit').triggerHandler('click');

        });
      }
    });
  }
};

To override the JavaScript file added to a page from a module, you need to implement hook_js_alter(). The example code shown for hook_js_alter() is the code used by the jQuery Update module uses to change the jQuery library used from Drupal.

  // Swap out jQuery to use an updated version of the library.
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';

In your case, if mymodule.module is the module that needs to change the JavaScript file, and the file added is script.js, then the following code can be used to achieve your task.

function mymodule_js_alter(&$javascript) {
  $javascript[drupal_get_path('module', 'editablefields') . '/editablefields.js']['data'] = drupal_get_path('module', 'mymodule') . '/script.js';
}

The same code works for a theme too. The difference is that instead of using drupal_get_path('module', 'mymodule'), the code should use path_to_theme(). *

Using hook_js_alter() would work also for JavaScript settings added by Drupal, external JavaScript files, and inline JavaScript code. What changes is how the array is structured in those cases.

* I didn't test the code I am suggesting to use for a theme.


How to add a css class to sidebar first render I am new to drupal theme development . I am customizing a sub theme of zen and wants to change the background of sidebar-first. So I want to know where this sidebar_first render array is defined and how can I add the CSS class to whole sidebar-first also to the nodes within the sidebar_first render array ?

I tried within my templates template.php :

function zensub_page_alter(&$page) {
 $page['sidebar_first'] = array(
 '#attributes' => array('class' => 'page-columns')
 );
}

But this causes the sidebar-first remove !

Create a template file with name region--sidebar-first.tpl.php in side the your theme template folder. Copy below code to inside the newly created template file

<?php if ($content): ?>
     <div class="my_class <?php print $classes; ?>">
       <?php print $content; ?>
     </div>
  <?php endif; ?>

replace my_class with you desire class name, clear the drupal cache. It will wrap a new class on the sidebar first region. Good luck


How to load a menu item and its children menu items? I have the menu item id. I want to display that menu item with its children.

Suppose for example I have menu item test and it has two children menu items. So I want to load them and display it as

test
  test1
  test2

I tried to load the menu item with the following code.

$menu_content = current(\Drupal::entityManager()->getStorage('menu_link_content')->loadByProperties(array('id' => 1)));

But I am unable to get the children from the variable. Can someone help me here?

Try these:

// Select the parent menu link with 49 id.
$menu_link_content_id = 49;
// Use the 'menu_link_content' entity storage.
$menu_content_storage = \Drupal::entityTypeManager()->getStorage('menu_link_content');
/** @var \Drupal\menu_link_content\MenuLinkContentInterface $menu_link_content */
// Fetch an entity with parent menu link.
$menu_link_content = current($menu_content_storage->loadByProperties(['id' => $menu_link_content_id]));
// Build a specific value for a parent property.
$parent_prop = "menu_link_content:{$menu_link_content->uuid()}";
// Load child menu items by 'parent' property.
$menu_link_content_childs = $menu_content_storage->loadByProperties(['parent' => $parent_prop]);


how to update the order total in checkout page? I'm calculating discount amount base on total order amount. how can I show the discount amount like something what coupon module has done? (see the picture)

what is the correct way to update the total order amount? I mean how should I subtract the discount amount from the order total so if any products has been removed or added it always works correctly??

You need to use hook_form_alter().

First, for integrity purposes, write a validator that will ensure all amounts are correct, and if not - update them & show form to user again.

Second - use AJAX. Drupal allows only for one callback, so your new one will have to take care of calling the original one in the first place, and you may have some problems if you will need to replace more than one form element, but it can be done.


Views contextual filter if field value is X then show this in views page Y I have content type Ads.
I have multiple views pages.
I have Views which shows this content type Ads as a view block. Views has multiple block displays, each display for each views pages.

Admin need to choose when adding new node Ads where he want this ad to be shown. He need to choose it from the list. List has for example values X, C, Z

In the Views which shows these Ads as a view block. How to configure contextual filter to check field value? Contextual filter should be set on PHP code - but how to code it?

For example:

If field value is X -> show this view block on the path: categories/x (which is Views page, not node!)

** Solution **

I found my own solution to do something like this.

Added custom manual list field type (field_category). For example: X, Y and C
Add view block for each ad category and set filter field_category for each category. (field category = X)
Then in admin/block edit view block: Show block visibility, set PHP format and added this code:

<?php
if (arg(0) == 'products' && arg(1) == 'categoryX') {
return TRUE; }
else { return FALSE; }
?>

As my views pages path are: products/categoryX.

This sounds like a job for Page Manager (part of C-Tools).
Create variants that activate on content type AND field value.


Drupal 7 field for expandable list I'm looking for a module that provides a D7 field type that's an expandable list: a list where new values can be added at run-time. Is there a module for that?

Ended up using a taxonomy term reference with a tag widget.


How to keep labels displayed for all facet filters I have Search API with Facets API set up.  For my checkbox selections, how can I prevent the facets from hiding when they aren't available?  I want all of the facets to be listed, even if not available.

I can't seem to find an easy way to do this.

EDIT: I may have incorrectly used the term "facets" here. I mean to say filter options.  So, if blue, red, and green are options, but the only available results are blue, I still want red and green to display as check boxes.

Try to set this option

on facet settings form.


Custom node Template for script tags I wanted to add script code to implement "LiveChat" functionality on just three pages of our website. So, I wanted to add one script code given by our LiveChat agency into three webpages of our website.

Script Code

So, I have created three separate html node templates based on their node ID.

Theses three custom node templates are under

/sites/all/themes/mytheme/templates along with (node.tpl.php and html.tpl.php)

(contact page) html--node--28.tpl.php

Url of this page: www.example.com/contact

(admissions page) html--node--1212.tpl.php

Url of this page: www.example.com/admissions

(market page) html--node--378.tpl.php

Url of this page: www.example.com/market

Code used in all custom node templates (html--node--28.tpl.php, html--node--1212.tpl.php, html--node--378.tpl.php) is the same:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>
<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>

<body<?php print $attributes;?>>
<?php print $scripts; ?>
//Adding script for LiveChat

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

But, I am not able to see my script () when I debugged it in view pagesource.

Thanks!

Instead of adding three template files for three nodes with the same content in it in my opinion will be a better solution to add the JS file conditionally using drupal_add_js

For eg:

 $allowed_nid = array(28, 1212, 38);
 if(in_array(arg(1), $allowed_nid)){
  drupal_add_js("http://www.examp.com/scripts/invitation.ashx?company=4444", "external");
 }

You can add the snippet in a hook_init function in any of your custom modules. (Best is add in a custom utility module which hold all general function to be used throughout.)
Else you can add it in your theme's template.php in the template_preprocess_page function.


How to get the operation Links in my own EntityListBuilder I use the Symfony framework the first time and goes through several tutorials to create an own entity type. https://www.daggerhart.com/drupal-8-custom-entities-bundles/ or https://www.daggerhart.com/drupal-8-custom-entities-bundles/

Now runs all very well, but I didn`t get the operation links(edit/delete) in every row for the saved content. There is only a devel link. If I moved directly to the content like www.exapmle/mytest/{id}/edit or www.exapmle/mytest/{id}/delete I can saw the content, edit the content, delete the content and the tabs are shown. So I think I have the permission for that.

Any ideas?

mytest.routing.yml:

entity.mytest.delete_test:
  path: '/tested/{mytest}/delete'
  defaults:
    _entity_form: mytest.delete
    _title: 'Delete Test'
  requirements:
    _entity_access: 'mytest.delete'

mytest.php in src/Entity

* @ContentEntityType(
*   id = "mytest",
*   links = {
*     "canonical" = "/tested/{mytest}",
*     "delete-shop" = "/tested/{mytest}/delete",
*     "collection" = "/tested"
*   },
* )

Ok, after I found the documentation at drupal documentation I get it! The naming of the link list must be:

* @ContentEntityType(
*   id = "mytest",
*   links = {
*     "canonical" = "/tested/{mytest}",
*     "delete-form" = "/tested/{mytest}/delete", // EDIT!
*     "collection" = "/tested"
*   },
* )

That's all!


validate a base field in a particular content type Since title field is considered as base field  in Drupal 8, I opted hook_entity_base_field_info_alter to add validation to it. But when I look at that hook.

hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type)

It doesn't holds a $bundle argument. So I couldn't add a validation for title field of a particular node type. How can I override it to be node type specific?

Base fields are by definition not bundle specific, you can't add something for a specific bundle in that hook.

However, what you can do is save it as a base field override. See how NodeTypeForm::save saves different default values and labels for base fields as base field overrides.


How do you add a nodequeue to an existing view on the front page? I'm confused on how to get a nodequeue to appear on the front page?

I took over an existing Drupal website with Views and Nodequeue installed.

I created the nodequeue I want to add to the front page view as well as the nodes to include in the queue.
I duplicated the "relationship" and "sort"/ "filter" settings from the views that are already on the homepage.
This nodequeue I created looks fine when I preview it..

How do I actually assign the nodequeue to display on the front page like the others? I can't figure it out for the life of me.

OPTION 1

Edit your Nodequeue view and click on +Add button and select Attachment.

Now go to your front page view and in the FOOTER add Global: View area and select your attachment.

OPTION 2

In blocks, place the Nodequeue view block on a region and configure the block, for Visivility Settings select only listed pages and put <front>


Superfish menu - Responsive problems I am building my site using drupal 7 and adaptivetheme.

Before I used superfish module, my main menu was very responsive and works great across all sizes.

Now, I started to use superfish (latest version) for the dropdown in my horizontal main menu, and the menu is not responsive. when I am resizing the window, the right tab of the menu is moving below the menu, instead of the text will get smaller.
but, If I resize just a little more it  looks like the text is getting smaller for less then a seconed, and than all the horizontal menu (6 tabs) become one dropdown with all the tabs inside.
I know that in a very small screen the menu is collapsing to one drop down, but why does it happen in a size of landscape tablet (and even a little bigger)?

How can I make my superfish main menu responsive, and become smaller (like the rest of the site) when the window size is getting smaller?

Get into your Superfish menu block (find from the block admin page: /admin/structure/block usually the specific address is: /admin/structure/block/manage/superfish/1/configure.

There under "Superfish plugins" -> "sf-smallscreen" -> "window width settings" and change the breakpoint value; make it smaller (default is 768 pixels).


Private Files and corrupted files Hello fellow Drupal expert,

I'm in search of wisdom. Some said i can find it in here :)

Okay so here's my issue. We got an intranet and we'd like to have some privacy (if you know what i mean). We're using IMCE and a module called private_file_download_permission (so we can map our existing roles to folders). But nothing is working, we can set private folders (and control their access) but every file we upload (through IMCE)is being corrupted.

Let me explain cause i've found some interesting things. First, if i download my file through FTP it work well. But if i go through the website it is corrupted. So I looked around and find that when i open my file with a text editor there's 2 empty lines added to it and if i delete them the file goes back to normal. But remember this happen only when the file is put on a private folder (works fine on public ones).

Have you some idea of what kind of sorcery is going on ?

Sorry for my english, and thank you for your answer;
Rémi

Ok my colleague found the solution !!

There was 2 lines added at the start of our settings.php :

This thing added lines at our downloaded files and corrupted them  !!

Ok so thank you for your time :)


Allow users to create video playlists I have created a content type called "Video" and I was wondering if I should create another content type called "Video Playlist" that act as a container for storing a collection of the nodes that are of content type "Video"?

Each user will have a list of favorites that will be public to everyone and all the other playlists would be optionally public or private only to that user. How would you go about creating this structure/layout? Is this the best approach?

You can use Flag Module with drupal views to create your playlist. Flag module allows you to bookmark contents, comments etc. Then you can display the flagged content by adding flag:content relationship in your view.


Get domain logo in views (using Domain Access module) I'm using Domain Access module and I have different logo for each domain. I have setup logo for each domain in domain theme settings.

I have view which lists all the domains (over relationship with user profiles, because each user has it's own domain), but I'm not able to display the logos for each domain.

Is it possible to get the domain logo in views?

I don't think you can do that with views only. You'll need to do some coding.
The point is that your logos are not linked to your Domains, but to your themes.

So you need to get your theme based on the domain_id, and then print the logo of the theme.

[EDIT]

If you look at the api of theme_get_setting, then you can see that you can pass as a second parameter the name of the theme you want the logo.
So it should be something like:

$MY_THEME_ID = domain_theme_lookup($MY_DOMAIN_ID);
$logo = theme_get_setting("logo", $MY_THEME_ID);


How to preprocess view field? I have view with one date field. Now I want to preprocess this date field(lets say I want to change the date format).

Twig file override : views-view-field--field_date.html.twig

Prepocess code I have tried but kint is showing me only DEPTH TOO GREAT value.

function my_sub_theme_preprocess_views_view_field__field_date(&$variables) {
    kint($variables['view']);
}

Please let me know how to preprocess this field. Is it possible to change date format in twig itself?

The output of views field templates is flat markup. You can't change a render array like you can in field templates when rendering entities in view modes.

So if you want to change the output you have to start from scratch with the values that are in the database. In views field templates you can use the getValue() method from the field variable. As parameter you have to provide row:

{{ field.value(row) }}

The result is a single value or an array for multivalue fields.

Example

views-view-field--created.html.twig

The raw value from created is a unix timestamp

Timestamp: {{ field.value(row) }}

You can use the timestamp for example to reformat the date with the date filter from twig:

Date: {{ field.value(row)|date("m/d/Y") }}


Chage View title with taxonomy term I have a Taxonomy Vocabulary as People. In it there are two terms Board and Staff.
I've created a view with two displays, to display the people content with respect to taxonomy terms. The view title is Board Members.

When I access the  board page http://example.com/people/board the title is Board Members.
When I access the  Staff page http://example.com/people/staff the title is Board Members too.

I want to change the staff display title to be like Staff Members? How to change it?

I've filtered by using Contextual filters.

In the contextual filters click on override title and set it to %1
Specify validation criteria to taxonomy term and select the vocabulary
Leave the views title empty.

This will set the present's term's title as the view's title.

If need you can add "text" %1 to display the text appended to the term's name.


Unable to transfer php logic from node--post-esl-material.tpl.php to template.php If I use the following code in template.php and print $link in node--post-esl-material.tpl.php, everything works fine; I get "hey baby."

function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $vars['link'] ='hey baby';
   }
}

However, if I use the following code and print $link in node--post-esl-material.tpl.php, it doesn't print anything.

function eslmooc_preprocess_node(&$vars, $hook) {
   if ($vars['type'] == 'post_esl_material'){
      $xyz = '';
      if (empty($content['field_link']))
         $xyz .= '';
      else {
         $xyz .= '
';
          $xyz .= '
LINK
';
           $xyz .= '
';
            $xyz .= $content['field_link'];
           $xyz .= '
';
         $xyz .= '
';
      }
      $vars['link'] = $xyz;
   }
}

I cannot get the PHP logic to work. Can anyone see a mistake within the code?

I think that the problem is that $content is not defined there. You have it only inside the template file but not in the preprocess hook.


Can I target a specific node type in page.tpl.php I just created a template page--article.tpl.php to apply ton nodes of the [article] type. It works when declared in the template.php file.
My problem is that there is a very slight change compared to the generic page.tpl.php, nothing worth having another file.

I was wondering if I could place the adde part between a condition, just as I could do with if $is_front
Something like:

<?php if ($node->type == 'article')
  // render my thingees
?>

I would be glad if someone could tell me.

--- Edit, to answer Kiwimind ---

I did the test with the 'page' content type, so I didn't have to skip my page--article.tpl.php file. I checked that 'page' was the actual machine name and 'nature' is my theme's actual name, it works on other functions.
I wrote in template.php

/**
 * Détection du type de contenu pour affecter le template page
 * https://drupal.stackexchange.com/questions/264550/can-i-target-a-specific-node-type-in-page-tpl-php
 */

function nature_preprocess_page(&$variables, $hook) {
  $variables['is_page'] = false;
  if (isset($variables['node']) && $variables['node']->type == 'page') {
    $variables['is_page'] = true;
  }
}

Then in page.tpl.php

<?php if ($is_page) : ?>

This is a “page” content

<?php endif; ?>

Nothing more, nothing less. Do you see any missing (or unnecessary) character, that could trigger a parse error? For I still get a whole blank page when clearing the cache.

As shown on Variable to check if the page is of some other Content Type, you can drop into template.php something like the following:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['print_extra_header'] = false;
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['print_extra_header'] = true;
  }
}

then in your template, add in

<?php if ($print_extra_header) : ?>
THIS GETS PRINTED
 <?php endif; ?>

So effectively you're checking on the node type in a preprocess page, to pass a custom variable to the template for you to act on.


Passing variables from modulefunction to theme I have a custom theme and a custom module. The module shows users. Every user has its specific image (that can be uploaded, changed). The location/name of this file is in the database.

I have an template with specific layout for that page: page--uspage.tpl.php
In this page, I need the location from the database when I access uspage.

$items['uspages'] = array(
    'title' => 'User pages', //page title
    'description' => 'User pages',
    'page callback' => 'show_uspages'
);

$items['uspage/%'] = array(
    'title' => 'User page',
    'description' => 'User page detail',
    'page callback' => 'show_uspage',
    'page arguments' => array(1),
    'access callback' => TRUE,
     'type' => MENU_CALLBACK,
);

I have a lot of other pages that doesn't need that. So I can't use preprocess_page.

What's the easiest and best way to pass an array with the backgroundinformation from the function show_uspage to page--uspage.tpl.php ?

Short but painfully: there is no way to achieve that. The page.tpl expects that your part of the code is a renderable array or HTML output fully generated in your page callback show_uspage(). Your part of the code is injected into the $variables of hook_preprocess_page() where ever the content block is placed in region settings for your theme. Your page callbacks really just handles the part of the output where the content block is placed. You can not store any data from your page callback for later use in theme layer or send the data by any mean to the page preprocess function or any other theming function for the page.tpl.

The only way would be to use hook_preprocess_page() and to add any data here again. You must use this hook even when you add data just for a specific page - you just need to assure to do that in this case and not on every page. Maybe by checking on which path the user is (like if(current_path == 'uspages')).

Another way would be to store the data in session in re-use it in hook_preprocess_page.


Entity Reference + View + security I have this scenario in DRUPAL 7

A content type named "Students" with a field "Legal guardian" that references to a User (her/his legal guardian).

A content type named "Reports" with a field "Student" that references to a Student.

With these reports I can do a view with 2 contextual filters (student id/date) to display a chart with the data provided from an specific report (using google chart tools).

All works like a charm, the problem is about the security because the url can be altered by anybody and get info for any student.

With Rules I can control:

A student is visible if you are the legal guardian (or if you are an admin)
A report is visible if you are an admin. I don't know how to control the legal guardian (in Students) of the Student field specified in this content type. But anyway, cos this information is used only to generate the charts, I don't really mind.

The problem is, as you can guess, that I need to control the access to the view. Only users that are legal guardian of student specified in that report can access the information.

All that comes into my mind is to set some rules to change the owner of the contents (Student, Reports) to the legal guardian's user and control the permissions, but maybe isn't the best way.

Could you please help me?

You might be able to get this to work by using the Rules module.
Depending on how the format of your URLs look like, you may want to also use the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface. Using those you might be able to build an appropriate rule to issue a redirect (+ display a message if needed) based on some Rules Conditions that implement your access restrictions.

For more details, refer to my answer to the question "How to use the Rules module to implement a custom redirect for an outdated URL?".


Fivestar multiple axis reviews and views I want to have multiple axis comment reviews for nodes.
Example - rate a restaurant by the following criteria: food, drinks, atmosphere, location.

I want to order the nodes in a view according to the average vote.

Questions:

How can I setup the views relationship and fields to order nodes by total rating?
Should I create a separate vote tag in fivestar settings for each axis?
Is this possible out of the box with fivestar for D7?

UPDATE

To illustrate better the problem, here are the screenshots and exact numbers I'm getting.

Views settings
Views output
Calculations from reviews

UPDATE 2

Thanks to everyone who posted here.

I'm still not able to aggregate the votes correctly but I think it's due to some settings in views.

I will award the bounty and post the code/solution I used as soon as I solve it completely. I think Ayesh and junedkazi gave the correct answer saying almost the same thing. Will confirm when I solve it completely.

FINAL UPDATE

The votes are not aggregated on the nodes properly. Custom module is calculating the "overall" value for each comment and that works as it should. But when the fivestar/votingapi calculates the votes for parent node on node view page and on views listing page, it does not work. It takes into consideration only the last review, and not the rest.

Just in case, here's the calculating code I'm using in a custom module:

/**
 * Implements hook_comment_presave().
 */
function MYMODULE_comment_presave($comment) {
  // Keep these as separate variables so the code doesn't have to be
  // updated if the number of axis has been changed from admin.
  $axis_count = 0;
  $rating_sum = 0;
  // Go through all elements and check if this is a rating field.
  // Avoid hardcoding the field names (except the overall field).
  foreach ($comment as $element_id => $element) {
    if (is_array($element) && isset($element[LANGUAGE_NONE][0]['rating'])) {
      $rating_sum += $element[LANGUAGE_NONE][0]['rating'];
      $axis_count++;
    }
  }
  // Trim out eventual weird decimals
  $overall = number_format($rating_sum / $axis_count, 0);
  // Save the value in the overall field
  $comment->field_overall[LANGUAGE_NONE][0]['rating'] = $overall;
}

Please if anyone has any ideas I'd be really thankful. Even though the bounty expired, I will award it for a working solution (I don't care about the points).

Fivestar Widget

I believe the Fivestar widget stores values as a percent average rather than as a vote average. In otherwords the Fivestar widget is storing a value between 0-100 rather than 0-5.

When you have a Fivestar widget collecting 0 to 5 stars, each star is worth 20.  This is why when you have an average of '2 stars', your seeing a value of 40. (2*20=40)

To extend this:

A node with 1, 2 star vote will be stored as 40
A node with 2, 2 star votes will be stored as 40
A node with 1, 2 star vote and 1, 3 star vote will be stored as 50

This can easily be fixed by dividing the displayed output by 20.

From there, I believe your view may already be setup properly.

I'll rework my answer if this isn't relevant here.


How do I find out which module handle a GET/POST/PUT? I'm reading a Drupal 7 project. However, unfortunately I can't find out which module handle an Ajax request.
I only know the destination address which has been rewritten. (Suppose it's http://example.com/abc)

So, the problem is how could I find out which module handle my Ajax request?

Menu items (in code)

Drupal module register endpoint with hook_menu(). You can search the endpoint within the project, such as abc. It should stay inside hook_menu() with type MENU_CALLBACK.

You may find something like below.

function mymodule_menu() {
   $items = array();
   $items['abc'] = array(
     'title' => 'Ajax endpoint',
     'page callback' => 'mymodule_ajax_callback',
     ...
     'type' => MENU_CALLBACK,
   ),
   return $items();
}

Menu items (in database)

In database, table menu_router saved all registered menu items. You can lookup the endpoint on path column and find the corresponding callback function on page_callback column.

Modules

There is a number of module which provide UI or APIs for developer creating endpoints. Such as services and RESTful Web Services.


Show core fields before Profile2 fields I have fields added to Drupal 7 core users (Config > People > Account settings > Manage fields) which are common to multiple user roles.

I also have fields on a Profile2 profile, which I only want to display for people registering for that role.

I cannot find a way to show the core user registration fields before the Profile2 fields. Tried Manage Fields and Display Suite, but unless you show the Profile2 fields on ALL user registration forms (which of course I don't want to do, as these fields are only relevant to one role on the Drupal site) I can't reorder them.

Been looking for a solution for over a year. Profile2 project on Drupal.org won't answer, Profile2 Reg Path project on Drupal.org won't answer either. Totally stuck, and very surprised that I seem to be the only one with this issue. I have this issue on multiple sites now.

You can use the hook_form_alter() to alter the form and change the weight attribute, if your field is field_username you can use something like this:

function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'YOUR_FORM_ID') {

    $form['field_username']['#weight'] = -50;
    $form['field_email']['#weight'] = -49;
  }
}


Giving custom argument value in 'q' variable We want to use  a custom template page when a specific value is given for the q variable in url .

For example if we give http://localhost/drupal/?q=xyz/123   , we want to use a custom template page say page-xyz.tpl.php ..

Have a hunch that hooks and template.php file may be the key components here but not sure what to exactly do.

Your question seem a little bit unclear to me. But my understanding is that you are having problems with theme template.

You should try it out using the node in your url. There is an example...

If you had the following path:

/node/99/edit

PHPtemplate looks for the following templates, in descending order:

page-node-edit.tpl.php
page-node-99.tpl.php
page-node.tpl.php
page.tpl.php


Module requires Composer install of third-party library I am trying to learn about drupal 8 and composer within aegir. It seems like aegir has some support for it but the problem that I am running into right now is that aegir doesn't seem to install composer dependencies for modules. For instance, I am using the "real_aes" module in my first drupal 8 deploy which requires that defuse php-encryption be required. Normally, I would just use composer require and everything would be no problem. However, I am trying to use aegir to manage all of this.

My question is really this. Is there a way in aegir to specify composer requirements or to get aegir to install all module requirements based on the module's composer.json file? And if not, what is the best way to handle this via aegir? Will i need to alter the composer.json file in the drupal root directory after I deploy the drupal 8 platform and run composer update via the command line or are there any other work-arounds that would be better?

I should say that I found the hosting_composer module and installed it and it's dependencies. However, I immediately got several warnings right after install. Since this is going to be managing live drupal sites, I am hesitant to rely on so many dev modules especially since they are showing issues right after install.

I have about 20-30 drupal 7 sites that I am looking to migrate to d8 over the next year.

For anyone else facing a similar problem, I just wanted to add that, as of Aegir 3.18, it seems possible to configure Composer to download and install third party libraries for Drupal modules from https://asset-packagist.org. Of course, those libraries should exist as Composer packages on the asset-packagist site.

I was able to get this going yesterday by following the instructions at the link below, but after a lot of trial and error as the docs are not always accurate, especially in terms of the line endings, JSON syntax etc.:
https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies#third-party-libraries

The composer.json file to edit is at the Aegir path /platforms/drupal-x.x.x/composer.json


How to change the field label in an API response How to change field_canonicalurl to canonicalUrl and field_teaser to Teaser?

Below is my API output from my View:

[{"field_canonicalurl":"","title":"This is the title ","field_teaser":"\u003Cp\u003EIn this is the teaser \n" }]

Go to field settings of the Rest export view, add Alias for each field, Save.
That's it. You're done


Google analytics per page I'd like to post alot of Google Analytics info about a page(node) on the page itself(visits, new visits, bounce rate, maybe even time series). What's the best module for this?

In particular, the info is for users that create their own pages and need to see analytics for their pages.

Any hints?

Thanks.

Try Drupal SEO may be what you are looking for.  http://drupal.org/project/seotools

From its project page:

  The Drupal SEO Tools module seamlessly integrates a sophisticated all-in-one suite of search engine reporting, analysis and optimization tools into your website. It provides a dashboard that integrates analytics reports with links to webmaster tools and vital Drupal SEO modules.

Hope that helps.


Database error when creating entities using hook_update_N I'm trying to create an entity (using entity->save()) in a hook_update_N function. The errors appear at the mysql insert query in the entity's insert function; the insert strings are wrapped in mysql_real_escape_string().

I get a series of warnings:

mysql_real_escape_string(): A link to the server could not be established mod_person.entity.inc:402

mysql_real_escape_string(): Access denied for user 'xxx'@'localhost' (using password: NO) mod_person.entity.inc:403

Followed by the error:

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'val' at row 1

When I remove the mysql_real_escape_string() from the mysql insert query code it works! However now I'm worried that leaves the server vulnerable.

My questions are:

[1] Why does using mysql_real_escape_string() work in normal site operation and not through hook_update_N?

[2] Do I need to use mysql_real_escape_string() with Drupal 7 database queries or is there another way?

I suppose I could remove the mysql_real_escape_string() for the update and then put them back but that feels like I'm missing the point somewhere.

Many thanks for any help.

Similar to what Clive said, you will want to use the Database API (db_update, db_insert) or use an Entity Metadata wrapper.


Add custom user image field on private messages list instead of default user picture ok, this is what I have done so far but it is still not working.

First I wanted to add senders profile picture to the private message list on each user profile page. To accomplish that, I used the following code from drupal.org forum:

https://drupal.org/node/1549540#comment-5956560

It does work on my site, but it is using the default user picture. I would like to use a different image for users profile page. So I created an image field named profile_image. I am not pretty sure what is the best approach. On this page, they are trying to change the default user profile picture by the image field but for some reason it is not working for me:

How can I display a picture from a field as the user picture rather than the drupal default with user-picture.tpl.php?

I took the user-picture-tpl.php which had the following code:

<?php if ($user_picture): ?>
  <div class="user-picture">
    <?php print $user_picture; ?>
  </div>
<?php endif; ?>

I removed it and add this code:

<?php if (!empty($user->profile_image[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->profile_image[LANGUAGE_NONE][0]['fid']);

  $account = user_load($account->uid);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
  echo theme('image_style', array('style_name' => 'people_profile_image', 'path' => $file->uri));
}

Nothing is working yet. what I am doing wrong? could you please help me?

Thanks

You have made mistake in your field name, Drupal creates an machine name of any field prefixed as "field_" if you create it using Field UI. Using thumbnail as the style and also ensure that the style you have added -- people_profile_image is created in the Image Styles

so your code should be

if (!empty($user->field_profile_image[LANGUAGE_NONE][0]['fid'])) {
  // Load the file
  $file = file_load($user->field_profile_image[LANGUAGE_NONE][0]['fid']);
  $account = user_load($user->uid);

  // Note the style name is "thumbnail" and that your field name is
  // field_profile_image not profile_image which you have put in second line
  // which loads the file
  echo theme('image_style', array('style_name' => 'thumbnail', 'path' => $file->uri));
}


Post method not working on non-CRUD methods I'm just trying to create custom rest service action but I can't get it. I have created end_point called "testing". Whenever I try to post the data it shows access denied for authenticated user. Where I'm going wrong?

The steps I followed:

used advanced rest client chrome extension
http://localhost/testing/test/username
In dataform I added data "username" = "abc";

I can't get the name. What I expecting is the post call must return the username "abc" according to my below function.

function my_module_service_services_resources() {
    return array(
      'test' => array(
         'actions' => array(
            'username' => array(
              'check' => array(
                'help' => 'Checks username for uniqueness',
               'callback' => 'test_module_username_check',
               'access callback' => 'my_module_service_access',
                'access arguments' => array('view'),
                'access arguments append' => TRUE,
                'args' => array(
                  array(
                    'name' => 'username',
                    'type' => 'string',
                    'description' => 'The username to check',
                    'source' => 'data',
                    'optional' => FALSE,
                  ),
                ),
              ),
            ),
          ),
       ),
    );
  }

  function test_module_username_check($username) {
    return $username;
  }

  function my_module_service_access() {
    return true;
  }

After debugging the action method of user/login (default in services module), I found where I went wrong. In my code, I added extra array called check inside username. When I remove that array everything is going well. Here the updated code

function my_module_service_services_resources() {
    return array(
      'test' => array(
         'actions' => array(
            'username' => array(
              'help' => 'Checks username for uniqueness',
              'callback' => 'test_module_username_check',
              'access callback' => 'my_module_service_access',
              'access arguments' => array('view'),
              'access arguments append' => TRUE,
              'args' => array(
                array(
                  'name' => 'username',
                  'type' => 'string',
                  'description' => 'The username to check',
                  'source' => 'data',
                  'optional' => FALSE,
                ),
              ),
            ),
          ),
       ),
    );
  }

  function test_module_username_check($username) {
    return $username;
  }

  function my_module_service_access() {
    return true;
  }


slide through nodes from the same content-type? I've got a content-type called design_portfolio, and created an amount of fields

I've created a view (using the Views module) of only the the field 'thumbnail-design'-image, which is sorted on taxonomy terms in the header

which gives me the next result on the front-end

Each 'thumbnail' links to its' own content, which is a node from the content-type 'design_portfolio' and gives me this result (I wrote a file 'node--design_portfolio.tpl.php' to style the pages for this content-type). Each thumbnail directs to another content within the content-type 'design_portfolio'

Everything what I have right now is working properly and has to stay, but what I want to achieve right now is,  the posibillity to slide through all the pages/nodes of just this content-type 'design_portfolio'. Like this:

I've allready tried to achieve it with creating a view with 'views slideshow'. Which gives me a good result, but when I click on my thumbnail, it still goes to the corresponding content (page/node), but not the the slideshow that I've created. I want every link to direct to the corresponding slide, because every thumbnails has it's own content.

settings of field thumbnail-design in my first view

inspecter to target a specific link of one slide in the slideshow (created of all content from content-type design_portfolio, used 'views-bootstrap-carousel')

Any solutions for my problem?

Views Slideshow
About this module
You could use the Views Slideshow module for this. Here is a quote from its project page:

... can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.
Potential uses:

News item slideshow (such as the title, image and teaser of the last 5 news articles submitted).
The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).
Rotate any image, based on any filters you can apply in views.
Hottest new products for any ecommerce drupal site.
Rotate contact links, share links, etc.
You could rotate entire nodes, categories, image galleries, etc. I wouldn't suggest it, but you have that power.
It's also a great space saver. Places where you had multiple images or multiple items such as RSS feeds or category listings can now be presented in a slideshow.

The possibilities are really endless, as the more ways you can think of to categorize and add to views, the more you can rotate.

How to install and use this module
Option a: Use the available (Community) Documentation
To actually enable and use this module, make sure you follow the instructions detailed in the module's Community Documentation within "3.x - Views Slideshow Tutorial". Especially this part of it:

...

Enable the Views slideshow and Views Slideshow: Cycle modules.

You should now see the new views style option called "Slideshow".

So make sure that you also enabled the Views Slideshow: Cycle sub-module.
Additional refinements:
Since in this case you want to do something special (tricky?), you need to do some extra things, within "settings of field thumbnail-design in my first view" (as in your last screenprint):

Where there is your "red arrow" (higlighter), it should say "link to" = "nothing" (you now have, in Dutch, "inhoud", which is "content"). FYI: That is what explains what is happening "now": you're asking a click on that image to be translated to something link "type an URL path = the path of the node where that image field is related to ...

Where there is your "red cross" (rewrite result), within the 'text' box ('Tekst' in Dutch), you need to further refine what you already have (with that div and token). More specifically, you need to REWORK that to something that corresponds to an hyperlink ('href', etc) (in which you can still use that div, with its class, and image token you already have). The PATH in that href needs to match the exact path that will bring you to what further on in your question you described as "I want every link to direct to the corresponding slide, because every thumbnails has it's own content.". What exactly that path is I cannot tell (I hope YOU know that path, if not we're done). However read on in the next bullet for 1 more hint to CREATE that path for the hyperlink to be added in this tekst box here ...

To create the correct path in the previous bullet, I "expect" that you might need something like the "nid", or something similar, of the actual node. It is possible that it is not available (yet) in the list of tokens within "replacement patterns". In my environment, at first I did not have the [nid] token available at first, only things like [title], %1, !1,  %2 and !2 . However, also making the [nid] token available is possible like so: add an extra field (node Id) BEFORE (important) the field you already have, and mark it with "exclude from display". That's tricky, but that's how this works in Drupal ...

Option b: Restart from scratch
From the details provided in the question, it appears that it might be an option to consider starting from scratch (which is what I sometimes also do ...). Use HOW TO INSTALL & SETUP VIEWS SLIDESHOW MODULE ON DRUPAL7? as a possible step-by-step tutorial to do so.
As a variation, carefully review that tutorial to get ideas about what in your current approach seems to be wrong, and go back to option 'a'.
Option c: Try another module
If you rather want to change to using "Views Bootstrap" (cfr. one of the prior "versions" of this question, which contained "Views slideshow didn´t pop-up while creating a view, so I used Views Bootstrap."), then please create a NEW question about using Views Bootstrap (which I'd be happy to answer "also" if I can. Because that is a completely different question (and compliant to recent guidance / instructions from @Clive also).
Further enhancements
Possibly you may want to further extended this with related modules  (there are dozens of modules to further enhance views) such as Views Slideshow: Galleria. Here is a quote from that module's project page:

Integrating Galleria with Views Slideshow.
Galleria is a JavaScript image gallery framework built on top of the jQuery library. The aim is to simplify the process of creating professional image galleries for the web and mobile devices.

jCarousel
Another option is to consider the jCarousel module. Here is a quote from its project page:

... This module allows developers and themers to make use of the jCarousel jQuery plugin. It includes a developer API that other modules can use, as well as Views integration in the 2.0 version so that you can turn any list of content or images into a carousel.
Features:

Built-in Views support.
AJAX-loading of additional items as needed.
Carousel pager/navigation to jump between multiple pages.
Circular wrapping of items.
API for direct usage of jCarousel without Views.


How do I set up this view? I'm using the https://www.drupal.org/project/views_field_view module on my Drupal 8 installation, and my current setup consists of:

Products (Content Type - has an entity reference to the Product Availability taxonomy)
Product Availability (Taxonomy)
All Products (View - with the Product Availability view as a field)
Product Availability (View)

Now, for each product displayed on my Products view I'd like to show the 'Product Availability' view fields, only for that product. For example, Product A might have the availability 1 and 2, whilst Product B may have only the availability 3. So I only want to show the availability for each product. I'm not sure how I'm supposed to set up a contextual filter for this, or if even that's the right way of doing this.

I somehow need to pass reference to my child view, Product Availability, the node ID of the product I would imagine.

Any suggestions?

EDIT: I've managed to get the result I wanted by going at this in a bit of a backward way. Instead of trying to configure the filter at the level of each product, I've set it up to be on the level of the Product Availability content type. Obviously this isn't as user-friendly, as to relate a 'Product Availability' to a 'Product' this way, you'll need to go into the 'Product Availability' content type and then select the products individually.

Follow the following steps:
Part one:
1. Install Views field view module and REST Export Nested (https://www.drupal.org/project/rest_export_nested)
2. First Create a View filtered by the content type mentioned, selecting Rest Export View.
3. Then Add nid, title and the special field Called "View" https://screencast.com/t/3la2zG6llfi
4. Duplicate this view as Rest Export Nested.

Part two:

Go and create another view filtered by taxonomy terms of your type(Product Availability), selecting Rest Export View.
Add as fields what you want to display for each term. For example, you can add the title of the term, and other fields.

I added 2 fields for example.
3. Add as the relationship the field name which is referenced to the taxonomy (Product Availability) from your content type(Products).
My content type is article and it has field_taxonomy which is a reference to the taxonomy term.
4. The last step on configuring this view is to add a contextual filter: Add "ID" and select to use the relationship created before,
selecting the "Provide default value" and choosing "Content id from URL".

5. Save this view.

Return to the first view created and configure the "View" field as the print screen is showed:
Choose the second view created in the "View " drop-down and o display "rest export". For contextual fields write the {{ raw_fields.nid }} . It will work only if you were added the node id as a field in this view above the "View" field.

The result will be the following:

Node id 1 has 2 field taxonomy terms assigned: "term 1" and "term 2", and in the view object, you can see that there 2 arrays, each array represents a taxonomy term with the fields values.


Customize HTML for field in field collection My field collection template is ds-1col--field-collection-item-field-video-item.tpl.php. I need to access the Image field so that I can customize the HTML. I've tried the following by neither work:

<?php print $fields['field_video_image'][0]['und']['value']; ?>

and

<?php print $fields['field_video_image']->content; ?>

I also need to wrap each field collection item in its own div. For instance, each image should be wrapped in a videoClip div but right now all field items are rendering inside videoClip. Also I need to get the delta value of each field item to add it to as part of a CSS class. How can I do this?

Current fields wrapped in custom HTML together:

If your template is being recognized you can access the fields and field content through the $content array. Below is the normal field collection item template file that comes with the field_collection module.

<?php

/**
 * @file
 * Default theme implementation for field collection items.
 *
 * Available variables:
 * - $content: An array of comment items. Use render($content) to print them all, or
 *   print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $title: The (sanitized) field collection item label.
 * - $url: Direct url of the current entity if specified.
 * - $page: Flag for the full page state.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. By default the following classes are available, where
 *   the parts enclosed by {} are replaced by the appropriate values:
 *   - entity-field-collection-item
 *   - field-collection-item-{field_name}
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      print render($content);
    ?>

Using devel you can use dpm($content); and you will see the below setup.

So as you see in field collection item you could use $content['field_field_1'][0]['#markup'] if your field has extra markup (like for instance if it was set to display as a link to from entity_reference). You could use $content['field_field_1']['#items'][0]['safe_value'] to get the safe value of the field (sanitized). If you want to customize the markup around a certain field you can hide the field and the render it somewhere else. See the below code for an example.

<?php

/**
 * @file
 * Default theme implementation for field collection items.
 *
 * Available variables:
 * - $content: An array of comment items. Use render($content) to print them all, or
 *   print a subset such as render($content['field_example']). Use
 *   hide($content['field_example']) to temporarily suppress the printing of a
 *   given element.
 * - $title: The (sanitized) field collection item label.
 * - $url: Direct url of the current entity if specified.
 * - $page: Flag for the full page state.
 * - $classes: String of classes that can be used to style contextually through
 *   CSS. It can be manipulated through the variable $classes_array from
 *   preprocess functions. By default the following classes are available, where
 *   the parts enclosed by {} are replaced by the appropriate values:
 *   - entity-field-collection-item
 *   - field-collection-item-{field_name}
 *
 * Other variables:
 * - $classes_array: Array of html class attribute values. It is flattened
 *   into a string within the variable $classes.
 *
 * @see template_preprocess()
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>
  <div class="content"<?php print $content_attributes; ?>>
    <?php
      // Hide field collection field.
      hide($content['field_image']);
      print render($content);
    ?>

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

Hopefully all of this helps, if not let me know and I can adjust to what exactly you are needing or explain more :)


How can I disable the "Text format" pull-down for users that are creating or editing content? Since the "Plain Text" format can't be deleted (within /admin/config/content/formats) the Text format pull-down will always contain it plus the default format that you would like for the user to use (i.e. Full HTML) when creating content.

When the user creates content (i.e. /node/add/article) I would like the "Text format" pull-down to be disabled so that they can't change it for non-administrators.

How can I disable the "Text format" pull-down for users that are creating or editing content?

The absolute easiest way would be to hide the selection using CSS.

I only say this because there's nothing "bad" that can happen if someone does use the plain text format.

Otherwise you're looking at assigning custom permissions and probably using hook_form_alter()  which just seems like it's more trouble than it's worth!

.filter-wrapper { display: none; }


Permission option for unblock the selected users not listed I have created a user & assingned it role 'superuser'.I want to give only two permissions to superuser, block the selected user account & unblock the selected user account.I have given 'block selected user' permission from admin->people->permission but the option for 'unblock the selected user account' permission is not listed in admin->people->permission.How can i give this permission to superuser?

You can create a view and give access to superuser role.

Below links will help you.

http://blog.safwan.in/post/69263954822/add-unblock-user-action-to-views-bulk-operation-vbo

http://dropbucket.org/node/486


How do I create a block for my heartbeat activity? I have a heartbeat activity and a message template. I'm able to log the activities using heartbeat_api_log(), but how do I show the activities in a block?

I'm using Drupal 7.

heartbeat has views integration. Just built a view and add it to a block.


How to make an editable catalog on Drupal? I'm trying to make something like an catalog (e.g. an address book) on my site, in which the user can interact with the fields, like adding, editing and removing entries, I'm thinking about putting each of those entries as a content type node and then using views to display and modify them... Is there any known problem with this approach? could you suggest another one?

I want it to be dynamic, on click the selected entry expands allowing for editing and automatically saves the content...

The simplest thing todo is to make a View thats lists your catalog entries. In the Header area of the view add a global text area in which you create a link such as Add New Entry.

Then also install the Editable Views module:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.

From the project page you can see a screencast on how to use the Editable Views module.


How can I programmatically bulk delete redirect entities based on their status code? I have a list of 3089 301 redirects URLs and want to delete them programmatically from the database.
E.g List of source URLs
/about/test/2013/page_61732.html
/about/test/additional/branches/page_38678.html
/about/test/additional/branches/page_38678.html
/about/test/additional/branches/page_38678.html
......

If I understand your question correctly, you want to delete all redirects with a status code of 301. That could be done like this:
$ids = \Drupal::entityQuery('redirect')
   ->condition('status_code', '301')
   ->execute();

$entities = Redirect::loadMultiple($ids);

\Drupal::entityTypeManager()->getStorage('redirect')->delete($entities);

If you only want to delete redirects that have a certain source URL, you should be able to add
->condition('redirect_source__path', $sources, 'IN')

to your query.


How to list members in a group using views Drupal 7? I am using Profiles 2 and Organic groups.

I was successful in listing users via views > Users.

I am using "profiles 2" module to collect and store details of users rather than the core drupal user management.

I have created few groups using "organic groups" module.

My question is how to list all the "PROFILES" (created via profile2 module) of members belonging to a group using views ?

I had forgotten to add Groups Audience as a field in the Profile type created by Profile 2 which in my case was "Main Profile".


Drupal 8 Commerce 2 Trigger custom mail to product author We can get the uid for purchased product after checkout using Event Subscriber.

How to sent mail to product author with product details when someone checkout the product. We can get all the details in $order.

This is described in the Commerce 2 documentation:

  In our case we want to send the email after the transition to the
  Fulfillment state has occurred. We therefore need to create an event
  subscriber that listens to the commerce_order.fulfill.post_transition
  event.

// my_module/src/EventSubscriber/OrderFulfillmentSubscriber.php

    namespace Drupal\my_module\EventSubscriber;

    use Drupal\state_machine\Event\WorkflowTransitionEvent;
    use Drupal\Core\Language\LanguageManagerInterface;
    use Drupal\Core\Mail\MailManagerInterface;
    use Drupal\Core\StringTranslation\StringTranslationTrait;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;

    /**
     * Sends an email when the order transitions to Fulfillment.
     */
    class OrderFulfillmentSubscriber implements EventSubscriberInterface {

      use StringTranslationTrait;

      /**
       * The language manager.
       *
       * @var \Drupal\Core\Language\LanguageManagerInterface
       */
      protected $languageManager;

      /**
       * The mail manager.
       *
       * @var \Drupal\Core\Mail\MailManagerInterface
       */
      protected $mailManager;

      /**
       * Constructs a new OrderFulfillmentSubscriber object.
       *
       * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
       *   The language manager.
       * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
       *   The mail manager.
       */
      public function __construct(
        LanguageManagerInterface $language_manager,
        MailManagerInterface $mail_manager
      ) {
        $this->languageManager = $language_manager;
        $this->mailManager = $mail_manager;
      }

      /**
       * {@inheritdoc}
       */
      public static function getSubscribedEvents() {
        $events = [
          'commerce_order.fulfill.post_transition' => ['sendEmail', -100],
        ];
        return $events;
      }

      /**
       * Sends the email.
       *
       * @param \Drupal\state_machine\Event\WorkflowTransitionEvent $event
       *   The transition event.
       */
      public function sendEmail(WorkflowTransitionEvent $event) {
        // Create the email.
        $order = $event->getEntity();
        $to = $order->getEmail();
        $params = [
          'from' => $order->getStore()->getEmail(),
          'subject' => $this->t(
            'Regarding your order [#@number]',
            ['@number' => $order->getOrderNumber()]
          ),
          'body' => $this->t(
            'Your order with #@number that you have placed with us has been processed and is awaiting fulfillment.',
            ['@number' => $order->getOrderNumber()]
          ),
        ];

        // Set the language that will be used in translations.
        if ($customer = $order->getCustomer()) {
          $langcode = $customer->getPreferredLangcode();
        }
        else {
          $langcode = $this->languageManager->getDefaultLanguage()->getId();
        }

        // Send the email.
        $this->mailManager->mail('commerce_order', 'receipt', $to, $langcode, $params);
      }

    }


How do I implement a notification/subscription solution? I can't get the Notifications or Subscriptions modules to actually send out emails, and installing the Comment Notify module crashes my entire site.

I realize that Drupal 7 is still fairly young, but I find it pretty remarkable that there is not yet a stable notification/subscription solution. Does anyone have any suggestions beyond the modules I listed here?

Ideally, I would like the following features:

Automatically become subscribed to nodes you create or comment on (with the option to turn this off, of course)
Subscribe to taxonomy terms
Receive notification emails at an interval you specify, such as immediately, once a day, etc.

Seems like maybe 1 & 2 are possible to do through Rules, which I'll begin to explore. But the third point above is pretty critical as well.

Have a look at the Message Stack, which consists of these modules (quotes are from the module's project page):

Message:

The Message module is the core of the message stack. It enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Message Notify.

This module provides a method for sending a message via a notifier plugin. Message Notify comes with plugins for email and SMS and may be extended to other transport mechanisms as required.

Message Subscribe.

With this module, users who subscribe to content will be notified when events occur that involve that content. The module leverages the Flag module, which provides a subscribe functionality to users.

These are the basic components and dependencies of the message stack:

Quite a few popular Drupal distributions already adopted to this Message Stack, such as such as Commerce Kickstart, Drupal Commons, ERPAL and Open Atrium. And it will make you well positioned for Drupal 8 also (because of he modules' object orientated architecture).
If you want to have a closer look at the Message Stack in your own environment, then experiment a bit with the Answers module (disclosure: I'm a co-maintainer), together with the Answers Notification sub-module, which allows logged in users to subscribe to selected questions, so that they receive notifications (using the Message Stack) when Questions receive Answers.


Where is the maintenance mode value in the database? I know the maintenance mode value used to be in the variables table, but in D8 that table is replaced by (or joined with) the config table, but I couldn't find any row with that name.

Where is it located now?

It's no longer a part of the config system; it's a part of the state system which is stored in the key_value table as a part of the state collection.


Should I use t() in hook_update_N() or admin UI in a custom module? Background / motivation
Many implementations of hook_update_N() and hook_install() in contrib and core modules in D7 and D8/D9 contain calls to the t() function. In general, I think it is considered a "best practice" to use t() for all kinds of strings that will be displayed to any user unknown to us.
For custom site-specific modules, I often avoid the t(), if I know that the message will never be shown to anybody outside the developers. This applies especially to hook_update_N() and hook_install(). Sometimes I use format_string() instead, to get the replacement without the translation.
My own motivation is like this:

I don't want these one-off strings to pollute the database and the translations UI. (not sure under which circumstances this would happen)
The audience of an update hook is a small team of developers and devops, who are used to code comments written in English.
I want the original English message to appear in logs, UI and CLI output, and in copy+paste snippets sent around between developers.
I want developers / site builders to always see the same string.

Personally, I sometimes even go further, and don't use t() for names of custom field formatters, plugins etc.
I have a colleague who is not convinced by my pragmatic arguments, and wants to do things "by the book". He places high value on consistency, and wants to use t() everywhere.
Perhaps one argument in favor of t() is that it would make it easier to later copy parts of the code into a contrib or in-house module, without having to modify all the strings. Not very likely for a typical hook_update_N(), but the possibility exists.
Question
Can it be "acceptable" as a team policy to not require t() for strings with an "internal" audience?
In which cases could it be acceptable to not use t()?
Is there any convention or good reason we could use to decide this, beyond personal preference?
EDIT
There are some more specific questions hiding in the original question. I am putting these in a section clearly marked as "EDIT" to not be accused of a Heisenberging.

In which cases could it be acceptable to not use t()?

Specific cases which could be discussed:

Messages returned from hook_update_N().
Exceptions which are thrown in hook_update_N() on failure. (#817160 suggests to NOT translate exception messages.)
Names of field formatters and other plugins defined in custom modules. An argument could be made that original names should not be translated.
(watchdog() / Drupal::logger() calls are mentioned in a comment, but I am less interested in those atm)

The arguments for/against apply differently to these cases.

Ever hear the expression "You Play Like You Practice"? If you get in the habit of NOT using t() for strings that are translatable just because it's only for your site ("practice"), then when it counts (i.e. "play") you will probably also leave out t(), because that's what you're used to.
There is really no downside to doing it correctly here. You're not saving anything or making any measurable difference in performance. The upside is that if you do it the same everywhere, you're not going to introduce a bug by leaving off t() where it is needed, and you can then also use the automated coding standards tools to check your code without seeing a lot of fails from your missing t() functions - that keeps these many fails from obscuring the few real problems you might have.


Is it necessary to use cache in hook_init? I wonder, since hook_init doesn't run on cached pages, is it useful to use cache_set in a hook_init() ?

I am going to retrieve an array of strings from the database on each page request (not on cached pages obviously), so I am wondering how to do it properly. For this purpose, should I use cache_set, a persistent variable or maybe no cache at all in hook_init ?

Sure, why not. All three options should work fine. But using Drupal's cache mechanism will work the best. The page cache is not the same as other caches which can still be used for whichever purpose you require, in this case, to store the results of a DB call. There are a number of core caches each with their own purpose besides the generic one (simply named cache), and you can also roll your own cache table if you like.

Here's an example on using cache_set and cache_get which should be similar to what you are attempting to do (albeit not in hook_init).


drupal 7 xml sitemap showing nodes that are unpublished we have xml_sitemap 7.x-2.0-rc1 and drupal 7.23 core and it is putting unpublished nodes in the xml site map. What can we do?

solution - turn off the individual node. with the xmlsitemap node module enabled.  at the bottom of the content page when you are editing you can choose Inclusion: Excluded.


How to use same database for two website but different panel? Is this possible to use same database for two different domain? Example domain1.com and domain2.com but their views and designing are different for both site but content will be same .

If I change in one domain1.com it will reflect also in the domain2.com

You should start from https://www.drupal.org/docs/8/multisite
Drupal supports multisite structure out of the box. You don't need Domain Access module to reach it.
You may share some db tables among your websites, e. g. content but keep settings (Views, display settings unique). It depends of your purpose. Also you may have shared or unique modules and themes.
The idea is that you specify the list of the sites in sites.php and have several subfulders under /sites folder. At least it worked with Drupal 7. I'm sure there is no drastic charge with Drupal 8.
But be careful with cache. Mind which caches you want to keep shared or unique.


Using a template_preprocess_node in an adaptive subtheme I'm using the adaptive theme with the pixture_reloaded subtheme, and I'm trying to place a preprocess to change the format of $date. This is what I thought should do the trick but haven't had any luck with getting the output I want.

In ./sites/all/themes/adaptivetheme/adaptivetheme_subtheme/template.php, I've entered the following:

function adaptivetheme_subtheme_preprocess_node (&$vars)
{
   $vars['date'] = format_date($node->changed);
}

In ./sites/all/themes/adaptivetheme/adaptivetheme/templates/page.tpl.php, I've added:

print $date;

under the location where the main content is rendered.

The date prints where I want it to, however, the date format is still showing up as the date which the content was created, and not the updated date. I've edited the content multiple times as well.

Is my preprocess hook supposed to be placed into a different area to make this work?

Any help is much appreciated.

Since you are using a node preprocess function, the variable you created will be available to the node.tpl.php file, not the page.tpl.php file. You need to either move your print statement to node.tpl.php or implement template_preprocess_page() in template.php.


How to remove "display name" from edit user I'm building a site that leverages the user email address for the user login instead of a username (via modules Logintoboggan  & Email Registration). I'm also using Real Name to display the "first name" field of the user instead of the username.

My solution is working perfectly apart from when the user is on the edit user account page (and some native drupal system notification message), which displays a "Display Name" field instead of the desired "first name" field.

Question: How can I remove/delete the "Display Name" field from the edit profile page and Drupal system messages/notification fields?

The first one was easy. To hide any field from the user edit form simply set the '#access' to this field to FALSE or any other logic you desire. The second one was more difficult. Turned out the display name was still used on the password reset page. That's how we finally solved it:

/**
 * Implements hook_form__alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_profile_form') {
    $form['account']['name']['#access'] = FALSE;
  }

  if ($form_id == 'user_pass_reset') {
    // Here we take the corresponding user ID from the URL, second argument
    $user_id = arg(2);
    // Then we load the user
    $user = user_load($user_id);
    // Now we have the mail
    $user_mail = $user->mail;

    // extracting the date string with a helper function
    $sub_text = getContents($form['message']['#markup'], '', '');
    $expiration_date = $sub_text[1];

    // Now we alter the existing form
    $form['message']['#markup'] = '
This is a one-time login for '.$user_mail.' and will expire on '.$expiration_date.'.

Click on this button to log in to the site and change your password.
';
  }
}

/**
 * Helper function to extract a string between two given delimiters
 * Credit: http://stackoverflow.com/a/27078384/2199525
 */
function getContents($str, $startDelimiter, $endDelimiter) {
  $contents = array();
  $startDelimiterLength = strlen($startDelimiter);
  $endDelimiterLength = strlen($endDelimiter);
  $startFrom = $contentStart = $contentEnd = 0;
  while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
    $contentStart += $startDelimiterLength;
    $contentEnd = strpos($str, $endDelimiter, $contentStart);
    if (false === $contentEnd) {
      break;
    }
    $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
    $startFrom = $contentEnd + $endDelimiterLength;
  }
  return $contents;
}


Display referencing entity in panels I have two content types.
1. Lecture
2. Notes

Notes have an entity reference field which references lecture.
Different users create different notes each referencing to a lecture.

Now,
How do I display note created by user on lectures page.

I know how to do it with Views and Panels modules.
First you need to create two Views:

First one is Lecture_view create a block and add fields you want to display(Title, body, most important - Content: Nid  and any other fields your Content type has).
Second one is Notes view, create same block but fields for notes to display, and also in a
Contextual filters menu add  new filter (Content) Content: Nid

Now you should go to Lecture view and in Advanced menu, click on theme information link, and you need to create template file, find row with Field Content: Nid and create one of suggested fields, something like (views-view-field--conversations--page--nid-1.tpl.php) in /sites/all/themes/YOURTHEMENAME/views/YOURVIEWNAME(lecture_view--block)/YOURTEMPLATEFILE(views-view-field--conversations--page--nid-1.tpl.php) in this file you will past code from theme view, its something similar to

<?php print render($output); ?>

you need to add one more thing embed that views:

<?php print views_embed_view('notes', $display_id='default', $row->nid); ?>

your contextual filter should work, and now you can add this view to your Panel to display, in Panel menu.

Maybe this is not the best way to do this


add last user IP in view How to add last IP address for online user ( only last IP address ) and link to ban user IP address ?

i tried display all ip address but that showed to me all ip addresses from any time

i want show last ip address

Because it needs lots of coding and building a new module I only give you the tips and the algorithm, you need to know how to build a module.

build a module and create a variable (called IP) using drupal_get_variable, in this way a variable will be created in the `variable`` table.
for any user who visits your website, replace its IP address with the existing one (drupal_set_variable) in the IP variable (so far it is easy to implement).
you need output this variable in your view, so use the hook_views_prebuild ($view) hook function, get the IP and embed it in the view.


allow anonymous post to organic groups Does organic groups allow anonymous posts of content to groups?

I want to enable a simple workflow on my site running organic groups - anonymous users should be able to post blog entries to groups. I've got permissions set up so that anonymous can post blog entries, and blog entries are a group type, but I can't get it to let them associate a new blog post with a group.  Logged in as admin I can do this just fine.

Debugging Notes

I dug into og to see if it was a permissions issue.  It looks like og_form_add_og_audience isn't adding the og_groups array to the form.  Looking at the logic in that function, I don't see where it would add all the groups for an anonymous user.  What am I missing?

I wasn't able to make this work, so I ended up setting up a "fake anonymous" user in its own module - a bit of a superhack that I'm not happy with.  That said, it works.  This "fake anonymous" user id is set via an admin settings page, and gets added to every group created.  When new posts are created I added a form hook to change the author to this "fake anonymous" user id if the submitter is anonymous.  Maybe this is easier in D7?


Theme Image Style for image located in module directory Probably coming at this from too much of a Drupal 6 view point but...

How do I theme an image in a given image style when that image lives in a module folder?  This is driving me batty and I know I'm just missing something simple.

Here is some example code showing what I'm trying to do:

$file_uri = 'public://sites/all/modules/my_module/logo.jpg';
$data['logo'] = theme('image_style', array('style_name' => 'medium', 'path' => $file_uri));

Even if I use file_build_uri(), I end up with a path to a file that doesn't exist. If I move the image to the files directory and change the $file_uri to 'public://logo.jpg', it works just fine.

Do I need to copy the image to the files directory as part of the module code?  If so, isn't this ridiculous?

What am I missing?  Is there documentation on how to do something like this?  I've spent over an hour mining the Drupal documentation and came up completely dry.

I just came across this and had to write the code to handle this.

This effectively clones theme_image_style() to create image derivatives during execution of the page request. Generation bypasses the security issues that would otherwise normally trigger a 404, but that also means a slower page the first time the page is visited.

I am only using the public file schema, but I would expect this to fail with the private file schema based styles.

    /**
     * Implements hook_theme().
     */
    function MODULE_theme() {
      return array(
        'remote_image_style' => array(
          'variables' => array(
            'style_name' => NULL,
            'path' => NULL,
            'width' => NULL,
            'height' => NULL,
            'alt' => '',
            'title' => NULL,
            'attributes' => array(),
          ),
        ),
      );
    }

    /**
     * Returns HTML for an image using a specific image style.
     *
     * Clones theme_image_style() with the additional step of forcing the creation
     * of the derivative to bypass any 404 issues.
     */
    function theme_remote_image_style($variables) {
      // Determine the dimensions of the styled image.
      $dimensions = array(
        'width' => $variables['width'],
        'height' => $variables['height'],
      );
      image_style_transform_dimensions($variables['style_name'], $dimensions);

      $variables['width'] = $dimensions['width'];
      $variables['height'] = $dimensions['height'];

      $image_style_dest_path = image_style_path($variables['style_name'], $variables['path']);
      if (!file_exists($image_style_dest_path)) {
        $style = image_style_load($variables['style_name']);
        image_style_create_derivative($style, $variables['path'], $image_style_dest_path);
      }
      $variables['path'] = file_create_url($image_style_dest_path);
      return theme('image', $variables);
    }


Can't get favicon/shortcut icon to show up Despite trying multiple times various favicon location approaches:

at theme root
at files root
uploading the file through admin/appearance/settings
typing in a path of manually uploaded icon

always clearing cache afterwards, I cannot get my shortcut icon to show up.

I tried pasting into the browser's address bar the path of the ico file so to force an update, but I got a generic server error that there was no such file at this location. When I looked into the generated source code, I could not see neither my file nor the default drupal icon. So I'm completely lost.

I'm close to modifying the html.tpl.php by pasting the link tag manually or through drupal_add_html_head_link but I'm puzzled because it happened to me for the first time. Any clue what else I could double-check?

Just went through this Drupal favicon mess myself :) Hope this helps:

  When I looked into the generated source code, I could not see neither my file nor the default drupal icon.

This is the first problem to solve – getting at least the default blue Drupal drop icon to show again. For this:

There is both a global "Shortcut icon settings: Use the default shortcut icon." setting at admin/appearance/settings and an equivalent one for each theme that can be enabled on that page. In all these forms, tick this setting and save the form. If neither this box is ticked nor a valid path entered into the "Path to custom icon" field of the form whose settings "win" the overwriting, Drupal will interpret this as "do not show any favicon".
Make sure Drupal's default favicon is readable by your webserver user: visiting http://example.com/misc/favicon.ico for your domain should show that icon. If it is not accessible to the web server, Drupal will detect that and not even render a shortcut icon header entry.
Cache clearing should not be necessary, but who knows. If still no favicon shows up, do a drush cc all and check again. Check the HTML source code, not what the browser shows, to prevent issues with the browser cache.

Now that the "blue drop" Drupal default favicon shows up again, let's configure your own one. The surefire way is this:

Navigate to the settings screen admin/appearance/settings/theme-name of your "most-sub-theme" applying to the page where you want your favicon to be in effect. So if you have a theme A, a sub-theme of A called B and a sub-theme of B called C, go to admin/appearance/settings/c.
Click "Shortcut icon settings: Browse" and upload a custom favicon. It will end up in the files root directory of your default site.
Load your site again, and it should show your favicon now, at least in the HTML source. If not, try a full cache clear, though that never helped in my case.

Explanations:

Choosing the most-sub-theme. This is necessary because the admin/appearance/settings form is just the global setting for all themes, and values entered here will be overwritten by each theme and sub-theme down the chain of themes. So the setting in the "most-sub-theme" will win. Plus, it seems there is no option to not enter a value into the "Shortcut icon settings": when you keep the "Path to custom icon" field empty, Drupal will not fall back to the theme higher up in the chain, but interpret it as "do not use any favicon".
Uploading, not typing in a path. There seems to be a Drupal bug with the "Shortcut icon settings" form: it will only accept typed-in values for the "Path to custom icon" field after uploading an icon before. You can then modify the value in that field and it will modify what favicon is used, but when you delete the value, save the form, enter a new value and save again, no favicon will show up even though the same value worked before.
Base path when typing in a filename. If you use the above trick to upload first, then modify the value in the "Path to custom icon" field, also remember that the base path for filenames entered here is the files directory of your default site. So, sites/example.com/files/ from web document root. You can be sure it's the right one by checking that your immediately before uploaded favicon arrived in this directory. (If the referenced file exists, Drupal will also accept without form validation errors if you type in a path starting at document root (like sites/all/themes/my_theme/favicon.png) – but I never could get favicons referenced this way to show up.)


How to remove taxonomy term reference field from simplenews newsletter HTML I have spent a week watching videos and reading tutorials on how to customize the HTML generated by Simplenews. I'm stuck on how to remove the following from my newsletter. I discovered the following using Firebug. There is a bewildering array of CSS, HTML, and php files that are involved. I'm clueless as to how to find the one that it is control.

Can you tell me how to code CSS in the new theme I created for newsletters to remove the following?

div class="field field-name-field-simplenews-term field-type-taxonomy-term-reference field-label-hidden view-mode-full"ul class="field-items"li class="field-item even"a datatype="" property="rdfs:label skos:prefLabel" typeof="skos:Concept" href="/newsletter/test">test

</div

Go to

  Home » Administration » Structure » Content types » Simplenews
  newsletter

Go to Display and customize it

There will be Newsletter category - you can change it's format to Hidden

But first activate needed display type on that page in

Full Content fixes the node display. Email HTML fixes it on the email itself.


Commerce Kickstart on secure server I am in the process of building a Commerce Kickstart 2 site and need some guidance.

From what I can see it is now recommended that e commerce sites are fully hosted on a secure server.

I have in the past looked after a non commerce Drupal site on a standard server.

So my question is apart from having a SSL certificate installed do I need to do any other work to the site or is it a case of just uploading via the hosts control panel onto the secure server as I would with a normal server.

If it's not going to be that easy any advice please

Yes it should be that easy, Drupal doesn't tend to mind what protocol it's served under. I say "should" because who knows what contrib/custom modules you have that might be doing who knows what, but in my experience contrib tends to be pretty good and you can sanity check the custom modules before implementing anyway.

You'll probably want to un-comment the http -> https redirect in .htaccess (or implement similar in the vhost if you're using something other than Apache), that way any errant insecure requests will be upgraded before they hit Drupal.

A useful check is to crawl a test version of the secure site (e.g. with Integrity on a Mac) and look for requests for insecure resources. If you see any, you can check the referring URLs to find out where the insecure request comes from (link, iframe, script tag, etc), and use that as a jumping point to find out which module/sub-system is responsible.