Why can't I delete both account and content when cancelling a user account, in Drupal 8? Before, drupal 7 core, and in drupal 6, a contrib module called user_delete,  had this 4th option in deleting user accounts settings:

"Delete the account and its content." (drupal 7) and

"delete a user and delete all submitted content including nodes and comments" (drupal 6)

But this option seems unavailable in drupal 8 core. Why?

I really want both account and content deleted. The option they offer would force me to periodically delete the unpublished content of the removed account via cron.

Or am I missing something here?

Deleting content requires an access check, and as such the Delete the account and its content. option can't be selected as the default. I presume this is because a user can have access to cancel their own account, but not be able to select the method, and there's no mechanism implemented to provide a fallback for the default.

You'll still see it when cancelling an individual account, provided you have the administer users permission:

If you'd rather get control of that process yourself you can implement hook_user_cancel_methods_alter to remove or change the access check.


How do I use an external data source in a view? I am trying to display some TV schedule information from a thirdparty json api.
I need to know what is the best way to do this.
I have tried various module wsclient module,json query plugin, wsclient view integration. But none of them worked and overkill.

I can write a module to do this, but I need some information. One option I was thinking off was making a new data source available to the Views module. What hooks need to implemented for this?

Check Views JSON Query.

  JSON Query is a Views 3 plugin that adds native JSON query generation.
  It allows you to parse JSON using Views' graphical query builder. It
  works much like Views XML Backend but with JSON.


Re-Indexing on Search setting, What for? What is the function of re-index in the search setting in Drupal? And if not re-indexing, what happened? What different with run cron?

The possibility to re-index makes sense if your structure has changed or you gather information for the index in another way. For example if you want to show on a node a referenced node in another viewmode (e.g full instead of teaser). But this depends on your general setup and how you configured your content types and viewmodes.

The re-index option deletes the current search index. The "run cron" writes the new search information to the search index everytime the cron runs.


How to add class in li element (for page where I am) in menu for drupal 8 I would like to add class in li element in menu for drupal 8 for page where I am. For example if i am on page Start, that li have active class. Or If I am on Join page that li element for join have active class.

START

About

join

So, How to ask if li is active or no?

{% for item in items %}
  {% if item=SOMETHING %}

      {{ item.title }}

  {% else %}

      {{ item.title }}

{% endfor %}

To add active class to
 need to add the following code in your .theme file and menu.html.twig

In .theme file add this

function themename_preprocess_menu(&$variables, $hook) {
  if ($hook == 'menu__main') { // If it is not working replace "main__menu" with "menu"

    // Get the current path.
    $current_path = \Drupal::request()->getRequestUri();
    $items = $variables['items'];
    foreach ($items as $key => $item) {
      // If path is current_path, set active to li.
      if ($item['url']->toString() == $current_path) {
      // Add active link.
      $variables['items'][$key]['attributes']['class'] = 'active';
      }
    }
  }
}

In menu.html.twig replace your
 with below line.

replace this line

{{ link(item.title, item.url) }}

by

 {{ item.title }}


Which hooks can alter the display of a node? I have a custom content type in Drupal 7. It consists of a fixed number of images. I would like to make it so that when its viewed, it comes up as a form. Each image would have a text area underneath, and when a user hits 'submit', the text they entered are displayed below each image.

We're not going to store the text that they enter for the nodes. It's just going live for that form submission.

What hooks can I use to alter the display and functionality of my content type?

It looks like the best solution is hook_node_view(). Unfortunately it gets called on all node renderings, so I'm putting in a check for my content type. The hook hook_view() also exists, but that's only for content types that are completely defined within the module.


Restful permission is required I've created a @RestResource plugin to provide a REST endpoint to get some data, but when I try a GET from Postman it shows this error:

  {
      "message": "The 'restful get ez_share_document_resource' permission is required."
  }

I thought it was because I need to add something else, so I decided to enable the Watchdog database log REST resource to prove it, but I got the same error:

  "message": "The 'restful get dblog' permission is required."

Rest module has set bc_entity_resource_permissions  as false.

This is the annotation of the plugin.

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "ez_share_document_resource",
 *   label = @Translation("Ez share document resource"),
 *   uri_paths = {
 *     "canonical" = "/ezshare/{ezshare_id}"
 *   }
 * )
 */
class EzShareDocumentResource extends ResourceBase {

And this is my get method:

public function get($ezshare_id = NULL) {
    if ($ezshare_id) {
      $record = ['It Works!!'];
      if (!empty($record)) {
        return new ResourceResponse($record, 200);
      }

      throw new NotFoundHttpException($this->t('EzShare doc with ID @id was not found', ['@id' => $ezshare_id]));
    }

    throw new BadRequestHttpException($this->t('No EzShare doc ID was provided'));
  }

Drupal core is recently updated to 8.8.1.

Finally, I was able to solve this issue adding the method permission to the RestResource plugin like so:

public function permissions() {
  return [];
}


drupal multisite and symbolic links with various subdomains i create two subdomains dev.example.com and dev1.example.com in cpnael admin and i create a drupal installation in public_html/dev/sites/ and i create two folders dev and dev1 inside of sites and your own database and the sites.php your settings are

<?php
$sites['dev.example.com'] = 'dev';
$sites['dev1.example.com'] = 'dev1';
?>

i create symbolink links in this way

  ls -s ~/public_html/dev ~/public_html/dev1

working good dev.example.com but no dev1.example.com

but in this way dev1.example.com/dev and working the other installation, how to make this work enter to dev1.example.com instead dev1.example.com/dev?

thanks

I am not sure what the symbolic links are for. Normally, you would add another web server virtual host for dev1.example.com pointing to the same Drupal root directory as dev.example.com.


how do I add a favicon to RSS feed in Bitnami Drupal? I have the Bitnami Drupal AMI that is on the AWS marketplace. I have set up a blog and it is being syndicated at another site.

Everything is working great (the Bitnami Drupal AMI rocks), but (you knew there was a "but") I see other blogs that are being syndicated and they have favicons.

How can I get a favicon into my Drupal blog's RSS feed so a favicon shows up when that feed is syndicated at another site?

You can try to modify the line 1611 of the file installdir/apps/drupal/htdocs/includes/theme.inc. Change feed.png for the name of your image previously placed in the folder installdir/apps/drupal/htdocs/misc/

The original line is:

  if ($image = theme('image', 'misc/feed.png', t('Syndicate content'), $title)) {


Theme not working when using non-standard port number I've been having some performance issues with my local WAMP install and saw a suggestion to move Apache to a different port.  I achieved this by updating httpd.conf:

Listen 89
ServerName localhost:89

I also update my vhosts to use the new port:

<VirtualHost *:89>
    ServerName mysite.local
    DocumentRoot "D:\wamp\www\mysite"
</VirtualHost>

This works.  I can now access the site via mysite.local:89.  However, the site appears unstyled because the CSS and JS files are not linked properly. For example, the following CSS file cannot be found:

<link type="text/css" rel="stylesheet" href="http://mysite.local/sites/default/files/css/css_0-h4tIT-Kdty3gonMCX41fM-7MgTrV9BMd5XQoTqeaQ.css" media="all">

I need the CSS and JS to use mysite.local:89 instead of mysite.local.  When I change this manually via the web inspector it works.

How can I change the CSS and JS imports to use the new port?

Update on WAMP Slowness

For anyone who is interested, WAMP is running much better now. I followed the recommendations in the following article (specifically, I disabled IPv6, put all host file entries on one line, moved Apache to a new port): http://devside.net/wamp-server/wamp-is-running-very-slow

It should just be a matter of setting the $base_url in settings.php

  If Drupal is generating incorrect URLs on your site, which could be in HTML headers (links to CSS and JS files) or visible links on pages (such as in menus), uncomment the Base URL statement below (remove the leading hash sign) and fill in the absolute URL to your Drupal installation.

For your case that would be:

$base_url = 'http://mysite.local:89';


Node reference field options supplied by Views 3 work in preview, not in content I am trying to associate a node with a product type in Drupal Commerce. It is like choosing a t-shirt color, but instead they are choosing a node they published as a product attribute.
 I'm using Views to filter for only nodes published by current user, then I click the check box "Enable this field to function as an attribute field on Add to Cart forms" while editing this field type.

When I view this product display, the node reference selection box is there, but there are no selections aside from "-none-".

I have flushed the cache, multiple times; I run the cron tasks. I've done everything I thought I could do.

What am I missing?

I faced this problem. After some hours of googling, I found the solution in these issue reports.

http://drupal.org/node/1306106
http://drupal.org/node/1356006

What you basically need to do is to install the development snapshot (7.x-1.x-dev, 25 Dec 2011) of Drupal Commerce. The patch has already been committed there.


Change the order of a sort criteria in views to a custom hierarchy I have a content type called Technique that contains a title field, a description field, and a node reference called "belt level" referencing a content type called Curriculum level. The content in Curriculum level are as follows:

Yellow belt
Orange belt
Blue belt
Brown belt
Red belt
Black belt

I have created an Integer field in the Curriculum level content type called level int. I have set "yellow" to 1, "orange" to 2, "blue" to 3, "brown" to 4, "red" to 5, and "black" to 6. Now I have a view of techniques, in which I want the sort criteria to display results based on the level int field value of the content that the node reference field (called "belt level") in the technique was referencing. The problem I am running into is that I have no way of connecting the two. If I use the belt level field to try to set the sort criteria, I can only sort it alphabetically based on the title. How can I sort it based on the level int field instead?

Add a relationship Content: belt level (or whatever your node reference field is called) to the view.

Then add a new sort, choose Content: level int (or whatever the integer field is called) and under 'relationship' choose the one you just added.

That should do it.


Publish press release at a precise time My department is planning to move its website to a new platform in the next year. We are evaluating several options including Drupal and Liferay.

One of the critical requirements is that we need to publish press releases at 11:00 each day. This time has to be very precise; how precise was not specified, the specification just said at 11:00 exactly but I would interpret this as meaning within 5 seconds or less after 11:00. This precision is needed because some of the statistics we publish are "market-sensitive" and we don't want some people to get them sooner than others (the media receive them ahead of time under embargo, other people get to see them at 11:00 via other channels).

We were told that Drupal would be able to do this, but in the initial test rounds it did not work. Now we are told that Drupal does not have the capacity to do this, or at least not with the specific architecture which the central IT service has set up with the assistance of Acquia. To quote:

  As it stands now, the proposed solutions by Acquia and the central IT department, which
  are based on existing modules, will not be able to publish 'by design'
  a press release at 11:00 'sharp'.

  'By design' means that content in Drupal which is 'published' is
  identified with a simple 'flag' which is set by a 'cron job' that
  checks at regular intervals if the publish date for an item has
  passed.

  This means that in Drupal content can only be published (better:
  flagged as published) after the publish date/time and not on the
  publish date/time.

It is said that this might result in press releases appearing 5-60 seconds after 11:00.

Does this information make sense? I would have assumed that quite a few organisations have this requirement and that it would not pose a problem for Drupal? I would like to think that a clean solution can be found, as Drupal meets all our other requirements.

Notes:

Our present website uses Oracle Portal version 10.1.4. According to our website team, this platform has built-in timed publishing which works fine. That is, pages and portal items (files) are set up with a specific time to become visible, which is quite precise. We have had some cache-related issues, but none with the actual timing of the publishing.
We normally publish only 1 press release per day, occasionally 2. The press releases themselves are PDF files (ca 150 kbytes) with a 1-line title published on the front page of the website. Therefore the operations which have to happen between 11:00:00 and 11:00:05 are something like (a) do something to make the PDF file accessible (b) write new version of front page (c) manipulate cache(s) so that users actually get the new version of the front page.

I'm not aware of any architecture that can guarantee publishing of N number of items exactly at some atomic time -- as the number of items N increases; you will always have more processing time given linear execution.

It sounds like they used hook_cron and an interval check for publishing unpublished items.

Option 1 (get rid of interval cron and provide 1 specific cron task @ time)

They could easily change the architecture to use a specific cron task to check at a specific time via Cron and publish all unpublished items via a Drush task -- removing timeout errors.

This requires new, relatively easy code.

Option 2 (parrallelize option 1)

call option 1 with like ultimate_cron module and background task, with N tasks to publish approximately N content items; parallelize the publishing process to limit how long it takes.

This is new harder code, and harder to debug.

Option 3 (crazyiness here)

create an unreachable directory which can be scraped. Scrape the result of viewing the Drupal pages final result to static files; remove restricting .htaccess file or rule at 11pm based on a simple cron task. Eg, make all your dynamic content -- into static pages prior to release and make they public instantly. Your page content may not allow this approach -- but everything would be made public in an instant.

This is crazy and pretty much a rewrite of any approach and removes Drupal and largely the DB almost (but for a reason).

Whose fault is the problem

Well, no 1 party is at fault ... the requirements were vague on how many items (at most) would be published at X time and also how long a lag in publishing is allowed.


How to use Display Suite to trim whitespace from a field I have created a new content type, Plants, for my web site. One of the fields, scientific name, requires special formatting. Usually it is all italics, but sometimes a mixture of italics and non-italics such as Abelia x grandiflora 'Kaleidoscope'.

To make this work I defined the field as long text. I have tried several combinations of formats and field templates using Display Suite. The only one that seems to preserve the proper italics is Format Default and Field Template Drupal default. This preservers the proper italics, but results in an empty blank line that looks pretty crummy. See image.

Generated HTML according to Firebug:

Scientific name:&nbsp;

Abelia x grandiflora 'Kaleidoscope'

How can I eliminate the blank line or trim the white space at the end?

Sorry for the digression — but semantic markup does matter. This articles speaks well to what it is: https://boagworld.com/dev/semantic-code-what-why-how/

Your input filter (or, less possibly, your rich text editor) is adding the paragraph tag. Check out the input filter you're using for this field. If this filter has "Convert line breaks into HTML (i.e. <br> and <p>)" enabled, found here: admin/config/content/formats/<inputfiltername> — this could be adding paragraph tags. Keep in mind changing this will impact how all your fields that use this input filter are rendered. You can always create an additional input filter to suite your needs.


Exporting Panel setting to a Feature Does anyone know how to add the Panels > Settings > General > 'Make all views available as panes' checkbox to a feature?

I guessed the Strongarm box but I don't see the setting.

Yes, it's variable and it's in the Strongarm box. His name is ctools_content_all_views. It can be not set by default - then just submit your form and check again.


Moving a Drupal installation to a subdirectory Ok, I've got a Drupal install with a lot of links inside various nodes. All of these links are relative.

The problem is that if they're going to say, an image or a pdf in the /sites/default/files directory, they stop working.

Let me give an example:

There is a link in a node like this:

/sites/default/files/image1.png

www.livesite.com/sites/default/files/image1.png works

www.domain.com/devsite/sites/default/files/image1.png does not work

How do I (easily) switch the links to work in such a way? Do I have to do an .htaccess edit, or is there something in the Drupal settings for this? This is for Drupal 7

You can use the module Pathologic that acts as a filter on your text formats (Full HTML, Filtered HTML) and basically rewrites URL's which are parts of fields depending the site configuration and Pathologic settings.

You can for example set Processed URL format to Path relative to server root (/foo/bar) and for the All base paths for this site, you fill in the different website URL's.


Views Escaping Special Characters in URL I am creating a view with a list of titles that link to the relevant full article that is also displayed via a view.

The view that contains the article has a contextual filter which contains the Title and the of the views is "mysite.com/%"

So the article that is named "hello world" will be found at "mysite.com/hello-world"

However if the article has the ' special character in it for example "Children's Book" the link that I create to point at the article will be "mysite.com/Children%26#039;s-Books" which brings back an empty result.

With the Pathauto module you can strip the special Chars. Here is a quote about it (from the module's project page):

  ... automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias. This allows you to have URL aliases like /category/my-node-title instead of /node/123. The aliases are based upon a "pattern" system that uses tokens which the administrator can change.


Custom Block in custom 404 node I have a node.

This node is set to be the 'Default 404 (not found) page' in

  admin/config/system/site-information

I've got a custom block that I want to show within the node mentioned previous. I have used the 'restrict to certain pages' feature in configure block.

The problem is that it is not showing whenever I trigger a 404.

Can anyone offer a solution?

Thanks in advance.

The page you configure for a 404 code in admin/config/system/site-information is not a redirect to the new path, it reuses the original request and keeps the path. You see this in the browser, where the url remains unchanged when the custom 404 page is invoked. So you can't use the path from the 404 page to control the visibility.

See this feature request: Allow blocks to be configured to show/hide on 403/404 pages. I doubt that there will be any progress soon, because there is no activity for some time and the patch no longer applies.

You could implement the block visibility in a custom condition plugin or if you are looking for a simple solution do this in preprocess on theme level.

Or what I would prefer use a custom controller instead of a block, create a route to this controller and put this in the site settings.


How to have a proper breadcrumb path I have a problem with my breadcrumb path on my drupal 7 installation. I am using URL-Alias (Module: pathauto) and have a "blog" content type.
Now the view with all blog entries in the URL is on /blogs/ and entries are like /blogs/entryname.
Unfortunately the breadcrumb still shows: frontsite / entryname no matter what I do instead of frontsite / blogs / entryname.

Same goes for taxonomy terms. I have an overview over taxonomy terms which is on /tags/ and when I click on a certain tag on that overview, i get a view with all nodes associated with that tag and the URL is like /tags/tagname but breadcrumbs still show frontsite / tagname instead of frontsite / tags / tagname.

Thanks for any help in advance

I used a module called Smart Breadcrumb that builds breadcrumbs by using the url path and determining the title for each page. So far its Drupal 7 only.
https://www.drupal.org/project/smart_breadcrumb


Expand +/- button for taxonomy display in a page I've a taxonomy with years as its terms. It has some content within each terms. Now, I want to display the terms in a list like structure with a + as its suffix. So, when a user clicks the + button, the content within the terms will be displayed as expanded.

The taxonomy term list should appear as below

I'm using Drupal-7, tried to install Advanced book block module, but it works with drupal-6.

Thanks in advance..

You want to try to use Views Accordion:

  Views Accordion provides a display style plugin for the Views module.
  It will take the results and display them as a JQuery accordion, using
  the first field as the header for the accordion rows.

  For Drupal 7 the module integrates the jQuery UI Accordion plugin as a
  views style plugin. You can configure the options provided by the
  jQuery UI plugin.

  For Drupal 6 the module used it's own jQuery code, so a different set
  of features is available for D6.

Views can override the default taxonomy pages, or you can try to create your own grouped taxonomy listing which uses this display plugin.


Views filter group "or" operator not working I'm having an issue with the "or" operator in a view acting like an "and" operator (at least, I think that's what it's doing).
The view is meant to display articles with either "Primary Feature" checked, or one of the "Secondary Feature" options selected. The "Secondary Feature" is a list of radio options with three values: Secondary Feature 1, Secondary Feature 2, Secondary Feature 3. I've tried setting up the view a couple ways, first with a single "Secondary Feature" filter using the "is one of" operator with all three values selected (first screenshot), and second with three "Secondary Feature" filters, each using the "is one of" operator with only one value selected (second screenshot).

There are only four articles these filters apply to, one with each type of feature selected (1 Primary Feature, 1 Secondary Feature 1, 1 Secondary Feature 2, and 1 Secondary Feature 3).
From the Googling I've done it seems that checking "reduce duplicates" fixes this issue for some folks but it doesn't here. When I check "reduce duplicates" on the Primary Feature and Secondary Feature filters, it displays the article with "Primary Feature" checked, but none of the articles with "Secondary Feature" checked.
Any ideas on how to fix this?
Edited to add: This is on Drupal 7.

I got this working — I had to check "distinct" under Advanced > Query Settings, uncheck "reduce duplicates" for the Primary Feature filter, check "reduce duplicates" for the Secondary Feature filter (set up as a single filter using the "is one of" operator with all three values selected), and clear the cache. Now it's working fine.


Retain Guzzle Session During Batch Operations On a Drupal 7 site, I am using the Batch API to perform operations on many entities, one at a time. During a typical operation, the D7 site uses Guzzle to make a POST call to a Drupal 8 site. The D7 Batch callback looks like this:
function example_operation($foo, &$context) {

  // Login to Drupal 8.
  // ...

  // Make POST call to Drupal 8.
  // ...

  // Logout from Drupal 8.
  // ...

}

The D7 client uses a Guzzle client and cookie jar to authenticate with the D8 server (REST+cookies), with no issues. Great!
Now imagine running this on 100K+ entities, that's an awful lot of logging in and out unnecessarily, wasting a whole bunch of time and resources. So I figure, let's login once on the first operation, retain that session for each operation, then logout when finished. Sounds reasonable.
I thought I'd use D7 Batch API's $context['results'] array to hang onto the cookie jar and D8 rest tokens, that way each operation would have access to them, no problem, or so I thought. Take a look at this attempt in the D7 Batch callbacks:
function example_operation($foo, &$context) {

  $jar = NULL;
  $csrfToken = NULL;

  // Login to Drupal 8 (first time only)
  if (!isset($context['results']['jar'])) {

    // Login to Drupal 8.
    // ...

    // Set aside cookie jar and tokens.
    $context['results']['jar'] = $jar;
    $context['results']['csrf_token'] = $csrfToken;
    $context['results']['logout_token'] = $logoutToken;

  }
  else {

    // We've already logged in, grab the cookie jar and token.
    $jar = $context['results']['jar'];
    $csrfToken = $context['results']['csrf_token'];

  }

  // Make POST call to Drupal 8 (using cookie jar and token).
  // ...

}

function example_finished($success, $results, $operations) {

  // Pull out cookie jar and tokens.
  $jar = $results['jar'];
  $csrfToken = $results['csrf_token'];
  $logoutToken = $results['logout_token'];

  // Logout from Drupal 8 (using cookie jar and tokens)
  // ...

}

This approach works fine on the first operation only. Then on the second operation, the tokens are available in $context['results'] as expected, but the cookie jar always comes through as a __PHP_Incomplete_Class Object, and then if I try using it with the Guzzle client a cookies must be an instance of GuzzleHttp\Cookie\CookieJarInterface is thrown.
How do you retain a Guzzle session between batch operations in Drupal 7?

Perhaps $context['results'] cannot contain "complex" class/objects like a Guzzle cookie jar
I tried using the cookies request option when instantiating the Guzzle client, but that breaks any authenticated POST calls (including the first operation)
Maybe the way D7's batch http requests work, it starts confusing the client/cookies/etc

Between two batch runs, the data is saved in the database serialized. Before the second batch run, the data is taken from the database and unserialized. __PHP_Incomplete_Class Object tell us that, at the moment the data is unserializes, no GuzzleHttp\Cookie\CookieJarInterface class is available, and objects of that class cannot be unserialized.
To retain a Guzzle session between batch runs, you can save the data as  array.
$context['results']['jar'] = $jar->toArray();

To get back the data, you can then use the following code.
$jar = CookieJar::fromArray($context['results']['jar'], 'domain.com');

If you save an object in $context, as in your case now, it would be available through all iterations at one batch run, but at the next run, an error is thrown.
If you still prefer to keep objects during iterations instead of arrays, to avoid errors you should check if $context['results']['jar'] is an instance of GuzzleHttp\Cookie\CookieJarInterface.


Grant permission for custom role from hook_install programmatically Drupal Version: 8.5.5

Need to assign permission to existing role during module installation:
Am using below code in hook_install:

use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
function hook_install() {

 $permission = 'test permission';
    $tester_rid = RoleInterface::TESTER;

    if ('tester' == Role::load($tester_rid)) {
      $tester_role->grantPermission($permission);
      $tester_role->save();
    }
}

Above grant permission is not working.
I have also tried with

user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
      'my custom permission',
    ));
user_role_grant_permissions(RoleInterface::TESTER, array(
      'my custom permission',
    ));

Above hook_install is not working.

Pls help

Try this:

use Drupal\user\Entity\Role;

function mymodule_install() {
  $role_object = Role::load('my custom role name');
  $role_object->grantPermission('my custom permission name');
  $role_object->save();
}


Changing the text "Add to Comment" in a given content type I have a pretty frustrating problem going on here. I have been reading the answers over at this question:
How to change "add to comment" in comment form?.

But unfortunately neither of the suggested solutions worked for me. I tried with the following code in template.php:

function custom_node_view_alter(&$build) {
  if ($build['#node']->type == 'bar') {  //extra check for content type (optional)
    $build['links']['comment']['#links']['comment-add']['title'] = t('Add new review');
  }
  kpr($build);
  dsm($build['#node']->type == 'bar'); // true
}

I've also tried adding comment-wrapper-<my content type>.tpl.php to sites/all/themes/custom/templates but its not picking up either of these changes.

I've flushed all my caches so many times I'm getting RSI, but it's not showing the change. Am I missing something simple here?

You missed a key ['title'] in the array.

$build['links']['comment']['#links']['comment-add']['title'] = t('Add new review');

Make sure you follow the naming conventions while creating a custom module, or if you are doing it from theme replace the custom from custom_node_view_alter with the theme name (e.g. garland_node_view_alter for garland theme).

You can eliminate the extra check (for a while) of the content type for a while to check if the solution is working.


How can I monitor for bot accounts accessing drupal paths without permission? On my site, users do not have permission to create content.

However, looking through the watchdog logs, I found several accounts that were attempting to access

node/add/article
node/add/page

and so on.  In this case, all the accounts were registered from @ad.drupaler.org, so it was easy to eliminate them, but in case the same thing happens from a variety of domains in the future, I'd like to set up some way to alert myself that users are attempting to access these paths.

I am thinking about using the Rules module to do this, but I was wondering if there was already a "best practice" for this kind of thing-- since there are automated bots to attack Drupal sites, there might be an automated way to fight back.

You could try adding bot protection to your registration form,

e.g with reCaptcha

Other worthwhile things are blocking the bots in your webserver,

e.g nginx

https://github.com/mariusv/nginx-badbot-blocker or
https://github.com/oohnoitz/nginx-blacklist/blob/master/blacklist.conf

Custom options include using the Flood control API,

e.g flood_is_allowed and flood_register_event with ip blocking (e.g system_ip_blocking_form_submit) or user_block_user_action on the node/add or 403 page.


Getting redirected to the referenced node instead of the created node after node save I have two organic nodetypes.
One of the types has a prepopulated reference field referencing the other nodetype.
This means that when i create a node of OG type A it will automatically reference to OG type B.

My problem however is that when i save nodetype A it i get redirected to nodetype B.

I am looking for a way to (using rules ) redirect to nodetype A (the node just created, which is the normal workflow).

Help appreciated..

As a workaround i created a rule (rules module) where i redirected the user upon saving new content.
In my action i used this piece of code:

global $user;
$uid = $user->uid;
$result = db_query ( "SELECT * FROM {og_membership}
WHERE etid = :uid
and entity_type = 'user'
order by gid DESC", array (':uid' => $uid ) );

Then i used this for my page redirect:

<?php print "node/".$_SESSION['ses_user_group_gid'];  ?>


How to see Database logs in Devel module I have installed Devel module in Drupal 7. I am able to see logs of error in each page I visit (when I am logged as admin), but, however, have not been able to see the database logs except in the Admin GUI, in the layer windows.

When I close the Admin GUI (without logging out) and visit other pages of my site, I cannot see the database logs. I installed Devel in other project long time ago, and I would dare to say that I saw these database logs in every page.

What is the recommended config: see all errors, and which template to use?

You need to give Devel permissions to the user from which, you are logged in, and want to view logs.Go to People >> Permissions and give Devel permissions to the role you want to.

However, giving Devel permissions to anonymous user is a security risk. So, avoid that.


Using the same hook more than one times I have several custom modules and each one of them serves different functionalities. Each module contains from few to many hook implementations and inevitably there are cases where I have to use a hook more than one times between the modules, hook_menu for example.
What are the downsides (if any) of using the same hooks more than one times in different modules ? Is that recommended ? What about performance?
Thanks!

That's exactly how it is supposed to work. Hooks are functions defined by Drupal for you to add functionality to the system through your modules. Hooks are like open doors for you to add things.

From Drupal's documentation:

  To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.

Obviously, the more hooks defined in different modules, performance gets hit. But you can't avoid that. You shouldn't stop adding functionality to your modules through hooks because of this.


Can 'terms' be shared across 'vocabularies'? I think I might have a fundamental misunderstanding of how taxonomy works in Drupal.

I've set up some vocabularies, such as 'accommodation', 'things to do' and 'eating out'. Within those, I've added parent terms 'accommodation types' and 'ratings' for accommodation, 'nationality' and 'suitable for' for eating out and so on.

Both vocabularies share some common features, though, such as 'location'. I set up 'location' within the 'accommodation' vocabulary first and then tried to make it available to 'eating out' by setting it as a parent, but I could only see other terms within the vocabulary.

What is the best way for me to allow each vocabulary to share a location without manually recreating and updating a 'location' term in each vocabulary (which surely must be the incorrect way of doing what I'm trying to achieve?)?

It sounds like you are using vocabularies where you could be using nodes.

So a node called the 'grand hotel' would have a rating, it may be suitable for some types of people and may also have a location.

So you can create node type 'accommodation' which can use the vocabulary 'accommodation types', 'suitable for' and 'location'.

You could have a node type 'eating out' which can use the vocabulary 'cuisine type' but share 'suitable for' and 'location'

So each cafe or hotel could be a node of the respective type, but could appear in the search results for 'London' for example.


How do I use it only in the frontend theme? Using the jQuery Update module, I set version 1.8. This version "broke" the views UI in the Admin theme; it seems that the AJAX calls in the Views UI work only with jquery 1.5.

How can I fix it?

With jQuery Update 7.x-3.0-alpha2 and later, there is a setting that allows to change the jQuery used for a specific theme; you can select:

The site default version (set with the jQuery Update module)
The version that comes with Drupal
Any version supported by the jQuery Update module


sql-dump failing when run as cron I have a shell script that executes drush sql-dump, compresses the result and then sends it to a backup server.

It works fine when run from the command line as root but it is failing silently and dispatching an empty file when run as part of a scheduled cron job.

This script has worked previously for me on another website as a cronjob and so I am somewhat confused what would be wrong now.

I work with Drupal 8.3.1 and Drush Version 8.1.11.

Any suggestions?

After much frustration I have resolved the issue and will post the answer in case it is of use.

Cron seems to not always have access to the same PATH information as when a normal user - or even root - runs a drush command in a command line.

The solution came from comment #7 in this drush thread.

You need the path to drush. You can find this with the command:

which drush

In my case it was /usr/local/bin/drush

Then add the path info to the top of the shell script.

export PATH=$PATH:/usr/local/bin

And then it worked perfectly.

Additionally, it appears if your local mail is not set up correctly cron discards output from scripts which is why the drush: command not found error was not turning up in logs. To make sure you get logs from cron configure it for local mail. See this post.


Dependent multiple selection drop down in drupal form - illegal choice error I'm new to Drupal , in my project I have 2 multiple select drop down box. I don't know how to do dependent multi select drop down action in drupal form alter function using ajax.

Single selection dependent drop down selection is working. But when i tried the same in case of 2 multi select dependent drop down i couldn't find any solution . On multi select error "An illegal choice has been detected. Please contact the site administrator." is shown.

Please help me how to use 2 multi select dependent drop down in drupal.

Here is my code : here "field_department" is the 1st multi select drop down. "field_policy_categories" is the 2nd muti select drop down. i want 2nd drop down values corresponding to 1st field's multi selected options.

function policy_node_form(){
$form['field_department'] = array(
    '#type' => 'select',
    '#title' => 'Department',
    '#multiple' => TRUE,
    '#options' => array(
        '' => t('-Select-'),
        '1444' => t('department1'),
        '1445' => t('department2'),
        '1446' => t('department3'),
        '1447' => t('department4'),
        '1448' => t('department5'),
        '1449' => t('department6')
        )
);
$form['field_policy_categories'] = array(
    '#type' => 'select',
    '#title' => 'Categories',
     '#multiple' => TRUE,
    '#options' => array()
);

}
function page_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'policy_node_form') {
$category = array();
$category[''] = '- None -';

$form['field_department']['und']['#ajax'] = array(
    'wrapper' => 'policy_category_list',
    'callback' => 'ajax_policy_category_callback',
    'method' => 'replace',
);

$form['field_policy_categories']['#validated'] = TRUE;
$form['field_file_upload']['#validated'] = TRUE;

if (isset($form_state['values']['field_department'])) {

    $array_departments = array($form_state['values']['field_department']['und']['0']['tid']);

    $query = db_select('field_data_field_department', 'f');
    $query->join('taxonomy_term_data', 't', 'f.entity_id = t.tid');
    $query->join('taxonomy_term_hierarchy', 'h', 't.tid = h.tid');

    $query->condition('f.entity_type', 'taxonomy_term', '=');
    $query->condition('f.bundle', 'policy_categories', '=');
    $query->condition('f.field_department_tid', $array_departments, 'IN');
    $query->condition('h.parent', 0, '=');
    $query->fields('f');
    $query->fields('t');
    $query->fields('h');
    $result = $query->execute();

    $policy_vid = taxonomy_vocabulary_machine_name_load('policy_categories')->vid;

    $category[''] = '- None -';

    foreach ($result as $record) {
        $parent_arr = taxonomy_get_parents_all($record->tid);
        $parent_level = sizeof($parent_arr);
        $parent_level--;
        $parent_tid = $parent_arr[$parent_level]->tid;
        $parent_name = $parent_arr[$parent_level]->name;
        $category[$parent_tid] = $parent_name;

        $policy_children_arr = taxonomy_get_tree($policy_vid, $parent_tid);
        foreach ($policy_children_arr as $key => $policy_children) {
            $depth = '';
            for ($i = $policy_children->depth; $i >= 0; $i--)
                $depth .= '--';
            $category[$policy_children->tid] = $depth . $policy_children->name;
        }
    }

    $form['field_policy_categories']['und']['#options'] = $category;
} else {

    $form['field_policy_categories']['und']['#options'] = $category;
}

$form['field_policy_categories']['#prefix'] = '
';
$form['field_policy_categories']['#suffix'] = '
';

$form['#validate'][] = 'form_validate_policy_add';
}
}
function ajax_policy_category_callback($form, &$form_state) {

return $form['field_policy_categories'];
}

To try take your second $form['field_policy_categories']['und']['#options'] to individual function instead of inside hook_form_alter().

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

  if ($form_id == 'policy_node_form') {
    $form['field_department']['und']['#ajax'] = array(
      'wrapper' => 'policy_category_list',
      'callback' => 'ajax_policy_category_callback',
      'method' => 'replace',
  );

  $form['field_policy_categories']['#validated'] = TRUE;
  $form['field_file_upload']['#validated'] = TRUE;

  $form['field_policy_categories']['und']['#options'] = categories_options($form_state);

  $form['field_policy_categories']['#prefix'] = '
';
  $form['field_policy_categories']['#suffix'] = '
';

  $form['#validate'][] = 'form_validate_policy_add';
}

function categories_options($form_state) {
  // option go to here
}

.


Up-to-date lineup of WYSIWYG editors? I've been browsing through modules at drupal.org, in search for a Drupal7-savvy WYSIWYG editor. I looked into this (horribly outdated) lineup. It looks like the only actively maintained editor at this moment is CKEditor. Has anyone come across any other solution? Even if not wrapped into module, perhaps it would be easy to integrate into admin-side.
I'm obviously looking for the least expensive option. Ability to define custom templates and integration with Media module - would be a plus.

The reason you see so many abandoned projects is that instead of maintaining multiple separate modules for individual packages, work has gone into making those packages compatible with the WYSIWYG API module. By abstracting the editor library from the editing interface, you gain the ability to use different editors for different input formats, and it becomes quite simple to swap one out for another.

According to the project page, WYSIWYG API has direct integration with

CKEditor
FCKeditor
jWysiwyg
markItUp
NicEdit
openWYSIWYG
TinyMCE
Whizzywig
WYMeditor
YUI editor

as well as a whole host of useful plugins.


How to print login form on page How to print login form with destination url on a page using code in drupal 7  ?

You can use below code to print login form block

<?php
print(drupal_render(drupal_get_form('user_login_block')));
?>

For login redirect to destination you can use Login Destination module

Project page says

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.


Add autoupload property after page load using plupload In a form I have added a field for images, set the file source to "Advanced upload widget (Plupload)" ( all other checkboxes are unchecked ) and I get the interface. I want to make it autoupload images after being drag and droped or selected via the add image link. The form is loaded in a custom created page using a personal made module. I tried to set

$form['field_image_article1']['#autoupload']=TRUE

in myModule_form_alter and also called a myModule_after_build. None of the situations work and I can't figure out where or better sayd when should I set this value. Here is the code for the module :

function add_new_article_menu() {
  $items['addAnnouncement'] = array(
  'title' => 'Adauga anunt',
  'page callback' => 'add_new_article_simple_page',
  'access callback' => TRUE,
  );
return $items;
}

function add_new_article_simple_page() {
form_load_include($form_state, 'inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'announcement';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form('announcement_node_form', $node_form);
return $form;
}
function add_new_article_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='announcement_node_form'){
    $form['#after_build'][]='add_new_article_after_build';
    return $form;
  }
}
function add_new_article_after_build($form, &$form_state) {
  $form['field_image_article1']['#autoupload']=TRUE;
  return $form;
}

Modules installed for plupload : FileField Sources Plupload,  File Field Sources , Plupload integration module

Any help is most appreciated.

Drupal's plupload module does not support '#autoupload'. Or at least that's what I experienced. I wrote my own behavior for this:

(function($) {

Drupal.plupload = Drupal.plupload || {};

/**
 * Attaches the Plupload behavior to each Plupload form element.
 */
Drupal.behaviors.mymodule_plupload = {
  attach: function (context, settings) {
    $(".plupload-element", context).once('mymodule-plupload-init', function () {
      var uploader = $(this).pluploadQueue();
      if(uploader !== undefined) {
        uploader.bind('FilesAdded', function(up, files) {
          $('.form-submit').prop( "disabled", true );
          uploader.start();
        });
        uploader.bind('UploadComplete', function() {
          if (uploader.files.length == (uploader.total.uploaded + uploader.total.failed)) {
            // If nothing is being uploaded right now:
            $('.form-submit').prop( "disabled", false );
          }
        });
      }
    });
  }
};

})(jQuery);

I based it on codes and hints from the Internet, but I can't recall exact sources. I'll be happy to fix that and add reference links if someone recognizes parts of this.


How can I allow a person to create multiple orders at once, for both themselves and others? I have a site that offers in-person trainings and I'm currently using CRM Core to track registrations.  That is working just fine, but I am having trouble coming up with a flexible way to pay for these registrations online.

Example use case:

I have a group who will be taking a class together, say 5 people.  I'd like to allow a single person (the person organizing the group) be able to register all 5 people (already possible), but then select which of these registrations to pay for, creating separate orders for those the organizer doesn't want to pay for.

Say I am registering myself, my spouse, my kid, and 2 friends.  Each registration should create a line item, but I want the first 3 (me, spouse, kid) to be on one order I'll pay for immediately, with the other two becoming separate orders each owned by the other students.

Once I figure this out, it should be easy to then send emails to the other two students letting each know a new account has been created for them w/instructions on how to log in and pay for their registration.

This seems like something others would have thought about before, but I can't find any info on how to make it happen.  Any suggestions?

Honestly, this sounds like a place where your best option will be custom code. The only thing I could see you doing without custom code is creating two variants for your event registration products, one that is free as a "reservation" and one that is the full price as an actual registration. This means the line items would be present on the order until the customer completes checkout, at which point you could process the order to split it up and then send out e-mail notifications as needed. To capture the e-mail address information, I'd add a field to your line item type to collect it as part of the Add to Cart form, allowing you to loop over the line items later and create user accounts / generate e-mails on a line-by-line basis. The main challenge there will be grouping multiple "reservations" into a single order via a simple rules loop... at the end of the day, this really smells like an ideal use case for custom code.


How to get date field object value? datetime object is

[start_time] => Array
                (
                    [0] => Array
                        (
                            [value] => Drupal\Core\Datetime\DrupalDateTime Object
                                (
                                    [formatTranslationCache:protected] =>
                                    [inputTimeRaw:protected] =>
                                    [inputTimeAdjusted:protected] =>
                                    [inputTimeZoneRaw:protected] =>
                                    [inputTimeZoneAdjusted:protected] =>
                                    [inputFormatRaw:protected] =>
                                    [inputFormatAdjusted:protected] =>
                                    [langcode:protected] => en
                                    [errors:protected] => Array
                                        (
                                        )

                                    [dateTimeObject:protected] => DateTime Object
                                        (
                                            [date] => 2017-03-17 02:04:03.000000
                                            [timezone_type] => 3
                                            [timezone] => UTC
                                        )

                                    [stringTranslation:protected] =>
                                )

How to get [date] => 2017-03-17 02:04:03.000000 ??????

I have tried using print_r($ruleContentNew[0]['start_time'][0]['value']->getValue());die;
But it is giving me error.

Try

  $node->get('start_time')->getValue();

This actually gives you an array, if you inspect/dump the array, then you'll see that you can get the value like this.

$node->get('start_time')->getValue()[0]['value'];

Alternatively, you can simply use $node->start_time->value;

Note: I am using the default Date field from Core and assuming you're using a Node. Hence the $node, and also worth noting, usually your date machine name will be field_something. Which makes me believe that OPer is using some contrib or custom module.

If you're using some contrib module that allows you to have start and end times on your date field, probably will require a diff solution.


Any way to alter script tag for some javascript and add custom attributes? In order to work with Cloudflare's Rocket Loader service, certain scripts need to have their script tags updated with the cf-async="false" attribute like so:

<script type="text/javascript" cf-async="false">

Specifically, I need to add this attribute to the Drupal settings script tag, that gets added inline at the top of every page.

My first thought was to do this via hook_js_alter(), like:

function custom_helper_js_alter(&$javascript) {
  $javascript['settings']['cf-async'] = 'false';
}

But it doesn't seem to be possible to add custom attribute tags via this function. So my question is, is there any way at all to do what I want without hacking core?

There is, but it's not pretty. The markup produced by drupal_get_js() is pretty closed off; it uses theme_html_tag(), but what it provides for variables means identifying the Drupal.settings script is a pain.

This is about as good as you'll get. In custom module:

function MYMODULE_preprocess_html_tag(&$vars) {
  if ($vars['element']['#tag'] == 'script' && strpos($vars['element']['#value'], 'jQuery.extend(Drupal.settings') === 0) {
    $vars['element']['#attributes']['cf-async'] = 'false';
  }
}

As you rightly mentioned through the comments you could also attack it at the theme override level instead of the module level. In template.php:

function MYTHEME_preprocess_html_tag(&$variables) {
  if ($variables['element']['#tag'] == 'script' && strpos($variables['element']['#value'], 'jQuery.extend(Drupal.settings') === 0) {
    $variables['element']['#attributes']['cf-async'] = 'false';
  }
}

If you have modules that mess with JavaScript (e.g. LabJS), the string match will be slightly different.


Theme styles and scripts not printing I'm having a problem in my html.html.twig file where the styles and scripts variables are not printing anything, and when I debug with dump:

{{ dump(styles) }}
{{ dump(scripts) }}

Both variables are empty and 'NULL' is returned.

Any suggestions on how to debug this further?

Those variables have been changed in beta16/RC1.

See HTML template head, scripts, styles and scripts_bottom replaced with placeholder_token:

Before

{{ head }}
{{ styles }}
{{ scripts }}
{{ scripts_bottom }}

After

<head-placeholder token="{{ placeholder_token|raw }}">
<css-placeholder token="{{ placeholder_token|raw }}">
<js-placeholder token="{{ placeholder_token|raw }}">
<js-bottom-placeholder token="{{ placeholder_token|raw }}">

The markup should be stable now with RC1, but when you're having trouble with a custom template, always compare it with the core default markup in the module providing it and/or the classy theme.


Some errors when I save my content I have some errors when I try to validate my content, I add a lot a modules at the same time, and I don't know witch module causes this error. I uninstalled some of them without success, Is it some explanation in the following errors for the specialists you are?

Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1108 dans /var/www/V1/modules/node/node.module).

Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1134 dans /var/www/V1/modules/node/node.module).

Notice : Undefined property: stdClass::$is_new dans node_save() (ligne 1140 dans /var/www/V1/modules/node/node.module).

PDOException : SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'nid' cannot be null: INSERT INTO {location_instance} (nid, vid, uid, genid, lid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => [:db_insert_placeholder_2] => 0 [:db_insert_placeholder_3] => cck:field_endroit: [:db_insert_placeholder_4] => 9 ) dans location_save_locations() (ligne 1132 dans /var/www/V1/modules/location/location.module).

The error is related to the location module. Uninstalling that module will remove the errors.


How can I override the autocomplete.js file while developing a module? I want to override the default tags field wherever it is used. After looking through a few files, I figured that I should override drupal/misc/autocomplete.js and the Drupal.jsAC object.

Is it correct to override this file, since I only want to work with tags field?
How is it possible to create a module which overrides this file?

As long as all you want to do is achievable by using form_alter() and #autocomplete_path, you should avoid modifying core's JavaScript files. To address specific field widget, use hook_field_widget_alter().

If you need to alter what JavaScript is doing, use corresponding behaviours, as described on StackOverflow.


Subtract one field from another (Quiz, Getting difference between revisions) I am using the evaluation quiz module. Users fill out the question and (not using the score that is calculated by the quix module) they are given a score by giving each of their answers points which are then totaled.

I'm wondering is there an easy way to subtract one revision of the users answer from another revision to get the difference.

I have no problem getting the results from each revision but just dont know how to subtract the second to latest revision from the latest revision.

I could not find a module which does the same, but you can achieve this by custom codes.Not the exact codes but still covers the major things

  // get all revisions for a node
  // this function returns array of revision in order of revisions are created,with the latest revision at the top and last revision as the next array element
  $get_revisions = array_values(node_revision_list(node_load($node_id))));
  if(count($get_revisions) > 1) {
    $current_node_version = $get_revisions[0]->vid;
    $last_node_version = $get_revisions[1]->vid;
  } else {
    // No differnece,since there is only one version.
  }

  //Now load the nodes with the versions
  $current_node = node_load($node_id,$latest_node_version);
  $last_node = node_load($node_id,$last_node_version);

  // Once you have loaded nodes you can easily do the custom calculations,something like
  $field_1_diff = $current_node->field_1_diff... - $last_node->field_1_diff...


Rearrange/remove content UI I've seen this on Blackboard and other sites before. How in drupal could have user interaction(UI) with content on each node?

The user should be able to:

-rearrange content on each node with out being a administrator or logged in.
-remove view of content from node and re-populate with more content. The content removed will not be deleted but removed from user view.

I know of panels and I have created panels, but I do not see any UI that allows me to do what I would like to above with panels.

Some help please! Image of what I am talking about. see how user can drag and drop content

Take a look at Homebox module.

  Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.


How to add edit button in content type? I am new to drupal and I was adding a button for editing the data from database.
but when I am adding edit button using add content type then this error message is showing to me.Please help me to guide how to add buttons and relate them to database.

You actually need to add the edit button in a node. well, first you need to get the node ID, create template.php and add this function :

function YOUR-THEME_preprocess_node(&$variables)
{
    if (isset($variables['node']))
    {
         $variables['id'] = $variables['node']->nid;
    }
}

in this way the node id will be saved in the $id variable inside the node template file. if you want to use the default node.tpl.php copy this file from modules/system/node.tpl.php. now add this code where ever you want in the new copied node.tpl.php

<?php
    global $base_url;
?>
<a href="<?php print $base_url;?>/node/<?php print $id;?>/edit">Edit the Content! </a>

if you suggest any theme hook (theme the node page) no difference does it make, use the above code, the link always will be

"<?php print $base_url;?>/node/<?php print $id;?>/edit"

Good luck


How do I figure out what module is using drupal_set_message()? Some module is using drupal_set_message() to show a message at the top of the administrative pages.

I would like to figure out from where it is coming from. Is there any way to determine what module is creating it? How do I remove it?

Are there any messages in your error log? You should be able to see a module name there.

drupal_set_message has no parameter to add a module name to the message so there is no straight forward method of finding the module. You could copy the string from the message and search in the translation page (if you have the locale module enabled. Or throw the string at Google and see what you find. That usually helps!


Use date as Views Contextual filters I need to retrieve all nodes where updated date is between date A and date B.
I had a look at contextual filters and they seem to allow only the equality operator (SELECT where date = X) whereas I need greater than and lower than operators (SELECT where date > X).

Any idea to achieve this? Any help would be much appreciated.
Thanks!

No need adition module but date module.
go to your views add a filter with type date choose Date: Date (node_revision) pass Configure extra settings for filter criterion Date: Date (node_revision) with  your optionals ,and in Configure filter criterion: Date: Date (node_revision) select Is between option.
If you want expose your filter check  Expose this filter to visitors, to allow them to change it


How to change the local code Link? I am using the Aqcuia Dev Desktop where near to the local code label is written the following link: ( C:\Users\Wessam\DrupalSites\devdesktop\drupal-7.34 )
lets say that i want to move my drupal localhost site files & folders to another folder so it will be under the following link: ( C:\Users\Wessam\AllSites\CompanyName ) so the link near to the local code label should be changed also...
How to do the mentioned above?

1)

Follow the Path below:

C:\Program Files (x86)\DevDesktop\AcquiaDevDesktop\datamodel.xml

2)

Open the " datamodel.xml " using the Notepad++ or any other similar programming language editor program

3)

Edit the Link written within:

 HERE HERE HERE

 HERE HERE HERE

to any link required by you .


How to avoid custom module hook_node_presave being overriden by a profile module node_presave I'm willing to override a value before it get saved in database.
The same value is already overriden by commons_trusted_contacts module using hook_node_presave.

So my custom module hook_node_presave get overriden by commons_trusted_contacts_node_presave.
How do I let drupal know that he need to run my custom hook_node_presave after other hook node presave or to not override that single field value.

Below line being overridden :

$wrapper->group_content_access->set(OG_CONTENT_ACCESS_PUBLIC);

The order of a module's hook invocation is determined by its weight. In Drupal 7 this set in the weight column in the system table.

This can be updated through SQL query by setting your module's weight to the heaviest (last) value.

# Update with the appropriate values for your install
drush sqlq "UPDATE {system} SET weight = [your_preferred_weight] WHERE type = 'module' AND name = '[your_module_name]"'

Or using a module like Modules weight if you need a UI.

See the Drupal.org documentation for more info..


How to add a filter in view with list of values I have a content type which has a Number(Integer) field.

I created a view. I would like to expose the price field as a filter to the public like the following with a list of price range.

In view > filter criteria, I added the price field. How to add the list of values with price range?

To add a list of ranges you can use the Grouped filters option with Widget Type: Select, instead of Single filter.

Then you can add your groups below. Each group becomes an option in your select list.


Block is displayed on page even though no region is selected, how is this possible? I am fairly new to drupal, while doing some maintenance I came across a situation that I don't understand

A block, which is defined inside a view has no region selected, yet it appears on pages determined by the "Only the listed pages" option below

It appears in a specific region, an <aside> named as "region-sidebar-second"

I'm unable to find anywhere in admin, or in the code to determine that is the region where this block should appear.

What could I be missing?

This happened to me once, turns out it was added through the context module. So check if your site has it.

Else, could have been added through the Panels module or the Display Suite module. So check if you have any of these modules also.

If you have non of the above modules are installed then maybe it was added via a template file. So check your template files in your theme's template folder.

Last but not least, perhaps through a preprocess function? check your template.php file if on D7 or themename.theme file if you're on D8.

Good luck detective.


Printing a function on a content type page? So if I have a custom function with a DB query within template.php such as

function innovista_get_page_children() {

 $result = db_query("SELECT link_path FROM {menu_links}");
 return $result;

}

and I have a content type specific template page, then how do I echo the results in the template file?

I tried this:

<?php
$results = innovista_get_page_children();
foreach($results as $result){
    print $result;
}
?>

I get the following error

  Recoverable fatal error: Object of class stdClass could not be
  converted to string in include() (line 83 of
  /var/www/vhosts/vidanlawnes.co.uk/innovista2/sites/all/themes/innovista/node--level_1.tpl.php).

If I remove print $result; and replace with print 'hello'... e.g

<?php
$results = innovista_get_page_children();
foreach($results as $result){
//print $result;
print 'hello ';
}
?>

It echoes hello out multiple times, so the query is providing results, but I can't seem to print them as $result. Any ideas?

Thanks for your time

The error message itself is clear I think. You are trying to print an object as a string.
otherwise, your query seems correct.

function innovista_get_page_children() {

 $result = db_query("SELECT link_path FROM {menu_links}");
 return $result;

}

<?php
$results = innovista_get_page_children();
print '
';
foreach($results as $result){
    print_r($result);
}
print '
';
?>

Now you will see a formatted variable information of each $result.
it will look like

stdClass Object (
  [link_path] => admin/structure/views
)

So when you print the results, it will be like,

<?php
    $results = innovista_get_page_children();
    foreach($results as $result){
      print $result->link_path;
      print '
';
    }
?>

However, keep in mind that it's never OK to print link paths or database queries like this. It will cause huge performance problems and will arise security problems.
Try to use url() and/or l() functions for links (suggested it because you seem to make a link).
Also, in most cases, there is a function for core/contrib modules to retrive data.


Full Html Text format (and wysiwyg) show only for administrator role I use Wysiwyg module with CKeditor since months and all worked well.
Wysiwyg module is linekd only wit my input-format "Full html" and this is granted to use to my role "Editor". it worked very good.

Unfortunately, since the last Drupal core update i have a big problem:

it seems that only Administrator users can use the FULL HTML text format, my other roles don't see that format and so also the Wysiwyg module doesn't appear.

I've done many checks and tests (permissions, cache etc) but the only thing i discovered is that is a problem of permission on the TEXT FORMAT and not on the wysiwyg module...
The proof is that if i apply wysiwyg to the "Plain text" format, also the EDITOR role see the wysiwig editor.

how can i fix this problem? i also tried to remove and re-set the permissions for the role to use the "Full HTML" format

I've got the same issue because of js error 'once is not defined'. To fix an error I've added to my html.tpl.php:

<?php print $scripts; ?>
<script src="/misc/jquery.once.js"></script>


taxonomy CSV import in linux taxonomy CSV import
  How do use taxonomy CSV import the Chinese characters in linux ,Now I import all is empty
Thank you for your help me to answer

you can use this module to import taxnonomy terms with any translations Taxonomy CSV import/export


How to access date value from a datelist form element for validation? I have a simple form element using datelist as the type. I need to validate this to make sure the date is in the future. But I cannot work out how to access the date itself in the validation method.

Form:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['date_field'] = array(
    '#title' => $this->t('Expiry'),
    '#type' => 'datelist',
    '#date_part_order' => array('month', 'year'),
    '#date_year_range' => '2017:2027',
    '#date_increment' => 1
  );

  return $form;
}

Validation:

public function validateForm(array &$form, FormStateInterface $form_state) {

  $date_input = $form_state->getValue('date_field');

  if(strtotime(date($date_input)) < strtotime(date('now'))) {
    $form_state->setErrorByName('date_field', $this->t('The date must be in the future.'));
  }
}

From the above, $date_input currently returns an object (see below). Essentially, I want to access $date_input->dateTimeObject->date; but doing exactly that will return a fatal error.

  Fatal error: Cannot access protected property
  Drupal\Core\Datetime\DrupalDateTime::$dateTimeObject

$date_input object:

stdClass Object
(
    [__CLASS__] => Drupal\Core\Datetime\DrupalDateTime
    [formatTranslationCache] =>
    [dateParts] => Array
        (
            [0] => year
            [1] => month
            [2] => day
            [3] => hour
            [4] => minute
            [5] => second
        )

    [inputTimeRaw] =>
    [inputTimeAdjusted] =>
    [inputTimeZoneRaw] =>
    [inputTimeZoneAdjusted] =>
    [inputFormatRaw] =>
    [inputFormatAdjusted] =>
    [langcode] => en
    [errors] => Array
        (
        )

    [dateTimeObject] => stdClass Object
        (
            [__CLASS__] => DateTime
            [date] => 2027-12-01T00:00:00+11:00
            [timezone] => Australia/Sydney
        )

    [stringTranslation] =>
)

I could do something like:

$form_state->getValue('date_field')->format('d m Y');

But I suspect there is a better way?

Yes, to compare the date it's better to use the unix timestamp. You can get it by using the method getTimeStamp() and compare it to the current date:

      $value = $form_state->getValue('date_field');
      if ($value->getTimeStamp() > REQUEST_TIME) {
        drupal_set_message('Time is in the future');
      }


How can I set an API key, which contains equal sign set at Drush site-install? When I use the drush site-install command and a form value contains the equal sign (an API key for example), then Drush cuts the value at the equal sign. For example:

  drush si -y profile_name
       --account-name=...
       --account-pass=...
       --db-url=mysql:...
       form_name.field_name="e+gklgfssdk=jgfsfg/11iXP6VJM0MjDpRk2MEKyc="

The value of the form_name.field_name at install will be "e+gklgfssdk", the last characters are missing, Drush cuts the value at the equal sign. This is a bug? Or how can I set the correct value?

It looks like there isn't a way to do this, actually. The site installation code splits the string on the '=' and doesn't do any unescaping nor does it look like it would support this. I haven't tried escape()ing the value and then passing it in (so that = would become %3D) but unless you were expecting an escaped value this would probably still not work.

Depending on what you're setting, your best bet might be to do some sort of drush variable-set and set the values after the site install completes.


How to redirect on User based? I am new to drupal So
I want to redirect the user based on login
Say,
if there is an Anonymous user, he will be redirected to specific page,
and if is an Authorized user along with login id and password, then he will be redirected to other specific page using script

Use Rules module and create redirect rules.

Project page says

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules).

Example use cases

Build flexible content publishing workflows changes
Send customized mails to notify your users about important
Create custom redirections, system messages, breadcrumbs, ...
Build an eCommerce store using Drupal Commerce And many more...


How to run drush make on remote using relative path? I'm writing a script where I'd like to run .make file, but it fails with the following error:

$ drush @remote.test make --no-core profiles/foo/contrib.make --yes
Calling proc_open(ssh drush@remote 'COLUMNS=278 drush  --verbose --yes --root=/var/www  make profiles/foo/contrib.make   --no-core 2>&1' 2>&1);
file_get_contents(profiles/foo/contrib.make): failed to open stream: No such file or directory make.utilities.inc:487

despite the file exists. I don't want to hardcode absolute path, as I'd like to use the same command for other remotes.

The command fails, because current directory of drush is set to HOME folder, instead of webroot (which is correctly passed internally via --root). This example could be related to issue where drush shell alias is downloading the project into wrong directory.

So the question is: How I can use drush make to execute .make file on remote host using relative path? As it seems to work fine on local.

I'm using drush 7.0-dev on local and remote.

For workaround, the following command should work:

$ drush @remote.test make --no-core $(drush @remote.test dd)/profiles/foo/contrib.make

Command drush dd will return the webroot path and pass it to outer command.


How to minify Javascript in D7 I'm on rackspace's cloud sites service, so I can't modify my server environment. I'm also running Drupal 7. I've spent the last couple days looking for a way to minify JS in Drupal 7 and it is my conclusion that one does not exist yet. Am I wrong? Or do I need to wait for a D7 release of http://drupal.org/project/advagg?

List of modules in D7 that might provide similar functionality.
  http://drupal.org/project/core_library
  http://drupal.org/project/agrcache

It is what reported in the project page for Advanced CSS/JS Aggregation, which is where your link takes to.


How to keep the size of the database reduced? I found out a very simple D7 site with less than 150 nodes had database dumps of 65M (gzipped). Which caused my entire server to become slow during the nightly database dumps.

After some searching I found this useful query:

SELECT TABLE_NAME, table_rows, data_length, index_length,
round(((data_length + index_length) / 1024 / 1024),2) "Size in MB"
FROM information_schema.TABLES WHERE table_schema = "DRUPAL_DATABASENAME_GOES_HERE";

With that I immediately found the culprit: the sessions table.

After a TRUNCATE sessions my dump is now <1M (gzipped).

How can I make sure this site's dump doesn't blow up again in the future?
I found periodic purging of watchdog and sessions tables? on drupal.org, but it's from 2007.

Don't dump session, cache_*, watchdog table content (make sure to keep the structure).

For watchdog there's syslog replacement.

If you don't need the access logging in Drupal disable that module and dump that table as well.

For huge content driven websites with lots of edits (and revisions) clearing the revision tables from time to time might help too. (e.g. with node revision delete).


Show all values for a field collection in node.tpl.php I have a problem with theming field collection. I want to create a loop and I have a field called field_earth inside field_helloworld that displays unlimited images. The following code doesn't show any image.

<?php
  $counter = 1;
  foreach ($node->field_helloworld['und'] as $key => $value) {
    $field_collection = entity_load('field_collection_item', array($value['value']));
    $idx = $value['value'];
?>

    <?php print $counter; ?>
    <?php print $field_collection[$idx]->field_venus['und'][0]['value'];?>

    <?php print $field_collection[$idx]->field_earth['und']['0'][value];?>

  <?php $counter++; ?>
<?php  } ?>

Can anyone show me how to display all images?

/**
 * @Show all field collection values from node object
 *  Example field collection name: "field_helloworld"
 *  Example fields within a field collection:
 *  - field_title       (string)
 *  - field_image       (image)
 *  - field_description (string)
 */

// get field collections from node
$field_helloworld = field_get_items('node', $node, 'field_helloworld');

// get all fields values if collection exists
if (!empty($field_helloworld)){
    $field = field_view_value('node',$node, 'field_helloworld', $field_helloworld[0]);
    foreach ($field['entity']['field_collection_item'] as $id => $field_collection){

        // load the field collection item entity
        $field_collection_item = field_collection_item_load($id);
        // wrap the entity and make it easier to get the values of fields
        $field_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

        // all values from a field collection
        $field_title        = $field_wrapper->field_title->value();
        $field_image        = $field_wrapper->field_image->value(); // an array of image data
        $field_description  = $field_wrapper->field_description->value();

        // an example of getting image url from field_image
        $image_url          = $field_image['uri'] ? file_create_url($field_image['uri']) : '';
    }
}

Notice that there is no ['und']['0'][value].


Installing TinyMCE Text Editor I followed this video tutorial in youtube for installing TinyMCE Editor in drupal. Below are the steps I did.

1. Downloaded and installed the updated WYSIWYG 7.x-2.2, IMCE 7.x-1.9 and IMCE Wysiwyg API bridge 7.x-1.0 succesfully.

2. Downloaded TinyMCE and placed it on `htdocs\drupal\sites\all\libraries` succesfully.

3. Installed TinyMCE unsuccesfully.

I refresh drupal's page and still gets the 'Not installed.' message.

I suspect the path may be wrong/different from the image above. The actual path in my computer is sites\all\libraries\tinymce\js\tinymce\tinymce.min.js

I downloaded TinyMCE here. Where did I go wrong?

There might be TinyMCE version issue with 4.7.x. Once I have facing the same problem. Then I uses the version 3.5.x of TinyMCE and its worked fine for me.

I hope it will work.


Moving from subdirectory to root When I installed Drupal, I put it in a subfolder /drupal. Got everything set up and then moved everything into my root folder. When I went to the site I got this error:

Failed opening required '/home3/XXXX/public_html/drupal/modules/field/field.crud.inc'
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home3/XXXX/public_html/drupal/modules/modules/field/field.module on line 20

Then I moved everything back to /drupal and still get the same error.

Can anyone tell me where I should be looking for the issue?

I looked in my settings.php file and didn't see anything about a directory listing. I looked in /sites/default/settings.php and couldn't find anything to do with directories.

Thanks for the help!

for show the subdirectory site in the root I followed this guide.
I hope it could be usefull for you too ^^


Create a simple quiz I have a videos content type and I want users, who have watched this video, to answer some questions related to each single video.

How can I create a quiz for each single video node?
I tried the webform module and create a video block but there is a problem.
The  video will be shown in all forms and I can't insert video for next question.
Please help me.

You can always try the Quiz module. I have some experience with it and it mighty suffice for your needs.

Or you can always create your own form with the well-documented FormAPI. You can define your own validation- and submithandlers. Very, véry cool features.
What you can do is create a custom block, and fill it up with your own form.

Depending on your experience level (and time), you can one of above options...
Good luck!


How can I change page elements (menu, blocks, etc) based on a chosen 'audience' link? There are many sites which allow users to select their "customer type" or "audience", which then displays different information on the front page and provides them with navigation and content appropriate for their needs. Banks, higher-education institutions, and medical providers do this often (http://chase.com, http://aetna.com).

I'm looking for the best way to implement this on a site I'll be developing over the next few weeks. I need the main navigation to change per audience and I'd like to show specific content on the home page and sidebars based on that context. I don't think I want to use subdomains or multi-site; it seems that there should be a better way.

I'd like the URL structure to look like "mysite.com/audience1", "mysite.com/audience2", "mysite.com/audience3", and so on for the front page. Deeper pages would follow that url prefix ("mysite.com/audience1/products/tools")

There are also 'global' resources which any audience would find useful and I've been wondering about how I'd handle that use-case as well.

Should I look into panels, context, display suite, other modules? Any guidance is appreciated. Thanks!

Explaining the whole process would be bit complicated

i ll provide you some steps try to follow that.

In our project the same structure you have mentioned is used we have global pages like mysite.com/products and some further branch level pages like mysite.com/chennai/products

Step one: create a view page in views.

Step two: create a taxonomy term reference for the audience.

step three: create a block and in contextual filter add taxonomy term as contextual filter and in provide default value give get taxonomy term by url.

step four: for every content you create it should have the term reference field.

step five: when you pass the audience name in the url it should display the content related to the taxonomy term.

step six: like wise you have to configure the block in all the pages

step seven: in block settings give display only in that particular  page

now what this will do is for every block it will be displayed their content based on the url if you change the url to audience two it will show the content having the taxonomy term as audience two as their value.

hope this will give you a start up for the task :p


How to create a content type to embed video in drupal 6? I want to create content type to embed videos.

When admin want to post an article which will have a video content then he will just provide the video link in the field and then automatically video will be get embedded into that article.

Currently I have created a new content type but there is no field type to embed video link.

How can I achieve it ?

You are looking for Embedded Media Field module. After enabling just paste the URL of the video, it will render the video on the page. It supports almost all the videos like youtube, vimeo, etc..

  This extensible module will create fields for content types that can
  be used to display video, image, and audio files from various third
  party providers. When entering the content, the user will simply paste
  the URL or embed code from the third party, and the module will
  automatically determine which content provider is being used. When
  displaying the content, the proper embedding format will be used.


How to configure breakpoints and picture to use span data-picture I have follow the documentation that appear here: Picture documentation, but I'm not able to configure the module to use the same html that appear in the examples.

This is the code from the example Page:

  &lt;img typeof="foaf:Image" src="http://picture7w.h011.attiks.com/sites/picture7w.h011.attiks.com/files/styles/piccustom_user_tablet_1_5x/public/field/image/38054784.jpg?itok=zyO3uMRu" width="1300" height="867" alt="" /&gt;

Instead I get this html code:

<picture title="ejemplo">

  <source srcset="http://domain.new/sites/default/files/styles/verisure_breakpoints_theme_tc_mobile_1x/public/block/footer/LADRONA_en.jpg?itok=TrydhOr5 990w" media="only screen and (max-width: 767px)" sizes="(max-width: 767px)">

</picture>

Any idea how to configure the module?

Thanks

Oskar

The demo page you've linked says it was Submitted by admin on Thu, 04/25/2013 - 13:31. That's over 1 year ago.

What makes you think the output you're seeing isn't correct for your current installed version of Picture? If your breakpoints are installed and configured correctly as in the documentation you have linked, then the images should be responsive.


Getting the source URL of image in Media Gallery Module I need one more thing to get my custom lightbox running in the Media Gallery module for Drupal 7.

The link that is clicked which leads to a custom page which contains the image is at this moment the following:

l($image, $link_path, array('html' => TRUE, 'attributes' => $attributes)) : $image;

The thing is that I want to link directly to the image, and not to a page where the image is on! I know that this is hard to understand so I'll try to clarify. At this moment, when you click the link you will be directed to something like this:
/media-gallery/detail/xxx/xxxxx

But I want it to link to the image itself (e.g. /files/folder.1.JPG) and I can't seem to find where the image is transformed into a page on itself. Does anyone have ANY idea? I would be soooo grateful!

Thanks a lot you guys.
EDIT: I have found that the generated link can be edited by the following snippet of code in colorbox-display.js:

var $ = jQuery, $galleries, $gallery, href, $links, $link, $dummyLinksPre, $dummyLinksPost, i, j;
    // Add a colorbox group for each media gallery field on the page.
    $galleries = $('.field-name-media-gallery-media');
    for (i = 0; i < $galleries.length; i++) {
      $gallery = $($galleries[i]);
      $links = $('a.sbEnabled', $gallery);
      $dummyLinksPre = $gallery.parent().find('ul:has(a.shadowbox-supplemental-link.pre)');
      $dummyLinksPost = $gallery.parent().find('ul:has(a.shadowbox-supplemental-link.post)');
      $dummyLinksPost.appendTo($gallery);
      $links = $links.add('a', $dummyLinksPre).add('a', $dummyLinksPost);
      $links.attr('rel', 'shadowbox-' + i);
      for (j = 0; j < $links.length; j++) {
        // Change the link href to point to the lightbox version of the media.
        $link = $($links[j]);
        href = $link.attr('href');
        $link.attr('href', href.replace(/\/detail\/([0-9]+)\/([0-9]+)/, '/lightbox/$1/$2'));
      }
}

Unfortunately this doesn't bother to work.

The link you're looking to override is hard coded into the template_preprocess_media_gallery_media_item_thumbnail() function in the Media Gallery module.

Fortunately, as it's a preprocess hook for a theme function, you can yourself override it in your site's theme. It does mean having to duplicate some code from the original preprocess function, and also another theme function so you can add the rel attribute, but it's not too much. You'll also need to implement hook_js_alter() to remove the colorbox js the the Media Gallery module adds by default.

Place the following code in your theme's template.php file and replace all occurrences of THEMENAME with your theme's name:

function THEMENAME_preprocess_media_gallery_media_item_thumbnail(&$variables) {
  $element = $variables['element'];

  // Only make the changes for images, no other media type.
  if (strtolower($element['#bundle']) != 'image') {
    return;
  }

  $format = $element['#media_gallery_entity']->media_gallery_format[LANGUAGE_NONE][0]['value'];
  $lightbox = is_numeric(strpos($format, 'lightbox')) ? TRUE : FALSE;

  /*
   I'M PRESUMING HERE THAT YOU'RE ADDING THE SHADOWBOX SCRIPT USING ANOTHER
   METHOD (PERHAPS IN THE THEME'S .info FILE). IF THAT'S NOT THE CASE JUST
   UNCOMMENT THE FOLLOWING LINE AND CHANGE THE PATH TO ADD IT HERE

   if ($lightbox) {
     $element['file']['#attached']['js'][] = drupal_get_path('theme', 'THEMENAME') . '/path/to/shadowbox.js';
   }
  */

  // Get the rendered file without annoying DIV wrappers.
  $element['file'] = array('#theme' => 'media_gallery_file_field_inline', '0' => $element['file']);
  $image = drupal_render($element['file']);

  $gallery_id = $element['#media_gallery_entity']->nid;
  $media_id = $element['#file']->fid;

  // Add a class that is a more targeted version of what template_preprocess()
  // automatically adds for this theme hook, to enable per-type (e.g., video vs.
  // image) styling.
  $variables['classes_array'][] = drupal_html_class('media_gallery_media_item_thumbnail_' . $element['#file']->type);

  // Add a class for the wrapper.
  $variables['classes_array'][] = 'media-gallery-item-wrapper';

  // Create an array of variables to be added to the main thumbnail link.
  $link_vars = array();
  $link_vars['image'] = $image;

  // THIS IS WHERE YOU MAKE THE CHANGE TO THE LINK PATH. YOU MENTIONED THAT
  // YOU'VE ALREADY MANAGED TO ADD THE 'rel' ATTRIBUTE THAT YOU NEED SO I WON'T
  // ADD THAT HERE
  // Old code: $link_vars['link_path'] = "media-gallery/detail/$gallery_id/$media_id";

  // New code:
  $style_name = 'media_gallery_large'; // Name of the image style for the full sized image you want to link to
  $url = image_style_url($style_name, $element['#file']->uri);
  $link_vars['link_path'] = $url;
  $link_vars['rel'] = 'shadowbox'; // The rel attribute
  // End new code

  $link_vars['classes'] = array('media-gallery-thumb');
  $link_vars['title'] = $element['#bundle'] == 'image' ? t('View larger image') : t('Watch video');
  // Add the image as a link to the detailed view
  $variables['media_gallery_item'] = theme('media_gallery_item', $link_vars);

  // Set the variables to theme the metadata.
  $meta_vars = array();
  $meta_vars['location'] = $element['#media_gallery_entity']->media_gallery_image_info_where[LANGUAGE_NONE][0]['value'];
  $meta_vars['title'] = isset($element['media_title']) ? $element['media_title'][0]['#markup'] : '';
  $meta_vars['link_path'] = $link_vars['link_path'];

  // Theme the metadata.
  $variables['media_gallery_meta'] = theme('media_gallery_meta', $meta_vars);
}

function THEMENAME_media_gallery_item($variables) {
  $image = $variables['image'];
  $link_path = $variables['link_path'];
  $attributes = array();
  if (!empty($variables['classes'])) {
    $attributes['class'] = $variables['classes'];
  }
  if (!empty($variables['title'])) {
    $new_image = str_replace(array('title=""', 'alt=""'), array('', ''), $image);
    $image = str_replace('/>', ' title="'.$variables['title'].'" alt="'.$variables['title'].'" />', $new_image);;
  }

  // Below is the only change to this function, just to add the rel attribute.
  if (!empty($variables['rel'])) {
    $attributes['rel'] = 'shadowbox';
  }

  // Add sliding door top div and wrappers
  $item = '

';
  // Create a link around the image
  $item .= empty($variables['no_link']) ? l($image, $link_path, array('html' => TRUE, 'attributes' => $attributes)) : $image;
  // Add sliding door bottom div and close wrappers
  $item .= '

';
  return $item;
}

function THEMENAME_js_alter(&$js) {
  // Remove the media gallery colorbox js. It interferes with the rel attribute.
  if (isset($js['sites/all/modules/media_gallery/colorbox-display.js'])) {
    unset($js['sites/all/modules/media_gallery/colorbox-display.js']);
  }
}

I've added some comments to the code to explain what's happening so it might be worth giving the code a quick glance over.

After you've cleared Drupal's caches you should get exactly what you're after :)


Views Results - Display specific user I have created a view based off the webform submission data.  So if [Mary] has submitted five forms, and [Julie] has submitted three and [Steve] has submitted 8--  When they look at my results page, I only want julie to see her rows/submission info, Mary should only see her five rows and steve his 8.

The users are authenticated users so they have to login to complete the form and I capture their user and other personal info and of course to access the results page they must me authenticated as well.

I thought getting the submission data layed out in the view was going to be the hard part.  I want the user to click on a link to "previous submissions" and when the results page opens, only their rows appear.  I know the query will be return all the rows where the userID matches the userID of the currently logged in user.

I'm thinking this is hard because I am using webform submission data versus typical views of regular content.

Any help ?

Doesn't sound any different to displaying content as long as you can access the uid you have stored in 'filters'.

Set up a relationship from the data you wish to display to the person who created the data and then make a filter for 'author uid' (or similar) = 'current user uid'.  You will probably need to use tokens for the right side of that equation.


How can I include a list of what a user ordered (the line items) in an e-mail sent by Drupal Commerce? I want to send an e-mail that contains the content of a user's Drupal Commerce order (the line items) with Rules.

I tried modifying the default Send an order notification e-mail (in Rules) provided by Commerce.  I noticed that there was a [commerce-order:commerce_line_items] token, but when I insert this into an e-mail, I get a message of No line items found when the e-mail is sent, even though the order has line items.  What am I doing wrong?

The [commerce-order:commerce_line_items] token does not work when Completing the checkout process, which is the event for which the Send an order notification e-mail rule is triggered.

Instead, one way to do this is to use the Commerce E-mail module, which provides a [commerce-order:commerce-email-order-items] token and a new interface for editing the e-mail.  Note that you will need to disable the e-mail-sending rule when using this module (or else you will get duplicate e-mails, as the module help points out).


How to prevent jQuery from loading during ajax callback Using Drupal 7's implementation of jQuery and Drupal.behaviors, how can I get some of my jQuery to run only once when the page is initially loaded, and the rest to run when the page is loaded AND during AJAX callbacks.

How can I prevent ajax callbacks from triggering certain parts of my Drupal.behaviors?

(function ($) {
    Drupal.behaviors.fsrevs_user = {
        attach: function (context, settings) {

            //I want to run this only during the first page load.
            jQuery('#edit-message').after('
Do Once
');

            //I want this to run during first load and during each ajax callback.
            jQuery('#edit-message').after('
Do Every Time
');
        }
    }

})(jQuery);

This'll do it:

var msg = $('#edit-message');
msg.once('fsrevs_user', function() {
  msg.after('
Do Once
');
});

msg.after('
Do Every Time
');


How can I add the +0430 timezone to Drupal 6? As you know, Drupal 6 doesn't have the +0430 timezone in the date/time page. I want to add this specific item into timezone drop-down list.

Does anybody know about this core patching? How can I do it?

I think this looks like a problem in PHP. The timezone is being used by the Date module, and that contains date_timezone_abbr(), which uses PHP's timezone_abbreviations_list().

Only the keys are stored, and the PHP function is being used. I am afraid there is no way out of this, unless there is a way to convince PHP.

When I tried the following code, I get 4, not 4.5.

$a = timezone_abbreviations_list();
echo $a['aft'][0]['offset'] / 3600;


Disable the overlay for admin using a feature? Every time i spawn a new website the first thing i need to do is disable the very slow overlay in /user/1/edit?destination=admin/people

Is there a way to export admin user settings each time after an install?

You can use a feature for this, but IMO it makes more sense to do this in an install profile, because you are just setting this once. One way or the other, you will need to add some code to the .install file of your install profile or feature, in the form of a hook_install implementation.

This is untested code but I believe it should work:

<?php
/**
 * Implement hook_install().
 */
function PROFILENAME_install() {
  user_save(user_load(1), array('data' => array('overlay' => 0)));
}
?>

Of course you need to replace 'PROFILENAME' with the name of your install profile or the name of your feature.