Drupal 7 Migration - redirect old dynamic urls to new domain name I just cloned a drupal 7 site to another domain name. Now i want to only redirect some of the URLS from the old site to the new site. Problem is that I have many (300+) dynamically generated URLs via views. Most likely I will have to do this via .htaccess modrewrites doing a 301 redirect. Basically I want to do is this:

Site #1:

abc.com/products/shoe

abc.com/products/shoe/blue

abc.com/products/shirt/neon

Site #2:

xyz.com/products/shoe

xyz.com/products/shoe/blue

xyz.com/products/shirt/neon

-- Where would I create this modrewrite in the .htaccess file? on the bottom or do I have to edit anything else? also would it affect anything else?

There are three ways to tackle this.

You can make the mod_rewrite rules in you Apache configuration.  The benefit of this is that you can keep your Drupal .htaccess stock, so you don't need to worry about losing changes when you update core.  How/where this goes depends on you have Apache configured.  On my servers, I use virtual hosts, so I add a <IfModule mod_rewrite.c> inside the <Directory> section.
You can edit the stock .htaccess that comes with Drupal.  You need to add them above the main rewrite that punts to index.php, which starts on line 112 in Drupal 7.x HEAD.  When you do this, you need to make sure you back up and restore this file when you update core (or track in RCS and merge changes).
You can use a combination of the Pathologic and  Redirect modules. Pathologic will set up rules that rewrite URLs in your content when they get rendered out.  Redirect can set up 301/302 redirects for inbound requests.

Of the three choices, I try to avoid #2.  I manage a lot of sites, and I don't want to keep track of which have custom .htaccess files.

Between #3 and #1, I tend to prefer #3 because I can have someone else manage this process via the UI.  However, if I have a lot of URLs with common patterns, or for simple domain redirections, I will use #1.  Typically, I end up using a combination of #1 and #3.


Add class to image in view Is there a way to add a specific class to the img tag in a view? I'd prefer to use a template to perform it. I can see how I can change what classes the image is wrapped in, but I don't see a way to edit the classes of the img tag itself.

I see there's a way to edit the image field using views-view-field--field-image.tpl.php however the only variable I can see that is available is $output.

If .myclass img { your code goes here } is not good enough and you must have the class inside the img tag, then:

1) Download and enable the Image URL Formater Module

2) On your view's picture field, select url as format.

3)

Option A) In the rewrite results field type

Option B) if you want to use the .tpl.php file, put this inside it.

<img src='<?php print $fields["field_image"]->content; ?>' class='yay-we-did-it'>


Combine 2 fields in one div with Twig I have three templates

field--field-custom.html.twig
field--field-custom1.html.twig
field--field-image.html.twig

I also have a teaser template containing all three fields like that:

<div{{ content_attributes.addClass('node__content', 'container') }}>
    {{ content }}
</div>

I want to have the first two templates in a bootstrap div, for example

col-sm-6

and the third template in the other div

col-sm-6

If I include the second template in the first template file it just repeats the field instead of rendering the intended field (both templates are name suggestions of the same file).
What can I do in order to have both fields in the same template file?

Just chunk the output by using the field names:

{{ content.field_custom }} {{ content.field_custom1 }}

Then do the same for the remaining field.


Searching entity reference field value with Search API I am using Seach API, Solr Search modules in my website for searching.
I've created an index, say 'Blogs index',
I've selected blogs content type to index
Fields - title, body, Author are added to index.

Created the View for the search results.

Issue is when I search the name of the author, I'm getting no relevant results. Result should be the list of blogs written by the searched author.

field Author is an entity reference field referencing the content type 'Blog Author' and is a multi-valued field.
Any help is appreciated.

I haven't tried this with Search API but if your "Author" is a separate content type and not the actual default Author field you need to add the Relationship for that Entity reference field (for the "Blog Author" content type).

Different Content types store data in different database tables. Relationships introduce that other table data into your Views.

You'll probably have to add the Title field using that Relationship (which is, I presume, your blog author name), and include that field in the Search API settings so it gets searched.

Entity reference fields only store the ID of the referenced entity, so using them alone won't let you search the actual Title field text of the referenced entity. You can only do that through the Relationship and the relevant Title field (or however you named that field).


Hook user register action How to hook user registration page? Basically I want to save some cookies when user comes on the register page through an affiliate link. I used hook_user_view but it is working only when user is logged in. Can someone please tell me how to do that?

Implement hook_form_alter() and check $form_id == 'user_register_form'


Drupal equivalent of wget (with permissions)? I'm working on a drupal 6 module and need a way to save a static html version of a node to the server, using the user's permissions.  Basically I need the equivalent of "wget -O out.htm http://mydrupalsite.org/node/1635" in drupal, that uses the activating user's permissions and login, but don't know enough about drupal to make this work without some pointers in the right direction.  I've looked through the functions list and the module code for http://drupal.org/project/print, but no luck.  Any help?

Thanks in advance.

EDIT: Clarification:  What I'm trying to accomplish is have a sidebar link for users to use that saves a copy of the current page -exactly as apache just sent it the user- to the server.  I'm trying to do this through drupal -without- using wget or any other system utility.

Is this for your site users to have a preview a static html page or node on your site?!

Cant you use drupal_render at a custom menu callback URL or Rule to get the HTML generated for 1 of your pages and save it to a file in your webroot or sites/all/files/SOMEDIR
then using RewriteCond in your Apache site configuration to ignore these static files so you can access them via a non-drupal URL ...
In drupal 7 at least there is like function node_view that lets you load a node for viewing, it respects user access rigts for visibility of stuff on the node.

There are programmatic ways to create and load a user (with assigned roles as well) in any version of Drupal. So you could tie all these bits together as:

Generate HTML fragment of node/page logic could be:

switch to some user by UID.
node_load() some node owned by user NID.
node_view() the node contents as some user.
drupal_render() get the raw HTML.
save to some filesystem location as .HTML file.


Using Rules to Prune Inactive Users - will this work? I am relatively new to Drupal and learning as I develop a new website for our network of chapters. Needless to say, that has been quite the challenge :)

One of the functionalities I needed was the ability to prune inactive users. We have this on our current system and like having it to keep our membership numbers accurate, as well as help our members feel more "secure" by knowing only active members have access to the chapter.

There were a couple of modules out there to do this, but they were all for Drupal 6 or only had development modules for Drupal 7.

I found this link:
https://drupal.org/node/1582710

and have followed it to set up my own "prune users" using rules. But I have NO idea how to test this in the development stage and certainly don't want it to screw up and accidentally mess up memberships when we move to the live versions.

What I have done is as follows:

Set up the following components:

Send email stating user has been inactive for 30 days and schedule next letter in 30 days
Send email stating user has been inactive for 60 days and schedule next letter in 25 days
Send email stating user is in danger of being pruned and must login to keep account and schedule blocking user in 5 days.
Block user

Set up the following rules:

Inactive User: When user logs in, remove all currently scheduled rules and set component evaluation for inactive for 30 days letter.
Never Logged In: When user account is first approved, set component evaluation for inactive for 30 days letter.

I think this means that when a user first signs up, they will get scheduled for the inactive user letter. Every time they log in, it will reset to the 30 day letter in 30 days. If they never log in, in 30 days, they will get the first letter and the 2nd letter will schedule... until they are pruned. If they log in, everything resets.

I know this means that every user will have a scheduled inactive user letter task -- not sure if this will bog down my system too much?

Also, if this does sound right -- how do I go about testing it to make sure it works the way it is supposed to and doesn't accidentally block users its not supposed to?

One last thing -- what can I do to automatically delete the users that are "blocked" and have been members for a certain amount of time (to ensure that new members who are just not approved yet don't accidentally get "pruned"?)

If I have made a complete mess of this, please feel free to tell me so! Like I said, I am really new at this and still figuring it out as I go along... I appreciate any help you can give me!

Your solution "may" work, but another approach is to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of users that are candidate for deletion.
add a loop to perform a Rules Action "delete user", for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

The advantage is that, if you first run it manually, you can see which users will get deleted (simply by browsing the Views results). When you feel comfortable enough, just automate this by rescheduling it every day (at the end of the rule itself, after you first triggered the rule manually).


Drush post-installation - where can I find drushrc.php? Just getting my first hands-on with Drush 5.1. The stuff works and is very promising as per how modules can be installed and enabled. One question though. Where should I look for the drushrc.php file that everyone is referring to and how should I code it to set up aliases for my sites?

I did a search over my disk and found nothing except examples.aliases.drushrc.php. Also I found a couple of mysterious locations:

C:\Program Files\Drush
C:\Program Files\Propeople\Drush
C:\ProgramData\Drush
C:\ProgramData\Propeople\Drush

They surely contain vital stuff and I'm not going to touch anything, but I'm wondering if this is the correct post-installation shape.

First off, note that alias records go in *.aliases.drushrc.php, whereas general (global) Drush settings go in drushrc.php.  You can find example.aliases.drushrc.php and example.drushrc.php in the Drush "examples" folder.  Drush will look for aliases.drushrc.php and drushrc.php in the ".drush" folder in your home directory.  On most of my systems (Linux), my home directory is /home/ga; on Linux, $HOME and ~ will expand to your home directory.  On my Windows system, my home directory is at 'c:/Users/Greg Anderson'.  To find out exactly where Drush thinks your home directory is, run:

drush ev 'print(drush_server_home());'

Create a .drush folder inside of your home directory, copy example.drushrc.php to .drush/drushrc.php, and example.aliases.drushrc.php to .drush/aliases.drushrc.php, and customize to suit.


What causes very long initial visit load times intermittently? I'm working on what is basically a one page site externally:

http://drupals.badgerfort.com.

There's very little to it. But I'm getting reports that it's sometimes loading so slow to the point that a couple refreshes are required to get it to load on first visit.  Now as this is such a small site, virtually every significant module is turned off.

I mean Update is off, Views is off, Date is off and on and on. In addition to that the few graphics are optimized. There's no external content integrated that could be causing it to hang that I can think of. CSS and JS are being aggregated. Caching is off, but it is a one page site, so on initial visit I wouldn't think caching would provide any advantage.

What are some of the potential causes of an issue like this?

If users experience very long response time for initial visit, but then next visits are fast - then it definitely could be related to the cron (as suggested by Geoff).

Here is a quote from official cron documentation:

  It [internal cron] works by checking at the end of each Drupal request to see when cron last ran and, if it has been too long, processing the cron tasks as part of that request. The two down-sides are (1) cron tasks will only run when Drupal is processing requests; and (2) the 'weight' (processing and memory) of running the cron tasks will be added to some arbitrary unknown page request, which may slow down those requests, and has the potential to exceed memory limits on a complex site.

To prevent this, configure external cron job that will trigger Drupal cron jobs more often that 3 hours (my suggestion is to run external cron every hour).

In addition you can configure internal cron to run less often by configuring it here /admin/config/system/cron.


Drupal 7 views grouping and aggregation with recipe ingredients I'm using drupal 7 in conjunction with the recipe module, Every recipe has a number of ingredients that are stored as fields in the database. I'm trying to create an xml view (using views datasource) that lists all of the recipes, but also lists their ingredients. Here is my problem, rather than this;

<node>
<title>The Title<title>
<ingredient name> Ingred 1<ingredient name>
<ingredient name> Ingred 2<ingredient name>
<ingredient name> Ingred 3<ingredient name>
<node>

the output I'm getting is this;

  <node>
    <title>The Title<title>
    <ingredient name> Ingred 1<ingredient name>
  <node>

  <node>
    <title>The Title<title>
    <ingredient name> Ingred 2<ingredient name>
  <node>

  <node>
    <title>The Title<title>
    <ingredient name> Ingred 3<ingredient name>
  <node>

It lists it as three seperate nodes, even though there is only one node. I've tried using the "aggregation" settings but still no luck, any ideas?

I use the group by option in the Format settings.  If you group by the Title, then Exclude that field from display...you should end up with a list as you describe above.


Custom Content Type Design I have a custom content type with a image field and several other fields, how do I make the other fields appear next to or inline with the image?

Two ways here. The fields all have CSS that is unique to them. All CCK fields start with "field-" you can absolutely position the items or make them inline and then float the image on the left or the right.

I found a good blog post on this from my bookmarks.

http://zroger.com/2009/06/theming-cck-fields-the-right-way/

You can also make a custom tpl file that drupal will call when it opens the given node type. The link to that is below. The prose used is interesting and shows their frustration over making these.

http://www.advantagelabs.com/drupal-colonoscopy-or-how-theme-cck-field-drupal-6


Drupal Bootstrap - Regions Placement I'm making my first attempt at creating my own Sub-Theme of the Bootstrap theme. I've got the theme installed, the sub-theme created and working, I've added some new regions and populated them. The situation I'm encountering is, the regions just display one under the other, where I want (at least certain ones) to display side by side. I've added "float: left;" code, but that doesn't seem to make any difference. I'm guessing that I need to "float" the region, rather than the block inside of it. However, I'm not sure how to do that. I've searched Google, I've searched YouTube, I've searched Drupal.ORG, I've searched the Drupal Bootstrap site documentation, and I'm not finding anything. Someone on Drupal.ORG told me that such modifications could be made via CSS, however, I've searched the bootstrap-theme.min.css file, and I find no mention of any of the regions. I would appreciate some pointers on how to do this correctly.

I'm using Drupal 8.5.3 and Bootstrap theme version 8.x-3.11

With Bootstrap you can have two regions side by side wrapping them with a row and adding a col-size-number class to them, like this:

    ...

    ...

You have to do that in the page.html.twig file.


How to add an attribute to User reference I would need to add an attribute to a user_reference field that "explains" the type of relationship.

Example:
My users are music players and the play in different groups.
The same user can play guitar in one group and the bass in another group.

Groups are my nodes and I can link them with the players. While I am linking them, I would also like to set the instruments they play in that group.

Group 1 - Player1|guitar
Group 2 - Player1|bass
Group 3 - Player2|guitar

Probably a way to do that is using "field collection"; is there another way?

Alternatives could be Paragraphs, Multifield, Inline Entity Form or Double Field.


Is there a difference in the use of hook_preprocess_HOOK() Is there a difference in the use of hook_preprocess_HOOK()?

In Drupal 8 when I use :

hook_preprocess_page
hook_preprocess_node
hook_preprocess_block

All my Implements for page, node or block work good.

But when I use hook_preprocess_menu some staff don't want to work, what work in preprocess function up.

For example:

This work perfect

function theme_name_preprocess_page(&$variables) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}

But this don't work.

function theme_name_preprocess_menu(&$variables, $hook) {
$variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
  }

If you use:

function theme_name_preprocess_menu(&$variables, $hook) {
  $variables['logopath'] = '/' . drupal_get_path('theme','theme_name') . '/logo.png';
}

The hook is menu, so Drupal will look for menu.html.twig, if you define any var inside this preprocess you only be able to use in menu.html.twig. Look the Hook at your theme suggestions comments, if you see 'block' you will need use theme_name_preprocess_block instead.


How to unpublish or disable webform components without code for d7? How  to unpublish or disable webform components without code for d7?

I've seen answers to do this programmatically, but I'm looking for a simple "unpublish" or "disable" field from back end GUI, is that possible?

Webform itself offers no UI-based method for disabling/un-publishing components.

Unless you can find something in contrib that can help (or perhaps convince the developer of webform to add it as a feature), you'll need custom code to achieve it.

As an example you may be able to configure Webform Conditional to disable fields unconditionally, or based on a contrived condition, to simulate the effect. But it wasn't necessarily built for the purpose you need.


Adding new fields using hook_field_schema_alter() I have an entity whose field schema is already defined and now I am trying to add couple of fields to it.

But I am not sure how to code it up using schema_alter.Below is an example on how I would code the schema for the field using hook_field_schema().

function hook_field_schema($field){
  $columns = array();
  if($field['type'] == 'some_field_name'){
  $columns = array(
              'col1'=>array(
                     'type =>'text'
                     'size' => 'big'
                     'not null' => false),
              'col2'=>array(
                     'type =>'text'
                     'size' => 'big'
                     'not null' => false),
              );
  }
 //Similar for other fields
}

Confusion is on how to decompose this schema according to schema_alter.

I am following this article to implement hook_field_schema_alter()

Edit: I am using an update function to create the field (field_create_instance), since this is an already an existing module and I do not want to disable it and enabled it again.

You would need to call the field_create_instance() function passing a new array.

 $instance = array(
    'field_name' => 'field_my_custom', // ** This already exists, or check with field_info_field()
    'entity_type' => 'node',
    'label' => 'a label',
    'bundle' => $content_type,
    'widget' => array(), // if you're not sure about your widget settings, take a glimpse at an existing field instance using debug(field_info_instance(...));
);
field_create_instance($instance);

More links to read and better understand the above functions:

https://api.drupal.org/api/drupal/modules%21field%21field.info.inc/function/field_info_field/7
https://api.drupal.org/api/drupal/modules%21field%21field.info.inc/function/field_info_instance/7
https://api.drupal.org/api/drupal/modules%21field%21field.crud.inc/function/field_create_instance/7

Also, take a look at the Examples for Developers module, node example and field example.


return all content types name containing text files I want to get the content type name instead of the file name:
I have this function that access to the files folder: site/all/default/files and get all the file with a text extension and put the text files in an array, is there a possibilty to retun all content types names that contain text files instead of the text files names?

function get_projects(){

$directory= variable_get('file_directory_path', 'sites/default/files');
$filenames = array();
$extension =".txt";

$iterator = new DirectoryIterator($directory);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
    //check the extension ".txt"
    if (strpos($fileinfo->getFilename(),'.txt') !== false)
    {
        //Delete the extension ".txt"
        $filenames[$fileinfo->getMTime()] =substr($fileinfo->getFilename(), 0, -4);
        //$filenames[$fileinfo->getMTime()] =$fileinfo->getFilename();
        //$fileinfo->getFilename().get
     }
 }
}
 return $filenames;

}

function get_content_type_by_filename($filenames = array()) {
    $sql = "SELECT nt.name, fm.fid
    FROM file_managed AS fm
    LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
    LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
    LEFT OUTER JOIN node_type AS nt ON (n.type = nt.type)
    WHERE fu.type = 'node' AND n.nid IS NOT NULL AND fm.filename IN (:filename)";
    $results = db_query($sql, array(':filename' => $filenames));
    $results = $results->fetchAll();
    return $results;
  }

This function accepts an array of file names you want to find content types for and returns an array of matched objects with properties fid and content type.

Update:

Please take a note that I am not trying to give you the exact code rather point you in the right direction.

To achieve what you want, call the function you mentioned in the question (i assume it does what you say, that it returns an array of file names)

so :

function get_content_type_by_filename($filenames = array()) {
    $sql = "SELECT nt.name, fm.fid
    FROM file_managed AS fm
    LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
    LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
    LEFT OUTER JOIN node_type AS nt ON (n.type = nt.type)
    WHERE fu.type = 'node' AND n.nid IS NOT NULL AND fm.filename IN (:filename)";
    $results = db_query($sql, array(':filename' => $filenames));
    $results = $results->fetchAll();
    $types_array = array();
    foreach($results as $obj) {
      $types_array[] = $obj->name;
    }
    return $types_array;
  }
$files_array = get_projects();
$content_types_array = get_content_type_by_filename($files_array);

The $content_types_array will contain the array of content type names.
Hope this helps.If this does not give please debug by installing devel module and passing the variables and arrays through dpm() function to see contents of the array.


How can I untheme a fieldset provided by theme_fieldset()? I'm allowing users to set their time zone upon registration.  However, I don't want to show the "Locale settings" fieldset that is provided (border, title "Locale Settings", etc.)  Is there a simple way to use hooks to remove the fieldset markup but not the content of the fieldset itself?

With theme_devel, I've been able to get the function that makes the fieldset (theme_fieldset()) as well as the form id (edit-timezone).  But I don't know what to do with these to hide the fieldset markup but allow the content to remain.

You need to alter the form that contains that fieldset. You could do it using code similar to the following one.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Only alter user forms if there is more than one language.
  if (drupal_multilingual()) {
    // Display language selector when either creating a user on the admin
    // interface or editing a user account.
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      if (isset($form['locale'])) {
        foreach (element_children($form['locale']) as $id) {
          $form[$id] = $form['locale'][$id];
          $form[$id]['#access'] = $form['locale']['#access'];
        }
      }

      unset($form['locale']);
    }
  }
}

The code I wrote removes the fieldset from both the registration form, and the user profile form.
For the user registration form, the language fieldset is normally hidden to the users that don't have the permission to administer users. There could be a module that shows that fieldset to every user.
If you want to be sure that your code doesn't create problems to other modules, you should be sure it is executed after all the other modules that add fields to $form['locale'].
Usually there isn't any reason to remove a fieldset. It is convenient for the users to have related fields grouped together; in that way, if they don't need to edit them, they just collapse the fieldset.

To be sure the code of your module is executed after all the other modules, you could do proceed with two methods:

You can alter the module weight, and increase it. In this way, the hooks implemented in your module would be executed for last.
You can implement hook_module_implements_alter() to alter the order some hooks are executed.

function mymodule_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move mymodule_form_alter() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

The documentation for hook_module_implements_alter() reports the following notes:

  Note that hooks invoked using drupal_alter() can have multiple variations (such as hook_form_alter() and hook_form_FORM_ID_alter()). drupal_alter() will call all such variants defined by a single module in turn. For the purposes of hook_module_implements_alter(), these variants are treated as a single hook. Thus, to ensure that your implementation ofhook_form_FORM_ID_alter() is called at the right time, you will have to have to change the order of hook_form_alter() implementation in hook_module_implements_alter().

Between the two methods, I would use the latter, as it doesn't change the order other hooks are executed, differently from the first.


Hook that runs after template.php Currently, I am using hook_page_alter() in my module, but this runs too early. I am loading some fields from the node in template.php so that I can put them into other regions. These fields need JavaScript code from my module, after they are loaded, as the JavaScript depends on the IDs which are generated during the field loading process.

If anyone can help or point me to a list of hooks ordered by the point at which they are run then that would be a great help.

template_preprocess_field() hook is your friend.

The general flow is:

theme($hook, $var) >> preprocess functions >> process functions >> finally either goto template.php or call theme function >> return output as string

therefore, template.php or theme function call is the final destination, no hook runs after template.php


Accessing content type data using mysql I'm trying to use data captured within my drupal database to drive some analytics in another tool.
I am trying to develop a view which gets the field data for a content type i've created.
The db model seems rather complicated, can anyone give me any tips on how to join the tables together to find fields for a given content type.

Cheers
A

I would advise you to learn how to use the views module.

In order to achieve what you want. Make sure to install the views module first. To add a new view go to admin/structure/views/add and you should see the page below. Select the content type you want

On the same page change teasers to fields. And then click continue and edit. It should take you to a new page. To add more fields from the content type you want, click on the Add link under the fields category. To make it better formatted, you can change the format type under the format category. Once you have added all your fields, click on the save button at the top.


Overriding the User entity list_builder handler I'm trying to override the User entity list_builder handler to add another column to the table and implement some JavaScript search functionality.

The code I'm using is below which is in my modules mm.module file.

function mm_user_override_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setHandlerClass('list_builder', 'Drupal\mm_user_list_builder\UserListBuilder');
}

The issue I'm having is this code gives me the following error

Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException</em>: The &quot;user&quot; entity type did not specify a list_builder handler.

Which from what I can tell is not correct, even $entity_types['user']->getHandlerClasses() tells me the list_builder handler exists.

Why is this error happening & how best to resolve it? Or is there a better way for me to add a column & search to the user list page?

my_module.module :

<?php

use Drupal\my_module\MyModuleListBuilder;

function my_module_entity_type_alter(array &$entity_types) {
  $entity_types['user']->setHandlerClass('list_builder', MyModuleListBuilder::class);
// $entity_types['user']->setListBuilderClass(MyModuleListBuilder::class); // Other solution possible
}

my_module\src\MyModuleUserListBuilder.php :

<?php

namespace Drupal\my_module;

use Drupal\user\UserListBuilder;

class MyModuleListBuilder extends UserListBuilder {
    // Implement the function you want to edit
}


Manager of groups stopped appearing as member and groups stopped appearing in her "my groups" list I'm utterly befuddled.

I'm in the process of building a site (D7) that is group-based. I have a few users on the site right now as I develop it and try to work out bugs. One of my users had created several groups, joined a couple others, and everything worked fine until sometime between yesterday and today. Suddenly, the groups she started (and is therefore manager of) stopped showing in her list of groups she is a member of. At the same time, she lost non-manager memberships of all groups but one, and then whenever she added a group it removed the prior one.

I had (and continue to have) the number of groups someone can join set to unlimited. I've also gotten it so she can be a member of more than one group again. However, groups she's a manager of still don't appear on her list, and her name doesn't appear on the members list on those group pages. When she views the groups she's manager of, it does say "You are the group manager." That relationship doesn't seem to appear anywhere else, though.

To further add to the confusion, on my non-admin account on the site I am manager on one group and member of another. I never lost visibility of my group I manage, and it never lost visibility of me. This seems to have affected only her account.

I'm at a loss to figure out what happened and how to solve it. I did back up the db yesterday morning (before whatever broke this happened), although I've had 2 new users and have made other adjustments since then. Can I compare her uid in the two databases and manually correct differences? Where would I look to set elements of group membership/management? Is there an easier way to do this just through Drupal admin interface?

Apparently the user was still manager of her groups, but was no longer registered as a member. I was able to use the Masquerade module to assume her identity, go to the appropriate node/%/group menus for each one she was manager of and give her membership again. Everything seems to be back in line after that. My guess is it was caused by overzealous use of an alternate link/rule-set I was experimenting with to manage group enrollments/drops. I've now disabled that until I figure out how to get to function properly.


Hook for a JS library in a custom module not working drupal 8 Well I have created a JS to validate a form, and when I try to attach the hook in my custom module the JS its not showing. My custom module it's call "ajax_form"

My ajax_form.libraries.yml

ajax_form:
  version: 1
  js:
    js/ajax_form.js: {}
  dependencies:
      - core/jquery

My ajax_form.module

<?php
function ajax_form_page_attachments(array &$attachments) {
    $attachments['#attached']['library'][] = 'ajax_form/ajax_form';
}

I have a console.log('test'); in the first line of my JS but this is not displaying.

I have run out of ideas of what it be. Also I'm new to Drupal maybe is that.

Just wrong indentation. Dependencies need two spaces indentation:

ajax_form:
  version: 1
  js:
    js/ajax_form.js: {}
  dependencies:
    - core/jquery


Making custom database text fields available for search I have a custom module that stores text records in a table, however this table records are  not mapped to nor an entity neither a node, so as far as I know, I can't expose them to the search module or the search API.

So my question is how do I expose my data (custom table fields) to Drupal so I can use some sort of search module (preferably search API or the core search) ?.

You can use

hook_search_info
hook_update_index

To define your own search type and add the required data to the index.


Drupal Commerce add form to cart page I'm wanting to add a custom form field to the DC cart page - not the add to cart page but the cart page. It wants to be specific to the cart rather than specific to individual line items which will then save to the order information to be available later. I've looked at dozens of questions and answers on the internet and done some digging of my own and haven't figured out even what would be the right hook to use. Any suggestions?

Use hook_form_alter() on its form ID. The form is built via Views, and I can't recall the ID off the top of my head, but any time I don't know the ID to use I just use a general hook_form_alter() and print out the form ID of every form on the page. You'll find it fast.

Depending on the type of data you're collecting and how you need it stored, it could be that you add a field to the base order type and then populate it based on the value of whatever field you add to the shopping cart form.


Creating dynamic pages for content-type/taxonomy-term I have two content types:

news
review

I have a taxonomy vocabulary attached to them with following terms

tech
entertainment
other
(More may come)

I need to have a listing of these contents in following format:

tech/news (or news/tech)
tech/reviews (or reviews/tech)
other/news (or other/news)
other/reviews (or other/reviews)

..and so on.

I could create a page for every required URL pattern and create a separate view for each. But is there any dynamic way to do it in views?

At least, can I add a drop down filter for content type on term pages?

I'm using Drupal 6.

Thanks for any help. :)

I think you can do something like this:

Create one page view and give him a path like: %/%
Add contextual filters
Create a module
Implement hook_menu.

..

function test_menu() {
  $items['test/%term_name/%node_type_name'] = array(
    'title' => 'My test page',
    'page callback' => 'test_page_callback',
    'access callback' => TRUE,
    'page arguments' => array(1,2),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function test_page_callback($term_name, $node_type_name) {

  /**
   * here we are getting arguments from _to_arg() functions and processing them to
   * get $tid and $SECOND_ARGUMENT
   */

  return render(views_embed_view('test_veiw', 'test_display', $tid, $SECOND_ARGUMENT));
}

function term_name_to_arg() {
  // return term_name as argument
}

function node_type_name_to_arg() {
// return node_type_name as argument
}


How to override confirmation messages when saving or updating content in Drupal 8? I've got a few taxonomy vocabularies, but the confirmation message on save/update is generic - Created new term %term. or Updated term %term..
Those messages come from \Drupal\taxonomy\TermForm.
Usage of that class is defined in \Drupal\taxonomy\Entity\Term class annotation.

I would like to have custom confirmation messages specific to each vocabulary.

What's the best way to accomplish that? Ideally I'd like to have separate form handler classes for each vocabulary.

Don't know if that's the best way, but it worked for me.

In your my_module.module:

/**
 * Implements hook_entity_type_alter().
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
 *
 */
function my_module_entity_type_alter(array &$entity_types)
{
    $entity_types['taxonomy_term']->setFormClass('default', '\Drupal\my_module\Form\MyTermForm');
}

Create my_module/src/Form/MyTermForm.php and override the save() method of Drupal\taxonomy\TermForm.

/**
 * @file
 * Contains \Drupal\my_module\Form\MyTermForm.
 */

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\TermForm;

class MyTermForm extends TermForm
{

    /**
     * {@inheritdoc}
     */
    public function save(array $form, FormStateInterface $form_state) {
        $term = $this->entity;

        $result = $term->save();

        $link = $term->link($this->t('Edit'), 'edit-form');
        switch ($result) {
            case SAVED_NEW:
                drupal_set_message($this->t('Created new :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName())));
                $this->logger('taxonomy')->notice('Created new :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName(), 'link' => $link));
                break;
            case SAVED_UPDATED:
                drupal_set_message($this->t('Updated :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName())));
                $this->logger('taxonomy')->notice('Updated :type %term.', array(':type' => $this->getType($term), '%term' => $term->getName(), 'link' => $link));
                break;
        }

        $current_parent_count = count($form_state->getValue('parent'));
        $previous_parent_count = count($form_state->get(['taxonomy', 'parent']));
        // Root doesn't count if it's the only parent.
        if ($current_parent_count == 1 && $form_state->hasValue(array('parent', 0))) {
            $current_parent_count = 0;
            $form_state->setValue('parent', array());
        }

        // If the number of parents has been reduced to one or none, do a check on the
        // parents of every term in the vocabulary value.
        $vocabulary = $form_state->get(['taxonomy', 'vocabulary']);
        if ($current_parent_count < $previous_parent_count && $current_parent_count < 2) {
            taxonomy_check_vocabulary_hierarchy($vocabulary, $form_state->getValues());
        }
        // If we've increased the number of parents and this is a single or flat
        // hierarchy, update the vocabulary immediately.
        elseif ($current_parent_count > $previous_parent_count && $vocabulary->getHierarchy() != TAXONOMY_HIERARCHY_MULTIPLE) {
            $vocabulary->setHierarchy($current_parent_count == 1 ? TAXONOMY_HIERARCHY_SINGLE : TAXONOMY_HIERARCHY_MULTIPLE);
            $vocabulary->save();
        }

        $form_state->setValue('tid', $term->id());
        $form_state->set('tid', $term->id());
    }

    /**
     * @param \Drupal\taxonomy\TermInterface $term
     */
    private function getType($term)
    {
        $vocabularyId = $term->getVocabularyId();
        switch ($vocabularyId) {
            case 'pages':
                return 'page';
            default:
                return 'term';
        }
    }

}


How do I hook before the user is created in Behat tests? I have a Behat test where I have a Given user step, and I want to alter some fields (token replacements). Which Behat hook should I use? I know that for Given content, the Behat hook would be @beforeNodeCreate.

Which hook is for users?

Somewhat predictably, which I'm pretty sure is deliberate, it's @beforeUserCreate.

The Drupal Extension Hooks section of the docs has a bit of background in case you need it.


How to add a link to the CSV download to my module page, for a report created with Forena? How do I add a link to the CSV download created by the Forena module to my module page?

Do I just copy the link in 'inspect element' and put that in my $output variable that I return on the recommendations page?

For any report that you create (using Forena), just add .csv as an extention to the report (output) URL. That contains the CSV equivalent of that report.

As a sample, consider the sample report located at /reports/sample.states (in your own site, one of the samples shipped with Forena). Change the URL to /reports/sample.states.csv (= just add .csv to it) to get the same report in .csv format.

If you'd adding such .csv to the URL of the Simple Table of States in the demo site, the result is like so ...

Same technique applies for other supported extensions (export formats), such as adding .html, .xls (MS Excell), .pdf or .doc (MS Word).

By the way, all data blocks are accessible directly via their url also, provided you have permission to access that block. Here are a few samples of that, for the sample report located at /reports/sample.states:

in XML format (= demo with anonymous access).
in JSON format (= demo with anonymous access).
in XML format (= demo without anonymous access).
in JSON format (= demo without anonymous access).


Why are the edit/delete/reply links missing in the Comment module? I'm using 8.6.0 core's Comment module. I can add comments, but I can't edit or delete them. I also can't reply to anyone else's.

Permissions have been set that all authenticated roles can edit. I'm even an admin and nothing.

I even looked at the comment.html.twig template. I don't see any of those links. The only link showing is {{ permalink }}. The variables also don't supply any of the links I require.

I looked around and can't find anything related to Drupal 8.

It ended up being layout builder. Enabled full content and layout builder, cleared cache and it worked.


How to define the right dependencies in .info, so drush can understand it? Currently in my booking_timeslots.info I've the following dependencies:

dependencies[] = date
dependencies[] = date_views
dependencies[] = hierarchical_select
dependencies[] = hs_taxonomy
dependencies[] = hs_taxonomy_views

which fails with the following errors:

  No release history was found for the requested project
  (hs_taxonomy_views).

  No release history was found for the requested project (hs_taxonomy).

  No release history was found for the requested project (date_views).

when I'm trying to either enable the module, or installing it with quick-drupal command like:

drush qd --yes --core=drupal-7 testsite booking_timeslots

How do I specify to which main project they belong to, so the installation process won't fail?

Personally I know to which modules they belong, but I would like to automate this process, ideally by adding appropriate syntax into .info file so other services can understand its dependencies (such as drush). It seems running module in Simplytest sandbox can recognise these dependencies fine.

I can't find anything relevant in .info syntax docs apart of specifying (major.minor).

You can declare the project name of the dependency using the following syntax:

dependencies[] = project:module

However, this this is a new feature that was added in Drupal 7.40, and as far as I can tell, Drush doesn't seem to understand it yet.


How to integrate outlook 2013 calendar? I'm working in an organization where we have our own exchange server. I'm developing a performance system to our employees using erpal.

I need an integration between exchange and Drupal that allows the employees to use their outlook calendar and tasks as same as erpal calendar and task (I mean the synchronization).

I found some ways doing it by using import and export but I think these ways are for Individual person. I need an automatic synchronization for all employees who have an email in our exchange server and can login to the system.

Is there any setting or module I have do? Or any steps link I can follow?

Have a look for the following modules:

Click to Schedule

It has sync capabilities for Outlook, Google calendar or iCal for Mac. Meetings are automatically confirmed, added to your Outlook, Google Calendar, or iCal and confirmation emails are sent to both parties.

CiviCRM activities iCalendar feed

Users can access an iCal feed of their upcoming (future) Activities, suitable for subscription via Google Calendar, Microsoft Outlook, and/or similar software.


Don't show user fields on admin/people/create Basically I don't want to have fill out all the required fields that I have added to a user when I am adding a user via admin/people/create. In Drupal 6 there was an option to not even show those fields when the admin makes a user. I have looked around for that but have failed to find it in drupal 7. I suppose I could do a hook_form_alter but I was hoping there might be something already made that I can drop in.

I was using content profile in D6 for this and it has become profile2 for D7. Since posting I have found this issue which states that a module needs to be made in order to have that same type of option.

On each of the field settings for user fields, there is an option "Display on user registration form.". Just uncheck it.


Site affected by PSA-2014-003, revoke all public keys? I didn't patch my website right after PSA-2014-003, it run about one week unpatched.

Now, I'm moving my website to a new server, using an old database backup. In my old server, I used an passphrase protected authentication key to login to the server over ssh. The website in question doesn't use SSL (https).

In the chart on http://drupal.geek.nz/blog/your-drupal-website-has-backdoor, is says: "Revoke public keys for any of the server's private keys." I don't really understand what does it means. Does it refers to certificate-authenticated SSL (https://) or does it refers to the authentication keys used to login to the server over ssh? Do I have to generate a new pair of authentication keys for my new server?

Thanks!

Short answer

You don't need to replace your SSH-keys if only their public part was stored on the server. And that's usually the case if you've only used it for logging into the server.

Long answer

Since the server may have been compromised all the data on the server might have been copied by any number of attackers. This includes everything used for authentication:

private keys (SSH, SSL, GPG, …)
passwords, if they were stored in an insecure manner
API-keys for other web-services
The mysql password

You should replace all of them.

For SSH's public-key authentication you usually copy your public key into the ~/.ssh/authorized_keys file. Your private key remains safely on your computer. Therefore there is no need to replace your ssh-keys. That's the main benefit of asymmetric encryption: Everyone can have your public key without compromising the security.


Creating filter seems to work but doesn't "stick" So I want to create a view filter programatically using hook_update in the .install file. I feel like I have it going, but the changes will not show up in the UI. Here is what I am doing, and the results:

This view already contains 2 filters. I used this code to view those filters:

$filters = $view->display_handler->get_option('filters');
var_dump($filters);

and it was clear that they were there. Then I went into the UI and created the new filter using the GUI tools there. Then I ran the above code again, and it showed me all 3 filters (the 2 previous ones, plus my new one). So far so good.

So now I backtracked the database to the initial state, so I only had 2 filters again. Then inside my install file I ran this code:

$name = "soccer_scores";
$view_display = 'default';
$view = views_get_view($name);
$view->init_display($view_display);
$view->preview = TRUE;
$view->is_cacheable = FALSE;

$filters = $view->display_handler->get_option('filters');

$filters['field_is_livescore_value'] = array(
'id' => 'field_is_livescore_value',
'table' => 'field_data_field_is_livescore',
... a bunch of other array data

$view->pre_execute();
$output = $view->display_handler->preview();
$view->execute();
$view->post_execute();
var_dump($filters);

So after the install file runs, when that last var_dump runs, it prints out the $filters array and it looks exactly like when I created the new filter using the GUI. However, when I reload the admin area for that view, no new filter appears, it just shows the existing 2 filters, but not the new one.

So I feel there is some step I am missing to make the change "stick". I can find so few docs on this, can anyone help?

To modify the value of a view programatically you don't need to actually render the view like you do with this part:

$view->pre_execute();
$output = $view->display_handler->preview();
$view->execute();
$view->post_execute();

They are only functions involved in rendering the view output.

The part you are missing is saving the view.

You are adding things to it but because you don't save it they don't end up in the database.

You will need to use the view::save() function like this:

// Load the view.
$view = views_get_view('VIEW_NAME');
// Modify the view here.
...
// Save the view.
$view->save();

[EDIT]

As for actually adding the filter. I recommend using the view::add_item() function instead of just manually adding to the view object because it does some extra work with the handler that isn't being done by your current code.

Some examples of using add_item() are https://drupal.stackexchange.com/a/134872/10729 and https://drupal.stackexchange.com/a/70649/10729


Node/website architecture visualization I am seeking to build a website which contains quite a lot of information. All this information will be structured in a specific way. As such I am looking for a way to represent this data/articles/nodes visually.

The purpose is to be able to add new articles to an already existing visual structure by simply adding a node and classifying it/linking to existing articles that are already structured/adding taxonomy terms etc.

The visual structure will as such have a changing shape/size. A map of the information presented on the site if you will.

A way to navigate the wealth of information visually.

Does something like this already exist or is there a way to create such a module/program for the site - potentially as a separate site that presents the drupal site?

Thanks,

I don't believe there is a Drupal specific option, but you can utilize a module like XML Sitemap:

  The XML sitemap module creates a sitemap that conforms to the
  sitemaps.org specification. This helps search engines to more
  intelligently crawl a website and keep their results up to date. The
  sitemap created by the module can be automatically submitted to Ask,
  Google, Bing (formerly Windows Live Search), and Yahoo! search
  engines. The module also comes with several submodules that can add
  sitemap links for content, menu items, taxonomy terms, and user
  profiles.

and then use a number of third party online or software based options for visualising xml data.  A quick search in google yielded a number of options for 'visualise sitemap'


Filter data using exposed filter using country in drupal 7? I want to filter all views data through IP address (or country) on the front page.

How can I work with exposed filter module? Is there any other method to filter data using selection box (Countries)?

Entities are opened for views to show results. Fields are attached to entities, and with views you can either show the fields or can filter your results with the fields. So, assuming you are trying to make a view of any entity (node,user etc.), you can use the Address field or the Countries module and add the field provided by any of the module to entity you are listing though views.

After adding the field to the entity, the same field will be available in views to be showed or used as exposed filters.


Views multiple Exposed Filters I have a view with three exposed filters like age, gender and city. Is it possible that, if I select for example "city = NY" and there are no "ages = 14-16" that this filter option will not be shown? I guess I want my exposed filters to narrow down each other (to work as a facet search). Is this possible?

Try the views hacks module (really not the best name for a module).

Specifically see the part on the project page at https://drupal.org/project/views_hacks#views_filters_selective


How to import the webform without changing the node id ? I am trying to import a webform from another drupal installation, but it was changing the node id of the webform. How can i preserve the node id of the webform ? Is there any module for importing without changing the node id

There are no module allow you to do it, but if you want to transfer webform I suggest you to use Webform share module.

Also, if you just want to determinate webform by any unique id, you should use UUID module.


Redirect links to nodes of past events to the up-to-date version On a event-centered site we have a lot of recurring events, but there's no pattern like every first monday etc. So the editors just clone the event with node-clone and with pathauto we generate a date-token that is appended to the url.

After the date is gone, these events are deprecated and get unpublished (by Rules). But still people find links to these events via search engines and the like.

How can we automatically redirect links of past events to a up-to-date one?

Right now the url looks like this:
www.mydomain.com/events/eventname-300518 (which would be today the 30th of May)

I could add a "basic" event without the date token if that would help. So if a event gets unpublished a redirect to the basic node could take place.

Can you point me in the right direction?

Rules and Redirect

Since you're already using Rules to automatically Unpublish past events, you could try adding an Action that creates a Redirect from the unpublished node path to the latest one. You'll need a Redirect module that provides Redirect actions. I haven't tried this but I expect Redirect module to have that.

Match Redirect

Or you could use the standalone solution Match Redirect.

Server side Redirect

Redirects don't have to be handled within Drupal. You could create Rewrite rules in your server configuration too.

But this all might be the solution for the wrong problem.

Better structure within Drupal

If the original event information doesn't change, and you only change the times, maybe you should structure it with 2 different content types, Event and Event instance or something that makes more sense.

The Event would hold everything except the times, and the Instances would only hold times. Then use Entity references to connect Instances to their Events.

Use Views to display Instances information on Events (Block or Attachment), you can use Views to filter out only future dates to display on Event nodes. And when marketing your event only ever share link to the Event node, that will always be showing correct relevant dates through the power of Views.

You can set your robots.txt to not index Instance content nodes on search engines, and in general don't link to them or show them to the users, only use the Instance information on Event nodes.

Or if you have per-date relevant information for the event (comments or similar), store it on the Instance node, and then again with the power of Views you can list past event info on the Event node itself, if anyone wants to read, look at past image gallery or similar.

That way you'd have both the future and past info available to be displayed how you want them, and only one Event link for marketing that would probably even be beneficial for SEO ranking.


How do I programmatically create a route? I'm trying to create a route programmatically using this code.

example.routing.yml

route_callbacks:
    - '\Drupal\example\Routing\ExampleRoutes::routes'

Drupal\example\Routing\ExampleRoutes.php

namespace Drupal\example\Routing;

use Symfony\Component\Routing\Route;

class ExampleRoutes {
    public function routes() {
        $routes = array();
        $routes['example.settings'] = new Route(
            '/example/',
            array(
              '_form' => '\Drupal\example\Form\ExampleForm',
            ),
            array(
              '_permission'  => 'access content',
            )
        );

        return $routes;
    }

}

When I install the module, I get the following error

  Class \Drupal\example\Routing\ExampleRoutes does not exist

Why doesn't the above code work?

I think that in your case the problem is in this line:

    '/example/',

that should be:

    '/example',

so without the final /.

You can try with the other method extending from RouteSubscriberBase and your routes method needs to receive as a parameter a RouteCollection.

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ExampleRoutes extends RouteSubscriberBase {

  public function routes(RouteCollection $collection) {

  }

}

And you need to define the Route Subscriber as a service

  example.route_subscriber:
    class: Drupal\example\Routing\ExampleRoutes
    tags:     - { name: event_subscriber }

Take a look at this example:

Dynamic Routes in Drupal 8 with a RouteSubscriber


D7 + Views: How to hide fields labels? I have set all my fields labels as hidden in content types > display fields.

It seems like Views overrides this by displaying labels of the filter fields.

How to hide them?

Click on the field in the filter section, and you'll see a "Label" option.


How to make author name hyperlinked to it's profile For my site this is the sample page. Users are submitting articles and I (as admin) am creating myself a new page node and pasting the user article into it. At the same time I'm changing the author name to that of user's.

I've two questions:

The author name( in this page it is some "clifflowe") is not hyperlinked to the user profile but when I see in as admin it is hyperlinked. How to make it hyperlinked for all users?
Secondly after I create a new article page and simply change the author name with that of another user, will that user get any added permission on this article? Who is the original owner of this article then?

To the first question: users (anonymous or authenticated) need to have the "View user profiles" permission.

To the second: the user you set will be the original owner. The fact that admin created it is not stored in the node anymore.


It's possible to pass custom variables into Views? It's possible to pass custom variables into Views ? I'm trying to manipulate some elements from a Views by using the administration page.

This how I ask the custom variable ...

custom_module.module

/**
 * Implements hook_menu().
 */
function custom_module_menu() {
    $items = array();
    $items['admin/structure/custom_module'] = array(
        'title' => 'Custom Module Integration',
        'description' => t('Custom Module'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('custom_module_form'),
        'access arguments' => array('administer  custom module configuration'),
        'file' => 'custom_module_form.inc',
    );
    return $items;
}

custom_module_form.inc

/**
 * custom_module
 */
function custom_module_form($form, &$form_state) {

    $form['custom_variable'] = array(
        '#type' => 'textfield',
        '#title' => t('custom_module configuration page'),
        '#default_value' => variable_get('custom_variable'),
        '#description' => t('Enter my variable'),
    );

    return(system_settings_form($form));

}

The variable is store in my Drupal variable_get which I can confirm on variable editor. So my goal is to be able to used custom_variable on Rewrite Results or Global: Custom text on Views. Which I have try it but does not translate to the variable value.

What I'm doing wrong ? Or is not possible to used variable on Views ?

You have to write a custom module that creates a suitable handler (for example, a Views area handler). In that handler you can read your custom variable and act accordingly.

Keep in mind Views cache. So, if you change that variable you should invalidate the cache object for that view or views that uses that handler.


Jquery and Ajax 404 Undefined Error Hi I am developing a module in which i am sending data from javascript to drupal using jquery ajax.

but i am getting 404 error undefined.I am not able to figure out. Pls help

Here is my code

This is tbg.js an external js file

$.ajax({
        url: 'localhost/drupal/my_currenttime/10',
        type: 'GET',
        success: function(data){
            alert(data);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(jqXHR.status+textStatus + errorThrown);
        }
    });

In my module file i am calling this js file in hook_nodeapi

function modulename_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL)
{
  switch($op)
  {
    case 'view':
    drupal_add_js(drupal_get_path('module', 'modulename').'/tbgscript.js', 'module');
    break;
  }
}

I have created a call back url for the ajax request in modulename_menu() hook

function modulename_menu()
{
  $items['my_currenttime/%'] = array(
  '#title' => 'My custom callback',
  'description' => 'Desc',
  'page callback' => 'custom_currentTime',
  'page arguments' => array(1),
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );

  return $items;
}

and my page call back method is

function custom_currentTime($args)
{
   echo "HELLO".$args;
}

i want to access the value $args in my module file.

I would guess that the URL is wrong in your javascript.

Currently, if your site is on http://localhost, the page requested will be:

http://localhost/localhost/drupal/my_currenttime/10

When I suspect it should be:

http://localhost/drupal/my_currenttime/10

To fix that just add the http:// part to the beginning of the URL variable in your JS code, or make it relative:

url: '/drupal/my_currenttime/10'


List nodes of children using taxonomy_select_nodes I want to list nodes from children terms using or editing taxonomy_select_nodes function.
Actually I added these few lines but I get an infinite loop or slow response:

function taxonomy_select_nodes_ext($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'),$promote) {
  if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
    return array();
  }
  $query = db_select('taxonomy_index', 't');
  $query->addTag('node_access');
  $query->condition('tid', $tid);
  if ($pager) {
    $count_query = clone $query;
    $count_query->addExpression('COUNT(t.nid)');

    $query = $query->extend('PagerDefault');
    if ($limit !== FALSE) {
      $query = $query->limit($limit);
    }
    $query->setCountQuery($count_query);
  }
  else {
    if ($limit !== FALSE) {
      $query->range(0, $limit);
    }
  }
  $query->addField('t', 'nid');
  $query->addField('t', 'tid');

      // This block of code is the custom code I added.
      //SELECT only promoted article
      if($promote==1){
        $query->join('node', 'no', 'no.nid = t.nid');
        $query->condition('promote', 1);
      }
      $taxonomies=array();
      $taxonomies = taxonomy_get_children($tid);
      $taxonomies[]=$tid;
      $query->condition('t.tid', $taxonomies,'IN');

  foreach ($order as $field => $direction) {
    $query->orderBy($field, $direction);
    // ORDER BY fields need to be loaded too, assume they are in the form
    // table_alias.name
    list($table_alias, $name) = explode('.', $field);
    $query->addField($table_alias, $name);
  }
  return $query->execute()->fetchCol();
}

I would say these are your problems:

taxonomy_get_children() returns term objects, not term IDs, so that is going to break that query. This I would say is your main issue. Instead you could do this:

  $taxonomies = array();
  $taxonomies = taxonomy_get_children($tid);
  // Get the child term tids.
  $taxonomies = array_keys($taxonomies);
  // Add the parent tid.
  $taxonomies[] = $tid;
  $query->condition('t.tid', $taxonomies,'IN');

Your IN statement with the children won't work currently because earlier in the function is this line:

$query->condition('tid', $tid);

So that will only ever return values for $tid, never for the children unless you remove that line also.

Also I would recommend giving the new $promote parameter a default value, like this:

function taxonomy_select_nodes_ext($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'), $promote = 0) {


Correct way to customize modules? When making changes to files in sites/all/modules/moduleidownloaded where should the changes be stored? I know you shouldn't edit the core module files for risk of updates etc. So where should I put customized module files such as templates and styles?

You can create two folder contrib and custom inside sites/all/modules. Drupal is able to look up any folders inside sites/all/modules to discover the modules.

If it is multiple site structure, you can do the same in sites/[site_name]/modules

For the custom templates and styles, if you means the theme one, you can place the theme in sites/all/themes/custom, otherwise, templates and styles can be placed inside custom module.


Drush not working on Mac OSX I am developing on Mac OSX 10.10. I am not using MAMP, Aquia Desktop or anything like that. Instead, I am using the built in PHP/MySql in Mac (set up using this tutorial).

When I run Drush, I get this error:

Command pm-enable needs a higher bootstrap level to run - you will   [error]
need to invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en views' could not be executed.

(No other text is displayed).

If I do Drush status, I get the following:

 Drupal version         :  7.37
 Site URI               :  http://mysite.local
 Database driver        :  mysql
 Database hostname      :  127.0.0.1
 Database username      :  dbuser
 Database name          :  dbname
 PHP executable         :  /usr/local/bin/php
 PHP configuration      :  /usr/local/etc/php/7.0/php.ini
 PHP OS                 :  Darwin
 Drush script           :  /Users/myname/.composer/vendor/drush/drush/drus
                           h.php
 Drush version          :  8.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/myname/Sites/mysite
 Site path              :  sites/site1

Steps I have tried

1. Re-installing Drush via this tutorial

The tutorial says to install Drush via Composer. The install works, but when I re-run Drush, I get the same error.

2. Install Drush via this tutorial

This tutorial recommends to install it via Homebrew. When I do this, I get this error:

  Problem 1
    - Installation request for d11wtq/boris v1.0.10 -> satisfiable by d11wtq/boris[v1.0.10].
    - d11wtq/boris v1.0.10 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system.

I've looked extensively on the Internet for how to fix this, but I just find sites saying I need to compile from source. They provide no steps on how to to do this, and I don't know what it means.

3. Using the 127.0.0.1 trick

(Changing host to 127.0.0.1 in settings.php).

Thanks for any help

A "possible" reason might be because Drush commands must be issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site), and then retry your Drush comand.

If that doesn't help, it could well be an issue with the version of Drush that you are using. Would it be an option to downgrade to a lower version of Drush? FYI: Drush 6.x does support D7 also ...


Can I attach a jquery.ui.datepicker widget to a form element using the form api? I have a generic form element:

$form['date'] = array(
    '#type' => 'textfield',
    '#title' => t( 'Date' ),
);

That I want to add the jquery ui datepicker to this element. Is there a way to do this through the form api, or do I have to add the following using drupal_add_js:

$('#edit-date').datepicker();

Or is there another, even better way?

You can use after_build in your form to call a function that contains drupal_add_js


Clean URL/.htaccess problems with multiple subdirectories I've inherited a large Drupal web site and now we're updating from Drupal 6 to Drupal 7. I cannot enable CleanURL for more than one subdirectory at a time! I think I've read just about every article on CleanURLs there is, and possibly my situation is unique, or maybe I'm going about things wrong?

We have a couple versions live on our web site using different subdirectories and databases. There are two sites total on one domain, each with a Drupal 6 "live" copy and a Drupal 7 "test" version on the host. They are organized as follows:

siteA_D6 -> example.com/
siteB_D6 -> example.com/siteB_D6
siteA_D7 -> example.com/siteA_D7
siteB_D7 -> example.com/siteB_D7

We want the subdirectories to work as I've listed them above, but eventually we will retire the D6 versions and redirect D7 to example.com/ and example.com/siteB

Currently, all 4 sites are accessible, but, CleanURLs only work on siteA_D6 (or example.com). Ideally we want to have CleanURL enabled on all of them, so that

http://example.com/test/arguments and
http://example.com/siteA_D7/test/arguments

resolve to the "same" page in different versions, and we never see ?q=test/arguments in the address bar

Our shared-server web host considers this issue "beyond ordinary technical support"... can't blame them, I've been banging my head up against this wall for days now. I'd really appreciate a solution or just some pointers.

(.htaccess copied below)

Options All -Indexes

ErrorDocument 404 "This page was not found on this server"

RewriteEngine On
RewriteBase /

Options +FollowSymLinks

# Closing the back door
RewriteCond %{QUERY_STRING} (ch|php_code)=(.*)
RewriteRule (.*) ##pretend url here, it won't let me post "too many links"## [L]

# Block pharmaceutical hotlink chicanery
RewriteCond %{HTTP_REFERER} ^http://.*pharmacy [NC]
RewriteRule .*\.(jpe?g|gif|bmp|png)$ - [F]

# stuff to let through
# I have been commenting these out when testing new rules
RewriteCond %{REQUEST_URI} "/siteB_D6/" [OR]
RewriteCond %{REQUEST_URI} "/siteB_D7/" [OR]
RewriteCond %{REQUEST_URI} "/siteA_D7/"
RewriteRule (.*) $1 [L]

#this one redirects all requests from domain to new folder
RewriteCond %{HTTP_HOST} ^.*example.org$
RewriteCond %{REQUEST_URI}  !^siteA_D6.*
RewriteRule ^(.*)$ "site_A_D6/$1" [L]

<IfModule mod_suphp.c>
suPHP_ConfigPath /home/username
<Files php.ini>
order allow,deny
deny from all
</Files>
</IfModule>

It seems that your .htaccess is custom made, first of all you should have a look at the one Drupal provides as you're missing some criticals rules like

<FilesMatch "\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$">
  Order allow,deny
</FilesMatch>

Regarding your problem, I think you should change the RewriteBase condition like this:

RewriteBase /siteB_D6

for each of you subsite (make it matches the subdirectory where it's located).


Coding standards for long strings? I've been looking for some official guidelines on how to format long strings in module code, but the closest thing I've found is an ambiguous section on indenting long SQL queries which suggests any of the following styles:

$text = '
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
  hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
  hendrerit varius felis id dignissim.
';

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula'
. 'odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer'
. 'hendrerit varius felis id dignissim.'
;

$text = <<<TEXT
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula odio,
  hendrerit consectetur porta vitae, sollicitudin sit amet eros. Integer
  hendrerit varius felis id dignissim.
TEXT;

The Drupal Coding Standards talk about how to use the concatenation assignment operator:

$string .= 'Foo';
$string .= $bar;
$string .= baz();

but they don't actually state whether single long strings should be broken up that way.

To add further confusion, the Coder module handles long strings differently again in its "good.php" test file:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ' .
        'ligula odio, hendrerit consectetur porta vitae, sollicitudin sit ' .
        'amet eros. Integer hendrerit varius felis id dignissim.';

Personally, I've just been doing it like this until now:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ligula
        odio, hendrerit consectetur porta vitae, sollicitudin sit amet eros.
        Integer hendrerit varius felis id dignissim.';

However, I'd like to start doing it the "right" way (if there is one). Does anyone have a definitive answer?

Drupal does not restrict the usage of long strings in code. It is advisable to concatenate each line ($output .= '...';) for a readable code, but as you can see in Drupal code, long strings are not broken up, especially when used with t():

function field_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.field':
      $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#';
      $output = '';
      $output .= '
' . t('About') . '
';
      $output .= '
' . t('The Field module allows custom data fields to be defined for entity types (see below). The Field module takes care of storing, loading, editing, and rendering field data. Most users will not interact with the Field module directly, but will instead use the Field UI module user interface. Module developers can use the Field API to make new entity types "fieldable" and thus allow fields to be attached to them. For more information, see the online documentation for the Field module.', array(':field-ui-help' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) :'#', ':field' => 'https://www.drupal.org/documentation/modules/field')). '
';
      $output .= '
' . t('Terminology') . '
';
      $output .= '
';
      $output .= '
' . t('Entities and entity types') . '
';
      $output .= '
' . t('The website\'s content and configuration is managed using entities, which are grouped into entity types. Content entity types are the entity types for site content (such as the main site content, comments, custom blocks, taxonomy terms, and user accounts). Configuration entity types are used to store configuration information for your site, such as individual views in the Views module, and settings for your main site content types.') . '
';
      $output .= '
' . t('Entity sub-types') . '
';
      $output .= '
' . t('Some content entity types are further grouped into sub-types (for example, you could have article and page content types within the main site content entity type, and tag and category vocabularies within the taxonomy term entity type); other entity types, such as user accounts, do not have sub-types. Programmers use the term bundle for entity sub-types.') . '
';
      $output .= '
' . t('Fields and field types') . '
';
      $output .= '
' . t('Content entity types and sub-types store most of their text, file, and other information in fields. Fields are grouped by field type; field types define what type of data can be stored in that field, such as text, images, or taxonomy term references.') . '
';

I would stick with this drupal usage, this is the best compromise for usage and good readability. Your first examples looks good, but adds extra line feeds. The second example is not good to read and the third is often used in scripts, but not very common in php code.


Views 3 : Set header/footer/empty text for view via views_embed_view I update my views from views 2 and I do the same on embedded code. But actually I can't set footer content as it changes in views 3.

My views 2 code :

$emptyTextVue = $view->display_handler->get_option('empty');
$emptyText = $view->display_handler->set_option('empty','
Pas images.
');

I think I do use the export code like :

$handler->display->display_options['empty']['area']['content'] = 'Pas d\'images à afficher.';

but how ?

EDIT : extract result for var_dump() : ["handler_type"]=> string(5) "empty" ["options"]=> array(11) { ["id"]=> string(4) "area" ["table"]=> string(5) "views" ["field"]=> string(4) "area" ["relationship"]=> string(4) "none" ["group_type"]=> string(5) "group" ["ui_name"]=> string(0) "" ["label"]=> string(13) "Zone de texte" ["empty"]=> int(0) ["content"]=> string(25) "Pas d'images à afficher." ["format"]=> string(1) "2" ["tokenize"]=> int(0) } ["definition"]=> array(4) { ["handler"]=> string(23) "views_handler_area_text" ["group"]=> string(6) "Global" ["title"]=> string(13) "Zone de texte" ["help"]=> string(33) "Provide markup text for the area." } ["is_handler"]=> bool(true) ["localization_keys"]=> array(4) { [0]=> string(7) "default" [1]=> string(5) "empty" [2]=> string(5) "views" [3]=> string(4) "area" } ["table"]=>

First up, don't use views_embed_view(). It is a very simple function that doesn't allow for customisation.

Do something like this:

// Load the view.
$view = views_get_view('VIEW_NAME');
// Set the options for the header text.
// To get an idea of what options are available, set up a view with header text
// and then use the devel module to print out the view definition.
// For example, add a header text area field and print it with
// dpm($view->header['area']); after you have loaded it with views_get_view().
$header_options = array(
  'label' => t('Header text'), // Administrative label. Not really needed here.
  'content' => 'This is the header text content.', // Content of header text.
  'format' => 'filtered_html', // Format of header text.
  'empty' => 1, // Show even when there are no results. Set to zero otherwise.
);
// This adds a header handler for a text area. The table is views because it is not
// a database field. The field is area because it is a text area.
// The header_options are the settings.
$view->add_item('DISPLAY_NAME', 'header', 'views', 'area', $header_options);
// This is the preferred way to get the rendered view.
$output = $view->preview('DISPLAY_NAME');
// If you want you can check for results with this.
if (!empty($view->result)) {
  // Do something if there are rows.
}

You can do the same for footer handlers:

$view->add_item('DISPLAY_NAME', 'footer', 'views', 'area', $footer_options);

and empty text:

$view->add_item('DISPLAY_NAME', 'empty', 'views', 'area', $empty_options);

You can also change the field type if you don't want to use Global: Text area.

For more information see $view->add_item()


Clear block cache in panels page I'm having trouble with refreshing content in a block created with a custom module, placed within a panels page. My end goal is to display either regular or seasonal hours based on a set date range. My hook_theme() implementation looks like the following:

function daily_hours_theme() {
  if (daily_hours_is_summer()) {
    $table_template = daily_hours_get_summer_vars();
  } else {
    $table_template = daily_hours_get_regular_vars();
  }
  $items =  array(
    'todays_hours_table' => $table_template,
    'daily_hours_text_content' => array(
      'render element' => 'element',
    )
  );
  return $items;
}

I'm using hook_block_info() to test cache settings; the following doesn't seem to have an effect on caching:

function daily_hours_block_info() {
  $blocks['hours_table'] = array(
    'info' => t('Daily Hours Table'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

And hook_block_view() to call the theme function:

function daily_hours_block_view($delta = '') {
  switch ($delta) {
    case 'hours_table':
      $block['content'] = theme('todays_hours_table');
      break;
  }
  return $block;
}

Ideally, I'd clear the module's block data at midnight every day, but I'd settle for just knowing how to implement any caching rules in this context.

The variables were being cached at some point in the hook_theme() function, so after reading the documentation on hook_theme(), I moved the logic to conditionally use different variables in to my hook_block_view() implementation, passing them in to the call to theme() at that point. So that function looks like the following:

function daily_hours_block_view($delta = '') {
  if (daily_hours_is_summer()) {
    $variables = daily_hours_get_summer_vars();
  } else {
    $variables = daily_hours_get_regular_vars();
  }
  switch ($delta) {
    case 'hours_table':
      $block['content'] = theme('todays_hours_table', $variables);
      break;
  }
  return $block;
}

And my hook_theme() function:

function daily_hours_theme() {
   $items =  array(
     'todays_hours_table' => array(
       'template' => 'hours_table',
       'variables' => array(
          // set default variables here
       )
     )
   );
   return $items;
 }

The cache setting in my hook_block_info() implementation did not seem to have an impact once I set up the logic in the hook_block_view() function.


Saving the value for a taxonomy term field I'm trying to save a field value for a taxonomy term, my value appears in the term array, but the "fields" array is empty. I'm not sure if it's right what I am going to do. You can see everything about my case in the attached screenshot.

Yes, as @Trupal said, forget about the internal properties of the term objects, that's internal details that are not relevant to you.

If you want to see what's inside, try $term->toArray() and look at the result of that in your debugger. Or access the field value with $term->field_foo->value.


Avoid drupal bootstrap for each image styles in private filesystem Consider a scenario, where large number of images are attached to a node and they are displayed as thumbnail gallery when that node is displayed/rendered. The node has access control so it displayed accordingly. All images and corresponding image styles are stored on private file system.

Since every thumbnail is accessed from private filesystem it incurs a high latency due to permission check an every image.

Is it possible to avoid bootstrap/permission check for every image when they are displayed/rendered as a part of a specific node? So behave like public filesystem in this special case only. When any item is directly accessed via url, the permission checks kick in as they normally do for private filesystem.

No because it are separate http(s) requests. Every requests needs to redo the check.


What happens to Webform data when a component is deleted? Can I change a component type? I inherited a complicated Webform with several hundred submissions. One of the components was a Textfield used to capture the email address of the form submitter. For some reason this is a Textfield and not an E-mail field which prevents me from using the E-mail address to send a confirmation email.

If I were to delete the textfield email component what would happen to all the data? I'm assuming it would be erased.

Is there any way to change the type of a form component while still preserving the data?

Update: I am using Drupal 7 and Webform 3.19

When a Webform component is deleted, the submitted data for that component are deleted.  The data for the form's other components are preserved.  I've confirmed these by querying the webform_submitted_data MySQL table on Webform 7.x-3.23.

As user calebtr indicated, there's a "Private" checkbox for each component that can be used as an ersatz delete-but-save-the-data feature, except that logged-in users with the privilege to read results will still see the component on the form (not only in the results).  These fields could be hidden using a stylesheet or custom template, potentially after corralling them into a private fieldset.

The Webform UI does not allow the changing of component type.  I see this information stored in webform_component.fieldset, so you could probably modify it there.  You'd also want to update the component settings in the "extra" column.


How to add a view for a node with an ID? I have a simple blog application and would like to add style my nodes with views. More specifically I want to style node/nid path and when I point that in the views configuration, it only works if I type: http://example.com/node/3/3 but if I type http://example.com/node/3 it doesn't work. How can I make the nodes view work with the id being pointed out only once?

If my frontpage is called /content then that would be the path I would point out in the views configuration. In this case, however, I am trying to style an opened node - t.i. where the path is node/id . Everything works fine if I type node/id/id in the adress bar, but not if I type node/id . As the path for that view I have done so: PAGE SETTINGS Path:/node/%

I think you'd find Panels with a node_view panel page override suits there.

Install and enable page manager then enable the default "Node view" panel page.

It will override node/%node with a page in which you can embed views content pane displays etc...


How to Add\Edit ECK entitys from front-end? I'm using the ECK module for defining custom entities. Also there are users that have permissions to add and edit entities from specific bundle. I'm trying to create a front-end menu for these users with 'Add entity' and 'Edit entity' items.

My question: how to provide an option to Add/edit custom entities to the front-end users?

ECK create CRUD permissions for all entity type/bundles that has been created with it, so all you need to do is to give the users the permissions needed.

Since the path is located in admin/ you might need to create a link for users to use to create some of your custom entities.


Why is there a module for version 9 of core? I checked this module page, it have the download option for Drupal 9 version. Why is Drupal 9 is launched when there isn't an official stable Drupal 8 release? Is there anything wrong with Drupal 8?

Why did they ignore Drupal 8? I also found the Drupal 9 development snapshot release.

Well the "Bad Judgment" module you linked to claims:

  This module provides an explicit dependency for modules whose usage requires bad judgement. Joke modules often require "bad judgement".

So I wouldn't take that version number too seriously.

From the core download page you linked to:

  Placeholder for the Drupal 9.x release. Not intended for actual use by anyone except the issue queue version selector.

It's just a placeholder for the next version (forward-thinking and all that). It doesn't mean there's anything wrong with Drupal 8, and it doesn't mean Drupal 9 will be out any time soon.


How can I get the sub-navigation to show up in the sidebar on child pages Drupal newb here :) So I may not have the Drupal lingo correct in my explanation...

I have a menu block called "Sub Navigation".  Here are my configurations:

(I've inherited this site so I'm not sure if this is a default block or not etc)

So, the navigation shows up just fine in the sidebar of parent pages, but it does not on any child page. (The admissions parent page has a context configuration, is why it is omitted here).

Am I missing a configuration here?

Thanks for any help!

I got some help with this, and what it needed was for this checkbox to be selected:


Change image style during hook_node_view() I'd like to programmatically change an image style during hook_node_view(), and I thought this would be relatively straightforward like so:

/**
 * Implements hook_node_view()
 */
function example_node_view($node, $view_mode, $langcode) {

  if (example_ok()) {
    $node->content['field_image'][0]['#image_style'] = 'new_image_style';
  }

}

Unfortunately this does not work. I'm aware of the picture and breakpoints modules, and am in fact using them, however there are sometimes when a dynamic decision needs to be made that these modules don't cover.

I hate to answer my own question, but this answer pointed me in the right direction. Here's the hook that worked in this case:

/**
 * Implements hook_preprocess_HOOK().
 */
function example_preprocess_image_style(&$variables) {
  if (example_ok()) {
    $variables['style_name'] = 'new_image_style';
  }
}

function example_ok() {
  global $user;
  // If the logged in user is bob, everything is ok.
  if ($user->uid && $user->name == 'bob') {
    return TRUE;
  }
  return FALSE;
}


How to dynamically change the path to store commerce files depending on some product variables? All my Drupal Commerce files are being saved in the same directory on the server.

I have a Commerce product variation of type of album. Each album contains multiple Commerce files (mp3’s, m4a’s). I want each album to have its files saved in a different directory depending on artist name and album name.

For example: commerce_mp3s/artist_name/album_name/album_files*

I tried looking in the DB where these Commerce files are referenced, table name being field_data_commerce_file, but file paths are not used there.

The worst case scenario would be to change the file path of the content type every time I add a new album, but that’s not a solution. This must be a common scenario.

How can I accomplish this?

You need to use the Token with File (Field) Paths and Pathauto modules.

  Note: File (Field) Paths extends the token module by adding Node tokens, without this module, you will not be able to use the node fields as tokens.

Then edit your file field.

We then use Pathauto to fix names with spaces. Ex: If the album name is "Hello World" the path/folder name will change to /hello-world/


Views - How to display results in nested groups? I have a View listing out members of staff. Each staff member belongs to a department, or sub-department. I want to list out all staff members but group them under their (sub)-department in a nested manner. For example:

# School Board
John Doe

# Teaching Staff
Jane Doe

    ## Chemistry
    Eric Betzig

    ## Physics
    Shuji Nakamura
    Isamu Akasaki

I know you can use the Group by Fields option, as described in this answer, but it doesn't allow for nesting:

# School Board
John Doe

# Teaching Staff
Jane Doe

# Chemistry // Not nested
Eric Betzig

# Physics // Not nested
Shuji Nakamura
Isamu Akasaki

I think this is more a question of styling than views itself. You could assign a class to the row output (e.g. with a replacement pattern token or something) and then style the css to show the output "nested".


Group views exposed taxonomy filter terms based on parent Here is the scenario :

We've got a taxonomy vocabulary called regions, this holds continents as parents and countries as children, this vocabulary then is used as a taxonomy term field in a content type called "Note", there user can select unlimited countries for the content. The user is forced to select from children so he/she cant choose a continent for that field.

Now I'm working on a view of "Notes", the country filter is exposed and user can select multiple countries, What I want now is to separate countries based on the continent they belong and show them in different part of form.

I know I can add a filter for each continent and select countries related to that continent using views but I'm looking for a programmatically based situation as the number of countries are so many and there might be human fault selecting proper countries for each continent.

You have to use an additional module to influence how the Exposed filter is displayed: Views Reference Filter.

This module adds special new Filters to Views that rely on (existing) Entity reference Views Displays to filter the View. Basically, it's filtering one View Display with another View Display.

In your case, you first have to:

create an Entity reference Views Display that shows all the Countries, grouped by their Continents. It will be the Term type of View, not Content.

You're designing here what your Exposed Filter will later look like.
List Countries as Fields,
then use Parent item Relationship to show Continent for each Country,
Group the results by Continent (Parent) field in the Entity Reference list settings

You will now see a list of Countries grouped by Continents.
Save the View

With this ready you can:

edit your "Note" Content view,
add a new Filter Has taxonomy term that has (reference filter) in its name, expose it, and choose the Entity reference Display you created in previous steps above.
Use Better exposed filters module to display the choices as Checkboxes

You will now have a working Exposed filter by Countries that will be grouped by Continents.


Overwrite the url function of a specific node entity Can I overwrite the url function of a specific content type of node entity ?
 So to have a different pattern when i use: $node->url();

Entity URI callback

You can implement an URI callback. Example in comment.module:

/**
 * Entity URI callback.
 */
function comment_uri(CommentInterface $comment) {
  return new Url(
    'entity.comment.canonical',
    [
      'comment' => $comment->id(),
    ],
    ['fragment' => 'comment-' . $comment->id()]
  );
}

and add the callback to the annotations of the entity type:

*   uri_callback = "comment_uri",

For an existing entity use a hook_entity_type_alter().

Bundle specific URI callback

A URI callback for a specific content type can be defined in the bundle definitions:

**
 * Implements hook_entity_bundle_info_alter().
 */
function mymodule_entity_bundle_info_alter(&$bundles) {
  if (isset($bundles['node']['my_content_type'])) {
    $bundles['node']['my_content_type']['uri_callback'] = 'my_content_type_uri';
  }
}

The callback:

/**
 * Bundle URI callback.
 */
function my_content_type_uri(NodeInterface $node) {
  // build a url object $url
  return $url;
}

A bundle-specific callback takes precedence over the generic one for the entity type and a link template (defined in the links array of the entity type) takes precedence over both, so you need to remove the link template if you want to override an existing one, e.g. canonical, which makes you responsible to provide the route needed for the custom url, if it was built before by a route provider and is not defined in a *.routing.yml file.

Edit:

To modify the url in links to a specific content type you can use a hook_link_alter():

function mymodule_link_alter(&$variables) {
  $url = $variables['url'];
  if ($url->isRouted() && $url->getRouteName() == 'entity.node.canonical') {
    if (isset($variables['options']['entity'])) {
      $node = $variables['options']['entity'];
      if ($node->bundle() == 'article') {
        // modify the links to articles
      }
    }
  }
}


What is the equivalent of hook_translated_menu_link_alter() to alter a menu link? I want to alter the menu link in Drupal 8. In Drupal 7 we can achieve this using hook_translated_menu_link_alter().

function module_translated_menu_link_alter(&$item, $map) {
  global $user;

  if (!empty($item['access'])) {
    // Administrator will access all menu's.
    if (strpos(current_path(), 'admin/structure/menu/manage/' . $item['menu_name']) === 0 && user_access('administer menu')) {
      return;
    }
    // If userid is equal to menu user id.
    if ($user->uid == 1) {
      $access = 'UNBLOCK';
      break;
    }
   // Block menu.
    else {
      $access = 'BLOCK';
    }
    // Access FALSE if Menu not for USER.
    if ($access == 'BLOCK') {
      $item['access'] = FALSE;
    }
  }
}

In Drupal 7 I am hiding/disabling menu based on some conditions like the user ID.

Similarly, I want to alter the menu link in Drupal 8. How can I achieve it?

HOOK_link_alter would be one D8 equivalent to hook_translated_menu_link_alter:

/**
 * Implements hook_link_alter().
 *
 * @inheritdoc
 */
function HOOK_link_alter(&$variables) {
  $url = $variables['url'];
  // Check url is routed in Drupal.
  if ($url->isRouted()) {
    // Load the current user by user ID.
    $currentUser = User::load(\Drupal::currentUser()->id());
    // Check access.
    $urlAccess = $url->access();
    // Get url options.
    $urlOptions = $url->getOptions();
    // Your code here.
  }
}

See Drupal 8 class URL for more API info.

However, you could use Hook_preprocess_HOOK() as such:

/**
 * Implements hook_preprocess_hook().
 *
 * @inheritdoc
 */
function HOOK_preprocess_menu(&$variables) {
  if (isset($variables['menu_name']) && $variables['menu_name'] === 'menu_name') {
    foreach($variables['items'] as $key => $item) {
      $url = $item['url']->toString();
      if ($url == '/user') {
        // Remove menu item.
        unset($variables['items'][$key]);
      }
    }
  }
}

Just checking path above, but it shows you can hide a single menu item based on certain criteria.

For the access restrictions, depending on your needs, you might look at routing and permissions based on the entity instead of the menu item and let Drupal handle the menu item display.

For menu access by role look at this module: https://www.drupal.org/project/menu_item_role_access