Calling a module function from jQuery and Ajax I am getting some problems calling a custom module function from jQuery and AJAX.

ajax_example.module

function ajax_example_init() {
    drupal_add_js(drupal_get_path('module', 'ajax_example') . '/ajax_example.js', array('scope' => 'footer'));
}

function ajax_example_menu() {
  $items['ajax_username'] = array(
    'title' => 'Get Current User Name',
    'page callback' => 'ajax_example_get_username',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function ajax_example_get_username() {
  global $user;
  $user_name = $user->name;
  drupal_json_output($user_name);
}

ajax_example.js

(function ($) {
  Drupal.behaviors.ajax_example = {
    attach: function (context) {
      $.ajax({
        url: '/ajax/username',
        success: function(data) {
          console.log(data);
        }
      });
    }
  }
})(jQuery);

I am trying to call JavaScript by a JS Injector module using these commands.

(function($) {
  $.ajax({
    url: 'ajax_username',
    type: "GET",
    success: function (data) {
      console.log(data);
    }
  });
})(jQuery);

Unfortunately, I get the same 404 error again and again.

What am I doing wrong?

To answer to The second block of JS code is a test I am trying to do to call the ajax_username function of ajax_example.module. you wrote in your comment, what you can use in JavaScript code like $.ajax({url: 'ajax_username'}) as url is a route exposed in the hook_menu() implementation of a module, or the path of a PHP file. It isn't the name of a PHP function implemented from a module, nor the name of a file containing Javascript code (without the .js extension).

As concrete example of what Drupal core modules do, see the content of the statistics.js file.

(function ($) {
  $(document).ready(function() {
    $.ajax({
      type: "POST",
      cache: false,
      url: Drupal.settings.statistics.url,
      data: Drupal.settings.statistics.data
    });
  });
})(jQuery);

What $.ajax() gets as url is Drupal.settings.statistics.url, set from statistics_node_view() with the following code.

$settings = array('data' => array('nid' => $node->nid), 'url' => url(drupal_get_path('module', 'statistics') . '/statistics.php'));

In the test site I am using, the output of url(drupal_get_path('module', 'statistics') . '/statistics.php') is /modules/statistics/statistics.php.

So, if you want to call the callback associated to your ajax_username menu, you need to use $.ajax({url: '/ajax_username'}) or $.ajax({url: '/index.php?q=ajax_username'}), but in both the cases, the module must be installed and enabled.

If you don't want to enable a module for that, you cannot use hook_menu(), but you could create a PHP file containing the code to use, in the same way the Statistics module does with its statistics.php file.
Be warned: Use this only if you know exactly what you are doing, as using the wrong code could be a security risk for your site and its data.

I would rather use hook_menu().


Duplicated content shown in a view using a relationship I am using a view that has a contextual filter ("Content: Has taxonomy term ID") and a relationship ("Content: Taxonomy terms on node"); for some reason, I keep getting duplicated content. In the view settings I have "Distinct" checked.

Are there any other options I can look into?

Yes. Check if one of your fields have multiple values, like Taxonomy Terms, or Images. Then, you have to group those values with the according option to prevent this.


Using JSON:API to replicate content on external location I would like to create content on another Drupal instance using JSON:API. Using the jsonapi_extras service, serializer.normalizer.entity.jsonapi_extras, entities can serialized but contain more node information than is required for remote location.

What I need to do is to prune this JSON object further to only include what is required, but haven't found an elegant way to do this with the EntityToJsonApi class. It seems like a workaround might be to request this JSON object from the HTTP API and limit included data with sparse fieldsets, but wanted to get some feedback on the best way to achieve this.

For consideration, an interesting way do this that was suggested to me by gabesullice, is to deny access to the fields. This also resulted a performance improvement in jsonapi 1.x, maybe 2.x as well.

/**
 * Implements hook_entity_field_access().
 */
function MYMODULE_entity_field_access($operation, $field_definition, $account, $items = NULL) {

  $request = \Drupal::request();
  if (strstr($request->getUri(), '/jsonapi/node/')) {
    $name = $field_definition->getName();
    switch ($name) {
      case 'field_blah':
      case 'uid':
      case 'moderation_state':
      case 'promote':
      case 'sticky':
      case 'unpublish':
      case 'review_date':
      case 'vid':
      case 'type':
      case 'revision_translation_affected':
      case 'revision_timestamp':
      case 'revision_log':
      case 'revision_id':
      case 'revision_uid':
      case 'langcode':
      case 'default_langcode':
        return AccessResult::forbidden();
    }
  }
  return AccessResult::neutral();
}


Flexslider JS not Loading Using the Nexus theme, I'm getting the following error when using the theme rotater.

"The History Plugin requires Galleria version 1.2.5 or later."

Updated and its still busted.

http://www.athleteyouniversity.com/

I see in your page source it says:

http://www.athleteyouniversity.com/sites/all/themes/nexus/sites/all/libraries/galleria/plugins/history/galleria.history.min.js?o30qzc

You have a sites/all/ folder inside your theme /nexus folder, which is not how it's suppose to be. The libraries folder needs to be outside of your theme folder.

It's suppose to be /sites/all/libraries/galleria/plugins/history/galleria.history.min.js


Displaying commerce product with all product variations and attributes I’m building a drupal commerce store using product displays that reference multiple product variations. But i need the product display to show all of its product variations with all attributes one after another, not hiding the attributes by AJAX. And each product variation should have its own add-to-cart-button. So it’s a simple, flat design where a customer can see every variation and every attribute at a glance.

I know this could be easily accomplished using views, but for certain reasons views is not an option for me. I need a real node of the productdisplay with its variations.
What’s the best and most performant way to achieve this?

EDIT
According to @nvahalic it’s a mess to solve my issue without Views. So maybe i have to reconsider my decision not to use Views. To clarify, the products will be displayed like this:

+------------------------------------+
| Title Product 1                    |
| =====================              |
| General Text (for all variations)  |
| General Image (for all variations) |
|                                    |
|    Title Product Variation 1       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
|                                    |
|    Title Product Variation 2       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
+------------------------------------+
+------------------------------------+
| Title Product 2                    |
| =====================              |
| General Text (for all variations)  |
| General Image (for all variations) |
|                                    |
|    Title Product Variation 1       |
|    =========================       |
|    Text                            |
|    Image                           |
|    *Add to Cart*                   |
|                                    |
|    ...                             |
|    ...                             |
+------------------------------------+

As far as i know when using views to build this structure, i will need something like the module Views Field View to achieve the nested structure consisting of fields belonging to the product display as well as fields belonging to the variants. Since the shop will have very long lists of products, i’m concerned about performance issues coming along with this kind of modules.
Or maybe i got it wrong and such module isn’t necessary at all?

EDIT 2
Finally i solved the problem by using the EVA module: i created a view showing the attributes of all products as fields and added am add-to-cart field. This view i attached to my product display – it seems to me this approach is way more performant than using the Views Field View module …

EDIT 3
It is a huge mess: using nested views is not a good idea, because commerce-add-to-cart buttons can not be cached, so caching views does not work as it is discussed here https://www.drupal.org/node/1926888
From my point of view it was a very, very bad choice to use views for this task. Now I can not use views for caching and the module commerce entity cache is not usable neither because the view does not rely on entities.

If you're insistent on not using Views, you might pull it off like this:

Create a new node type and then add an entity reference field that will reference the product displays for each of your products. Set the values to unlimited.
For each of your individual products, create a product display.
Set the renderer of the entity reference field on the new node you created to "rendered entity"
Theme the product display nodes that are linked to the entity reference field accordingly

  +------+     +------------------+     +----------+
  | Node |1---M| Product Displays |1---1| Products |
  +------+     +------------------+     +----------+
            ^     ^
            |     | Theme this entity appropriately.
            |
            | Set this display rendered to "Rendered entities"

At that point, you should have a list of rendered node entities that would each have their own add to cart form. You could also add a new view mode (using Display Suite) and use that view mode specifically if you still wanted to use the other view modes.

But honestly, this is an extreme amount of work for something that you could accomplish in 30 minutes with Commerce Add to Cart Extras and Views. And regardless of what I said above, that's still my recommendation.

Edit: You're on the right track with Views Field View. If you're worried about performance (how many products do you have?) then you can also:

Use Views cache. It's configurable under Advanced in the right-most column of the view configuration screen.
Enable Views Content Cache.
Implement Redis and perhaps Entity Cache.


Overriding the logic of "request new password" in Drupal? I currently have:

function mymod_menu() {
    $items['user/password'] = array(
        'title' => 'Request new password',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('user_pass'),
        'access callback' => TRUE,
        'type' => MENU_LOCAL_TASK,
        'file' => 'user.pages.inc',
    );
}

mymod_form_alter() {
if ($form_id == 'user_pass')
    {
        // do form alterations here...
    }
}

The first part isn't really necessary for editing the form. But my problem isn't the form. My problem is that I don't know how to change the IMPLEMENTATION of this form. I want the change the way the entire "forgot password" process works. I have a fully integrated login solution that relies on a separate database, and I now need to be able to access that database to generate a unique forgotten password url, based on different validation rules.

What would I have to override to change the way the forgotten password page works?

The login system uses various core functions in the core User module to process logins and forgotten passwords.  You really don't want to mess with those (don't edit them).

At any rate hook_form_alter cannot change what those functions do but it can change which function is called.

I would suggest a custom module that

Creates your own separate login page with the logic you desire
Has a function that sends an email with the tokenised link to your new form
Alters the user_pass form to call the function in #2 instead of the standard function which you can do by editing $form['#submit'].


How install Drupal on SSD on Linux I have an installed SSD on my Ubuntu Linux machine. It's blank, partitioned, and formatted. I'd like to install my Drupal sites on it so I can work on them locally there. However, the only way I've found to install Drupal so far on Ubuntu is in the /var/www/html folder (and only 1 site there at a time at that).

Anyone have a suggestion (or a tutorial! - dare to dream) for installing multiple Drupal 7 sites on a SSD on Ubuntu Linux for local development?

You can do many things to fix this.

Delete the /var/www/html directory. Create a symlink from your SSD to the location.

$ rm -rf /var/www/html && ln -s /media/ssd/document_root /var/www/html
Modify your web servers configuration to use the SSD as the document root.
Create a virtual host for your webserver and point it at the SSD. Edit. I just saw youur previous question. Copy your 000-default.conf to 25-example.com.conf and alter the document root and directory durectives. Don't forget to restart apache.

Are you using stock Apache? What version of Ubuntu?


Override user registration function The default behavior for user registration is that if a user tries to register with an email that already exists, it lets them know and asks if they have forgotten their password.

We have a custom link to our product download in the email the user receives, and what we'd like to do if a user tries to re-register with the same email is to just resend the email, without notifying them that they already have an account.

I can't seem to find a way to do this. Any ideas? I'm not super-experienced with Drupal anymore.

CODE

function create_vector_user_form_user_register_form_alter(&$form, &$form_state) {
    error_log("form alter"); // this logs
    $form_state['values']['pass']['pass1'] = 'password';
    $form_state['values']['pass']['pass2'] = 'password';
    $form_state['values']['op'] = t('Create new account');
    $form['#submit'] []= "create_vector_user_user_register_submit";
}

function create_vector_user_user_register_submit($form, &$form_state) {
    error_log("submit handler"); // this does not log
  $form_state['build_info']['args'] = array(&$object);
  drupal_form_submit('create_vector_user_form', $form_state);
  drupal_set_message("The form is being submitted, do some extra stuff now...");
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  array_unshift($form['#validate'],'my_first_custom_validation' );
  $form['#validate'][] = 'my_last_custom_validation';

}

function my_first_custom_validation(&$form, &$form_state){
  if(isset($form_state['values']['mail'])){
    if($user = user_load_by_mail($form_state['values']['mail'])){
      rules_invoke_component('rules_send_email_to_user', $user);
    }
  }
}

Hook into register form using hook form alter
Add custom validation handler to the top of submit handlers (must execute first before any other submit handler )
In the handler function  try to load user by email using user_load_by_mail
If true send the email using drupal_mail or rules then redirect to same page or any page to stop the execution.

The only problem with this code that the validation error still showing , I could not find way to stop drupal from execute the rest of validation handlers


Override Views RSS Feed Display I've been struggling with trying to create a custom xml REST API in D8 to replace a simple Views RSS feed (that is imported into other D7 sites using a custom Feeds importer) in a D6 site that's being migrated, and after pulling my hair out with the custom REST endpoint, I'm looking at doing what I did in D6, which is to create a Views RSS display. However, the feed requires some customization, so I need to determine how to add custom fields to the RSS feed. For other feeds in D7 sites, I've used the Views RSS module to add fields, but the D8 branch is still apparently not stable, so that does not seem to be an option.

To customize my RSS feed, I need to do two things:

Add custom elements (hook_nodeapi($op = 'rss item') in D6)
Modify the query so only nodes with specified tids in a term reference field based on a views global null param passed in (hook_views_query_alter() in D6)

So it appears that for an RSS Feed display in D8 views, the only fields displayed in the feed are the ones predefined in the row style settings (using Fields as the row type). With the Views RSS module not being available, is there a way with core Views to override the view to add custom fields (such as a class override)? I appears I can still use hook_views_query_alter() to modify my query, but it doesn't do me much good if I can't add fields.

I could probably spend a few hours reading through code, but if anyone has a quick answer as to the best way to add custom elements to a D8 RSS display, or could point me in the right direction, I'd appreciate it.

Thanks.

As documented here, I went with overriding the views row style plugin. All I did in the override was add the render() method and add my own modifications to the $build array to make it work.

<?php

namespace Drupal\video_export\Plugin\views\row;

use Drupal\views\Plugin\views\row\RssFields;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "mymodule_rss_fields",
 *   title = @Translation("Custom Fields"),
 *   help = @Translation("Display fields as RSS items."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class MyModuleVRssFields extends RssFields {

  /**
   * Override of RssFields::render() with additional fields.
   *
   * @param object $row
   *
   * @return array
   */
  public function render($row) {
    $build = parent:: render();
    $item = $build['#row'];

    // Add MRCTV nid
    $item->elements[] = array(
      'key' => 'source-nid',
      'value' => $row->nid,
    );

    // Add channels and their target nids. We can get them from $row->_entity.
    $site = $this->view->args[0];
    // Get source nids from view.
    $channel_tids = array_column($row->_entity->field_channels->getValue(), 'target_id');
    // Now, get destination tids from config.
    $mapping_config = \Drupal::config('video_export.mappings');
    $all_mappings = $mapping_config->get('sites');

    foreach($channel_tids as $source_channel) {
      if(in_array($source_channel, array_keys($all_mappings[$site]['mappings']))) {
        $item->elements[] = array(
          'key' => $site . '-channel-map',
          'value' => $all_mappings[$site]['mappings'][$source_channel],
        );
      }
    }

    // Re-populate the $build array with the updated row.
    $build['#row'] = $item;

    return $build;
  }
}


add condition in apache solr serch query I want to alter apache solr search query with my custom filed.

I have custom content type called "Restaurant" and in this content type i have 1 field called "country". Now I want to add condition that display search result only those restaurant which is belong to "Jamaica" and display facet as per this condition.

So,how can I alter query with apache solr serach?

You can use hook_apachesolr_query_alter()

  Alter the query after it's prepared and cached.

Example from the docs page

function hook_apachesolr_query_alter($query) {
  // I only want to see articles by the admin.
  //
  // NOTE: this "is_uid" filter does NOT refer to the English word "is"
  // It is a combination of flags representing Integer-Single, which is
  // abbreviated with the letters i and s.
  //
  // @see the <dynamicField> definitions in schema.xml or schema-solr3.xml
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}


drush config:import "There are no changes to import." for "content" view On a Drupal 8.7.14 system with Drush 9.7.2, I modified the "content" view and now want to roll it back to the previous version that was exported with drush cex.
Unfortunately, drupal does not roll it back to the previous state. drush config:import only says:

There are no changes to import.

I did then delete the "content" view, and the import said:

Operation create für views.view.content: "view" entity with ID "content" already exists.

To circumvent that, I created the view manually and tried to import the original configuration. Again, drupal thinks that:

There are no changes to import.

Why is that?
What can I do to force Drupal to restore the original configuration?

The problem's source was the configuration file that configured the database as cache on CLI, while using redis when served via http.
This caused all kind of confusion, since clearing the cache in the browser did not do that for CLI :/


Display non search results in Drupal 7 I've been looking for a way to show all taxonomy terms that are not searched for in a view.

What I mean is: I want a search to sort out safe food for customers that are allergic to some food. If a customer is allergic to nuts the customer type nuts in the form and the customer gets a list of all dishes that DON'T contain nuts. Anyone know a module that will help me do this?

Sure, you can do this with Views.

Build a view that displays your dishes.
Set a FILTER for 'Has taxonomy term', expose it, and use the 'is none of' operator

I made that example using the 'dropdown' option, you may find the 'autocomplete' option more suitable to your needs.  I recommend trying both to see which fits best and allowing multiple values so that people who are allergic to nuts AND gluten can still use it.


How can I redirect users after they cancel their accounts? Is there a way redirect users after they cancel their accounts?  I've configured my site to allow users to cancel their accounts without e-mail confirmation, but I want to be able to redirect them to a "goodbye" page to reassure them that their account was in fact cancelled.

In user_cancel(), though, account cancellation is performed with the Batch API.  I tried adding a drupal_goto() after the call to batch_set($batch), but this forces the goto and the batch processing is not performed.

How can I redirect non-admin users after they cancel their accounts?

There are two fine ways to do it :

With Rules : If you have installed it already then you must use this. Select the event "After a user account has been deleted". Check the conditions you want and add action "Page Redirect".
With Hook : Write a hook_user_delete and add drupal_goto in your condition.


Drupal 7 Solr 4 $query group by I'm beginner in Drupal 7 et Solr 4. I have $query and I want to do a group by category. How can I add 'group by' as a parameter to $query (DrupalSolrQueryInterface) ??

You can add custom parameters through hook_apachesolr_query_alter, eg

function MYMODULE_apachesolr_query_alter(DrupalSolrQueryInterface $query) {
  $query->addParam('group', 'true');
  // etc
}


Pages are not accessible, menu links are not displaying properly I'm trying to resurrect a Drupal 4 site which stopped working at some unknown point, possibly months ago. I can login as admin and reach the front page. Every link after that returns 'you are not authorized to access this page'. The primary_links and secondary_links menus are not being retrieved properly. I have tried switching themes and clearing the cache table. I have also set up a local version for debugging but there are no PHP errors being thrown.

I'm running php 5.2.13, mysql 5.1.44.

As I have noted in the comments of the first answer, the issue was due to a change in versions of PHP. The bug was previously reported here.


Can I use Views query in my custom code or not? Through views I am getting result perfectly in update preview. But when I use the same query in my custom code, its not working as expected. Do I need to do any modification in code or do I need to do any configuration in views so that I can get a query which should be executed through code also. Any help will be appreciated.
For example code is here:

SELECT node.nid AS nid,
   node_uc_product_kits.nid AS node_uc_product_kits_nid,
   node_uc_product_kits.language AS node_uc_product_kits_language
 FROM node node
 LEFT JOIN uc_product_kits uc_product_kits ON node.nid = uc_product_kits.product_id
 LEFT JOIN node node_uc_product_kits ON uc_product_kits.nid = node_uc_product_kits.nid
 WHERE (node_uc_product_kits.status = 1) AND (node.nid = 1 )

In code:

$ord_weight = db_result(db_query("SELECT node.nid AS nid,
   node_uc_product_kits.nid AS node_uc_product_kits_nid,
   node_uc_product_kits.language AS node_uc_product_kits_language
 FROM node node
 LEFT JOIN uc_product_kits uc_product_kits ON node.nid = uc_product_kits.product_id
 LEFT JOIN node node_uc_product_kits ON uc_product_kits.nid = node_uc_product_kits.nid
 WHERE (node_uc_product_kits.status = 1) AND (node.nid = 1 )"));
print_r ($ord_weight->num_rows);

Long story shory, if you run the same query that the views module runs, you will get the same result.

If you are getting a different result this means that you

Don't run the same query (where do you get the views query from)
Don't provide the same dynamic variables if any is used

You should also note that Views has it's own magic variables in views, that only works in views, like ****CURRENT_LANGUAGE**** which maps to the current language.

You should also note that views does a lot of work in the theme layer to output data. Getting the same data from SQL doesn't mean that the actual output will be the same.


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

What are the options to do that with drupal 8?

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

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


How do I prefill a paragraph field in a node form? I have a content type with a paragraph entity reference field and every time a user is going to add a node of this type I want to have the paragraph field already open and prefilled. I've tried with hook_form_alter, but it's not opening the paragraph form with prefilled values.

In the form display for that content type you can tell the paragraph field to have a default paragraph selected. So when new nodes are created it will appear there

Then on your actually paragraph you'd need to set the default values for each field it contains (Just by editing those fields on the paragraph and setting the defaults)


ViewsJSON module not working with Google Store Locator I was wondering if anyone came with a solution for this. The Google Store Locator module is not working with ViewsJSON module. There seems to be an issue

I've installed the ViewJSON Alpha 4 and applied the patch but it doesn't work on my end.

Any suggestions?

I have managed to get it working with version 7.x-1.0-alpha2 of module GeoJSON.

Please see my question and my own answer at Localize nearest store to a zip code in Drupal 7


CSS is not aggregated anymore - how to debug? On a rather complex Drupal 6 site (multi domain etc.) CSS files are not aggregated anymore and CSS style definitions appear directly inside the HTML pages.  The output of ´drupal_get_css´ is ok, but when I installed the Advanced CSS/JS Aggregation module, I see that the module reports the aggregated css files as Missing files.  But when these files are opened manually, they are ok.  The problem itself is not related to the the advagg-module, I only enabled it for debug reasons.

I have not switched themes on the site affected, but I have been playing around with a new theme (mobile jquery) and a correcponding jquerymobile module on a different module from the same installation.  I do not currently think, that the problem has been caused by this module.

I guess the problem is caused by some module weights, but I am having trouble debugging the theming process.  I am looking for help, where I should start debugging, why the aggregated CSS files are not used.

Update:
I have edited drupal_add_css to default to not preprocess files.  The difference is, that each css-block is inserted in a seperate style statement, whereas right now, only a single aggregated CSS style statement is generated.  So I am really tryng to find out, why I am ending up with the long css style definition, instead of a link to the aggregated stylesheet.

I am extremely sorry, but I have found out that the problem was not caused by Drupal.  It seems that the a proxy has been installed by the ISP that automatically compresses pages and rewrites stylesheets to be included into the page directly.

The pages work correctly when being fetched via other networks.


use drupal_add_js for file outside drupal dir I would like to add a js file thats outside my drupal installation dir, but keep it relative to that dir.

mysite
  |-- drupal
  |-- dirWithJsFile
      |-- thisfile.js

i have already tried things like

/../dirWithJsFile/thisfile.js
../dirWithJsFile/thisfile.js

but add_js seems not be able to go outside the drupal dir or is there an option i must set?

In D6, no dice, but in D7, you could fudge it with setting $options to external and then using the full sitename and path to the file.


Is it possible to display user's first login (activation) date in a view? All the users are imported (only admin can create accounts), they receive an activation email to connect with a one-time login.
What I would like to know is how to display the date when they actually came at first (first login) and/or activate their account with the account process (password changing and save)?

Apart from the basic profile augmented with a few fields, my users have a native role that is dropped when they activate their account just to unlock automatically a function. So if there is a lead on "when the role was removed or changed" that I can't figure out right now, I might work with that.

I didn't put https://www.drupal.org/project/login_history yet unfortunately.

There is no field that stores this information in the database.

The only thing you have by default are user account creation date, last login date and last access time.

Once a user has logged in for a second time those values are no use to you.

There are also not user revisions by default so you can't see when the first time a user changes their username/password/etc. you can only see the data the most recent change was made.

The only way is to use something like login history or user revisions, however that only helps you from now on, not for existing users.

Off the top of my head I can't think of any way you can get reliable data for this for existing users.

[EDIT]
Actually, the drupal watchdog log stores user login events.

When a user logs in this watchdog call happens:

watchdog('user', 'Session opened for %name.', array('%name' => $user->name));

So if you check your drupal logs for "Session opened for" you can find all user logins.
This will only help you if you have a record of all your watchdog logs since the beginning of your site (probably not likely).
If you only use the dblog module that logs to the drupal watchdog table it is likely you don't have all logs because old ones will usually be purged to keep the database table size under control.
If you use the syslog module to that logs to your web server's file system it is possible that you could have backups of all logs for the whole life of your site, however that also isn't guaranteed.
It's probable that old logs are also purged in this case too.


Views Better exposed filter, input required In which hook_ of the views.api can i hide the results if no exposed inputfilter is selected.

I tried:

hook_views_query_alter($view, $query) {

if($view->getExposedInput() ...) {
 // Do not show any results, make clear no results should be shown..
}

Or

hook_views_pre_render($view) {
    if($view->getExposedInput() ...) {
      $view->result = array();
      // But pager still shown and $view->getPager()->destroy() gives error.
      // Also feels wrong, query should not be executed.
    }
}

Any suggestions, solutions, .... Thx!

Solved it by adding condition which yields no result.

hook_views_query_alter($view, $query) {
    // Don't show any result if exposed filter empty.
    $exposed_input = $view->getExposedInput();
    if(!isset($exposed_input['field_partner_address_country_code']) || $exposed_input['field_partner_address_country_code'] == 'All') {
      $query->addWhere(NULL, 'node_field_data.nid', 0);
    }
}


Webform - Mandatory text field depending on select option state I was hoping to get some direction on how to make a textfield in my webfrom mandatory but only if a particular select option was not checked.

So the textfield is mandatory by default but if the select option is checked, the text filed is no longer mandatory. I have tried to do this via jquery but have then read that validation is server side so I'm not sure what best practice is for this.

Does this type of behavior need custom validation via hook_form_alter() - or is there another way to achieve this? I am running Drupal 7.

Thank you in advanced.

I found a module called Webform Validation that lets you achieve this without any custom code.

To accomplish the above, add the 'Require at least one of two fields' validator under 'form validation' and then select both components that you want to validate against.


Using taxonomies to enhance SEO: Hard Situation I am working on a site that the client required a dynamic url creation for a huge number of keywords for each city (for example). So the result url would be like www.domain.com/city/citname/keyword.

And each URL shall direct to a page which has the same content except the city name and keyword.

So I directly thought of taxonomies, but when I reached the development stage ... it was very hard to apply this over Drupal. I think of making two vocabularies one for the cities and the other for keywords as keywords are repeated the same for each city.

Summery: every city should have all the keywords connected to it

So, If my approach is good, how to mix two vocabulary? and how to maintain one content for all resulted taxonomy terms.

I hope it is clear

best,

From an SEO perspective I'm not sure its a great idea, I have little experience optimizing for SEO. But....

If the title of your Node is the cityname. I would simply make its url path pattern in Pathauto as city/[node:title].

That takes care of the url /city/cityname.

Then you can simply use the Tagging taxonomy installed by default to tag the city with relevant keywords.

Then install the 3rd party contributed module: view_mode_page

It allows you to define alternate pattern(s) to get to a piece of Node content.

Then use its API to create the alternate urls based on the tags.

Something like this example code in a custom module (untested, as I dont have your exact setup):

/**
 * Implementation of hook_view_mode_page_get_patterns() from module
 * view_mode_page.
 *
 * This lets me define additional node urls (per NID) with a custom
 * view mode.
 *
 * Creating a custom view mode, and using Display Suite for example could let
 * you customize these pages so they're slightly more unique in content layout
 * and values.
 */
function MYMODULE_view_mode_page_get_patterns($results, $content_type, $view_mode) {
  $results = array();
  $defaults = array('content_type' => 'CITY_CONTENT_TYPE', 'view_mode' => 'full' /* or a custom view mode */, 'show_title' => 0, 'title' => '');

  // Load the terms for keyword vocabulary by its vocabulary name.
  $keyword_terms = taxonomy_get_tree(taxonomy_vocabulary_machine_name_load('city_keywords')->vid);

  // Loop through the Term objects and build the sub-url using the nodes pathauto alias denoted by %.
  foreach ($keyword_terms as $pos => $Term) {
    $results[$pos] = (Object) array_merge($defaults, array('url_pattern' => '%/'.$Term->name));
  }
  return $results;
}

If every city is to have different keywords, this may not work. Or you may have to load all the city nodes and iterate through them to get the correct paths and attached keyword terms. This is just taking a generic keywords list and building additional urls for each city.


howto use tokens as "views filter criteria" I want make a photo gallery with Drupal and i want show photos uploaded by user in user's page.
I tried add token [node:author:uid] to Content: Author uid as filter criteria, but that shows an error:

Unable to find user: [node:author:uid]

how to add a token to views filter criteria?
thanks :)

Try adding a contextual filter - Content: Author uid and make it like below. I think this is what you need.


help to understand files in sites/all/default/files/js folder I'd like to understand what are the ....js.gz files located in sites/all/default/files/js.

I thought they are cached js files.

But if I clear all caches (drush cc all) these files still remain there.

I've made a capture of the folder:

Like you said these are just cached versions of the javascript files. Drupal compresses them so they can be served to the user faster, notice the difference in file size between the version 29.1 KB opposed to 117.4 KB.

Are there any error when you clear cache through drush? Mostly I've found that they stay behind when you run drush as a user that cannot modify the files, e.g. a user not in whatever group owns the files. In this case you need to add your user to whatever group owns the files.


change field from int to big int in drupal I have a integer field in a custom content type, first we did't estimate that we have a data more than 2 147 483 647(max integer number_ , but I have some data that bigger than max integer range,
we input very data to that field and it not logic that install bigint module then remove integer field and create a bigint instead of it ( all of our data will lost),
I know I can change table in mysql database by myself,but maybe in future needs update drupal to newer version , what is your suggestion to me ?

Use the bigint module.

  The default core fields do not include a bigint field. This module
  allows you to have a true BigInt (19) value. That means the number can
  contain 19 digits.

So, with this module you can define fields with the appropiate range.

Your problem now is to migrate data from your current field to a new bigint created field.

The usual steps will be:

Create and configure the new bigint field.
Edit affected nodes copying data form old int field to the new bigint field (using Batch API, for example). Or using a direct SQL commands, if your are brave enough.
Update related configuration to use the new field (for example, Views).
Delete de old field.

Depending on your usual workflow you can do this by different means:

Manually, closing the web during update.
Using Features for the configuration (fields, Views, etc).
Update script (for example, a hook_update_N if you are using a installation profile).


Is there a date / time format that only shows minutes if they are non-zero? I want a time/date format in a View that renders like this when a time ends in :00
Sep. 16, 2017 - 2pm

BUT, renders like this only if minutes are present:
Sep. 16, 2017 - 2:30pm

Currently, I use this format: M. d, Y - g:ia but I need a way to make those zeros disappear when an event starts at the top of the hour.

A bit of a cludge but if your output allows simple html, you can write a format that includes a span around the colon and minutes and use the minutes as a class.  Then hide the span if it's 00.  E.g.

M. d, Y - g<\s\p\a\n\ \c\l\a\s\s='\m\i\n-i'>:i<\s\p\a\n\>a

Then css of

.min-00 { display: none; }

I've done this with dates to produce over/under large date/small month displays. If it's coming from a view, you may need to check the allow html option on the field.


Do I need to build out CCK fields before migrate_d2d_ui? Using the migrate_d2d_ui module to migrate Drupal 6 cck content to Drupal 7, I previously asked "Do I need to create CCK content types before migrate_d2d_ui?" and presume the answer is "Yes" based on my personal experience.

This follow-up question is whether it is necessary to also build out all the cck fields for content types containing cck fields.  I am hoping the answer is "No" as this would imply a lot of work.

It would seem that migrate_d2d_ should be smart enough to recognize the D6 cck fields and create the corresponding D7 fields.

Thanks

I eventually concluded that the answer to this question is 'yes' and ended up persisting my content structure (content types and field definitions) in features so it could be easily replicated when some errant step in the migration corrupted the database.


BBcodes module not working I have installed and enabled BBcode, BUEditor, Extensible BBcode and Advanced Forum modules on my site. I would like use BBcodes to post the topics in forum. When I post the topic with any value [for e.g [b]this is a test data[/b]] and submit the posting I see the raw data displayed without BBcode formatting.

Not sure what is going wrong. I see the errors in the drupal logs.

  Warning: preg_match_all(): Compilation failed: unrecognized character
  after (?< at offset 5 in XBBCodeFilter->process() (line 42 of
  /var/web/sites/all/modules/xbbcode/xbbcode.filter.inc).

Appreciate your help.

Thanks

xbbcode maintainer here.

It seems that the module uses a Regex syntax that was introduced in PHP 5.2.2: http://php.net/manual/de/regexp.reference.subpatterns.php

I'll release a fix when I can; it's a pretty small code change: For each occurrence of (?<...> in the pattern, insert a P to make it (?P<...>.

Alternatively, you can fix it by upgrading to PHP 5.2.2 or later.

Edit: In fact, Drupal 7's minimum requirements mention PHP 5.2.5 (https://www.drupal.org/docs/7/system-requirements/overview).


Get node id of saved node I want a function/hook to be called at a point just when my custom node type is saved, I want to get the generated node id in that function, as I have to perform some operations based on nid.

I know one solution is which form alter hook is defined and I give a custom submit function to it and that function is called just when form is submitted, but in that case node is not yet saved at that point so there is no nid.

You can use hook_node_update().

In Drupal 6, you can easily get the last node ID by calling db_last_insert_id().


How can I use an URL (being a field content) as a contextual filter in views? I'm working on an academic wiki containing two types of pages: an 'Author page' and an 'Article page'. I am trying to create a block view displaying all the articles written by an author into her corresponding page. The view selects the 'Article pages' using a content type filter and I tried to use contextual filters to select the articles written by a particular author.

The difficult part is that the 'Author page' and the 'Article page' do not share a similar field for the author's name. However, when creating an 'Article page', the user has to enter all participating authors and the URLs corresponding to their respective page in the wiki.

So what I would like to do is to use the last component of this URL (the node ID of the 'Author page') and compare it to the node ID of the page the user is looking at. If the IDs match, the view displays selected fields from the 'Article pages' which have written by the author the user is looking at. But so far I have been unsuccessful in doing so, any hint on how I could perform this functionality?

I'm new using Drupal (and site building actually), so I apologize if my question lacks clarity or details.

Thanks in advance for your help!

Igor

I found a much simpler solution than what I was trying to do: I used node references. That's exactly what I needed but I wasn't aware of the existence of this functionality. So yes, the solution is simply to use a node reference to link the 'Article page' to the 'Author page'.


How do I modify the breadcrumb? I want to modify my bread crumb ( remove one link from bread crumb and add one link to bread drumb).

I tried,

/**
 * Implements hook_system_breadcrumb_alter().
 */
function modulename_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
// to get current path and alias
  $current_path = \Drupal::service('path.current')->getPath();
  $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

// get current route name
  $route_name = \Drupal::service('current_route_match')->getRouteName();
// check route is an quickinfo content create in group
  if ($breadcrumb && $route_name == 'entity.group_content.group_node__quickinfo.create_form') {
// get bread crumb links
    $breadcrumb_links = $breadcrumb->getLinks();
// fetch titile of the current path
    $title = \Drupal::service('title_resolver')->getTitle(\Drupal::request(), $route_match->getRouteObject());
    if (!empty($title)) {
// change third link of a breadcrumb
     $breadcrumb_links['2'] = Link::createFromRoute(t('RZ-schnellinfo'), '<none>');
    }
//    set links again
   $breadcrumb->setLinks($breadcrumb_links);
  }
}

SetLinks() ==> work when only bread crumb links doesn't exist, i.e.. we can create new links by using addLinks(). Since we need to remove a link we can use this function .

Then I followed https://www.drupal.org/node/2026025  but I am getting below error.

  exception
  'Symfony\Component\DependencyInjection\Exception\LogicException' with
  message 'Service                                    [error]
  'xxxxx.breadcrumb_xxxx_create' for consumer 'breadcrumb' does not
  implement Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface.' in

As comment said above, you have to implement Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface. Here is a working snippet that I use to implement those Breadcrumbs :

It appends a custom routename to all 'Nodes' pages :

<?php

namespace Drupal\Your_Module_Namespace\Breadcrumb;

use Drupal;
use Drupal\Core\Breadcrumb\Breadcrumb;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;

class Your_Module_NamespaceBreadCrumbBuilder implements BreadcrumbBuilderInterface {

  /**
   * {@inheritdoc}
   */
  public function applies(RouteMatchInterface $attributes) {
    $parameters = $attributes->getParameters()->all();
    // I need my breadcrumbs for a few node types ONLY,
    // so it should be applied on node page ONLY.
    if (isset($parameters['node']) && !empty($parameters['node'])) {
      return TRUE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addLink(Link::createFromRoute('Home', '<front>'));

    $node = Drupal::routeMatch()->getParameter('node');
    $node_type = $node->bundle();

    // Put the needed logic here

    // addLink example
    $breadcrumb->addLink(Link::createFromRoute('My Page Name', 'drupal_internal.routename'));
    $breadcrumb->addCacheContexts(['route']);

    return $breadcrumb;
  }
}


Ajax Callback to Update Select List not Working I have defined couple of fields inside my custom entity basefielddefinitions() like so...
$fields['product_line'] = BaseFieldDefinition::create('entity_reference')...
$fields['product'] = BaseFieldDefinition::create('entity_reference')....
Then in entity form class (ProductLineForm.php), I try to attach an ajax callback to my product_line select list such that it populates the product select list, like this
    $form['product_line']['#group'] = 'details';
    $form['product_line']['#ajax'] = [
      'callback' => '::populateProducts',
      'event' => 'change',
      'wrapper' => 'edit-products'
    ];

Then my product select list looks like this...
    $form['product']['#group'] = 'details';
    $form['product']['#attributes'] = [
      'id' => 'edit-products',
    ];

and then my populateProducts() function...
  public function populateProducts(array $form, FormStateInterface $form_state) {
    $form['product']['#options'] = ['1' => 'One', '2' => 'Two'];
    $form_state->setRebuild(TRUE);
    $response = new AjaxResponse();
    $option = "<option value='45'>Just testing</option>";
    $response->addCommand(
      new \Drupal\Core\Ajax\ReplaceCommand(
        '#edit-products',
        ($form['product'])
      )
    );

    return $response;
  }

The problem is that nothing whatsoever happens, no signs of any ajax call, and the product select list stays empty as it always been.
(1)Is the the entityform class the right place for me to attach an #ajax call to a field defined in a custom entity? Or do I need a hook? Meanwhile I've done a lot of other modifications on the custom fields here in this entity form edit class (like grouping into fieldsets, vertical tabs and even modifying weight (eg $form['product_line']['#weight'] = 3 - and they all work, why not $form['product_line']['#ajax']....?
(2) Is there a way of attaching the ajax callback directly inside my custom entity's basefielddefinitions where I define the fields, I would prefer that...
Really stuck on this one, folks, please could someone help me? Appreciate all your input, Thank you all.

just got this sorted out! Decided to drill down to the array structure of the form, and found out that the #ajax element had to be attached to the widget array of the field, like this...
$form['product_line']['widget']['#ajax'] = [...]
Now it works. Another reason I keep crying "better documentation for Drupal"!!! How in the world was anybody supposed to know that for existing form fields, this was the format for adding Ajax?!!! Oh well, thanks community  for pointing in the right direction. Anybody knows the right place to insert this in the existing documentation? Cheers all.


Drupal 7 taxonomy add term missing url path settings I'm working with a Drupal 7 installation, I watched a video that shows how to work with taxonomy, http://www.youtube.com/watch?v=Qmr2HW6CtJQ but when I go to "add term" to create a new term in my newly created vocabulary, the "URL Path Settings" was missing which has to generate automatic url alias that was shown at 04:15 of the video.

How to get this to show up?

Thanks.

You probably have to enable path module (core) and pathauto module


Available approaches for moving userpoints from one user to another Using the User Points module, I have this use case to design:

"move user points from User A  to User B"

What are the possible approaches we have here?

There are at least 2 approaches you can choose from, as further detailed below ...

User points donations

Use the Userpoints Donation module, which is one of the modules included in the (D7 version of the) Userpoints Contrib module.

To use it, make sure to also grant the required permission related to it (and to avoid asking yourself "How is the module Userpoints Donation intended to work?" ...).

Rules

Use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer 25 user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved".

However, the above Rules example may need further refinements, e.g. if you want to ensure that after moving points van User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.


How can i modify the height of input textfield in login form in drupal 7? how can i costumize a form ( for example login form ) in /user and specifically the height of input textfield? And the button "login"?
I try with the function theme_form_element() but nothing good!

The easiest way to do this, is with CSS

An example could be:

.form-submit {
  height: 30px;
 }

You can't set height on textfields and submit buttons AFAIK, only text areas.


How do I add Bean content to solr? I have a bunch of pages that contain only beans. I need these pages to show up when searching (using search_api_solr) for words used in those beans.
The bean fields don't show up in the solr field settings page. Any ideas?
Update: though you can create an index containing both nodes and blocks this will just give me the blocks as results and not the pages they are on. Could this be 'fixed' in views?

Enable the 'Complete entity view' filter and then select the field 'Entity HTML output'. This will put the entire page in one field including any beans on that page.

I assume there is a better solution but I have not found one yet.


What's wrong with this simple debugging code? Spend whole day trying to make working simple debugging code for Tweme theme (using D8).

function tweme_preprocess_node(&$variables) {
   $node = $variables['elements']['#node'];
   kint($node);
   kim ($variables);
}

The only response is blank page no other info.

What's wrong with my debugging code?

The kint() and ksm() functions output the results in the status messages block.

Make sure in /admin/structure/block the Status messages system block is set to a region.


How to extract an nid from and EntityFieldQuery I'm trying to figure out if a node already exist, I'm using the following code

$query = new EntityFieldQuery;
$result = $query
                      ->entityCondition('entity_type', 'node')
                      ->propertyCondition('type', 'item')
                      ->propertyCondition('title', $full_name)
                      ->execute();

       if (!empty($result['node'])) {
         // do something
       }

The problem is this, when a result is returned, the structure of the result is this

    Array
    (
        [node] => Array
            (
                [96] => stdClass Object
                    (
                        [nid] => 96
                        [vid] => 96
                        [type] => item
                    )

            )

)

I'm trying to get the nid, but I can't figure out how to access it $

result['node'][0]

does not work. How do I get the nid in this situation


Export / import content via MySQL I want to migrate all my content from my old D7 website to my new D7 site, with the Features module I exported/imported all my custom views, fields, etc.

But I don't understand how to export content.

Is there a way to do it from PHPMyAdmin? My two sites are on the same host. I have zero content in the new website. Can I overwrite the tables?

Is there way via phpMyAdmin or importing SQL into the database? Yes. Between 2 Drupal installs of the same version that is possible, but that comes with a big caveat. You need to know exactly what you're wanting to import and that you're not missing anything.

For example, say you want to import roles. You could export/import the role.sql from the role table, but that would only get you the role definition. If you want the permissions with those roles, you'd need to copy over the role_permission table. Depending on your needs this might work; the smaller number of table dependencies, the easier this approach can work without a problem.

However, in your case, you've mentioned a few Drupal components that span multiple data tables (e.g. node types, views, fields, etc.), not to mention other configurations (e.g. module settings in the variable table) that a module might depend on to behave the same between 2 installs. To take the example above, the role_permission is filled with permission items that are created by various modules. There might be a problem if you don't have all the same modules installed on your new site.

In these cases, and in general, you're better sticking with the tools that the community has created to handle importing the various components of Drupal. For example, the maintainers of Views have already built in a export/import feature for views. There many posts on Drupal Answers discuss these tools (and how to use them). Here are a few examples:

Features (content types)
Feeds (content/users/taxonomy)
Drupal-to-Drupal migration (users/profiles/taxonomy/content)
User Import (users)


how to check if the image field is empty or have uploaded image? <?php
  $nid = arg(1);
  $path = arg(0);
  $node = node_load($nid);
  if(isset($nid) && is_numeric($nid) && isset($path) && $path == 'node' && isset($node) && $node->type == 'page') {
    $theme_img = file_create_url($node->field_page_cover_image[$node->language][0]['uri']); //origional image path
    if($theme_img) {
        //image having style
        print theme('image_style', array('path' => $node->field_page_cover_image[$node->language][0]['uri'], 'style_name' => 'page_theme'));
    }
   }
?>

I've loaded the above code in page.tpl.php. It is to load the uploaded styled image from individual pages.
I am getting error in line no. 6 ($theme_img), for pages which have empty image field. It is working fine in pages which have image uploaded. How to know if this field is empty or have image uploaded.

Try this:

if ($node = menu_get_object('node')) {

  // Set default language if not set
  $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;

  if ($node->type == 'page' && isset($node->field_page_cover_image[$node->language][0]['uri'])) {
    print theme('image_style',
            array('path' => $node->field_page_cover_image[$node->language][0]['uri'],
                  'style_name' => 'page_theme'));
  }

}

Odd you're printing out the image though, must be in a tpl file. I'd suggest moving the code logic to a hook_preprocess_node and setting a template variable instead.

e.g:

/**
 * Implements hook_preprocess_node
 */
function MYTHEME_preprocess_node($variables){

  $node =& $variables['node']; // by reference
  // Set default language if not set
  $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;

  if ($node->type == 'page' && isset($node->field_page_cover_image[$node->language][0]['uri'])) {
    // Add new template variable called $page_theme_image
    $variables['page_theme_image'] = theme('image_style',
            array('path' => $node->field_page_cover_image[$node->language][0]['uri'],
                  'style_name' => 'page_theme'));
  }

}

and then in your tpl.php file, you just go:

if (!empty($page_theme_image)) {
  print $page_theme_image;
}


How to share session variables across Drupal sites? On my main Drupal site, users need to be able to select a display preference (e.g. 'high visibility'). This will be available to registered and anonymous users but only for their session, so I plan to store their preference in a session variable:

$_SESSION['display'] = $my_preference;

Another Drupal site runs on a subdomain of the main site, and needs the same functionality. And if the user visits both sites, it would be great to remember their preference.

I think that if I uncomment this line in both site's settings.php, session variables can be accessed across sites on the same domain?

$cookie_domain = 'maindomain.com';

So then I could set $_SESSION['display'] on one site, and retrieve $_SESSION['display'] on the other?

Also, one site is D6 and the other D7 - will this be a problem? Is caching for anonymous users going to cause problems?

Am I on the right lines, or is this plan flawed? Thanks

There are two options to do this

Using session

Use a single session table for both the site using settings.php set up

Using Cookie

Use same cookie domain for both site and set cookie available in all pages.


White screen after installing on Ubuntu 15.04 I got the following error while installing Drupal 8 on Ubuntu 15.04.

  Uncaught PHP Exception
  Drupal\Core\Database\DatabaseExceptionWrapper: "SQLSTATE[42S22]:
  Column not found: 1054 Unknown column 'checksum' in 'field list':
  INSERT INTO {cache_config} (cid, expire, created, tags, checksum,
  data, serialized)

I downloaded Drupal via drush dl drupal-8 --select and used the beta15 branch. The web facing install screens ran perfectly. It was only after pressing either link for visiting the site or running the update script did this error occur.

How might I begin trying to fix this?

The output of php -v is the following.

  PHP 5.6.4-4ubuntu6.2 (cli) (built: Jul  2 2015 15:29:28)
  Copyright (c) 1997-2014 The PHP Group
  Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies
  with Zend OPcache v7.0.4-dev, Copyright (c) 1999-2014, by Zend Technologies
  with Xdebug v2.2.6, Copyright (c) 2002-2014, by Derick Rethans

MySQL version is 14.14 Distrib 5.6.25, for debian-linux-gnu (x86_64) using  EditLine wrapper.

I think that this error is recoverable if you drop the cache_config table because cache tables are created dynamically at run time if they do not exist when using a database backend.

Like Brady suggested there may be a bug in the Drupal installer where that table was not created correctly. To dig more into this bug, if you're interested, you would need to look at the MySQL log to see what happened and try to reproduce it.


How to use Rules for sending an email to all users with same field value in some select list? When users registers on my site, they choose their State of Origin.

Using Rules I would like to configure a rule which sends an email to all users from the same state when a user from that state edits his/her profile.

Is this possible using Rules or is there another approach?

Without knowing anything about your entity & field setup I can't give you an exact rules that will work however it is possible and I can give you a pseudo rule:

Install the rules bonus pack module.
Install the rules conditional module (I think you need this but I'm not actually looking at a site to confirm).
Create a view that lists all users with a contextual filter of the state field. - So when you call the view with a specific state you get all users who have selected that state.
Event: Before user profile is saved.
Action: Rules bonus pack action "Load a user list with Views". Use the user email list view from earlier and pass in the value of the state from the new user object (from after the edit).
Action: Loop through the user list you loaded from the view.
Action: In the user list loop send an email to the loop user object.

This will also send an email to the user who is actually changing their profile. if you want to exclude them you can either add more conditions in the rule to check against the edited user object or you can add another contextual filter to the view for uid, check the box in that contextual field to exclude that user from the results and then also pass in the uid as a contextual filter in the rule.

I would do that latter because it is a less complex rule and I would assume it would use less resources to run.


How to disable the first option of select form element I created a custom module that contains a form with select element
I tried to disable the first option like this, but failed to get it work

'#options' => $terms,
                '#empty_option' => '- Select category -',
                '#empty_value' => 'none',
                '#disabled_values' => array('none'),

How could this be achieved without removing the option?

Drupal by default doesn't allow for this, so you'll need to do two things:

Override theme_select()
Create your own callback the create the options
Change the way you define your select options in your form definition

Overriding theme_select():

function THEME_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '<select' . drupal_attributes($element['#attributes']) . '>' . custom_form_select_options($element) . '</select>';
}

Create your own callback the create the options:

function custom_form_select_options($element, $choices = NULL) {
  if (!isset($choices)) {
    $choices = $element['#options'];
  }
  // array_key_exists() accommodates the rare event where $element['#value'] is NULL.
  // isset() fails in this situation.
  $value_valid = isset($element['#value']) || array_key_exists('#value', $element);
  $value_is_array = $value_valid && is_array($element['#value']);
  $options = '';
  foreach ($choices as $key => $choice) {
    if (is_array($choice) && !isset($choice['data'])) {
      $options .= '<optgroup label="' . check_plain($key) . '">';
      $options .= form_select_options($element, $choice);
      $options .= '</optgroup>';
    }
    elseif (is_object($choice)) {
      $options .= form_select_options($element, $choice->option);
    }
    else {
      $key = (string) $key;
      if ($value_valid && (!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value'])))) {
        $selected = ' selected="selected"';
      }
      else {
        $selected = '';
      }
      $options .= '<option value="' . check_plain($key) . '"' . $selected;
      if(is_array($choice) && isset($choice['disabled']) && $choice['disabled'])
      {
          $options .= ' disabled';
      }
      $choice = is_array($choice) && isset($choice['data']) ? $choice['data'] : $choice;
      $options .= '>' . check_plain($choice) . '</option>';
    }
  }
  return $options;
}

Change the way you define your select options in your form definition. Turn the option into an array with two keys:

data: The display value of the element
disabled: A boolean indicating whether to disable the element

Example:

$form['select'] = array(
  '#title' => t('Pick something'),
  '#type' => 'select',
  '#options' => array(
    'yes' => array('data' => t('Yes'), 'disabled' => TRUE),
    'no' => t('No'),
  ),
);


Site in offline mode, any way to debug how this happened? I came in this morning to find my companies site in offline mode. I personally checked with the only other site admin, and none of other users have the ability to turn off the site. I was using the Backup module prior to me leaving last night, but I've backed up hundreds of times and never encountered the module leaving the site in Offline mode.

Would there be any logs or any location in the database where this activity might be logged? We don't allow users to login to our Drupal site, just our own editors and a

I've tired Googling answers but I haven't got very far :(

running Drupal 6.x

Site offline is a matter of a global variable site_offline set to 1. Any call of variable_set('site_offline', '1') can also result to put site into offline mode.

Invalid database configuration can also results as site offline but it adds some error message.

Unauthorized access to DB can be used to manually alter record in variable table for the values as
variable.name='site_offline', variable.value='s:1:"1"'


How do I add CSS body classes for logged-in and logged-out users? In Drupal 7 I would add a theme process function to add the body classes needed.

function template_preprocess_html(&$variables) {
  $variables['classes_array'][] = $variables['is_front'] ? 'front' : 'not-front';
  // Add a class that tells us whether the page is viewed by an authenticated user or not.
  $variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
}

In D8 this theme function exists but they don't have all the variables need for users.

Ok I think I figured this out as in Drupal 8 it uses TWIG to print the body classes for content types or users we need.

In the html.html.twig

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    user.hasPermission('administer')  ? 'isAdmin',
    user.getRoles()|join(' role_')
  ]
%}

Then make sure this line is added to the body classes

   <body{{ attributes.addClass(body_classes) }}>

So if the user is logged out we can use the role class to identify them.

   .anonymous { }

Or we can use the :not Css selector
:not

   :not.user-logged-in {}


How to fix the Invoice module's total amount? I recently started using the Invoice module. Everything seemed to work until the moment I was going to make some test invoices.

The total amount is wrong (see figure): 306.81 + 64.43 = 371.24, but on the invoice 371.25. Anyone have any idea how I can fix this?

It does show well in the back-end: The sum from there looks simple? 371.25 - 306.81 = 64.44, this is the only correct result (see figure).

It is not a mistake. That moduo do rounding. See the photo:

Subtotal: 134.50
VAT: 25.55
Total: 160.06

So, the real value of VAT is 134.50*0.19=25.555 and real total is 160.055 but for invoices you need to do rounding at two decimal places. And you get total 160.06.


Check which database is used Is there a quick, easy, safe way to check what database a Drupal 8 install is using?

I'm trying to do a Drupal backup but when I look in phpmyadmin I see 5 different DBs listed on the left. I'd prefer to only backup the one I'm using because I've had issues before backing up and restoring the "under the hood" DBs like information_schema.

I've searched a bit but none of the suggestions I've found seem to apply to Drupal 8. Everything I see like this, this, this, etc is from 5+ years ago and says to check the sites/default/setting.php for a db_url line, but I don't see that in that file for my site. Has the location of this info moved in Drupal 8?

FYI:

I'm using Drupal 8.3.7 via Bitname WAMP
I know there are some good backup modules - I've already backed everything up via the "Backup and Restore" module, but I'm paranoid and like to do a parallel manual backup in case something goes wrong with the module-based backup.

Thanks.

Can do it with drush

cd path/to/project
drush status

look for  Database name line

or look in your Drupal Settings File sites/default/settings.php and look for database found in the databases array

$databases['default']['default'] = array (
  'database' => 'database_name',


I've created a Webform. Whats next? I am completely new to Drupal. And I would really appreciate if someone could help me out here.

I used the "WebForm" module, and created a form. The data went into the database perfectly fine, as it appears under the results page.

Lets assume that this is a "Contact Us" form, that looks like this

Name: _______

Subject: ________

Message: ______

3 labels, 3 input fields. Easy enough.

I am trying to create a table for all users to see.

Name        |    Subject            |  Message

user1       | Hello                 | Thank you for helping me out

user2       | Goodbye               | Drupal is great

If I were to use raw php, I would essentially be writing a SQL statement to Select all the data from the database, and use a For loop to generate these data into the table.

But how do I do this in Drupal? It seems impossible, and I cant seem to find 1 relevant documentation to generate this result.

Is there a webform extension that does this? Or am I expected to create a view to generate these data? If so, how?

Any help would be greatly appreciated.

He Hui,

Currently the webform module does not provide integration of its submissions data with the views module.  You can see the status of this issue here: http://drupal.org/node/680386.  There is plenty of interest and work on the issue, but it is not functionality that currently exists.  By default, the only fields views will let you get to for the submissions are the sid, date created and a few others, but you can't get to the actual fields.

You can actually use additional modules to get to your webform submissions data in a round-about way, and there is lots of information online from folks who have made it work.  For Drupal 7, here is a sample post with instructions: http://drupal.org/node/1658784.  As you can see, you'll need three additional modules to get that functionality!

Hope this helps.


No default value for '#type' => 'date'? is there a way to configure a date form so it has no default value?
Setting the default value to NULL sets the default value automatically to the current date.

  /**
   * @return array
   */
  public function getFormFieldSampDate() {
    return [
      '#type' => 'date',
      '#title' => t('Date of Sampling '),
      '#default_value' => self::dateStringToArray($this->sampling_date),
    ];
  }

Thanks

Step 1) Install Date module.

Step 2) Enable the Date Popup module (comes with the Date module).

Step 3) Add code like the following:

  $form['date'] = [
    '#date_label' => 'above',
    '#type' => 'date_popup',
    '#date_format' => 'm/d/Y',
    '#datepicker_options' => [
      // limits date picker so no future date can be picked.
      // remove this section if you want to allow future dates.
      'maxDate' => "+0D",
    ],
    '#required' => TRUE,
    '#attributes' => [
      'autocomplete' => 'off',
    ],
  ];

Result:


Changing image styles in a node view (Drupal 7) In the node view of my custom content type I would like the image to stretch across the screen or at least be centered.  As can be seen in the below screenshot currently the image does not get resized and is left justified.  Would this be done through theming or some other means?

You can manage image-styles under

  admin/config/media/image-styles

and then use these styles to show up in your node view. Settings can be found on the "Manage Display" tab of your content-type. There's a little gear on the right side of the field row...


Location of Drush Error log I am getting a "terminated" message from Drush ARD command after it runs awhile. This happens in a shared environment on bluehost. I checked the error logs accessible via cpanel, but found nothing. There are also no messages in the Drupal error log. I need more information that just "terminated" to solve this problem. Where are Drush error messages logged?

Putty commands -

    Using username "columck5".
Authenticating with public key "imported-openssh-key"
Passphrase for key "imported-openssh-key":
Last login: Fri Nov  6 10:51:16 2015 from 98.142.53.79
columck5@columbiablooms.org [~]# drush status
 PHP executable         :  /ramdisk/php/54/bin/php54-cli
 PHP configuration      :  /usr/php/54/etc/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home5/columck5/.composer/vendor/drush/drush/drush.p
                           hp
 Drush version          :  7.1.0
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

columck5@columbiablooms.org [~]# cd /usr/php/54/etc
columck5@columbiablooms.org [/usr/php/54/etc]# ls -l
total 160
drwxr-xr-x 5 root root  4096 Nov  6 05:17 ./
drwxr-xr-x 5 root root  4096 Nov  6 05:17 ../
drwxr-xr-x 2 root root  4096 Nov  6 05:17 pear/
-rw-r--r-- 2 root root  1176 Jul 13 15:25 pear.conf
drwxr-xr-x 2 root root  4096 Nov  6 05:17 php.d/
-rw-r--r-- 2 root root 67071 Oct 29  2014 php.ini
-rw-r--r-- 2 root root 66936 Jul 23  2012 php.ini.rpmnew
drwxr-xr-x 2 root root  4096 Nov  6 05:17 rpm/
columck5@columbiablooms.org [/usr/php/54/etc]# nano php.ini
Error writing php.ini: Read-only file system
chmod gets the same error message

The Drush logs are emitted only to the console.  Use --debug to get more information about what is happening.

Your ISP is probably deciding that your Drush command is taking too long, and are killing the process.  Ask support at your ISP to determine if this is the case, and whether there is a way to increase the limit.   Drush does not have any support this sort of limitation; it assumes that it is running in a shell with no time limits.

PHP can also be configured to apply a maximum timeout to your requests. To find out what php.ini Drush is using, run drush status. One of the lines will provide the full path to your php.ini file.  Ideally, you should use a different php.ini for Drush than you do for your web server.  Set the environment variable PHP_INI to point to the php.ini file that Drush should use. Copy your webserver php.ini to serve as a starting point, and then customize to suit.

The variable you are looking for is max_execution_time.


How to correctly sort on accented letters when using the Lexicon module? I'm facing an issue with the Lexicon module which I still can't figure out.

I have a glossary of French terms, sorted alphabetically. And I notice that the accented letters are considered as different letters and make the words appear at the end of the list.

Example:

Dettes
Dividende
Droit de souscription
Débit/crédit
Dépôt de bilan

I found an issue reported here, that seems to match with my own problem.

I tried to apply the last validated patch, using my .make file like this:

projects[lexicon][patch][] = "https://www.drupal.org/files/lexicon-transliteration_for_lexicon-1275954-13.patch"

And proceeding to a deployment, using phing like this:

phing clean
phing dev-deploy
drush cc all
drush updatedb -y
drush fra -y
drush cc all

But it changed nothing.

EDIT:

The patch is applied correctly.
In the DB, when I sort the terms by "name", it appears in the right order.

Any clue is welcome!

If you want to find out whether or not the patch is applied correctly, open up lexicon.admin.inc and look for this code

if ($form_state['values']['lexicon_clear_filter_cache_on_submit'] == 1) {
 _lexicon_clear_filter_cache(NULL, TRUE);
function lexicon_alphabet_form($form, &$form_state) {
 '#type' => 'textarea',
 '#title' => t('Enter all the digits of your alphabet, in the correct order.'),
 '#default_value' => implode(' ', variable_get('lexicon_digits', range('0', '9'))),
 '#description' => t("Separate the digits by a blank. If you don't want terms to start with digits, leave this blank."),
);

If the patch has been applied successfully it will look like this

function lexicon_alphabet_form($form, &$form_state) {
  '#type' => 'textarea',
  '#title' => t('Enter all the digits of your alphabet, in the correct order.'),
  '#default_value' => implode(' ', variable_get('lexicon_digits', range('0', '9'))),
  '#description' => t('Separate the digits by a blank. If you don\'t want terms to start with digits, leave this blank.'),
  '#rows' => 1,
 );

$form['transliteration'] = array(
  '#type' => 'textarea',
  '#title' => t('Enter transliteration rules used for indexing terms.'),
  '#default_value' => _lexicon_transliteration_ruleset_encode(variable_get('lexicon_transliteration', array())),
  '#description' => t('Use the syntax "é:e,è:e,ê:e,...". Transliteration rules are only applied internaly for indexing. Terms are displayed unchanged.'),
  '#rows' => 1,
);

Notice inside the function lexicon_alphabet_form, in the '#description' attribute don't changed to don\'t and also the $form['transliteration'] was added in the patch. If you don't see these changes inside lexicon.admin.inc then the patch was not applied correctly. If you do, then the patch did not fix your problem. Hopefully this will help you narrow down where the problem is.

EDIT:

If the patch has been applied successfully,  go into the lexicon administration page and set the transliteration rules. Looking at the patch, it looks like it added a textfield for defining the rules you want to use in the following syntax é:e,è:e,ê:e,...


How to make panels with a node reference argument I have a multi-user site. When a new user registers, several nodes (such as gallery node, etc.) are automatically created for him/her.

There is a panel page for each user that displays a profile of its owner. The panel is composed of various view panes.

Very much like in other community sites, a visitor to the profile page will be able to leave comments (text + pictures.)

To that effect, and hoping this is the right approach, I am trying to include in the panel a comment form. Comment forms are attached to their respective nodes so that comments left on John's panel page do not show on Jack's panel page. Comments will be displayed under the form in a view. The view is obviously universal and the same for all panel pages.

Now, on to the comment form. There is a node, specially for comments, created at the time the user registers.

How do I include the comment form of that node in a panel context knowing that it has to be different for each user?

I see that a node context can be passed into the panel. However, it requires a node ID. So that limits it to one node.  Does it support some kind of token so that a different node ID loads on different users pages? If so, how would I write it?

If i am using the wrong approach on this, how should I go about it?

Any idea anyone?

Thank you. :)

I implemented a similar feature on my site: when a user registers, several nodes of different content types are created specifically for that user.  I also use Panels.

To (somewhat) easily link the content with the user, I used the Relation module, which integrates with Rules.  After I created the content upon account registration, I created relations between the user and the content (all using Rules-- if you do this, you'll need to make a rule set and create the content in one rule before creating the relations in a following rule; otherwise, you'll get some weird errors).

Then, without using Panels contexts, I simply created content panes in Views that pull in the content by adding relations (from the Relation module) as relationships (in the Views UI).

The challenge of this approach is that setting up rules to fetch the relations and loop through them is pretty complex.  It might be easier to use the Entity Reference module, which has Rules integration, but when I was building my site a year ago it was broken so I used the more complex Relation module instead.


How can I use Composer with no Internet access? I need to build and deploy a Drupal 8 site within an on-premise server with no internet access (developer machines have internet access, and access to a private repo).
I would like to avoid committing the whole vendor directory to the codebase, and use composer to build the site.
As far as I am aware, my options are:

Commit everything, including third-party modules and the vendor directory

Use something like Satis as a local repository and mirror all the necessary dependencies in there, and reference the private Composer repository

Any recommendations on this scenario?

I personnaly don't like to commit vendor dependencies. It makes the code review more complicated before a merge request cause the files you need to review are lost in the middle of an ocean of files you don't need to review.
In your case I would have a CI job which would be run on release branches and would exec composer install then generate a .tar.gz file containing all the files (including /vendor). That CI job would then push the .tar.gz on a repository manager like Nexus. And finally a deploy job in Jenkins would get the last hosted release on the repository manager, push it to the final host, untar it and run drush commands to update the site.


Load nodes into div using AJAX I've created a views block that loads all nodes of a certain content
type.
I've added the Content: Has taxonomy term ID contextual filter

This works great. In the preview area if I change the value in the "preview with contextual filters" input field it changes the nodes that load below according to which taxonomy term ID I input.

How can I have this same functionality on a normal Drupal page?

I will have a list of links on the page with an href value of the taxonomy term ID. When I click a link, I need it to load all nodes that have been associated with that particular taxonomy term into an empty div using AJAX.

I've read somewhere on here that if the nodes just contain some basic text then using a pure AJAX solution might not be the best but rather accomplish the same thing using views.

Here is the javascript I ended up using to load a views block using AJAX and pass in a contextual filter from the href value of given link on page.

function getInfo(args) {

  $.ajax({
    url: Drupal.settings.basePath + 'views/ajax',
    type: 'post',
    data: {
      view_name: 'agent_lookup',
      view_display_id: 'agent_lookup_block', //your display id
      view_args: args,
    },
    dataType: 'json',
    success: function (response) {
        if (response[1] !== undefined) {
        var viewHtml = response[1].data;
        $('#ajax-target').html(viewHtml);
        //Drupal.attachBehaviors(); //check if you need this.
      }

    },
        error: function(data) {
         alert('An error occured!');
        }
  });
}

$('.ajax_button').once().click(function(e){
    e.preventDefault();
    var the_id = $(this).attr('href');
    noSlashes = the_id.replace(/\//g,'');
    getInfo(noSlashes);
});


How many items has a multi-value field? I need to loop through all the values of a multi field as per example bellow:

for ($i = 1; $i < ???; $i++) {

    $a = $form['field_...']['und'][$i]['#entity']->field_...['und'][0]['value'];

}

of course I could do something like this

foreach ($form['field_additional_sections']['und'] as $key=>$value) {
   if (is_int($key)) {
    ....
   }
}

but I was wondering if there is a nicer option to do this. I should probably mention that I'm implementing hook_FORM_ID_form_alter.

Thank you

element_children() is the easiest way to get a list of all child elements in a render array, e.g.

foreach (element_children($form['field_...'][LANGUAGE_NONE]) as $key) {
  $element = $form['field_...'][LANGUAGE_NONE][$key];
}


Using #cache key on a render array generates 2 entries per role, how to change that? On a page controller I have a method that displays the content via a render array. It also caches the rendered output using the #cache key:

  public function viewContent(NodeInterface $node) {
    $content = array(
     '#entity' => $node,
     '#sorted' => TRUE,
     '#pre_render' => [[$this, 'buildList']],
     // Cache the render array until the lock history/node is changed.
     '#cache' => [
      'keys' => ['my_module', 'node', $node->id()],
      'tags' => ['my_module:node:' . $node->id()],
     ],
   );
    return $content;
  }

But I noticed that drupal is generating 2 cache entries per user role in the cache render table as you can see in the screenshot:

Is it possible to generate only 1 set of entries for all users and manually pick the cid using the builtin render #cache properties?

Yes, by default cached render arrays are varied by the hashed user permissions. See this container parameter:

/sites/default/services.yml

parameters:
  renderer.config:
    # Renderer required cache contexts:
    #
    # The Renderer will automatically associate these cache contexts with every
    # render array, hence varying every render array by these cache contexts.
    #
    # @default ['languages:language_interface', 'theme', 'user.permissions']
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions']

Though this should be changed only in rare cases, because caching content with the wrong user permissions can cause security issues.

If you don't want the variations of the render cache, another approach might be to cache the query results directly:

use Drupal\Core\Cache\Cache;

  if ($cache = \Drupal::cache()->get($cid)) {
    $data = $cache->data;
  }
  else {
    $data = my_module_query();
    \Drupal::cache()->set($cid, $data, Cache::PERMANENT, $tags);
  }

Then you can manually pick a cid. With the cached query results the rendering of the list shouldn't take too much cpu time and so probably you don't need render caching anymore.


Is it currently possible to install Drush locally on a Windows 10 PC? Is it possible to install & use Drush locally on a Windows 10 Notebook to manage Drupal sites (on shared hosting) online?
I have so far searched in vain, may be in wrong places. The places I see downloads or documentation, none seems to include Windows or in case of some tutorial on Youtube, the links related to drush on drush.org, do not seem to exist any more, such as that for "composer for Windows".

I would appreciate some specific guidance as a newbie on this.

Thank you & kind regards

You can install Drush on Windows using composer - http://docs.drush.org/en/7.x/install/

You can get composer from - https://getcomposer.org/doc/00-intro.md#installation-windows

In theory you can manage a remote site with Drush, but you have to have ssh access to the remote server. If you have ssh access, you are better off just logging in and running it on the server. If you have multiple sites across multiple servers, then setting up site aliases in Drush makes more sense.


Why don't I get any CSS after deploying my Drupal site? I have deployed my Drupal 8 website, but I don't get any CSS on it.

I deployed it on mydomain.com/newdrupal, maybe this needs extra configuring somewhere?

When I check my logs, I have about 20 messages with this warning:

  Warning: file_put_contents(temporary://filedGJSiQ): failed to open
  stream: "Drupal\Core\StreamWrapper\TemporaryStream::stream_open" call
  failed in file_unmanaged_save_data() (line 888 of
  /var/www/stijnAerts/notify/core/includes/file.inc).

I also have this in my console:

  Resource interpreted as Stylesheet but transferred with MIME type
  text/html: "*****/notify/?o66rbh".

Note: This is a base theme, so no custom theme.

In addition to @acrosman:

Make sure that your files and temporary files directories are writable by the server.


Naming conventions for Drupal permissions Looking through the Drupal coding conventions http://drupal.org/coding-standards#naming I have seen module, variable, function, and many other areas but not for permission names. Are there any conventions to the Drupal 7 permissions hook to keep from creating permission names that might interfere with others?

AFAIK there's no official recommendations.

Given that all permissions share the same namespace it's a good idea to avoid generic names. You can include the name of the module that defines the permissions to minimize collision risk.


Using views to generate a summary view of nodes I have been wrapping my head around this problem. Basically I have changed the post settings to teaser mode. And I have made views that filters node of certain type . To conclude, I want my nodes to be displayed like in this link http://asblab.mie.utoronto.ca/research
where the research links has a summary view with the read more.

Thanks in advance.

There are a million different ways to do things in Drupal, but:

Create a View
Filter on node published and type
Sort by whatever criteria you desire and select how many items you want displayed
In Fields, select:

a. Node Title - link to node

b. Body or Field that contains the description you want displayed (select Trimmed if you want it shorter than all of it) and remove the label

c. Node Link - enter Read More as the text to display and remove the label

and you should be on your way...


How to change category for Panels IPE How would I change the category from "Fielded panes" in Panels IPE to something else?

I can accomplish this through the following code:

function template_preprocess_panels_add_content_modal(&$vars) {
  $i = 0;
  foreach($vars['categories_array'] as $item) {
    $new_item = str_replace("Fielded panes", "New Content", $item);
    $vars['categories_array'][$i] = $new_item;
    $i++;
  }
}

However, I'd like to find a more elegant solution by altering the category name in a function that runs before template_preprocess_panels_add_content_modal().

Have a look at template_preprocess_panels_add_content_modal() and $vars['categories']. You should be able to override the category names there.

Edit:

Ahh, yes, I forgot about hook_ctools_content_subtype_alter(). That's more elegant :)

From the documentation:

  This hook can be used to add things like 'render last' or change icons
  or categories or to rename content on specific sites.

In the example below the category "Fielded panes" is changed to "New category name".

/**
 * Implements hook_ctools_content_subtype_alter().
 */
function MYMODULE_ctools_content_subtype_alter(&$subtype, &$plugin) {
  if ($subtype['category'] == 'Fielded panes') {
    $subtype['category'] = 'New category name';
  }
}


Fontawesome speed loading problems I’m using the Bartik Theme on Drupal 8.5 as a base theme (I have the Fontawesome module: 8.x-2.0 installed and I have the fontawesome being loaded from my local files) and I doing a few changes on my custom theme. In one of  the templates I took over, I used  fontawesome with the tag: <i class="far fa-comments"></i>.

Sometimes on loading of the pages, before the icon shows, it appear a small square on his place, and only an instant after the icon loads.
I still have the site on debug mode, but is this behavior normal? How can I make the loading of the icons faster?

Scripts are added to the last in the resulting HTML Page in Drupal 8, and External CSS is added in the head, but external CSS is loaded after internal CSS that is used in modules. This might be creating an unwanted delay in rendering your font awesome styles.

I suggest you minimize the delay of your font awesome script by hosting it on your own server and calling it from there.


Constant Contact module puts subscribe checkbox on every user profile page So, we are using the Constant Contact module to allow users to sign up for newsletters on our website. In the admin pages the module provides a 'Subscribe Method' option that let's you specify how users opt-in to the newsletter feature. We are using 'checkbox'.

This is all fine, except that we are also using user profiles, with multiple categories. When a user goes to edit his or her account details this 'subscribe' checkbox is appearing on every single category page, even when its totally irrelevant.

Is there some way we would be able to hide / remove this field from displaying anywhere other than the user's 'account' page?

I found this same issue.  It is due to a bug in the module.  I have submitted an issue here and have attached a patch which fixes the bug.


How do I reset all user passwords to 123 with drush or SQL? For testing purposes I like to reset all user passwords to 123.

Is this possible in Drush or SQL?
I guess the query will be someting like this but cannot find the exact yourhash:

UPDATE `<mydatabase>`.`users` SET `pass` = '<yourhash>' ;

Can I run the final query with drush?

Yes, you can do this using Drush, with following steps (e.g.):

1.Generate a password hash using following command:

$ cd [/var/www/html/drupal7]
$ php scripts/password-hash.sh '123'

2.Now run following drush command:

$ drush sql-cli
mysql > UPDATE users SET `pass` = 'pasted_big_hash_from_above' WHERE uid > 1;

Update pasted_big_hash_from_above with password hash generated using php command in step #1.