Adding nofollow to specific internal paths I am looking to add nofollow to specific internal paths when they appear within text anywhere in the posts.

I tried using the text filters but I only get the options to either nofollow all links within a post body or nofollow all external links.

What I am trying to achieve is to nofollow all links following this pattern (/user/* ) when they appear within text body.

What are my options? Custom filter? or a preg replace through preprocess. I will appreciate a bit detailed explanation as I am new to programming.

Thanks in advance.

Since you want to add this attribute only to custom URLs (those matching /user/*) within your content, you might have to write custom code, as I'm not aware of any module which does this.

You could use hook_preprocess_field() and then execute a regular expression to match your pattern and add the rel="nofollow" attribute. However, this could be highly inefficient, as you have to do it every time you render a node, besides the fact that parsing HTML with regular expressions is not a bullet-proof solution.

Here it's a very simple example that just adds rel="nofollow" to all links in the body field (you will have to adapt it to use your own regular expression).

/**
 * Implements template_preprocess_field().
 */
function MYTHEME_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'body') {
     $markup = $variables['items']['0']['#markup'];
     $variables['items']['0']['#markup'] = preg_replace('/href=/', 'rel="nofollow" href=', $markup);
  }
}

Another alternative would be using the Path Nofollow module, that does something similar:

  Specify paths on which a metatag is added to prevent search engines
  from indexing the page.

So you could specify the path /user/* and it will add a metatag in the head of your html <meta name="robots" content="noindex">. As I said, not exactly the same, but it might help or complement your goal.


I can't create a book under Internet Explorer 7 I can't create a book under Internet Explorer 7; when I click "add a new book" in Book outline, the browser shows, "To help protect your security, Internet Explorer blocked this site from downloading files to your computer. Click here for more options…."

When I click on "Download the file," the file name is "form8c01710d," and it contains { "status": false, "data": "" }.

Actually, it is an issue that continues into modern versions of IE as well.

If your site has the jQuery Update module running, http://drupal.org/node/860966 speaks of the issue; the real issue is found in comment #6.

The only reason I am following up on this post here is that it is has a high in Google search,  and I figured others are looking for how to solve the issue.


How can I assign a URL with a fragment (#) as an array value? In my form:

$form_state['redirect'] = 'mypage/' . $nid . '#comment-form';

redirects to:

/mypage/1%23comment-form

...so it doesn't jump to the comment form. I tried:

$form_state['redirect'] = l('', "mypage/$nid", array('fragment' => 'comment-form');

...that retuned a bigger mess. I need to link to:

/mypage/1#comment-form

Basically, I'm trying to jump to the bottom of the page the user is redirected to.

Thanks

You can use an array for $form_state['redirect'], the elements of which mirror the arguments passed to the url() function.

So you can use...

$form_state['redirect'] = array(
  "mypage/$nid",
  array('fragment' => 'comment-form'),
);

The method it used quite sparingly in core (just 5 occurrences as far as I can tell); node_form_delete_submit() contains an example.


How to hide header and footer from 404 page? I create a 404 page on D7 site ( ie. mysite.com/404), which is a Basic Page. I am trying to hide the header and footer from this page. The header and footer are blocks, and they are placed in every page using Context. I tried tweaking the Context so that if Path = 404, hide the header and footer.

It works when I go to mysite.com/404. However I try to hit an alias that doesn't exist (ie. mysite.com/asdf), instead of redirecting to /404, Drupal pulls the node body of the 404 page and stay at /asdf. The rule in the Context therefore doesn't apply.

I don't want to use the Visibility control in the Block module because migrating the configuration between sites can be troublesome. How would you go about it?

I do this by overriding the template used by the theme. In the template.php:

/**
 * Set path to page-error.tpl if http error is returned.
 */
function yourtheme_preprocess_page(&$vars) {
  // Set custom error template:
  $http_status = drupal_get_http_header("status");

  if (isset($http_status)) {

    switch ($http_status) {
      case "403 Forbidden":
      case "404 Not Found":
      case "500 Internal Server Error":
        $vars['theme_hook_suggestions'][] = 'page__error';
        $vars['http_status'] = "Error: " . $http_status;
        $vars['error_message'] = drupal_get_messages();
        break;
    }
  }
}

Then you can create page--error.tpl.php in your templates directory using whatever regions you want to display. This has added the benefit of automating error pages, so you don't have to set a path in the site config.


How to display the user name that created the profile (the owner or author of the profile)? I have a site with Drupal 8 and I want to customize the templates of my pages.

I use the module:

"Profile" https://www.drupal.org/project/issues/profile

Here is my template to customize the profile page:

{#
/**
 * @file
 *
 * Default theme implementation for profiles.
 *
 * Available variables:
 * - content: Items for the content of the profile.
 *   Use 'content' to print them all, or print a subset such as
 *   'content.title'. Use the following code to exclude the
 *   printing of a given child element:
 *   @code
 *   {{ content|without('title') }}
 *   @endcode
 * - attributes: HTML attributes for the wrapper.
 * - profile: The profile object.
 * - url: The profile URL, if available.
 *
 * @ingroup themeable
 */
#}

      {{ ??? USERNAME ??? }}

How to display the user name that created the profile (the owner of the profile) ?

You can get from getOwner() method

  {{ profile.getOwner().name.value }}
  {{ profile.getOwner().mail.value }}


drupal commerce multiple products on one page I'm building a website in which people can reserve plays(theater). I'm using a product display for this.

The problem is, a specific 'play' is going on for a number of days, and people should be able to reserve for a specific day.

For example : a specific play might go on the 18th,19th, and 20th of September and customers need to be able to select a date from those available.

How can this be achieved with Drupal Commerce ?

One idea I had was to create multiple products with the specific date, but how do I show multiple products on one product display ?

Thanks.

On your Product Display field setup a multivalued  entity reference field of type 'node'. Now as per your example

you add a product for date 18, in reference field add reference to other dates as well.
For all dates will have reference to each other.
Now with view create a block display to show related nodes using relationship on reference field and take node id from context filter.
Put this block on product display page so it can take node id from context and show related products.


Theme taxonomy term page based on depth Is there any solution on how theme the taxonomy term page per depth? Though this is doable with Views + TVI, we don't usually allow admin to manage TVI, but they're able to add new term and they're allowed to rearrange the terms. I would like that each depth has a different layout, but automatically changing based from its depth. This can done through hooks or how to achieve this in views?

For instance:

if ($depth == 0) {
  print $views_0;
}
elseif ($depth == 1) {
  print $views_1;
}
elseif ($depth == 2) {
  print $views_2;
}
else {
  print $views_default;
}

and so on...

Create a funtion to retrive term depth

//Gets the depth of the term id
function MYMODULE_term_depth($tid) {
  $parent = db_query("SELECT parent FROM {taxonomy_term_hierarchy} WHERE tid = :tid", array(':tid' => $tid))->fetchField();
  if($parent == 0) {
    return 1;
  }else  {
    return 1+MYMODULE_term_depth($parent);
  }
}

And Print the views based on depth

$depth = MYMODULE_term_depth($tid)
if ($depth == 0) {
  print views_embed_view('views_0');
}
elseif ($depth == 1) {
  print views_embed_view('views_1');
}
elseif ($depth == 2) {
  print views_embed_view('views_2');
}
else {
  print views_embed_view('views_default');
}

pass the view machine name to views_embed_view


Multiple exposed search filters Maybe I am trying to do something simple and I am just blind, but after a day of hard work I am desperate...:

I have view, created using Views 3 module, with source in index of Search API module
I have Profile two custom fields on User Entity, named "Name" and "Surname".
I am using two "Search: Fulltext search" exposed filters in View, grouped using AND. The first with "Contains all of these words" and the second with "Contains none of these words".
I have user with "Name" = Vysakh, "Surname" = Babu

Now:

When is in first "Search: Fulltext search" exposed filter with rule "Contains all of these words" written "Babu" (without speech marks), it founds his profile. Great.

But:

When is in second "Search: Fulltext search" exposed filter with rule "Contains none of these words" concurrently written "Vysakh" (without speech marks), instead of excluding his profile as well (thus showing empty result), view shows all the profiles, except Babu Vysakh...

Any ideas why and what can I do?

I tried all combinations of exposed filters, put them to different groups, switch from "Search keys" to "Search filter"... No luck.

There is actually a bug in Search API 7.x-1.8.

The full-text views' filters handler is able to use only one exposed filter (the last one in stack, the previous instances are overwritten).

While it was a LOT of hacking in the Search API module, the simple answer is: you can use only one exposed Search filter in Views with Search API 7.x-1.8 without extensive PHP coding.


Using .tpl.php templates instead of Twig templates Is there a way to use .tpl.php templates instead of Twig templates in Drupal 8, or is there a way to write PHP in a Twig file instead of that Twig language?

I am a beginner for Drupal 8, but I have worked with Drupal 7.

You don't need to write PHP in twig files. Twig is fairly expressive to the degree in which you need to template, for everything else, it should go into the .theme file, theme hook, and/or preprocess function.

There is virtually no reason to have PHP code in a template.

Spend a week with Twig and you won't go back.

Example:

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

vs:

{% if page.content %}
  {{ page.content }}
{% endif %}

Much more readable.

I'll expand with a more advanced example.

Lets say you have list of things you want to output, but every 7 items, you want to make a new unordered list. The end goal is the CSS inlines these lists, think of a superfish menu where menu links are ordered top to bottom, then left to right.

    {% for chunk in items|batch(7) %}

        {% for item in chunk %}

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

        {% endfor %}

    {% endfor %}

Where items is passed to the template. This small example will output a UL with 7 items until there is nothing left to print.

I have yet to run into an instance where I cannot accomplish something with Twig, or, because it's Twig.

Give it a shot and dive in, forget phptemplate.


Organize shows and episodes I'm moving from years after using joomla to drupal and i've hit the learning curve.

My question is below.

I want to create content like this:

Many shows
Each show has many episodes
Each show has many tags (genres)

Shows should be listable
Episodes should be listable per show
Shows should be listable per genre

It's basically a database for tv shows. But I want to hit the ground running.

I'm currently stuck with taxonomy and content types. Would a show and episode each be a content type? How can I relate them to each other?

I'm running drupal 7.x

It looks like two content types: Show and Episode. You'll want to look into the Entity reference module to relate episodes to shows. This adds an Entity reference field type. And you'll be using Term reference fields for tagging.


Change the input format in drupal 8 I would like to know how to change the input format (automatically or by sql ) for all articles in my website, because I migrated from D6 to D8 and I face a nasty bug that requires to edit all my nodes (more than 2000) manually and set either filtered HTML or FULL HTML format to all nodes.

Thanks to No Sssweat. His answer works. But I prefer to use sql so here it is.

Using Phpmyadmin navigate to node__body table (or just search it) then in SQL tab, write this:

UPDATE `node__body` SET `body_format`='full_html' WHERE `body_format`='full_html1';

Please notice the following:

in my case, I use different body format in my website so it is not good to change all body_format to full_html.
after the migration I got full_html1, but you may get different body_format.

After execution the SQL command, Clear Drupal cache


How to Trigger Existing, Non-Form Ajax from JavaScript Event I'm trying to figure out AJAX in Drupal 8.

I have a custom module that works, using AJAX to change the content of a div when a link is clicked.

The API says:

  Many different events can trigger Ajax responses, including:

  Clicking a button
  Pressing a key
  Moving the mouse

How do I trigger the same process that Drupal's AJAX does when a function is called from a JavaScript object's event firing instead?

JavaScript Object

function calledOnSomeEvent(e) {
  String data = e.target.data;
  // do something to call AJAX with the data
}

The AJAX backend works with this route:

myModule.routing.yml

myModule.myRoute:
  path: '/nojs/myFunction/{myParameter}'
  defaults:
    _controller: '\Drupal\myModule\MyController::myFunctionCallback'
    _title: 'myFunction'
  requirements:
    _permission: 'access content'

HTML

Click for testData!

My understanding is that Drupal injects some sort of event when that link is clicked, or the URL is just changed, and the controller is only activated when that URL is changed.

JavaScript

(function($, Drupal) {

  Drupal.AjaxCommands.prototype.myFunction = function(ajax, response, status){

    $('#targetDiv').html(response.data);
  }

})(jQuery, Drupal);

I omitted PHP code for the controller, which creates a command. The command renders the output to Drupal.AjaxCommands.prototype.myFunction, which updates the div.

Is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?

I think there might be a way for JavaScript interact with Drupal's AJAX handler to call the same function that clicking the link changed with "use-ajax" does, since that's being handled in some way...

Any insight would be appreciated.

Thanks!

If you don't want to ajaxify the link with "use-ajax" and trigger an Ajax request programmatically use:

Drupal.ajax({url: endpoint}).execute();

This creates an Ajax object with the endpoint as url and executes it.

More options you'll find in the comments of Drupal.ajax in ajax.js:

/**
   * Provides Ajax page updating via jQuery $.ajax.
   *
   * This function is designed to improve developer experience by wrapping the
   * initialization of {@link Drupal.Ajax} objects and storing all created
   * objects in the {@link Drupal.ajax.instances} array.
   *
   * @example
   * Drupal.behaviors.myCustomAJAXStuff = {
   *   attach: function (context, settings) {
   *
   *     var ajaxSettings = {
   *       url: 'my/url/path',
   *       // If the old version of Drupal.ajax() needs to be used those
   *       // properties can be added
   *       base: 'myBase',
   *       element: $(context).find('.someElement')
   *     };
   *
   *     var myAjaxObject = Drupal.ajax(ajaxSettings);
   *
   *     // Declare a new Ajax command specifically for this Ajax object.
   *     myAjaxObject.commands.insert = function (ajax, response, status) {
   *       $('#my-wrapper').append(response.data);
   *       alert('New content was appended to #my-wrapper');
   *     };
   *
   *     // This command will remove this Ajax object from the page.
   *     myAjaxObject.commands.destroyObject = function (ajax, response, status) {
   *       Drupal.ajax.instances[this.instanceIndex] = null;
   *     };
   *
   *     // Programmatically trigger the Ajax request.
   *     myAjaxObject.execute();
   *   }
   * };
   *
   * @param {object} settings
   *   The settings object passed to {@link Drupal.Ajax} constructor.
   * @param {string} [settings.base]
   *   Base is passed to {@link Drupal.Ajax} constructor as the 'base'
   *   parameter.
   * @param {HTMLElement} [settings.element]
   *   Element parameter of {@link Drupal.Ajax} constructor, element on which
   *   event listeners will be bound.
   *
   * @return {Drupal.Ajax}
   *   The created Ajax object.
   *
   * @see Drupal.AjaxCommands
   */
  Drupal.ajax = function (settings) {

Your second question, is an XMLHttpRequest the only way to make JavaScript interact with the route/PHP? If so, what path should be used?

You can use a normal non drupal jQuery.ajax(), then you have no restrictions for the format, you can use json (which Drupal uses for it's own ajax) or any other format. You can set up a route for an arbitrary path and use this in $.ajax().


Get more details about log messages I'm getting a lot of "Missing text format: 1." errors in my log. It seems to point to a bug where text formats used to get referenced by number in D6 (['format'] = '1') but now are referenced by a name in D7 (['format'] = 'plain_text').

How would I find where does bugs are?

Or a more general question: how can I get more details about error messages in the Drupal log?

Guess log means watchdog here. Generally, you only have what the developer passed to the watchdog.

You can try to parse the code for (a part) of the error message. There's a good chance that this points you to the code sending the watchdog, which in turn gives you more information about the problem.


Create a repeatable Drupal install? When installing Drupal for different sites I find myself frequently installing the same modules over and over again.  In the interest of DRY, how can I create a kind of custom site "template" which would allow me to install drupal and have the basic modules I install already installed, basic theme set, and possibly some other common configuration options set?

I've read a little about Drupal profiles and I've seen the Drush tool and perhaps there are other tools besides these.  I'm wondering what's the best way to do this?

UPDATE

Ok so it seems Drush make and Drupal installation profiles are the correct tools for the job.  I found these blog posts which talk about them:

Overview

Drush make

Installation profiles

I feel like I've got almost all the puzzle pieces.  What I'm still not clear on is how to combine the drush make process with the profiles?  How do you get your profile files into the profiles directory of the drupal install that drush make creates?  Or should I just do this via a shell script?

UPDATE 2

I found this video:

http://chicago2011.drupal.org/sessions/zero-distribution-using-features-profiler-and-drush-make

which explains using drush make with profiler.  Seems like the connection between drush make and profiles is you have one drush make file which downloads only drupal and your profile.  Then inside your profile "module" you have another drush make file which will download all your module components.

The video also talks about features which is another level of drupal setup automation.

I'm not sold on this work flow.  It all seems a little convoluted.  However this was my first exposure so maybe I will appreciate it more later.  I like drush make but I'm thinking I can use drush to enable modules instead of messing with profiles.  I think I will make a bash shell script that runs drush make and then uses plain drush to enable modules.

Next step would be how to do some configuration of the modules in a repeatable way.  I guess this might be features?  Or maybe I should look further into profiles.

Have a look at the Drush make project:

http://drupal.org/project/drush_make

There is also a companion website at:

http://drushmake.me/

This website allows you to select the modules you want to package with Drupal, and produces a Drush-ready makefile.

There are other varieties of this functionality out there, so I advise experimenting and testing with your specific configuration.


Using Contextual Filter to Filter "Entity Selection" on Node Edit won't pull Raw Value From URL I'm trying to filter the values available in an Entity References "Entity Selection" list on a node edit form to only show nodes relevant to the current node being edited.

I am using views and have selected the "Views: Filter by an entity reference view" for the Entity Selection Mode.

In my view I have created an Entity Reference Display with a contextual filter. I have tested that the contextual filter works the way I want it to by using "Preview with contextual filters" and entering a sample ID to filter on (1200). It filters just fine.

When I use "Display all results for the specified field when the filter value is not available" all the results display on the node edit form. But as soon as I choose "Provide a default value" -> "Raw Value from URL" then nothing is displayed on the node edit form.

I have checked that the raw value is in the URL: content/assembly/1200 (1200 being the value that works in the "Preview with contextual filters") and am using the right path component to reference it and ticking or unticking "use path alias" makes no difference.

Does anyone know why this would not be working?

Thanks very much.

Try Content ID from URL instead of the Raw Value.


How do I update without using the parameter --with-dependencies in "composer update --with-dependencies"? I just finished my first Drupal 8 project, and I want to have it up-to-date before submitting it to the remote server. I read that it's better not to use composer update --with-dependencies. I understand why this is. I will do this for the core and modules, so I updated core with composer update drupal/core --with-dependencies and one drupal/module but then when I run composer outdated I still see a large list of symfony/twig/phpunit/zendframework/and more.

Do I really need to update them one by one? It seems a lot of work to do this every time. There are maybe 30 or 40 to update.

Hope someone can explain me how this works.

I just use composer update --no-dev from the directory containing the composer.json file and the core directory, and I get all updated.

Loading composer repositories with package information
Updating dependencies
Package operations: 0 installs, 21 updates, 0 removals
  - Updating twig/twig (v1.33.2 => v1.34.3): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/yaml (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-mbstring (v1.3.0 => v1.4.0): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/translation (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/validator (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-php55 (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/serializer (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/routing (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-php54 (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/http-foundation (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/process (v2.8.21 => v2.8.22): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-iconv (v1.3.0 => v1.4.0): Loading from cache
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/event-dispatcher (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/debug (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/http-kernel (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/dependency-injection (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/console (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/polyfill-apcu (v1.3.0 => v1.4.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating symfony/class-loader (v2.8.21 => v2.8.22): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating guzzlehttp/guzzle (6.2.3 => 6.3.0): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
  - Updating drupal/core (8.3.2 => 8.3.4): Downloading (100%)
> Drupal\Core\Composer\Composer::vendorTestCodeCleanup
Writing lock file
Generating autoload files
> Drupal\Core\Composer\Composer::preAutoloadDump
> Drupal\Core\Composer\Composer::ensureHtaccess

I put drupal/core in the require section, so it gets updated too.

As for the output of composer outdated, I get the following.

doctrine/annotations            v1.2.7      v1.4.0      Docblock Annotations Parser
egulias/email-validator         1.2.14      2.1.2       A library for validating emails
symfony-cmf/routing             1.4.1       2.0.1       Extends the Symfony2 routing component for dynamic routes and chaining sever...
symfony/class-loader            v2.8.22     v3.3.2      Symfony ClassLoader Component
symfony/console                 v2.8.22     v3.3.2      Symfony Console Component
symfony/debug                   v2.8.22     v3.3.2      Symfony Debug Component
symfony/dependency-injection    v2.8.22     v3.3.2      Symfony DependencyInjection Component
symfony/event-dispatcher        v2.8.22     v3.3.2      Symfony EventDispatcher Component
symfony/http-foundation         v2.8.22     v3.3.2      Symfony HttpFoundation Component
symfony/http-kernel             v2.8.22     v3.3.2      Symfony HttpKernel Component
symfony/process                 v2.8.22     v3.3.2      Symfony Process Component
symfony/routing                 v2.8.22     v3.3.2      Symfony Routing Component
symfony/serializer              v2.8.22     v3.3.2      Symfony Serializer Component
symfony/translation             v2.8.22     v3.3.2      Symfony Translation Component
symfony/validator               v2.8.22     v3.3.2      Symfony Validator Component
symfony/yaml                    v2.8.22     v3.3.2      Symfony Yaml Component
twig/twig                       v1.34.3     v2.4.3      Twig, the flexible, fast, and secure template language for PHP

That is normal, though, since the core/composer.json file has some restrictions for the package versions that don't allow to update to the versions shown from composer outdated. For example, see the following lines in core/composer.json.

"doctrine/annotations": "1.2.*",
"egulias/email-validator": "1.2.*"

1.2.* is telling Composer that any version greater or equal to 1.2.0 and lower than 1.3 are acceptable. doctrine/annotations version 1.4.0 falls outside that range.


CCK Filefield source->IMCE No option to browse server unless UID1 I'm using a content type 'image' that uses CCK and filefield sources to browse and upload images.

When logged in as UID1, I'll get an option above the upload field to switch between 'Upload' and 'File Browser'. My problem is that I don't get that for all other users...

I've gone through the permissions and everything else I can think of and I just can't seem to get these options to appear. Any ideas? Probably something really simple I'm missing (it's been a long day....)   :)

Yes, it was me being stupid...

I didn't check the 'role profile assignments' at admin/settings/imce

:(


Module to turn on/off the whole block region My client wants to turn on/off the whole region for block from the drupal menu. Is there some module that can do that?

Right now he must move the all six blocks from that region to disabled area and then he needs to find them and rearange when he want them back and it is not very efficient.

I don't have a single great suggestions. Here are a few things that come to mind.

Wrap all the blocks in a single block. This way you could make a few "block groups".
Just don't use the block system. It's not very good. My personal favourite block handling mechanism is Panels (Everywhere) and Page manager
Panels Everywhere is capable of killing the entire block system. A peek into it's codebase could probably reveal how to do it on a region by region basis.


What is the procedure for deleting a project in drupal.org? I created a project in drupal.org but decided that a better name would better suit the project, so I created another one. I need to delete the old project.

What is the official procedure to delete the old project node?

If your project contains code usually it is not deleted. In that case, you can select as Project classification Unsupported and as a Development status Obsolete.

You can always create a post in the Drupal.org webmasters issue queue explaining your situation and requesting the project deletion.

But I can tell you that if you have people using your module, they will not delete the project.


Drupal-git-sandbox project: commits are shown but no new revision I don't know why I have no new revision, what I do:
I change my code locally, then:

git add -A
git commit -m "bla"
git push -u origin 7.x-1.x

Result:

A new commit is shown in my sandbox repository on drupal.org. But I need a new revision too! I'm new to git, so can anybody explain what I misunderstand?

Sandboxes on Drupal.org can't have releases (tagged revisions).

For a full project, if you want to push a specific release/revision, rather than just a SHA-identified commit, you create a tag locally before you push a tagged release.

git commit -am "Revision 7.x-1.0"
git tag 7.x-1.0
git push origin tag 7.x-1.0


Theming Views, getting a list of object I have access of I'm Currently trying to theme a view.
Unfortunately I'm having a hard time to find elements I should use to access my fields.

Is there any where on the web, where I could find those variables ? or the parent one, that will allow me to find out other by searching down.

The 3 tools that I find vital to this is:

Click "Theme: Information" in the view page itself. This will give you a list of template files being used for the view and suggestions of template files you can use to override them by placing them in your theme folder (or a template subfolder of your theme depending on how you have set up in your .info file).
Devel module - this will allow you to inspect just about any aspect of your site and all the variables, fields etc available to you in a particular node/view.
Drupalforfirebug module and accompanying firefox/chrome plugin. Although I find it somewhat buggy in certain areas of drupal, it is great for inspecting all aspects of drupal (especially views).


What is the best method to build a form to track N number of values? I have to create a block that will be a gallery of users. The users to be featured will be curated by site editors. So I'm thinking the best way to track this is a pretty simple Drupal form / settings page where they just enter in the usernames they want.

However, the form should track N number of users. Is there a way in the Forms API to have an element that includes an "Add another value" or something similar, to allow for unlimited entries?

Or would it be better to just have a text area and ask the user to fill out one username per line?

That, or step 1) you could use http://www.drupal.org/project/flag which would allow the editor(s) to click / unclick a toggle on a user's profile that says they are "curated" and step 2) create a view that lists which users have been flagged.


Custom exposed filter for year in date field with ajax I am trying to create a custom exposed filter which would be a select field with years (2015-2025).
This would filter the result with the year of the date they are created.
I followed this tutorial https://www.flocondetoile.fr/blog/filter-content-year-views-drupal-8
But here there is no solution for ajax submission, so the page does not refresh and the filter does not apply.

Currently I have this year as a contextual filter and the form field in the hook_form_views_exposed_form_alter():

$options = [
    'all' => t('- All -'),
    '2015' => '2015',
    '2016' => '2016',
    '2017' => '2017',
    '2018' => '2018',
    '2019' => '2019',
    '2020' => '2020',
    '2021' => '2021',
    '2022' => '2022',
    '2023' => '2023',
    '2024' => '2024',
    '2025' => '2025',
  ];

  $form['year'] = [
    '#title' => t('By year'),
    '#type' => 'select',
    '#options' => $options,
    '#size' => NULL,
    '#default_value' => 'all',
  ];

Is there a possibility for the filter to work with ajax submission?

You can use this custom filter to filter by year:
https://github.com/DarkteK/d8-views-custom-filter/tree/master/d8_filters
Just change the years you want to use in the file 'ViewsYearsFilter.php'
This will work with Ajax


How can I add multilingual taxonomy breadcrumbs? I have a site with two languages and a large number of taxonomy terms.  I want to use breadcrumbs on my taxonomy pages, but I can't find a system that works well with multiple languages.

I translated my taxonomy terms with the Entity Translation module, using the field method.  What can I do?

You can do this by making a content pane in Views.  Here's what you need to do.

For hierarchical taxonomies, determine the maximum depth.  Example: United States -> Illinois -> Chicago (child, parent, and grandparent)
Create a view showing fields of taxonomy terms.  Add a contextual filter: Taxonomy term: Term ID.  For When the filter value is NOT available, choose Provide default value of Taxonomy term ID from URL and leave Load default filter from term page checked.
Add a relationship of Taxonomy term: parent term.  Do this as many times as you need to get to the maximum possible depth.  Do not require the relationship because the term may be a root term.  To make sure that you can keep track of all the relationships even though they will be of the same type, when adding the relationship, click More at the bottom of the add dialog and type in an appropriate name (parent, grandparent, great-grandparent, etc.) for the Administrative title.
Add the taxonomy term name field (the one provided by the Title module, since we are using Entity translation).  Don't use a relationship.  As the administrative title, set "current page term" or something easy to remember.
Now to get the parent and grandparent terms.  First, add a term id for each relationship (parent, grandparent, etc.)  Make sure to uncheck create a label and check Exclude from display.  Make sure to set the proper relationship for each tid.
Then, add the taxonomy term name field again as many times as necessary so that you have a name field for each relationship.  Again, make sure to set the relationship each time you add a new field.  Also, for each term name that has a relationship, make sure that Hide rewriting if empty is checked under No results behavior.  Under Rewrite results, check Output this field as a link and enter taxonomy/term/[tid] where [tid] is the replacement pattern for the appropriate relationship.
Reorder the fields from "oldest" (grandparent) to "youngest" (current term).
Under Format, click Settings next to Fields.  Check the boxes next to all of the non-tid fields to make them inline fields.  Add the separator of your choice and you're done!


How to transform the CSV link in the Views Data Export module in a non-image link display? I'm using the Views data export module for my search interface so users can click a link to download the search results. It's working and displaying. But it's not pretty.

My Data Export has the following settings:

Format: CSV file
Filter criteria: published, type=resource, topic > (exposed), category (exposed), search terms (optional)
Data export > settings > path: /search-export Attach to: search footer: global: text > area (what I've been trying to add the manual link to)
pager: display > a specified number of items > 0 items (required to make the CSV export > not return all results be default)

Right now there's a button at the bottom of the page that the module creates in the format of a tiny bright orange button with white text that says 'CSV'. I think it's an ugly button. A user may not even know what it means. Here's the code via inspect element:

If the user set exposed filters or set a keyword in the search box when clicked this link adds parameters to the URL (ie. /search-export?field_topics_value=All&etc).

I don't know how it's adding those parameters which is probably the crux of my problem.

I could just swap out my own image I guess...but...

I'd rather change this to not use an image whatsoever and instead have it just be a link that says 'download results' or some such thing.

I tried just adding a link manually to the header or footer in the search view that has the same link as the image but it doesn't capture the parameters the way the button does for some reason.

The link I tried adding:

    Download Spreadsheet

When clicked the above doesn't include the parameters in the URL like the image does, it just exports ALL the results (and ignores whichever filters are set).

My question: How to fix my new download spreadsheet link so it outputs the results only with the exposed filters and keywords as the view itself does (and as the CSV button does)?

I agree that this CSV button needs some refinements, similar to what you are describing in your question. And quite a few others seem to think likewise.

To actually solve your issue, consider looking at the module's issue # 2261167, which is about an Option for non-image link display (issue status = needs review). Comment # 26 of that issue contains a patch which adds 2 new settings as shown in this screenprint:

Here are some more details about these 2 new settings:

a checkbox to (if selected) provide the download link as a text link instead of an icon/image link.
a textfield to add a class to the link, so that you can give the link a class like "button" (see picture) to your text link

Do I'd definitely consider this patch.

As an alternative (2nd choice?), you may also want to look at issue # 1379672, which is about Export Button, make it styleable with CSS. It also includes a patch that you may want to consider (eg if the previous one for some reason doesn't fit).


How do I 'reset' a theme completely? I think I have deleted some .css theme files in my local directory by accident and when I delete All the theme's files to re-install and get the original files back, they still aren't there. Is there a way to reset the whole theme folder?

If it's a core/contrib theme, just download the original and replace the modified version with it.

If it's a custom theme, just restore from whatever backup you have available (or from Trash or your OS's equivalent feature).

If you're wondering if Drupal somehow keeps track of file system changes and might be able to help you restore deleted files - it doesn't (I've yet to come across a framework that would do this).


Display Suite field content type class I've created a custom field in Display Suite using this code in my module:

function mymodule_ds_fields_info($entity_type) {
$fields = array();

$fields['node']['type_label'] = array(
  'title' => t('Label'),
  'field_type' => DS_FIELD_TYPE_FUNCTION,
  'function' => 'mymodule_ds_field_type_label',
);

function mymodule_ds_field_type_label($field) {

$entity = $field['entity'];
$content = $entity->type;

return $content;
}

Now, I was able to set the content of the field to match my content type, but I also want to set a dynamic class for this field equal to that content type, for example:

$fields['node']['type_label'] = array(
  'title' => t('Label'),
  'field_type' => DS_FIELD_TYPE_FUNCTION,
  'function' => 'mymodule_ds_field_type_label',
  'class' => 'CONTENTTYPE',
);

Or:

function mymodule_ds_field_type_label($field) {

  $entity = $field['entity'];
  $content = $entity->type;
  $class = $entity->type;

So the end result should be something like this:

...

How can I do this?

Thanks in advance.

Each time Display Suite is used in content output, it's wrapped in an <article> element with the content type as a class. You can see below that the content type can be found as node-enterprise-blog class.

I'm not sure what your end purpose for this is, but this way you can select the element using .node-enterprise-blog .field-field-name. If you need to add a class to the field, consider using the Field Template option under DS Extras. It allows you to change the markup of each field in a view mode.


Drush sql-sync not working on multisite I use drush site aliases and drush sql-sync as part of my daily workflow between my local development environment and my company's production/staging servers (Acquia dev cloud). This works great for single site instances, but I haven't been able to get it to work with multisites.

Example site structure for my @remote alias:

@remote
  - default.com ``drush @remote`` <-- commands not targeted with `-l` execute here
  - sitename.com ``drush @remote -l sitename.com status``
  - foobar.com ``drush @remote -l foobar.com sql-connect``

For other drush commands, I can target the multisite that I want use the -l switch to specify a particular multisite, and I get the correct output for drush status and drush sql-connect (correct URI and Database name).

However, when I try to use -l with drush sql-sync, it just targets the root site, no matter what. I can get around this by manually dumping the database and doing drush sql-cli @remote -l multisite.com < db.sql, but it's not half as quick as just doing drush sql-sync @local -l sitename.com @drush.remote -l sitename.com

I can open up a drush issue queue if this is a bug, but I'm wanted to check and see if I was doing something wrong first. Thanks!

It is true that mixing @alias and -l together does happen to work in the local case, but is not supported in sql-sync.  If this did work, you would need to use --target-uri and --source-uri to distinguish the two different -l/--uri options, but this has never been implemented.  Drush always uses the source and target alias records, and nothing else, to determine how to look up the source and target database records.

As Clive says, the best thing to do it so set up separate aliases for each site.  If you put all of your aliases in a single file, they will automatically create an alias group.

For example, I do something like this:

sitename.aliases.drushrc.php:

<?php

$aliases['live'] = array (
  'parent' => '@server.urpad',
  'root' => '/srv/www/sitename/htdocs',
  'uri' => 'http://sitename.com',
}

$aliases['dev'] = array (
  'root' => '/srv/www/sitename/htdocs',
  'uri' => 'http://sitename.com',
}

server.aliases.drushrc.php:

<?php

$aliases['urpad'] = array (
  'remote-host' => 'my.remote-server.org',
  'remote-user' => 'www-admin',
}

Using a 'server' alias file allows me to easily specify where I want to put each remote site without having to duplicate the remote host information.

Then, to use it:

drush sql-sync @sitename.live @sitename.dev


Rendering a content of a page using tpl php Our custom theme has page.tpl.php which takes care of the whole site. But I have a page which actually needs to display a collection of nodes. I have written a custom page--url.tpl.php where the url is the path for the page in question. But this way overrides the whole page.tpl.php.

What would be best method so that I just need to display my custom content when my page.tpl.php calls <?php print render($page['content']); ?>? Will modules be the only way? from which I will create my block and add it to the page?

Note: We like to have COMPLETE control over our page. And we are getting rid of views from our site.

You can use the same template, add your custom content to a variable in template_preprocess_page function.

function template_preprocess_page(&$vars, $hook) {
  $path = current_path();
  if ($path == 'url') {
    $vars['custom_content'] = "your custom content";
    $vars['theme_hook_suggestions'][] = 'page__url';
  }
}

Then print the variable after the content.

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


The drush command 'sql dump' could not be found Im a trying to do a backup of my drupal site with:

drush -v sql dump --result-file=DrupalBackups/nameofsqldb5.sql

but it results in following error message:

The drush command 'sql dump' could not be found.  Run `drush cache-clear drush` to
[error] clear the commandfile cache if you have installed new extensions.

I ran drush cache-clear drush but without success.

Any ideas?

The actual command is sql-dump not sql dump

drush -v sql-dump --result-file=DrupalBackups/nameofsqldb5.sql

From drush help:

  sql-dump              Exports the Drupal DB as SQL using mysqldump or
  equivalent.


Field added to user profile does not appear in database? Drupal 7 provides the ability to add custom fields to the user profile through admin/config/people/accounts/fields.

I have added a firstname field. It appears on the registration page but in the database the field is not added. Where it is stored?

The additional fields are stored in a separate table like field_data_field_first.


How can I dynamically remove an entity constraint? I'm working on a single-sign-on module for D8 and would like to disable the password fields on the user edit form, since passwords should be managed by the outside identity provider and not through Drupal.

Drupal adds a "current password" field to the edit page which is required if the user wants to change their email address. I can remove the field easily in a hook_form_alter, but there's a form constraint, ProtectedUserFieldConstraintValidator, that runs and fails validation if the password field is not filled out.

How can I remove this form constraint dynamically?

Things I've looked at so far:

In my hook_form_alter setting $form_state->getFormObject()->getEntity()->_skipProtectedUserFieldConstraint = TRUE. This is a property that this constraint checks and when TRUE will skip it, but changes to the entity here are tossed since ContentEntityForm::validateForm rebuilds the entity just before validation.
Looking at the BaseFieldDefinition class to see if there's a way to remove an existing constraint, but there are no API methods available to do so.

EDIT: It seems once possible approach is to extend ProfileForm, overwrite the buildEntity method to set _skipProtectedUserFieldConstraint = TRUE, and then tell core to use my forms instead. Thought a downside here is that I'm just disabling the constraint in the context of a form, but not in other contexts where the entity may be updated, like in a REST API.

Validation constraints are plugins with an alter hook: hook_validation_constraint_alter() (the hook name can be seen in \Drupal\Core\Validation\ConstraintManager::__construct()).

That means you can alter that plugin and replace it with your own class that doesn't do anything, or only under some conditions.

Note that constraint plugins are special, unlike everything else, they consist of two classes, the plugin class is just the definition and strings, and then here is a $classname . 'Validator' class that contains the actual logic. So you need two classes, first the constraint class, Drupal\yourmodule\Something and then an overriden version of the Validator as Drupal\yourmodule\SomethingValidator.


How to set the visibility rule for pane to not show up when any user is logged in? I have created three panes (as shown below) using Mini Panel module. as named below,

Login/Register  |   Username  |  Logout

This I want to keep at the top left of website. Now, how each pane is created

Login/Register: Created menu and added link named Login/Register and have given the path /user. So, it leads to login page.
Username: This I created using the Views, a block created of users and filter was given that the user is logged in. hence it will automatically show up only when the user is logged in.
Logout: This I created using menu, with name Logout and path user/logout, hence when it gets clicked the user gets logout and this pane disappears automatically.
When users are logged-in, only the Username and Logout pane should appear; hence, users can see their profile by clicking on their name, or they can log out. When users log out, this pane disappears.
When user are not logged-in, only the Login/Register pane should appear.

So, the Username and Logout pane works perfectly fine.

What SELECTION rule shall I give to the Login/Register pane, so it gets visible only to anonymous users?

While adding a Visibility rule to the pane, select User:Role and then select "anonymous". This way the pane will be shown only to anonymous (not logged in) users.


How to remove a views template file in theme folder? I put .tpl.php file inside my theme folder to override views output. Then I deleted this file because it was no use for me. And did "Rescan template files". Now it cannot find this file and gives errors on the page.

  File not found, in folder sites/all/themes/mytheme/templates/

I also cleared all my caches.

How can I remove this file for good?

It looks like my problem is related with APC or some sort of caching. After removing the file, I run

  $ httpd restart

from the command window on the server, then the errors are gone. Probably it cleared the APC cache.


How to perform a query using a specific field of a node entity reference I have a content type that has a node entity reference field. My base query looks like

$event_nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_content_type')
    ->execute();

I'd like though to be able to sort by the title field of the referenced field type. I attempted

$event_nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_content_type')
    ->sort('field_referenced_node.title', ASC)
    ->execute();

But I receive the error

  Drupal\Core\Entity\Query\QueryException: Invalid specifier 'title' in Drupal\Core\Entity\Query\Sql\Tables->addField()

Is it possible to sort a node query by a field inside a referenced node?

I believe you want something like below. Note that this isn't really a database query at this level but an Entity Query:

$event_nids = \Drupal::entityQuery('node')
  ->condition('type', 'my_content_type')
  ->sort('field_referenced_node.entity.title', ASC)
  ->execute();


function name to be called by another module via drupal_alter? I need to alter data of a contrib module, which does a call drupal_alter('workbench_access_user', $access, $account);.

How must my function look like? My module's name is workbench_access_crud_by_state.

Is the following OK?  What about the parameters? I am confused about that data and context stuff.

function workbench_access_crud_by_state_workbench_access_user_alter($access, $account) {
  //do sth
  $bla = 'test';
  debug($bla);
}

It seems that my hook implementation is not being called at all and there are no error messages.

A hook implementation is always prefixed by the short name of the module implementing it; alter hooks need to have _alter appended. So, in your case, since workbench_access_crud_by_state is the machine name of the module, workbench_access_crud_by_state_workbench_access_user_alter($access, $account) is the correct signature for that alter-hook implementation.

As for the parameters, drupal_alter() accepts:

$type is the type of the alter hook, without the _alter part; in your case, that is workbench_access_user
&$data is the reference to the variable which contains the value to alter

There are other three parameters, which are optional and normally used to give context to the operation being performed.

In Drupal 8, the call to drupal_alter() is replaced with a call to \Drupal::moduleHandler()->alter(); in this case, the number of context parameters has been reduced to 2.


menu is not showing for non admin I have facing this issue like I have given menu link say http://localhost/mcs/admin/config/b_creation  but that menu only admin can able to access not any other users, all most all the menu which comes under http://localhost/mcs/admin/config/ will not show to authenticated user I have tried many times by setting the permission in people->permission but no use of it it shows

  Access denied You are not authorized to access this page

. can any one tell me why is it happening?

You probably need to manage permissions in the following area,

Goto Structure->Menus->Management
Under Administration->Configuration->b_creation
Click Edit link
At the bottom check the roles you need to grant access and Save

But make sure this has security issues, give the permissions to trusted users only.


Cannot get any tweets using Twitter Block I have installed the twitter block module but I only occasionally get any tweets - if I do they disappear when the screen is refreshed.  I have tried all browsers and it is the same everywhere!

Have you tried using the twitter profile widget? The twitter profile widget allows you to stream a twitter feed from a specific user.

First you will need to log into twitter and configure a twitter widget. When you configure  the twitter widget (using your twitter account) you will have output html code.
Once you do this you can then create a content type called twitter widget. Once this content type is created all you have to do is place the html text from your twitter widget into the content type.
Make sure that in your content type text box you set the text to read plain html. Once saved this will create block that can then be configured and dragged around the page.


Need "carat" for currently active Superfish menu item I have a Drupal 7 Superfish menu (from the Superfish module) that I would like to add a "carat" to for the currently active menu item.

Here is my current menu:

But I would like a menu where the currently active menu item has a "carat" instead.
Here is what I would like: (altered in photoshop to give carat)

I'm looking for the easiest way to do this in Drupal 7.
Any ideas?

Your best bet would be to just use CSS.  You can create that effect using absolutely positioned pseudo elements with some border tricks.  For example:

.sf-menu li {
  position: relative;
}

.sf-hover:after,
.active-trail:after {
  content: "";
  display: block;
  position: absolute;
  width: 100%;
  height: 20px;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 20px solid #369;
}


How to alter a link of the language switcher? I would like to alter the link displayed on the language switcher for the second language of my site, for a certain node. Essentially when you viewing a certain node in the main language, and then use the language switcher to view the secondary language, I want the language switcher to serve a different link from the one that links to the translation of the node on the main language. (The design of this node is different from the one on the main language, so just translating the node won't help in this case)

I've tried both
MYTHEME_preprocess_links__language_block(&$variables) and
MYMODULE_language_switch_links_alter(array &$links, $type, \Drupal\Core\Url $url) but in both cases either the variable I was interested was protected or private or I couldn't get any interesting variables to work with.

Is it allowed to use these hooks above for what I'm after, or it needs to be a more hacky way?

To wrap this up, here is the complete solution to this problem.

function mytheme_preprocess_links__language_block(&$variables) {
  $internal_path = $variables['links']['ja']['link']['#url']->getInternalPath();

  // In this case 'node/30074' is the translated node that will normally go to
  if ($internal_path == 'node/30074') {

    // We need to create a new Url object with the node we need to redirect to
    $new_internal_path = Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 30073], []);

    // ...and replace the original Url object
    $variables['links']['ja']['link']['#url'] = $new_internal_path;
  }
}

Thanks to Clive for pointing out the process for this problem.


How do I call an implementation of hook_form_alter()? I have a function in my module that implements hook_form_alter(): function getuserform_form_alter(&$form, $form_state, $form_id).

How do I call it? How do I pass it the required parameters?

hook_form_alter comes in two variants:

hook_form_alter
hook_form_FORM_ID_alter

Both are called when a form is retrieved using drupal_get_form or one of the other form builder functions, but the latter is only invoked for the form with the specific form_id. Unless you are doing the same alterations to multiple forms, it's a good idea to use the hook_form_FORM_ID_alter variation, as it will create less overhead.

All hooks are called by Drupal when certain events happen. For form_alter, that is when the form is being built. So all you need to do, using the example in your question, is to do a check on the $form_id and do the alterations you want.

Notice $form_state should be passed by reference using the &$form_state notation. Sometimes you need to not only change $form but also $form_state to be able to modify the form like you want.


How do I limit the access basing on the user role? How do I use an access callback to limit the access basing on the user role?

For example, in my site I have the following roles:

Administrator
Authenticate User
Anonymous user
Teacher

I want to make a particular page available only to the users who have the Teacher role. How can I achieve this?

function form_test_menu() {
  $items['programme_reg'] = array(
    'title' => 'Approved Programmes Registration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('form_test_form'),
    'access callback' => 'user_access',
    'access arguments' => array('Teaching')
  );

  return $items;
}

My code is not working.

user_access function takes permission name as an argument you can not pass user role name to it.

Here is how you can achieve this:

function MYMODULE_menu() {
  $items = array();

  $items['programme_reg'] = array(
    'title' => 'Approved Programmes Registration',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('MYMODULE_form_test_form'),
    'access callback' => '_MYMODULE_check_user_role',
  );

  return $items;
}

function _MYMODULE_check_user_role() {
  $account = $GLOBALS['user'];

  // Assuming that RID 4 is Teacher.
  // You can also check for role name in $account->roles array.
  return (isset($account->roles[4]) ? TRUE : FALSE);
}

Assuming that user role Teacher has Role ID as 4, you can check and return TRUE/FALSE in your own custom access callback. You can also check using Role Name instead of Role ID, see here for more details.


How to change autocomplete_route_parameters value on change of select option? How to change autocomplete_route_parameters value on change of select option?

I have a form element and inside autocomplete_route_parameters, I want to change $langcode value when I select any language from select list.

$form['node_items'] = array(
            '#type' => 'textfield',
            '#autocomplete_route_name' => 'autocomplete_node_search.autocomplete',
            '#autocomplete_route_parameters' => array('skip_node_id_string' => $skip_node_id_string, 'langcode' => $langcode),

          );

So if I choose language french from select list, $langcode should become = 'fr' via ajax.

I have used below example to do that.

https://api.drupal.org/api/examples/ajax_example%21ajax_example.module/function/ajax_example_dependent_dropdown/7.x-1.x

Customized it as listed below.

$form_state_values = $form_state->getValues();
if (!empty($form_state_values['language'])) {
  // write your logic here to prepare $skip_node_id_string & $langcode
}
$form['first'] = [
 '#type' => 'textfield',
 '#title' => $this->t('first'),
 '#autocomplete_route_name' => 'autocomplete_node_search.autocomplete',
 '#autocomplete_route_parameters' =>
 array('skip_node_id_string' =>$skip_node_id_string,
 'langcode' => $langcode),
 '#prefix' => '
',
 '#suffix' => '
',
];
$form['language'] = [
 '#type' => 'select',
 '#title' => $this->t('language'),
 '#options' => ['someval'],
 '#ajax' => [
  'callback' => [$this, 'changeLanguage'],
  'event' => 'change',
  'wrapper' => 'change-lang-wrap',
 ],
];
// Ajax callback.
public function changeLanguage(array &$form, FormStateInterface $form_state) {
 return $form['first'];
}

Hope this will fix your issue.

Tried below links, but no luck.

https://www.drupal.org/node/1135288


How can I remove an entry from the blog front page? If you enable the Blog core module in D7, you have a multiuser blog. It will produce a blog front page for all blog entries published at the path /blog.  It is just like the ordinary front page <front>, but only show nodes of type "blog".  By default, all published blog nodes appear on the blog front page.

For the site's default front page there is checkbox "Promoted to front page" under "Publishing options". Unchecking that prevents the node from appearing on the default front page.

Adding a similar checkbox field named "Promoted to blog front page" to the "blog" content type will of course do nothing by itself.

I want to use this field to control whether a blog node appear on blog front page, but have not found a "hook" or a "preprocess-function" or similar Drupal-thing that let me do so with the view of blog teasers that the core blog module produces.

I know I can do this by replacing the blog core module with my own, using Views to produce the list of teasers for the blog front page.

But in this question, I am looking for a way to do this with the view produced by the core blog module?

Is this possible, or must I use Views if I want this?

The blog module builds this page in the function blog_page_last().

The query in blog_page_last() does have a node_access tag so you could use hook_query_TAG_alter() to add a condition but may be tricky to just target that one query on that page.

I think a better option would be to use hook_menu_alter() to change the callback for the blog menu item to a function in your own module. In this function you can just copy the code from blog_page_last() but add a additional condition for your new promoted field.


Add an entity reference to a user I'm attempting to programmatically create test users in Drupal 8 via  hook_update_n(). I have an array of user attributes I'm using to create users.

I've got three fields added to the User entity that add term references to existing vocabularies that have been populated with terms. Two of these fields store a single term reference, while the third can store multiple term references.

I've retrieved the term object using this code.

    $term = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term')
        ->loadByProperties(['name' => $user['bu'], 'vid' =>
    'tx_business_unit']);

I'm trying to add a term reference to my user field, called "user_bu".

I've attempted to use the solution given on Programmatically update an entity reference field, but it doesn't work for me.

Everything else on my user record is being populated without issue.

For those of you who may be looking to answer the same question, here's how I got it to work in my case (I'm working on a Drupal 8.3 site):

$users = [
  'test_local_contributor' => [
    'password' => '1testme1',
    'langcode' => $language,
    'preferred_langcode' => $language,
    'email' => 'test_local_contributor@example.com',
    'roles' => [
      'employee',
      'local_contributor',
      'testuser',
    ],
    'location' => [
      'Kentucky',
      'Paradise',
    ],
    'sbu' => 'energy',
    'bu' => 'natural_gas',
  ],
  ...(there were other test users, omitted for brevity)
];

foreach ($users as $key => $user) {
  $newUser = User::create();
  $newUser->setUsername($key);
  $newUser->setPassword($user['password']);
  $newUser->enforceIsNew();
  $newUser->setEmail($user['email']);
  $newUser->set('langcode', $user['langcode']);
  $newUser->set('preferred_langcode', $user['langcode']);
  foreach ($user['roles'] as $role) {
    $newUser->addRole($role);
  }
  $newUser->set('status', 1);

  if (isset($user['bu'])) {
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $user['bu'], 'vid' => 'tx_business_unit']);
    $keys = array_keys($term);
    $newUser->set('user_bu', $keys);
  }

  if (isset($user['sbu'])) {
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $user['sbu'], 'vid' => 'tx_sbu']);
    $keys = array_keys($term);
    $newUser->set('user_sbu', $keys);
  }

  $loc_keys = array();
  foreach ($user['location'] as $location) {
    $newkeys = array();
    $term = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadByProperties(['name' => $location, 'vid' => 'tx_user_location']);
    $keys = array_keys($term);
    $newkeys = array_merge($loc_keys, $keys);
    $loc_keys = $newkeys;
  }
  $newUser->set('user_location', $loc_keys);

  $result = $newUser->save();
}


Access denied when using webform submissions email link Interim admin here- no experience- just trying to keep the wheels turning until a new hire made. Drupal 7.43.

Site has "contact us" form implemented as a webform, with email notification to certain addresses, who get email of the form:

  Submitted on Monday, July 18, 2016 - 4:48pm Submitted by anonymous user: IP.IP.IP.IP Submitted values are: Full Name Test2 Email test2@example.com Message This is an example The results of this submission may be viewed at: http://thenameofthesite.com/node/XXXXX/submission/YYYYY

where XXX and YYY are ids.

Users receiving the email complaining that clicking on the link gives a page on the site
with:

  Access denied
  You are not authorized to access this page.

In the admin for the Webform contact form, under Access control, anonymous user is checked for both "View any webform content" and "View own Webform content".

Users are claiming this worked before, and I don't have the experience to gainsay them. Any suggestions on what else I can try?

Those permissions are for viewing the webform itself - you would need to set permissions to view/edit/delete the submissions.  You can find these settings under "Webform" at /admin/people/permissions


Error when viewing list of taxonomy terms I'm getting an "unexpected error" when I try to view a list of taxonomy terms. I recently updated to 8.7, though I have a feeling the problem has been around since before the update. Here's the error as it appears in watchdog:

  Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') AS expression FROM tfr INNER JOIN tr ON tfr. = tr. AND tr. = 0 INNER JOIN (S' at line 1: SELECT tfr.tid AS tid, MAX(tfr.) AS expression FROM {} tfr INNER JOIN {} tr ON tfr. = tr. AND tr. = 0 INNER JOIN (SELECT t.tid AS tid, t.langcode AS langcode, MAX(t.) AS expression FROM {} t WHERE t. = :db_condition_placeholder_0 GROUP BY t.tid, t.langcode) mr ON tfr. = mr. AND tfr.langcode = mr.langcode GROUP BY tfr.tid; Array ( [:db_condition_placeholder_0] => 1 ) in Drupal\taxonomy\TermStorage->getTermIdsWithPendingRevisions() (line 404 of /Applications/MAMP/htdocs/libnews/core/modules/taxonomy/src/TermStorage.php).

And I don't know if this related, but I am also getting an error when I try to update my database via drush:

  Error: Call to a member function getKey() on null in system_update_8702() (line 2278 of /Applications/MAMP/htdocs/libnews/core/modules/system/system.install) #0

This is outside my area of expertise, so I'm pretty stumped.

I got a similar error on my server too.
I had to change the function in TermStorage.php to get it to work.

Just a warning, this core hack and should be reverted once it is fixed in core.
Replace getTermIdsWithPendingRevisions() with the following:

  public function getTermIdsWithPendingRevisions() {
$table_mapping = $this->getTableMapping();
$id_field = $table_mapping->getColumnNames($this->entityType->getKey('id'))['value'];
$revision_field = $table_mapping->getColumnNames($this->entityType->getKey('revision'))['value'];
$rta_field = $table_mapping->getColumnNames($this->entityType->getKey('revision_translation_affected'))['value'];
$langcode_field = $table_mapping->getColumnNames($this->entityType->getKey('langcode'))['value'];
$revision_default_field = $table_mapping->getColumnNames($this->entityType->getRevisionMetadataKey('revision_default'))['value'];

$query = $this->database->select($this->getRevisionDataTable(), 'tfr');
$query->fields('tfr', [$id_field]);
$query->addExpression("MAX(tfr.$revision_field)", $revision_field);

$query->join($this->getRevisionTable(), 'tr', "tfr.$revision_field = tr.$revision_field AND tr.$revision_default_field = 0");

$inner_select = $this->database->select($this->getRevisionDataTable(), 't');
$inner_select->condition("t.$rta_field", '1');
$inner_select->fields('t', [$id_field, $langcode_field]);
$inner_select->addExpression("MAX(t.$revision_field)", $revision_field);
$inner_select
  ->groupBy("t.$id_field")
  ->groupBy("t.$langcode_field");

$query->join($inner_select, 'mr', "tfr.$revision_field = mr.$revision_field AND tfr.$langcode_field = mr.$langcode_field");

$query->groupBy("tfr.$id_field");
return 0;
//return $query->execute()->fetchAllKeyed(1, 0);

}


Add bootstrap row class on every n views rows I am using Drupal Bootstrap and to get the correct positioning I am using bootstrap rows and columns classes.

How do I render a bootstrap row class on every let's say 3 view rows (bootstrap columns)? The structure must be like this

Use views bootstrap module, in views format style chose Bootstrap Grid it will solve your problem.


adding rel attribute to image link in a node I have a few images in a node that can be opened in a fancybox lightbox. I would like to link those images together to create a gallery. To do so I need to add a rel attribute to my image link. How can I do this?

I tried editing the field.tpl.php template, but without any luck.

Help would really be appreciated.

I need to add a rel attribute to my image link. How can I do
  this?

You can add a data attribute to your link in l() function:

// your image
$image = array(
    'style_name' => 'the name of the image style',
    'path' => 'relative path to your image',
    'alt' => '',
    'title' => '',
    'attributes' => array('class' => array('some_class'))
);

// link elements
$text = theme('image_style', $image); // in your case it's an image
$path = 'link_url';
$options = array(
    'attributes' => array(
        'class' => array('some_link_class'),
        'rel' => 'some_relation'
    ),
    'html' => true
);

$link =  l($text, $path, $options);

result:


How to notify user using ->messenger() and ajax? I would like to send a message to the user on an event in the backend without a refresh. I have a 2fa login form that will send a token text. That form has a "did not receive sms" button/link using ajax that causes the text to be sent again. I would like to inform the customer of the incoming message.
You can send a notification to the user using the MessengerInterface. But this requires a refresh to show the message.
\Drupal::messenger()->addStatus('Some conditional message to the user');

I would imagine that there is a way to send a message to the user using ajax/XHR? Which would not require a refresh.
My form has a wrapping div which I can target, the button/link has an '#ajax' element with, as far as I know, all the prerequisite elements:
'#ajax' => [
  'callback' => '::ajaxCallback',
  'event' => 'click',
  'wrapper' => 'twofa_wrapper',
],

I found this comment on the Drupal forum but using this code, with obvious replacements, does nothing apart from sending a XHR response, visible in the network tab. The json response contains a number of things one being the html for the form which contains the message that I would like to show, but it doesn't show this content on the actual page.
public function ajaxCallback(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  // This by some Drupal magic gets the messages
  $messages = ['#type' => 'status_messages'];
  $messages = \Drupal::service('renderer')->render($message);
  $response->addCommand(new HtmlCommand('#twofa_wrapper', $messages));
  $response->addCommand(new ReplaceCommand(null, $form));
  return $response;
}

What am I missing?
edit:

The wrapping element was (is) not rendering for some reason, if I include it in the template the callback shows the messages in that element at the top of the form.
The problem is that I need to renew the entire form because the contents might change on the ajax call. Replacing the contents works when I actually enclose the form in the wrapper element, but then the messages are no longer included.
I can see that the messages are part of the response but separate from the form contents. Second element messages third element the new form. The strange thing is the message are also not shown on a refresh.

This works for me:
$element = NULL;
if (!empty($triggering_element['#ajax']['element'])) {
  $element = \Drupal\Component\Utility\NestedArray::getValue($form, $triggering_element['#ajax']['element']);
}
// Element not specified or not found. Show messages on top of the form.
if (!$element) {
  $element = $form;
}
$response = new \Drupal\Core\Ajax\AjaxResponse();
$response->addCommand(new \Drupal\Core\Ajax\ReplaceCommand('[data-drupal-selector="' . $form['#attributes']['data-drupal-selector'] . '"]', $form));
$response->addCommand(new \Drupal\Core\Ajax\PrependCommand('[data-drupal-selector="' . $element['#attributes']['data-drupal-selector'] . '"]', ['#type' => 'status_messages']));
return $response;


Adding members to a group dynamically in Drupal 8 I am trying add members to a group programmatically using Groups module in Drupal 8, and I am doing the following to achieve this:

use Drupal\Core\Entity\ContentEntityBase;
$roles = array('test_role');
$values = ['group_roles' => $roles, 'gid' => 1];
$account = $this->createUser();
$group = \Drupal\group\Entity\Group::load(1);
$group->addMember($account, $values);

So, users are already present in the site. I want to add only those users to a group who have successfully paid for it. Hence, I am trying to write a custom solution that I add a user to an already existing group on the site. I came across this addMember($account, $values) function in the group module, however am still not sure on what values its arguments ($account and $values) take. Above piece of code does not add users to my group. Can someone please suggest what wrong I am doing here?

So, modifying the code a little bit and saving the group after adding member to it worked for me. Pasting the updated code below:

use Drupal\Core\Entity\ContentEntityBase;
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$group = \Drupal\group\Entity\Group::load($group_id);
$group->addMember($account);
$group->save();


drush and connecting with a non-localhost database I am attempting to update a Drupal website and the associated modules with drush 7. The MySQL database resides on another server within the same network. When attempting to run any command where drush would connect with the MySQL database the following error is returned:

  Command pm-list needs a higher bootstrap level to run - you will need
  to invoke drush from a more functional Drupal environment to run this
  command.

Running drush pml --debug I see that drush appears to be reading the correct database credentials:

  Executing: mysql --defaults-extra-file=/tmp/drush_EDQIvN
  --database=dlc_ode --host=correct.internal.ip.address --silent  < /tmp/drush_ltZVnl

But on the line just below:

  ERROR 1045 (28000): Access denied for user
  'root'@'ip-ip.of.localhost.us-west-2.compute.internal' (using
  password: YES)

Neither the user root nor the AWS domain is correct. I am new to drush and am not certain what is overriding the database credentials in the settings.php file.

I can connect with MySQL from the command line with no problem using mysql -u username -p. Drupal itself connects fine.

Any suggestions of what I am overlooking will be appreciated.

Thank you.

Occurred to me right after I posted my question to check whether someone had created another my.conf or .my.conf file on the system at sometime in the past. And yes there was a .my.conf file that had been created some years ago. Renamed the file and viola, drush pml works as expected.

Hopes this helps someone puzzled by incorrect database connection.


How do I remove the active class in the main menu? One item in the menu has sub-items that point to the same page (just with different arguments) ex:

Products
- List item 1  \products?pid=1
- List item 2  \products?pid=2
- List item 3  \products?pid=3

Drupal assigns the "active" class in the  and  tag of the menu items since all the items have the same page url (\products)

I'm overwriting the menu_link function in template.php to remove the active class but the class remains in the  tag

function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {

    if (strtolower($element['#title']) == 'Products') {

      if (isset($_GET['pid'])) {
        $currID = $_GET['pid'];

        foreach ($element['#below'] as $Taxonomy) {

          if ($currTaxonomyID != $Taxonomy['#localized_options']['query']['pid']) {
            $mlid = $Taxonomy['#original_link']['mlid'];
            $key = array_search('active', $Taxonomy['#attributes']['class'], TRUE);
            if ($key) {
              unset($element['#below'][$mlid]['#attributes']['class'][$key]);
              $element['#below'][$mlid]['#localized_options']['attributes']['class'][$key] = '';
            }
            // remove active-trail class
            $key = array_search('active-trail', $Taxonomy['#attributes']['class'], TRUE);
            if ($key) {
              $element['#below'][$mlid]['#attributes']['class'][$key] = '';
            }
          }
        }
      }
    }
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

Final Result:

      Best Practices

      Checklists

....

How can I remove the class "active" from the  tag?

My menu Structure:

-Clients
-Products
  -prod1 (url:\\products?pid=1)
  -prod2 (url:\\products?pid=2)
  -prod3 (url:\\products?pid=3)
  -prod4 (url:\\products?pid=4)
-About

I had the same problem: the l() function automatically assigns an active class when a link is pointing to the current page.

I got around this using an (ugly) hack:

As noted in the documentation, $options['language'] is additionally compared with $language_url->language before assigning the active class.

So, the hack is to supply a deliberately incorrect language when calling l().

You can find out what the current language of your site is using dpm():

global $language_url;
dpm($language_url->language);

In my case, I know that the language of the site is definitely not und, so I appended array('language' => 'und') to my call to l():

l('link text', 'path/to/page', array('language' => 'und'))

After this, the a element no longer had the active class.


How to display uploaded files as images in Views? Is it possible to display uploaded image files (not File Entities or Image Fields) as images inside a View? When I create a file View I can either choose to format it using fields, which allows me to display the file name etc, or as a rendered entity which does not display anything at all. I would like to be able to display a list of uploaded images via Views, as oppose to a list of file names. Can this be done?

Here is why I am trying to do this. I have CKEditor module enabled and I am using One Click Upload module to allow users to upload image files into their text areas. I have tried using Media and File Entity with CKEditor but they were very unstable and caused a great deal of database errors on my website. I also prefer One Click Upload's minimal interface, as the name of the module implies. The problem of course is that One Click Upload does not use File Entities or File Fields for uploading, which is why I am trying to work out how to format the files in Views to show up as rendered images. Is this possible?

Ok I managed to work it out, it is quite simple really; you need to rewrite the output of the field using the html img tag and the replacement patterns available. This will convert any image files uploaded into the website from file names into actual images.


Output referenced entity in correct language The following code outputs referenced entities in the original language they were created.

{% for story in node.field_stories %}
  {{ story.entity.label }}
{% endfor %}

I want it to render in the current language (translation) instead. How can I achieve this?

Do not use the raw field value, use the render array of the field instead:

{{ content.field_stories }}

This will automatically use the correct language.

NOT RECOMMENDED:
If you have to go the custom, raw value route you can do something like

{% for story in node.field_stories %}
  {% if story.entity.hasTranslation('iso2_langcode') %}
    {{ story.entity.getTranslation('iso2_langcode').label }}
  {% else %}
    {# fallback default lang #}
    {{ story.entity.label }}
  {% endif %}
{% endfor %}


Import CSV to nodes/entities in Drupal 8 including a UI What’s the best solution for importing CSV files into nodes or entities in Drupal 8 that offers a UI so content editors can import regularly?

I’ve heard D8 Migrate works well but I understand there’s currently no UI for the import process.

CSV import via Feeds doesn’t appear to be ready yet.

I do this all the time, making use of migration configuration entities (provided by the migrate_plus module). Define a migration plugin in your migration module's config/install directory, using the CSV source plugin from the migrate_source_csv module - omitting the 'path' source configuration, which will be filled in from the form. Let's say the ID of this migration is example_csv. Create a form with a file upload element (named 'csv_file' in this case), and in the submitForm() method:

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $all_files = $this->getRequest()->files->get('files', []);
    if (!empty($all_files['csv_file'])) {
      $validators = ['file_validate_extensions' => ['csv']];
      if ($file = file_save_upload('csv_file', $validators, 'public://', 0)) {
        $csv_migration = Migration::load('example_csv');
        $source = $csv_migration->get('source');
        $source['path'] = $file->getFileUri();
        $csv_migration->set('source', $source);
        $csv_migration->save();
        drupal_set_message($this->t('File uploaded as @uri.', ['@uri' => $file->getFileUri()]));
      }
      else {
        drupal_set_message($this->t('File upload failed.'));
      }
    }
  }

This updates the migration settings with the new file. You still have to run the migration using drush mi example_csv to actually import the content.

Or add some code to the function to actually execute the import:

      $migration_instance = \Drupal::service('plugin.manager.migration')->createInstance('example_csv');

      $executable = new MigrateExecutable($migration_instance, new MigrateMessage());

      try {
        $migration_status = $executable->import();
      }
      catch (\Exception $e) {
        \Drupal::logger('migrate_drupal_ui')->error($e->getMessage());
        $migration_status = MigrationInterface::RESULT_FAILED;
      }
      if ($migration_status) {
        drupal_set_message($this->t('Import Successful'));
      }
      else {
        drupal_set_message($migration_status, 'error');
      }


How can I create a custom page with a different template? I want to have a page (e.g. the one at http://example.com/mypage) shown as a blank page. How can I use a different template for that specific page, to show it as a blank page?

You can use a different template for a page by suggesting a new template file that will be used.

This can be done in a theme, by writing its template_preprocess_page(), or in a module by implementing hook_preprocess_page().

function template_preprocess_page(&$variables) {
  if (arg(0) == "node" && arg(1) == "1") {
    array_unshift($variables['theme_hook_suggestions'], "page--custom-template");
  }
}

This code is for Drupal 7; for Drupal 6 you need to replace $variables['theme_hook_suggestions'] with $variables['template_files']. In the case you are using it in a module, template_preprocess_page() needs to be renamed mymodule_preprocess_page(), where "mymodule" is the short name of your module.
Instead of using arg() you can also use request_uri(), but the output returned from this function is similar to "/dr72/devel/php?render=overlay&render=overlay" when Drupal is installed in a subdirectory of the web server's root directory. request_uri() doesn't change an alias into the canonical path; supposing that example.com/node-1-title is an alias for example.com/node/1, in my test site, the function will return "/dr72/node-1-title" while arg(0) and arg(1) would return, respectively, "node" and "1" (the first two elements of the path).


Drupal 7 Exposed Filter Display Text I have an exposed filter in drupal, but some text is not displaying as expected. One list displays exactly as I want and that is the Acoustic Guitars as shown in the picture, but I cannot for the life of me figure out why the other filters are not displaying like the Acoustic Guitars. Here is the picture, does anyone know what settings I would need to change to get this to display the description instead of the category like the Acoustic Guitars list?

I'ts in your content type. You might have mistaken the label with the value, or not used the label at all. Open the content type, edit each field and change the allowed values as described above the textarea.

If I'm not mistaken it is

Label|value


How to filter a view based on tags applied to I'm working on an old (2009) Drupal 6 site that uses a custom module to add a field to the content creation pages for certain node types. That field lists a sub-set of the users of a certain user type.

Some of those users are now being free-tagged on the site. I'd like to be able to create a view that lists only the nodes that refer to users that have a specific tag.

If that sounds a bit complicated, here's an example. Imagine a D6 site that works as an intranet for a doctor's surgery. Each doctor has a user account on the site, as does each patient. A custom module lets patients be allocated to doctors. After every appointment, the doctor fills in a report. That report is a node type, and includes a field created by a custom module that allows the doctor to select the patient who had the appointment, from a list of all of the patients who are allocated to that doctor.

Now, imagine that each patient's account could be free-tagged, and tags such as "male", "female", "diabetic", "pregnant", etc. were added to the patients' user accounts. How would I go about building a view that would display all of the reports given to patients who are tagged as "pregnant"?

So, shortly after posting this question I worked out how to do it.

When I built this site I included the facility to create a Views relationship that points at the "referred to" user (the "patient" in the above example). So, I created this relationship in the view that I built. I then created another relationship that was itself based on the first relationship but pointing at the node created by the Content Profile module.

Then, I created a filter based on the second relationship, that filtered based on the taxonomy term I'd created (i.e., the "diabetic", "pregnant" stuff above). That did the trick.


Unlike other rules my custom Commerce Fees rule is executing on every cron job I have the following Commerce Fees rule:

{ "rules_setup_fee" : {
    "LABEL" : "Setup Fee",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce License Billing" ],
    "REQUIRES" : [ "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "NOT data_is_empty" : { "data" : [ "commerce-order:commerce-line-items:0:line-item-label" ] } },
      { "AND" : [
          { "text_matches" : {
              "text" : [ "commerce-order:commerce-line-items:0:line-item-label" ],
              "match" : "VS"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "setup_fee",
          "amount" : "999",
          "currency_code" : "USD"
        }
      }
    ]
  }
}

which is working just fine, however it is the only rule that shows in the log messages way too frequently:

Type    rules
Date    Thursday, January 14, 2016 - 17:50
User    drupal
Location    http://drupal/admin/config/system/cron
Referrer    http://drupal/admin/config/system/cron
Message Rules debug information:
" Reacting on event Apply a fee to a given order.
0 ms Reacting on event Apply a fee to a given order.
2.988 ms Evaluating conditions of rule Setup Fee. [edit]
3.538 ms The condition data_is_empty evaluated to TRUE [edit]
3.547 ms AND evaluated to FALSE.
3.563 ms Finished reacting on event Apply a fee to a given order.
Severity    notice

It seems like while other rules execute only when necessary, this one does on every cron run. What kind of condition I should add to the rule to make it execute only when someone tries to actually tries to put something in the shopping cart?

I take from the rule export that you're using Commerce License Billing? Well, if you are, then likely it is applying the fees whenever doing it's billing calculations.

Commerce Fees defines it's own rules event that fires off when an order refresh occurs. Order refreshes are done by calling commerce_cart_order_refresh(). When you load an order, a hook_commerce_order_load() gets invoked and commerce_cart has a commerce_cart_commerce_order_load() hook that refreshes orders if certain criteria are met:

The order hasn't been refreshed in this request.
The order is a shopping cart.
The order is the latest revision.
The order can be refreshed. (Commerce 1.9 added new rules to add performance by regulating this better.)

Long story short: It sounds like your install is working fine and in general unless you have thousands of rules firing on every page request, there is little to worry about. Rules are effectively just a wrapper around plan PHP functions. Your cron is running and a new order is being generated or refreshed in some way and so the rule fires.


Update a single field when saving an entity Question: How do I update a single field of an entity? For example, lets say I have a user and want to update field_my_field. How do I just update that without using user_save?

My Specific Problem:
I have a a bunch of user fields defined, and am trying to optimize the performance of my site. I am using views_bulk_operations, and my code is timing out (maximum execution time) because I am repeatedly calling user_save, and it's an expensive operation.

I am only updating a single field, and would like to optimize this code. Rather than calling user_save, which is taking 500ms to run, I'd like to update the field directly.

I attempted to use field_attach_update(), and that works a little better, but that's also updating all the fields. Is there any specific way just to update or save a specific field for an entity?

I'm not interested in batch operations, or anything at the moment -- I know how to do that, and can convert this into a batch so I don't run into execution timeouts. I just want to know how to save a single field for an entity.

Give a try with field_sql_storage_field_storage_write.

See this blog post with an example:

//Get the id of your field
$name = 'name_of_your_field';
$info = field_info_field($field_name);
$fields = array(info['id']);

//Execute the storage function
field_sql_storage_field_storage_write('model', $entity, 'update', $fields);


Get path of uploaded file inside a Twig template I've created a teaser template like this node--type--teaser.html.twig.
Within that template I want to conditionally create a link to a file that was uploaded via the field field_pdf.

How do you extract JUST the path to the pdf in the template.

I've tried {{ file_url(node.field_pdf.entity.url.value) }} but that just brings back an empty path.

If thats not possible, is there a way to get a file path from the fid in twig?

Manage teaser Display : Change Format of your file field to Generic File From  admin/structure/types/manage/YouRContentType/display/teaser .
In your twig node--type--teaser.html.twig just print  {{
file_url(node.field_pdf.entity.uri.value) }} you will get the path to your file.
Note : As mentioned in comment it's uri Not url.


Custom user_register_form for Auto Assign Role registration pages I'm using a function[a] to get custom templates to work for all pages, including role registration pages set by Auto Assign Role. By setting the role registration path to user/register/<rolename> I'm able to use page--user--register--rolename.tpl.php to make custom pages.

What I'm trying to do now is use a custom user_register_form for each role registration page. Using this function[b] I'm able to use user-register-form.tpl.php to customize the registration form. This affects the form for both role pages though. I tried using the Field Permissions module, but because an anonymous user will be using both forms it's of no use here.

I'm thinking I need to change what user-register-form template the page itself is looking for, but I can't figure out how to do that.

a.

function THEMENAME_preprocess_page(&$vars) {

  if (isset($vars['node'])) {

    $suggests = &$vars['theme_hook_suggestions'];

    $args = arg();
    // Remove first argument of "node".
    unset($args[0]);

    $type = "page__type_{$vars['node']->type}";

    $suggests = array_merge(
      $suggests,
      array($type),
      theme_get_suggestions($args, $type)
    );
  }
}

b.

 function THEMENAME_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'THEMENAME') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
       'THEMENAME_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'THEMENAME') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'THEMENAME_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'THEMENAME') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'THEMENAME_preprocess_user_pass'
    ),
  );
  return $items;
}

I think if you already have a template file for the form user-register-form.tpl.php, you should be able to use a preprocess like this:

function MYTHEME_preprocess_user_register_form($vars) {
  // if role2
  // use other theme
}

There should be no need to define your own themes with hook_theme


Drupal 7 : i want to add the registration fields (username/e-mail etc) to a profile 2 registration form i am relatively new to drupal. So, here is my question :

I have more profile2 types, assigned as roles (doctors/patients/partners etc). Each role has it's own registration form, shown at registration page, alongside with the obligatory fields of the registration (username, password, e-mail, etc...). For each role there is a unique registration path. The problem is that i want the registration form to be a multistep sort of "registration wizard". I have accomplished that with the multistep and field group modules, but this applies ONLY to the profile2 registration form. In other words, as the steps for the profile2 registration form go forward, the obligatory fields for registration remain at their position, below the form. I would like to integrate them as a step (the first one) of my multistep wizard. Any solutions???

I have achieved the above with a similar setup to yourself.

You state you have used 'registration wizard', so I assume you have created custom forms for the profile2 fields. Furthermore, you are validating and submitting the values at the end.

The simplest method is to create a custom form at the beginning of your process for username, email, password, etc. Then using the user_save() function. Of course you will need to ensure current users don't exist already, which is easy enough using user_validate_mail().

Hope this help.
Amarjit


Ways to implement auto voting feature on a content type? I have a content type called "articles".  A user adds a new article and other users on the site can vote for the article.  I am using the Drupal default poll module.  In order for this to work, I have to do the below steps:

Create new poll.
Link submitted article to newly created poll.
Publish article to open it up for voting.

I am trying to eliminate step 1 and step 2.  In other words, the poll would immediately be registered into the newly submitted article.  Aside from writing my own custom module, is there another way?

The Rate might be useful for what you are trying to accomplish.

  This module provides flexible voting widgets for nodes and comments.

  Administrators can add multiple widgets. By default, there are 8 widget types to choose from:

  Thumbs up
  Thumbs up / down
  Number up / down
  Fivestar
  Emotion (this makes me mad, angry...)
  Yes/no
  Slider (Drupal 6 only)
  Custom