Disable form or block cache for anonymous users?

What you need need to do, is not to use a cache tag but a cache context. In your specific scenario you want to use url.query_args:keywords. In code that would look like this

$form['keywords'] = [
   '#cache' => ['contexts' => ['url.query_args:keywords']],
   ...
];

For reference.

Cache tags are used to invalidate cache. Like if a cache element is tagged with node:1 and node with nid 1 is updated, then all cache containing node:1 cache tag is invalidated (other tags are also invalidated).

Cache contexts are used if cached element exists in multiple variations based on something like the query arg. What happens is that multiple cache entries are created and they will all be invalidated based on the same logic (cache tags).


If that file does actually exist within /sites/default/files/ then your link should work.

Have you messed around with the .htaccess file in the root of your site? Or it could be the hosting package your on as there's a rule in that htaccess to not go into drupal if the file exists in that directory


How to resolve my database connection error when using the Wordpress Migrate module?

Solved!
By adding anothe data base configuration with ['migrate'] in settings.php under the default database like this

$databases['migrate']['default'] = array (
  'database' => 'NAME',
  'username' => 'USER',
  'password' => 'PASS',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);


Need to add below code in your theme file

themename.theme

/**
 * Implements hook_preprocess_node().
 */
function theme_preprocess_node(array &$variables) {
  $node = $variables['node'];
  switch ($node->getType()) {
    case 'article':
      $my_paragraph = null;
      foreach ($node->get('field_content') as $paragraph) {
        if ($paragraph->entity->getType() == 'my_paragraph') { // Change to your paragraph type
          $my_paragraph = $paragraph->entity;
        }
      }

      if (!empty($my_paragraph)) {
        $variable['test'] = $my_paragraph->field_test->value;
      }

      break;
  }
}


Using mod_rewrite within .htaccess, in your server's document root. Untested, but something like this should work.

# Enable from .htaccess
RewriteEngine On
Options +FollowSymLinks
# For all URLs not starting with drupal
RewriteCond %{REQUEST_URI} !^/drupal
# Serve the same content from the /drupal directory instead
RewriteRule ^/(.*) http://pavescorner.com/drupal/$1


How to generate stats or reports for multi-sites?

Here's how I do this:

I created a "meta" site and database in the system where I added a new table called "databases".  In that table I store the access info of all the DBs in the system.

Then loading an array from a query to that table, query the other DBs individually using the methods outlined here:
http://drupal.org/node/18429


How can one run drush from project root when using multiple site configurations?

Try drush --uri=http://local.domain status from the root directory.

Also, you can create a file $HOME/.drush/aliases.drushrc.php, and define site aliases for each of your site. Then, drush @local status can be used.

Your aliases file would look something like this:

$aliases['local'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://local.domain',
);
$aliases['staging'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://staging.domain.com',
);
$aliases['live'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://domain.com',
);

However, although it is off topic for your question, I must also mention that the multisite configuration you have set up here fails to meet the basic requirements for a viable dev -> test -> live workflow. In this configuration, your code is shared between all three environments. This means that when you update Drupal core on your dev site, the updated code will also be immediately applied to the live site, which affords no opportunity for testing. A propper dev -> test -> live workflow should use completely separate codebases for each environment, so that you may publish code on a controlled schedule.

Multisite can be useful in certain environments where you have a very large number of copies of the same code, e.g. separate live sites that want to share the same opcode cache.  For simpler setups, it's easier to stick with single codebases for each environment.


What is the most efficient way to create and manage 500 sales/landing pages

Disclaimer: I'm a maintainer of Aegir.

Aegir is inherently multi-site, you can have many sites on a shared platform, which means you can have many independent sites with the same codebase. This is a lot more efficient resources-wise than having multiple sites without a shared codebase.

If you often need to create new domains, I developed a Software-as-a-Service suite for Aegir: https://www.drupal.org/project/hosting_saas

Since there is E-Commerce involved, you'll want to have an SSL certificate, with Aegir you can easily use the same wildcard certificate for all the sites if necessary.

If the landing pages don't need to be customized (much), you can even have a single site with 500 aliases in Aegir.

Lastly, one of the main advantages with Aegir is that you can simply clone a site when you need a new instance (which is what we do in Hosting SaaS).


There are a few possible reasons for the issue you're facing, as further detailed below ...

Drush commands need to be issued from within the correct subfolder

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

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

Use the Drush version that supports your Drupal version

It could well be an issue with the version of Drush that you are using. Check if it is an option to downgrade to a lower version of Drush? FYI: Drush 7.x does support D8 also ...

Note: in one of the comments in the question, the OPer wrote "Drush version is 4.5". Haven't double checked it yet, but that appears to be an extremely old version of Drush. I wouldn't be surprised if that version doesn't support D8 "yet". And since the D8 folder structure changed quite a bit, that would also explain the error like "A Drupal installation directory could not be found" ... More research (and clarifications from OPer) are seems appropriate here ... (I might update my answer here later on with some relevant pointers about "which version of Drush supports which version of Drupal".


I can't remove comma after currency in commerce price

In commerce.currency.inc the currency is defined as:

'IRR' => array(
  'code' => 'IRR',
  'numeric_code' => '364',
  'symbol' => 'REMOVED_DUE_TO_SE_ERROR',
  'name' => t('Iranian Rial'),
  'symbol_placement' => 'before',
  'symbol_spacer' => ',',
  'code_placement' => 'hidden',
  'minor_unit' => t('Rial'),
  'major_unit' => t('Toman'),
  'decimals' => 0,
),

If you wanted to override this and set the thousands_separator (not present) to and empty string. You can do this in hook_commerce_currency_info, documented here http://cgit.drupalcode.org/commerce/tree/commerce.api.php?h=7.x-1.x#n11

You need to set it as, let's say '' because the defaults are the following for missing properties:

  $defaults = array(
    'symbol' => '',
    'minor_unit' => '',
    'decimals' => 2,
    'rounding_step' => 0,
    'thousands_separator' => ',',
    'decimal_separator' => '.',
    'symbol_placement' => 'hidden',
    'symbol_spacer' => ' ',
    'code_placement' => 'after',
    'code_spacer' => ' ',
    'format_callback' => '',
    'conversion_callback' => '',
    'conversion_rate' => 1,
  );


Search API Attachments Facet returning part words

Before I go into to how I solved this; its worth repeating what feed back of this from our hosts.
'This will happen if you attempt to create a facet for a Solr field of type "text" (which might be the case here), because Solr stems and further processes all words before storing them on the index. There is no direct way to get around this.

Also, faceting on text is not really recommended:

UX-wise, searchers get too much noise, because words come from all over the place--your top facets could be just common words like 'the', 'with', 'you', 'they', etc.

Performance-wise, calculating the facets to show for large fields takes a long time. '

I have got things looking like how I want them though and that was to use 'Facet API BONUS' module.

Install and Enable Module
Configuration > Search and metadata > Exclude specified items > Add to Exclude items

  Save Configuration

You only get a limited amount of words with this module .  If needed this can be changed by extending the Form in

Facetapi>filter_exclude_specified_items .
class FacetapiFilterExcludeItems::settingsForm

And adding a '#maxlength'

This is a pretty good blog on adding how to other extended functionality changes to the Facet API module  http://www.trellon.com/content/blog/apachesolr-and-facetapi


User tabular data entry to build a budget worksheet?

You could try https://drupal.org/project/tablefield or https://drupal.org/project/slickgrid
From module page:

The Slickgrid module is an implementation of Michael Leibman's jquery slickgrid plugin, a lightening fast JavaScript grid/spreadsheet.
It defines a slickgrid view style, so all data can be output as an editable grid.
This module will only work with Slickgrid 2.1.

These do not provide spreadsheet functionality, but you would probably implement the summation or whatever calculation is necessary.


How to tell whether the current request is part of a cron run?

Implement hook_cron_queue_info() to set a global flag indicating that the current request is part of a cron run.

/**
 * Implements hook_cron_queue_info().
 *
 * hook_cron_queue_info rather than hook_cron, to ensure it executes before
 * any hook_cron implementations.
 */
function mymodule_cron_queue_info() {
  global $mymodule_in_cron;
  $mymodule_in_cron = TRUE;
}

Then, elsewhere in your module, you can check this flag:

global $mymodule_in_cron;
if (!empty($mymodule_in_cron)) {
  return;
}

This works both when invoking cron via the web server and via drush cron.


How should I balance Features and Installation Profile in a Code Driven Development workflow?

I've recently started using the Features module as a deployment system, as described in this presentation on features deployment. Assuming your using a similar setup with hook_update_N, features has one clear advantage that I'm aware of: it's aware of any changes that are not in code. This makes it a fair bit easier to track changes to (for example) views and content types, and also allows you to auto-generate the new features code to be committed and deployed.

I'm not overly familiar with installation profiles, but from the link you've provided it doesn't look like they provide this functionality. However it might be a case of use whichever suits you the best.

Edit: rethought response.


How to insert block into Article content type?

Have you tried Insert Block?

  Sidebar blocks contain all sorts of nifty stuff, but sometimes you
  want to include or embed that stuff into the body of your node.
  Instead of using PHP snippets (a possible security hole on public
  sites), you can use this module. When it's activated...

  [block:name of module=delta of block]

  ...will insert the contents of a rendered sidebar block into the body
  of your node. If no delta is specified, the default block for that
  module will be displayed.

There's only dev releases for this module, but it has almost 6.000 installations.


Is there a variable that keeps track of which pages are enabled or disabled in Page Manager?

Yes, there's a variable per page of the form "page_manager_MACHINE_NAME_disabled", eg. "page_manager_node_view_disabled". You need to set it to FALSE using Strongarm to enable the corresponding page.


Can't seem to edit page title in og/users/%/add_user

This is what helped me in this particular situation, but I'd be open to mark another answer correct if anyone had a better option inside of a hook_form_alter().

// Force Title on the Add Users OG form.
if ($form['#id'] == 'og-add-users') {
    drupal_set_title('Add Users');
}


How to add a custom variable that can be accessed on bootstrap's menu--account.html.twig?

I have done this for a theme on past projects. Be sure to pass it in through the content item:

Example

use Drupal\Core\Render\Markup;

function mytheme_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu__account']['variables']['nickname'] = 'default';
}

function mytheme_preprocess_menu__account(&$variables) {
  // code...

  $variables['content']['#nickname'] = [
    .. renderable properties
  ];

  // or also...

  $variables['content']['#nickname'] = Markup::create('Jeff');
}

Then, in the twig template:

{{ custom_var }}


The answer is the one suggested in Creating Entities in a Rules loop creates one first entity only.

After an actions of entity create, or data set, add the "Save entity" Action, and click on the "Force saving immediately" checkbox below on the form. Without selecting the checkbox, the Rules module creates only the first entity.


Inserting search term within "No results behavior"

you can use template_preprocess_views_view

 function template_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $variables['view_total_count'] = $view->total_rows;

  if ($view->total_rows === 0) {
    $exposed_input = $view->getExposedInput();
    $search_term = $exposed_input['your search input'];
    $variables['empty'] = 'No results found for'.$search_term.', please ...';
  }
}

then in your twig template, you print the empty variable.


Correct usage of hook_user_login and hook_user_presave for saving data to user

IMO you don't need the implementation of the hook_user_presave(), I see that in the implementation of hook_user_login() you have all the values that you need to create the user.


I think it highly depends on what the script is. There are definitely advantages to using third party scripts rather than including them locally. In most cases, I'll try to use the google Library API (http://code.google.com/apis/libraries/) when possible for things like swfobject, webfont loader, and the like. The advantage here is that clients may already have these libraries cached, giving a performance increase over hosting them locally. For situations where there is not a widely used third party host for scripts, I'll usually add them to sites/all/libraries/$library_name and include them locally, so you can take advantage of Drupal's ability to aggregate and minify JS.


No release history was found for the requested project

According to release updates.drupal.org, the module has release candidates for Drupal 7.x as per:

https://updates.drupal.org/release-history/registry_autoload/7.x

So try the following suggestions:

Make sure your IP is not blocked by going to https://updates.drupal.org/
Make sure your Drush recognise your Drupal root as 7.x (check drush status) and whether Drush can access the above endpoint by:

drush ev 'echo file_get_contents("https://updates.drupal.org/release-history/registry_autoload/7.x");

There could be a case that you are behind the firewall or corporate proxy, therefore the certificate could be not valid, so you'll have to configure your PHP's curl library either by importing the right certificate and mark it as trusted, ignoring it (not recommended) or use the non-secured connection to check for the new releases.


How to theme a field group (with div output and css class set)?

I know you mentioned wanting to use the field_group module, but I don't immediately see the need.

If the goal is to position a set of fields all together, why not override your node.tpl.php file, calling it node--my-content-type.tpl.php and then somewhere within it do something along the lines of:

<div id="field-group">
  <?php print render($content['my_field1']); ?>
  <?php print render($content['my_field2']); ?>
  <?php print render($content['my_field2']); ?>
</div>

That way they can A) be positioned by positioning #field-group, as well as allowing you to theme each field in their own field.tpl.php file.


Could it be that the drupal database doesn't work anymore after using jquery .load()

Most likely that drupal database API is not available in your page.php file because corresponding files are not included in it. What I usually do if I want to do stuff like this, is declaring a menu item:

function MYMODULE_menu(){
    $items['path/page'] = array(
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'title' => 'AJAX: Page callback'
    );
    return $items;
}

the code above adds a new page to drupal menu system and makes it available as: http://www.yoursite.com/path/page

and then in your function

function your_function_name() {
    $query = db_select('course_function', 'f');
    $query->fields('f', array('id'))
          ->condition('f.chapter_id', $id, '=');
    $result = $query->execute();
    print_r($result);
    foreach ($result as $res) {
        $id = $res->id;
    }
    echo $id;
    //You need to have exit in such callback functions to prevent drupal theme
    //functions from taking over the page processing
    exit;
}

Then in your javascript you can approach this page just like this:

<script type='text/javascript'>
function loadPage (id,level) {
$.ajax({
      beforeSend: function () {
        // here you can do things before the action start
      },
      success: function () {
          $('#contenpage').load("http://yoursite.com/pages/page", { 'var': [id,level]})
      }
    });
}
</script>


Client-Side Equivalent of drupal_set_message with javascript

I don't see JS API for dispaying messages even in D7. Maybe because all you need is DIV with classes like messages,status warning or error. You can see how drupal works with it in file /misc/tabledrag.js.
When you drag rows in tables drupal shows you a warning message with this code:

$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');


How to programmatically add / remove a value for an unlimited multivalue field?

You can use the entity_metadata_wrapper() function with entities (you'll find good examples here); it makes things a bit cleaner, but not that much.

Other than that, no - you're stuck using vanilla PHP for this, Drupal doesn't have any built in functions to help.

There's no reason you can't use array_push as normal though:

array_push($myfield[LANGUAGE_NONE], array('value' => 23424));

Although that's actually more verbose and less readable than the original.


for the page view use the normal node, and hide the stuff you want to display in one of the block in your node.tpl.php.

then create a new view showing your contenttype, with the actual node id as contextual filter. make block displays, put the fields you need for your different blocks in each block.
add the block in to the page, only showing it for the actual contenttype.


Instead of using route_name: <nolink>, I suggest providing a route for the link and e.g. pointing that route to Drupal's default overview page contoller. This should fix your issue and assures the users can click the menu link and get an overview of the available functions (e.g. when re-using your module in a Drupal that has no Admin Toolbar installed):

mymodule.links.menu.yml

scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  route_name: scrape.migration

mymodule.routing.yml

scrape.migration:
  path: '/admin/config/development/scrape'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::overview'
    link_id: 'scrape.migration'
    _title: 'Migration'
  requirements:
    _permission: 'access administration pages'

You might have to adapt the path/permissions accordingly.


How to access field values from a custom block

At the point when you build your block you don't know what other code will put in the page.

As alternative you can use the routing system, because the route is resolved in the bootstrap process (in D8 the symfony framework) before any custom code is run:

if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $field_my_custom_id = $node->field_my_custom_id->value;
}

Of course you don't know if other code will put this field on the page, but you know that the url of the page will produce the specific node as main content.


This is really not the ideal way to do this. Instead you may want to try something like:

$query = db_select('node', 'n')
  ->condition('n.type', $type)
  ->condition('n.uid', $uid)
  ->fields('n', array('nid'));

$count = $query->countQuery()->execute()->fetchField();

if ($count) {
  return true;
}

return false;


One way to create multiple sites within one drupal instance is to use the domain access module.

https://www.drupal.org/project/domain

Using this you can create different sites with different domains on the same instance. You won't be able to do www.example.com/saloon1 and www.example.com/saloon2 (unless you use the subfolder domain module that extends domain access. Though I'm having trouble getting that module to work)
But you could do saloon1.example.com or saloon2.example.com or you could do saloon1.com and saloon2.com

On all content and blocks you'd be able to specify whether it's available to one domain, the other, or both. You could also restrict user privileges to one domain. You could also apply different themes to each domain.


Trying to migrate Date values using migrate module.

At the base there was a problem: the module dates was patched.
The final code that have worked:

my.info

dependencies[] = migrate
dependencies[] = migrate_extras
dependencies[] = date
dependencies[] = date_migrate

my.make

projects[migrate][subdir] = "contrib"
projects[migrate][version] = "2.6-rc1"
projects[migrate_extras][subdir] = "contrib"
projects[migrate_extras][version] = "2.5"
projects[date][subdir] = "contrib"
projects[date][version] = "2.6"
projects[date][patch][] = "https://drupal.org/files/date-consolidated_migrate-1.patch"

my_migration.inc

$this->addFieldMapping('field_date', 'date_from');
$this->addFieldMapping('field_date:to', 'date_to');
$this->addFieldMapping('field_date:timezone', 'UTC');


What exactly are you trying to do? Is the page refreshing or the entire $form? What you're asking it to do is by attaching #ajax to the select is that when it changes a value resubmit the entire $form, which would probably include any submit handlers. Typically #ajax would be directed at a form element rather than the entire form.


How can I display a search form with a different style from search bock, inside a node?

Since blocks can only go in a single region (without some messing about), I think you'll have to use code for this. You could add the form in a preprocess function in your theme's template.php file:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'my_node_type') {
    $form = drupal_get_form('search_form');

    $vars['search_form'] = render($form);
  }
}

Now in your node.tpl.php file, or node--content_type.tpl.php file, you'll be able to output the search form like this:

<?php if ($search_form): echo $search_form; endif; ?>

The default classes and ID added to the <div> surrounding the node will be be perfect for targeting that particular instance of the form with CSS. You can easily use developer tools/firebug to determine what selector to use.


Change style for the reply link in comment.tpl.php

Just use the following code:

<?php print url($content['links']['comment']['#links']['comment-reply']['href']); ?>

If you pass node/1 to url(), it will  return /?q=node/1 when clean URLs are not enabled, and /node/1 when clean URL are enabled.


Can I change the HTTP user agent when writing browser tests?

No, you can't.

BrowserTestBase, just like other other tests that support web requests uses the user agent to identify which test environment you're in (there could be multiple, parallel ones). Changing the user agent would result in your request being sent against the main site.

The only workaround that I see is to send another header (if that's actually possible through the API, not sure). In your could you would then look at that header instead. It's not perfect and it requires you to write special code for tests, but I can't really see another way if you really rely on the user agent.


Uncaught TypeError: Cannot set property 'bootstrap' of undefined

Drupal exports in javascript the Drupal variable that has several subitems inside depending on your configuration. Your error suggest that the bootsrap property does not exist (at least yet). You can easily make sure that this is the case by opening the console in your browser (f12 in chrome) and type: console.log(Drupal.behaviors); if the property is not there you cannot use it.

Make sure you re loading the bootstrap library correctly. Usually you can do this by downloading the bootstrap module/theme or by using the libraries module.

Also note that Drupal behaviors intend to run every time an 'ajax' call is made by in a drupal page. I m putting ajax in quotes because drupal actually uses a legacy way for ajax called AHAH


The path admin/content/files is missing in Drupal 8.5

I had the same problem and was because the route that creates the page (view.files.page_1) was not recognized by Drupal. Why? I don't know, but I reinstalled the Views UI and the Views module and the problem was solved.

You can read about this problem in Add Item for Files under Content Menu and this is why we added in the Admin Toolbar module a validation for the route. The file module can be installed and the route can be missed from the site.


Is there a way to add a dynamic URL token to images so that the move from local host to live doesn't require code change?

Handling of the links in the field having a WYSIWYG editor, or any other long text field is a common issue when the site moves from one server (say dev) to other (say stage or production).
The links should be saved in such a way that they do not break.

Pathologic module does that for you.

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.


Why am I getting a "You are not authorized to access this page." on the Drupal Migrate UI page?

Are you logged in? Is your login the superuser? You can always get into your local site w/ drush:

$ cd /path/to/docroot
$ ../vendor/bin/drush uli --no-browser
http://default/user/reset/1/1527085618/[RANDOM_STRING]/login

Assuming your setup uses the drupal-project composer approach. Otherwise, you could use drush w/ a site alias or params.

If you're logged in as the superuser and still have issues, that's indicative of something wrong w/ the routing specification. That shouldn't happen with a contrib module, unless you've made any modifications? If you haven't and the superuser can't access the UI, then I would file an issue w/ the migrate module.


Deactivate the view with the same URL so there is no collision. Clear the cache and it should work.


How should the content structure for a Comparison website look like?

Your initial solution, having own content types, can also support that content editors can only edit their own content. Define an content type, setup user role for "Analysts", and set the appropriate user permissions for them.

Look at http://www.example.com/admin/people/permissions and http://www.example.com/admin/people/permissions/roles.

I'm assuming you have Drupal 7, but Drupal 6 has more or less the same functionality.


Maintain in-house repository of custom modules?

maybe this goes against good practices?

Wouldn't have thought so, providing a central repo for your modules can only be a good thing in my opinion. It's the best way to keep multiple sites up-to-date with changes to custom modules.

What you need is a combination of the Feature Server module:

  This module allows you to share features and custom modules on your own website. It lets you create projects and releases, and it produces an update XML feed compatible with the update module in core. In a way it's a highly simplified version of the project module.

And the project status url module .info file setting, for your custom modules:

  Allows module maintainers to define a URL to check for updates to their module using the Update status module. No module released on drupal.org should define this parameter. URL should point to an XML feed that accepts requests in the form of http://my.domain.com/projects/{project}/{core}. In that example, project status url should be set to http://my.domain.com/projects.


Get node data from entity reference field

You should be able to get the author like this:

{{ paragraph.field_blog.entity.Owner.name.value }}

and the creation:

{{ paragraph.field_blog.entity.createdtime|format_date('medium') }}


Retrieve node information in VIEWS template(s)

You can use hook_preprocess(&$variables, $hook)to find out which hook you have to react on, in your case it should be hook_preprocess_views_view_fields() and hook_preprocess_views_view_unformatted().

Next you have to find a way to access the node object. If your view is node based, then there should be an nid somewhere in the variables array. Don't be afraid to dif into the $variables array. You can use dpm (devel module) or print_ror whatever you're comfortable with. You can't really break anything without manipulating the array.


How do I render a field twice with two different field formatters?

So in drupal 7 you could use:

$output = field_view_field('node', $node, 'field_foo', array('type' => 'some_formatter', 'settings' => array(...), $langcode));

to render a field with a specific formatter. The drupal 8 the equivalent is:

$output = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));

source: Change record

Now to render the fields I would create a preprocess for a node

function HOOK_preprocess_node(&$variables) {
  $variables['my_field_formatter1'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
  $variables['my_field_formatter2'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
}

and then print my_field_formatter1 and my_field_formatter2 in your twig template for the node.


Entity Reference field in custom line item missing multiple field values

Line-item entity reference fields being displayed as views is most likely not supported, or not very well supported, because it's a very edge-case situation. Nothing appears to be in the issue queue regarding this limitation, so you might make a feature request and see where it goes.


Is there a way to use File Field but have it’s directory path be different for different instances of content, instead of the same?

You can define your file paths with node tokens. File (Field) Paths module provides the functionality that you are looking for.

  The File (Field) Paths module extends the default functionality of
  Drupal's core File module, Image module and many other File upload
  modules, by adding the ability to use entity based tokens in
  destination paths and file names.


Drupal views UI, is it possible for the user to limit the number of row of the result?

Go To view .Set pager options and do the change given in above screen shot


You can override the block template for a particular block and can modify the html for block subject.

You can check theme suggestions for more reference.


Local vs CDN libraries and how to check for available updates

We are using https://asset-packagist.org/ and manage our javascript dependencies just like any other, a composer update keeps those up to date as well then.

https://github.com/drupal-composer/drupal-project/pull/286 is a PR to add that to the drupal-project project by default.


Never had a usecase for that and no working Drupal 6 installation, but I assume your problem isn't t() related, more PHP related.

<?php

// This does not work!
echo '\n';

// This does work on UNIX!
echo "\n";

// This does work on Win!
echo "\r\n";

Hope this answers your question and helps.


Drupal 7 views admin redirecting to json returned after changing jquery version

You can't just upgrade the jQuery in the misc directory. You will get many many problems.

If you want to update jQuery because a specific plugin you want to use requires it, I would recommend the jQuery multi module.

However if you want your whole site to use a newer version, use the jQuery update module.
Currently though, the jQuery update module only supports up to jQuery 1.8.2.

In my experience using jquery update with versions above 1.5 was still too buggy, however those issues are claimed to have been fixed recently, so if you use the latest dev version it will apparently work.

However, you need 1.9 so jquery update isn't an option yet.

If you need 1.9 for a library (I assume that is probably the case), I would say use jQuery multi (I have successfully used it to run a bunch of things off on top of backbone.js and it has been working without issue for a long time now).


On content update email referenced users - Drupal 7 Rules module

I just figured it out, i used a loop that went trough all the referenced users and then I added a action that send an email to every user in the loop.


Difference between upgrade and migration

Seen as a process, upgrading will keep your existing database (where content and configuration lives) and update the code of your system. After the code is updated, all needed database modifications (configuration and content) will be performed.

Migration on the other hand, usually refers to content migration. That said, the migration process targets a Drupal instance different from the existing one, where the content will be transfered to.

A definitely good reference is the official Upgrade documentation page


Workbench is a great way to do this if you are OK with installing another module.

Workbench allows you to add moderation states. By default it gives you 'draft', 'published', and 'needs review'. (Drupal 8 also has "archived"). There is also a set of transitions that go with these states (ie, draft -> needs review)

For the three roles you described above, I would give the Content Editors the states to move from published -> new draft, draft -> needs review, needs review-> draft. Content Publishers would have access to all transitions, and super admins could override workflow entirely. This would produce the result you are looking for (and is what we commonly use with clients who don't need something more complicated).

D7 workbench can be a little confusing (very powerful means there's lots to configure!), but here's a good quickstart guide:https://www.youtube.com/watch?v=8nqWLrxH_4M

EDIT: As the OP points out, Drafty is a dependency for Workbench Moderation, which is needed for the above described solution. Drafty is no longer supported under Drupal' security advisory policy.


Is there a way to strip identifying data from commerce tables?

There's nothing special about sanitizing Commerce.  When I sanitize the db, I simply delete all the info in SQL:

TRUNCATE TABLE commerce_customer_profile;
TRUNCATE TABLE commerce_customer_profile_revision;
TRUNCATE TABLE field_data_commerce_customer_address;
TRUNCATE TABLE field_revision_commerce_customer_address;
TRUNCATE TABLE field_data_commerce_customer_billing;
TRUNCATE TABLE field_revision_commerce_customer_billing;

NOTE: This is just an example.  You need to check your database and make sure you get all the relevant tables.

If you want to use dummy data instead of deleting the data outright, you can use a statement like this:

UPDATE users SET users.name = users.uid WHERE users.uid > 0;

If you don't have a tool like PhpMyAdmin for accessing your database easily, I would use Sequel Pro on macOS or MySQL Workbench on Windows/Linux.

Drush has a sql-sanitize command but I have encountered several issues with it over the years.  I don't want to risk accidentally exposing anything before handing off a db to another developer, so I check the db anyway; in that case, there's no real speed advantage to using Drush vs. running the SQL myself and since I'm checking it with my own eyes I can be confident the job got done.


How to write a drupal cron job to fetch data from a link

Create a simple Drupal 7 module, there are a lot of examples for this (i.e. here). Then hook into cron with a function mymodulename_cron() and inside the mymodule_cron function fetch your json data.

Your mymodulename_cron() will be executed each time, the drupal cron is run. This can be done from outside or from the admin/reports page. Look at /admin/reports/status for info about this.


Kanban-style view : Group nodes in a view into columns based on a field value

I don't think it is possible right now without custom programming (either within a theme or custom module)

You can probably get started with grouping your view based on the status field and than using CSS in your theme (display:inline or float: left) you can get all groups next to each other.

There could be more sorting criteria for each column within the view.

For extra functionality like dragging/dropping within status areas (changing status) you will need to create your your own module to handle drag drop events and do ajax calls to the backend.

There was some work done for openlucius (drupal 7) that you can look at https://www.drupal.org/project/openlucius_board


How do I filter exposed taxonomy terms with other exposed taxonomy terms?

Use the Search API.  Totally awesome.  It will provide you with the Facets you need.  Don't be intimidated.  The instructions below are great.

http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/


Remove node_view rendered node's title link

Quoting from this comment, this code worked for the OP.

$node_view = node_view($node, FALSE, TRUE);
return '
Voorstel indienen
' . $node_view;


If you want to create content for the custom block type basic:

use Drupal\block_content\Entity\BlockContent;

$block = BlockContent::create([
  'info' => 'block 1',
  'type' => 'basic',
  'langcode' => 'en',
]);
$block->save();

And add a french translation:

$french_block = $block->addTranslation('fr', ['info' => 'bloc 1']);
$french_block->save();

Custom block types are content, not configuration. See this answer https://drupal.stackexchange.com/a/218244/47547


Hiding a drupal block on particular page

In the block configuration page, in the Pages tab select All pages except those listed; in the text area below, write alphabetical. As the example shown in the description for the text area, you don't need the slash at the beginning of the path.


Include a module template into an other module template

Include the template file with its namespace:

{% include '@modulename/template_file.html.twig' %}

{# @modulename refers to 'path_to_module/templates' #}

Drupal provides a @namespace for Twig based on the machine name of every module and every theme. The @namespace points to the templates sub-directory of that module or theme.


Unban repeated attempts via command or mysql?

Yes, it is true, but it is also excessive.

That table is also used for users sending emails with the contact form. Rather than truncating that table, it is better to remove only the necessary entries.
user_login_final_validate() contains the following code.

  if (empty($form_state['uid'])) {
    // Always register an IP-based failed login event.
    flood_register_event('failed_login_attempt_ip', variable_get('user_failed_login_ip_window', 3600));
    // Register a per-user failed login event.
    if (isset($form_state['flood_control_user_identifier'])) {
      flood_register_event('failed_login_attempt_user', variable_get('user_failed_login_user_window', 21600), $form_state['flood_control_user_identifier']);
    }

Just remove any row in the "flood" table where the "event" field is equal to "failed_login_attempt_ip" or "failed_login_attempt_user"; in that way, any login ban is removed.
This would remove the login ban for every user, including the ones who are trying to access somebody else's account by brute force. Unfortunately, without to know the IP of the user to unblock, it is not possible to unblock just a specific user: The login validation callbacks first check if the user is login banned basing on the IP, then basing on the user ID for the account used to login.


How do you dynamically redirect a user's role?

Checkout Auto Assign Role module.

You might need some customization or might have to play with the rules module as well.


Drupal provides a clean way of formatting dates any way you want throughout the entire site. Simply apply the settings that you're expecting for Danish:

Format dates in Drupal 6


You can specify a driver-specific column type for MySQL using the mysql_type attribute:

function MYMODULE_schema (){
  $schema['table_name'] = array(
    'fields' => array(
      'created' => array(
        'mysql_type' => 'timestamp',
        'not null' => TRUE
      )
    )
  );

  return $schema;
}

Then, on enabling your module, you can simply modify the column to add the default/on-update behaviour:

function MYMODULE_enable() {
  db_query('
    ALTER TABLE {table_name}
    MODIFY created TIMESTAMP NOT NULL
    DEFAULT CURRENT_TIMESTAMP
    ON UPDATE CURRENT_TIMESTAMP'
  );
}

I've just tested that on Drupal 7 and it works a treat.

NOTE: If you don't want the timestamp to update every time the record is updated then just remove the ON UPDATE CURRENT_TIMESTAMP part of the query.


Drush command to delete content going out of memeory. What can I do?

If you look at the code for node_delete_multiple() it does a node_load_multiple().  While this seems strange, it has to do this so that it can invoke all of the proper hooks so that other modules have the full $node object in order to do their thing (eg, delete the attached field data).

Because Drupal uses aggressive static caching to avoid redundant database accesses, memory usage can swell.  This can't be freed or disabled.  If this becomes an issue, you can do temp edits to the EntityControllers to comment out the static caches.  You could also make a temp edit to drupal_static() to effectively disable it.

I would come up with a good EntityFieldQuery to get the list of nodes to delete.  This will just give you back the nids.

Suck out the nids, and trim the array to some limit.

Call node_delete_multiple() on the result.

$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node', '=')
  ->entityCondition('bundle', $bundle)
  ->addCondition(...)
  ->execute();

$nids = array_slice($entities['node'], 0, 1000);

print 'Deleting ' . count($nids) . ' nodes ... ';

if (!empty($nids)) {
  node_delete_multiple($nids);
}

print "done\n";

Put this in a standalone PHP and execute is from drush, eg

drush -u 1 scr nuke_everything.php

Run it until everything is gone.

The above solution is for Drupal 7, but the approach is essentially the same for Drupal 6.  You would do a db_query() to get the nids, and then loop through and call node_delete() on each.  However, Drupal 6 also does a full node_load(), too.  In this instance, it does bypass its static cache, but this doesn't mean that modules aren't also doing any static caching.  For Drupal 6, you would need to chase all of the possible hook_nodeapi('delete') and look for static caching and static caching in any functions that get called, and do temp edits.


How to access an entity loaded out of the cache

Although the questions is not so clear I will try to give you some directions. I think it is time to dive into the new Cache API (I haven't done it so far!)

First of all, to get the "information" for a cached page you need to deal with the contexts and the cache tags.

To invalidate the tags you may need to use function invalidateTags(array $tags) (here is an example of using this class).

On the other hand if you want to invalidate cache of each node while loading the node you can set this option to the node_load($nid = NULL, $reset = FALSE) function by using $reset = TRUE.


Drupal8 site status - "unsupported release" / "not supported" is this deliberate?

That was probably a warning in Alpha. We're now at Beta 7, and it's now yellow instead of red:
There are currently 55 critical issues remaining:
https://www.drupal.org/project/issues/drupal?priorities=400&version=8.x
Which still gives a nice trend line toward 0, and release candidates:
https://plot.ly/~xjm/37/remaining-critical-issues-during-the-drupal-8-beta/


From the question details it is not clear if you're using the CKeditor module, or it you're using the WYSIWYG module in combination with the CKEditor library (so without the CKeditor module).

As a possible alternative to consider, I'd suggest you try this:

if you're using the CKeditor module, then replace the 4.4.6 ... version of CKeditor with some 3.6.x version of it (such as CKEditor version 3.6.6.1.7696), and see if your problem is resolved (the 4.x version is known to have "some" issues which don't exist in the 3.x version ...).
alternatively, use the WYSIWYG module (without the CKeditor module, but only using the CKEditor library with version 3.6.6, since WYSIWYG module does not support the 4.x version yet ...). In this case, you may also want to experiment with the various 'cleanup and output' options within /admin/config/content/wysiwyg/profile/your_txt_fmt/edit (with 'your_txt_fmt' the text format you're using, eg 'filtered_html').


Will I be able to run my site on PHP 7.0?

The canonical Drupal 8 issue is tagged "Needs backport to D7", which indicates the community intends to support Drupal 7 on PHP 7 but it may take a little time.


Create AJAX multi step form which changes based on user input

You need to keep track of the step you're in. The first time a user hit's the form you would initialize a variable, say $stepand give it the value 1. On submit you augment that value to be in step 2 on the form rebuild. In the form builder itself (_vista_form()) you add form items depending on the current step. The same goes for validation and submit handlers. Usually you would use switch statements.

Have a look at this very complete tutorial: http://www.jaypan.com/tutorial/drupal-7-ajax-driven-multi-step-forms-non-javascript-fallback


How can I include a .inc file before hook_node_access runs?

First, using the require include to load your file is perfectly sound, I think. Alternatively, you could add the include to the .info file of your module and allow it to be loaded on every page.

However, to answer your question: We could implement hook_hook_info() from a custom module and add node_access as a group for hook_node_access(). Now, in our module itself, we can have our access callback in a mymod.node_access.inc file.

This is probably not recommended as we are dabbling with core (in a small yet unreliable way) with no real value at all but is a way by which you could do it.

Once you have done this, I'd suggest running the entire Drupal core test suite once (at least node module's) to make sure that we are okay.


How do I get the list of all group members?

Use the Group module API.

$group->getMemberCount()


Location and Gmap relationship - what is alternative to show Location items on a google map?

According to the book Mapping with Drupal, the alternate to Location/Gmap is Geofield/Geocoder/Addressfield.  However, proximity searches don't currently work with this solution.

I have been experimenting with a lot of modules in this space and unfortunately Drupal 7 is behind the times in this regard.


How to filter GraphQL query by content language?

Your query is almost correct but you need to retrieve the entityTranslation in your entities, something like below for an article in English for example:

 entities {
    ...on NodeArticle {
      entityTranslation(language: EN) {
        entityLabel
      }
    }
  }

See also here for a similar question and answer.


Occasional Drupal Error in bootstrap.inc

The bootstrap.inc file is included, from index.php, using require_once './includes/bootstrap.inc' (Drupal 6) or require_once DRUPAL_ROOT . '/includes/bootstrap.inc' (Drupal 7). That one of the first instruction executed from Drupal when bootstrapping, as the bootstrap code is all contained in that file.

The errors you are seeing could be caused from a module that is using include or require to load the bootstrap.inc file, which would not be necessary, as the file is already loaded from Drupal.
Alternatively, the errors are caused from a module that defines those constants in one of its files, which is then causing those errors once it is loaded. For example, it could be a module that implements an alternative to the cache mechanism implemented from Drupal, which defines those constants with the wrong assumption that they would not be available.


How to decide to create a multilingual site or to create different site for each language?

In my personal view, I will consider if the new language site will be mostly identical to the existing one or not.

It means that if most of the pages / contents in the Turkish site will have its corresponding page / content in the English site, then I will build multilingual site, otherwise, I would like to set up a separate one.


You need to include the #allowed_tags property which is applied to #markup, #prefix, and #suffix. (See: Pass raw html to #markup)

button_submit:
  '#prefix': '
text<button>button text</button>'
  '#suffix': '
'
  '#value': Send
  '#type': submit
  '#allowed_tags':
    - div
    - button


While I don't have the detailed steps, I suggest you look to the Views module. The relationships and/or contextual filters provide WHERE and FROM type SQL queries.

If you have two views, one based on each vocabulary (taxonomy lists), and each has a contextual filter (with block settings to show only on specific page) then you will get a correlated listing on page/block sets.

If you have troubles getting it going, try exposed filters and AJAX refresh options - Get close enough to help your users help themselves. From a marketing angle, even if automatic/ideal results aren't automatic yet, IF views exposed filters get your customers/staff/partners to answers within 60 seconds from only a click or two, AND they also see message/indication you are actively working on the automatic results, the anticipated "better" site will up their anticipation and your reputation with most people (if, of course, presented with care).

Alternate possible "maybe" modules are "Views Field View" or "EVA". The "Better Exposed Filters" module might also be handy.

Try a search inurl:tutorial-6-10-views-relationships-and-contextual-filter for a great video.

Good luck.


How to set an alias to a fields on a db_select?

Use addField(). Here's an example:

$query = db_select('super_long_table', 'slt');
$query->addField('slt', 'mys_super_long_field', 'mslf');

Arguments passed to addField() are:

Table alias
Field - your long field name will be here
Alias - your short field alias will be here

Read more about it here.


If you enable Display Suite, you will get a format setting to choose a different view mode for each item.

You'd just need to set up each different view mode in display suite, then create your view and set each row to the needed style.


Make a node field read only after the node has been created

After educating myself on the Validation API, here's an example how to add the constraint to validate that the value of an entity reference field has not been changed.

Note: As pointed out by Ivan Jaros, this constraint is not validated if some module is programmatically saving entities without validating the entities first via Validation API.

Add a new constraint plugin.

/**
 * @file
 * Contains \Drupal\example\Plugin\Validation\Constraint\ValueNotChangedConstraint.
 */

namespace Drupal\example\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Constraint for checking that the value has not been changed.
 *
 * @Constraint(
 *   id = "ValueNotChanged",
 *   label = @Translation("Value has not changed", context = "Validation"),
 *   type = { "string", "entity:node" }
 * )
 */
class ValueNotChangedConstraint extends Constraint {

  /**
   * Message shown when the validation fails.
   *
   * @var string
   */
  public $message = 'Reference value can not be changed.';

}

Add validator for this constraint.

/**
 * @file
 * Contains \Drupal\example\Plugin\Validation\Constraint\ValueNotChangedConstraintValidator.
 */

namespace Drupal\example\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;

/**
 * Validates the ValueNotChangedConstraint.
 */
class ValueNotChangedConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {

  protected $entityTypeManager;

  /**
   * Constructor.
   *
   * @param EntityTypeManagerInterface $entity_type_manager
   *   EntityTypeManager service for loading entities.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager  = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    // Instantiates this class.
    return new static(
      // Load the service required to construct this class.
      $container->get('entity_type.manager')
    );
  }

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;

  /**
   * {@inheritdoc}
   */
  public function validate($data, Constraint $constraint) {
    $violation = $this->validateValueNotChanged($data, $constraint);
    if ($violation instanceof ConstraintViolationBuilderInterface) {
      $violation->addViolation();
    }
    return;
  }

  /**
   * Validates that the value is the same than previously.
   *
   * @param EntityReferenceFieldItemListInterface $data
   *   List of referenced entities.
   * @param Constraint $constraint
   *   Our constraint.
   *
   * @return \Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface
   */
  protected function validateValueNotChanged(EntityReferenceFieldItemListInterface $data, Constraint $constraint) {
    // Get the field name of the field we're validating.
    $field_name = $data->getFieldDefinition()->get('field_name');

    // Get the entity the field belongs to.
    $parent_id = $data->getEntity()->id();

    // Entities that are about to be created don't have an ID at this point.
    // We're only interested in existing entities.
    if ($parent_id) {

      // Load the parent node from the database. The new updates are not saved
      // yet so this will be the "old" version of the entity.
      $parent = $this->entityTypeManager->getStorage('node')->load($parent_id);

      // Get the old value we want to compare against.
      $old_value = $parent->get($field_name);

      // Compare the field item lists.
      if (!$old_value->equals($data)) {
        return $this->context->buildViolation($constraint->message);
      }
    }
  }

}

Add the constraint to the desired field with hook_entity_bundle_field_info_alter().

/**
 * Implemeantion of hook_entity_bundle_field_info_alter().
 *
 * Adds constraint to field_example_reference field.
 */
function example_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle){
  switch ($bundle) {
    case 'our_content_type':
      $fields['field_example_reference']->addConstraint('ValueNotChanged');
      break;
  }
}


In my superfish navigation block, under superfish settings, set the style of the superfish menu to none and under superfish plugins, disabled sf-Touchscreen.

In my main stylesheet I defined the menu style I wanted at the smaller size.


How to sync users profiles and user tables in 2 drupal sites

There are many ways you can sync Drupal accounts.

Using Drupal OpenID-Single-Sign on (OMniauth) which very common method for the big organisation who manage a number of drupal/websites. more on that please refer to Comparison of Single Sign On (SSO) Modules
You can also look into Account Sync module which I haven't tested myself yet and it has a very limited number of site "130" reported using it so you better be careful with it. The module provide basic single sign-on support.
The other way will be to export users from sites using User Export module. then use Feeds module to import site. You can use Rules module to to export and import users between both sites, probably by running crone on both sites in sequence.
Take look into Bakery Single Sign-On System, which is useful single sin-on for the sites that based on the same second-level domain "example.come, test.example.com".
Domain Access module which suite of modules that provide tools for running group of affiliated sites from on drupal installation and single shared database. The module allows you to share users.


Adminimal template and CCS adjustments and priority of css files?

Solved by

 drupal_add_css($adminimal_path . '/css/custom.css', array('group' => CSS_THEME, 'media' => 'all', 'weight' => 2));

in the template.php file


Where is list of theme features in Drupal 8 that can be exposed on the "Settings" page?

Here is the answer:

http://cgit.drupalcode.org/drupal/tree/core/config/schema/core.data_types.schema.yml#n172

There needs to be documentation for this. Maybe I'll write it.....


How to modify the image output for just one content type?

You can do this by defining a "lazy load" image style and using it as the image display.  This style does not have to do any resizing.  It would just be a placeholder flag for a preprocess function like:

function my_theme_preprocess_image(&$variables) {
  if ( $variables['style_name'] == 'lazy_load') {
    $variables['attributes']['data-src'] = $variables['attributes']['src'];
    unset($variables['attributes']['src']);
  }
}

Nice thing is that you can use this style anywhere to get lazy loading images.


Expose filter with collabsible div on click in a Calendar

I'm going to assume that each event is a node in Drupal, yes?

The filters you are describing are called 'facets', and there are a number of ways you can get them, but probably the most robust is to:

Install Apache Solr on your server if you haven't already
Install the Solr Search module in Drupal and configure it to search your events
Install the Facets API module and enable facets for your Country attribute

All of these things are well documented.

The one I had the most trouble with was the initial install of Apache Solr, but the instructions are specific to your O/S so unless you're using RedHat or a derivative, the blog post that helped me won't be very useful.


Performance Problem: Delay on first request

There are three things that I would check.

One, if you are on a production site and not editing PHP files, then you should ensure that APC is enabled, has enough memory, and has a long TTL (you could go with a day or never expire if you wanted).  You can also consider setting apc.stat=0.  The APC docs have all of the information you need for setting the TTL.  For choosing the amount of memory, you should stick the apc.php file somewhere protected and monitor the memory usage and churn statistics.  Adjust the APC memory so that your miss rate is very low.  Initial slowness could be because APC is full and emptying out (IIRC, APC dumps the entire cache when it is full instead of employing LRU or more advanced cache strategies).

Second, make sure you have MySQL tuned appropriately.  You can use mysqltuner to adjust your buffer sizes.  Your initial slowness could be because of loading tables from disk and/or query cache misses.  While not perfect, mysqltuner does get you going in the right direction.

Third, make sure you have a real Drupal cron strategy.  Personally, I would disable automagic cron on "admin/config/system/cron" and set up a crontab to run every night.  You can also try out Elysia Cron if you really do need finer grained control over things.  This way you can the necessary tasks run as often as you need, but have the normal ones run overnight.  Your initial slowness could be from cron runs happening every hour.  You can confirm this by looking at when cron runs on "admin/reports/dblog" and trying to match up with your slowness.


What is the difference between implementing hook_url_inbound_alter() and hook_url_outbound_alter(), and using a path alias?

Using hook_url_outbound_alter() has some potential performance issues because it is executed by every single URL on a page via the url() function. This means a module could implement hook_url_outbound_alter() with some complex and slow code that is called 100's of times per page.

Also hook_url_outbound_alter() allows a link's $options, including its query string, to be altered, which is impossible to do to path aliases and a very useful feature. For example, I have altered internal RSS URLs to point to their respective Feedburner and iTunes URLs.

Conceptually, the Path module should be calling the hook_url_*_alter() hooks but it is probably slightly faster to have the drupal_get_path_alias() calls directly in url().

My personal conclusion is when possible use the built-in path system, but for most special circumstances you will have to use the hook_url_*_alter() hooks.


How to order a view by access control on files?

In views under the Advanced section when you select the Theme: Information link, you can select to override a specific field.

Choose the most appropriate naming convention as this will dictate the scope of your override. Copy the text given by views and copy this into a new file in your theme called the .tpl.php file name you chose.

Once there you can add a conditional statement before outputting your field with user_access to check if your user has the right permissions to view the downloads.

You might have to specify the permission in your own module with hook_permission.


Best way to allow multiple users to edit a node but require approval?

You can look into the revisioining module

Revisioning is a module for the configuration of workflows to create, moderate and publish content revisions. You can set the role based permision for create , edit, view and delete revision of a content.


How to use multiple submit within a CTools Modal

Never figured out how to do this, but I worked around the problem by using CTools functionality. In a nutshell I used ctools_ajax_image_button in the table, specified a specific callback for the url and then alter the table with ajax_command_remove, ajax_command_restripe and finally returning it with ajax_render.

This is all based on the CTools AJAX example that deletes rows from a table.


If you use (Manage display) format: hidden (not label: hidden), the field will not show for this display for this content type. The field could still show in another display (like for teasers). So you will need to set the field format to hidden for all displays.

It is still possible to make a view with the Views module that displays the field. It depends on how you set up the view. If you set up a view of teasers, the standard teaser display is used (and the field is hidden according to the display settings). If you make a view of fields, you just have to avoid picking the "secret field".

If this is an existing Drupal site where this content type and field is a part of many different views and/or other modules, you will need to test this out. Also if the field is searchable or hardcoded in some template.


Accessing Drupal.settings outside of attach function

Worked it out myself.

(function($) {
  Drupal.behaviors.myModule_someJS = {

    anotherFunction: function() {
      console.log(this.vars.initial_page);
    },

    attach: function(context, settings) {

      this.vars = {
        initial_page  : Drupal.settings.myModule.initial_page
      }

      this.anotherFunction();

    }
  }
})(jQuery);

Drupal.settings won't contain the custom stuff sent through from my module until the attach function is called, so therefore every settings variable can only be called inside attach()

(and from Alice's comments above, it may be a matter of drupal_add_js being called from within the page rather than in the init() hook)


Update custom user fields programatically

It should be something like this:

$existingUser = user_load($uid);
$existingUser -> field_company_name['und'][0]['value'] = "Ciklum";
user_save($existingUser);


Is it acceptable solution to set session.gc_maxlifetime in hook_init()?

if you set it always and for all, you should do it in settings.php

ini_set('session.gc_maxlifetime',  36000);


How do I send a customized email to subscribed users?

You'll have to write some code, essentially you need to hook in when Job node is created, find the users referencing to that taxonomy the Job has and then use the Mail service, something like (pseudo)

When a Job node is created

Get all user that has a reference to the created Node's taxonomy:

$job_tax_tid = $node->get('job_taxonomy')->target_id

Then find the users, perhaps by using a Entity Query:

$ids = \Drupal::entityQuery('user')
  ->condition('status', 1)
  ->condition('field_job_refs', $job_tax_tid)
  ->execute();
$users = User::loadMultiple($ids);

To send mail programmatically, you need to use the MailManager: http://valuebound.com/resources/blog/how-to-send-mail-programmatically-drupal-8

Since there can be many users that needs to receive an email, you maybe want to use the Queue or Batch operations.

https://api.drupal.org/api/drupal/core%21includes%21form.inc/group/batch/8.2.x

https://api.drupal.org/api/drupal/core!core.api.php/group/queue/8.2.x


Add a field to the user profile and use this as a replacement for the logo. Use the page_preprocessor to add the user logo to the page template. Replace the logo by the one the user provided or show a default one.

Read more about this:

template_preprocess_page
Setting up variables to use in a template


Drupal logo is displayed with out the dimensions like width and height

The width and height is not required when using the img tag, but you can add it by overriding the theme template for the page, aka page.tpl.php in the directory containing the theme for your site. Usually sites/.../themes/YOURTHEME


How to add form fields dynamically using webform

You can use Webform Add More module to dynamically add more fields in webform.
The project page says:

  Webform Add More enables selected fieldsets to be initially hidden and
  progressively shown with an Add more button, mimicking CCK multiple
  fields. This module adds a checkbox
  setting to webform fieldset components to select which should have Add
  more functionality, as well as an advanced setting to override the
  button label per Webform


How to get user all order_items from different orders by entityQuery

Unfortunately, what you want to do isn't possible with an entity query, because that API does not support the appropriate joins. While you can simulate a join between a base entity and field value tables with field conditions, you cannot query against field values of referenced entities. If all you needed were order items referencing the order ID and specific purchasable entity ID, you'd be fine to write a single entity query against the order item table, but once you need to filter by order status (or support multiple purchasable entity types), you need to use \Drupal::database()->select().
To build a select query for this, I'd use the following:
$uid = 1;
$entity_id = 1;
$state = 'completed';

$query = \Drupal::database()->select('commerce_order', 'co');
$query->leftjoin('commerce_order_item', 'coi', 'co.order_id = coi.order_id');
$query->fields('co', ['order_id']);
$query->condition('co.state', $state);
$query->condition('co.uid', $uid);
$query->condition('coi.purchased_entity', $entity_id);
$result = $query->distinct()->countQuery()->execute()->fetchField();

The main change between your query and this code is that I'm fetching a count of the distinct number of orders. If you're trying to get the order IDs, remove the countQuery() and replace the fetchField() call with fetchAllKeyed(0, 0). If you really just want to search for a non zero count, you can remove the distinct() for faster query performance.


search only on taxonomy and user autocomplete drupal 7

Filters Search Autocomplete works great for that but there a bug with entity Reference

We can achieve this by following these steps:
Add the required node reference field as relationship.
Add a title field in fields and give them the above relationship.
Add the title in combine filters.
It Worked for me :)

read more on drupal.org


you are using drupal 6, or drupal 7?

If I understand well your questions:

you can change the query used to generate view results (Order BY, Where, etc) using query_alter hook. here one example: Making a field sortable in Views

About weight of arguments, I think that you can control order of precedence in 'rearrange' option:

If your question is related with weight of taxonomy terms, in your View settings > Add sort criteria > Taxonomy: Weight seems will be useful to sort according weight of each term:

regarding shows argument clicked, you can get argument from the current url easily using arg() http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7:

example URL: http://example.com/node/12345/edit

in this example

arg(0) is node

arg(1) is 12345

arg(2) is edit

here some experiences in Drupal forum to review, with or without using arg():

http://drupal.org/node/180589

http://drupal.org/node/283945

you can add a php code to get respective argument, for example using arg() in a view header or in a drupal php node/page/block:

<?php echo arg(0); ?> or <?php echo arg(1); ?> according your target argument.

I hope information be useful.


How do I use Taxonomy reference field tokens in a path alias?

Solved by two changes:

Apply the patch from this Token issue, "Inconsistent loading of third party hook implementations"
Make sure Token display mode exists for each taxonomy vocabulary

I tested and confirmed that both the patch and the display mode config changes were needed.


What happened to the "menupath" token in the URL aliases for Drupal 7?


Difference between browser session and Drupal session

What you are describing is not Drupal session vs. Browser session. There's just one session, always managed by Drupal (partially by using Symfony code. But it's still Drupal).

The (private) tempstore is just a custom storage that used to be provided by ctools in 7.x. For anonymous users, it actually requires a session to be present, as it uses the session ID to identify the entries.

The main difference is that session data is always loaded, on every request. While for the tempstore, you control when and what is loaded. If you have data that is small and you need on many/all pages, use the session directly. If you have big objects, consider using a temp store.

Drupal itself uses the tempstore for example to store node objects for the preview feature and views while editing them.


Looking for a way to trigger an event for testing custom event subscriber

You can use the event_dispatcher service to trigger an event.

Use this code to trigger your event.

\Drupal::service('event_dispatcher')->dispatch(MyModuleEvents::MY_EVENT, new MyModuleEventClass());

Of course you have to replace the names with your real names.

You can run the code using drush php.

You can read more about subscribing and dispatching events here.


How to filter Views records by day-of-week, including multiples

I have managed to create a usable filter, though there is still a portability issue. This is the filter class I ended up with:

/**
 * Filter to handle dates stored as a timestamp.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("views_dates_day_of_week")
 */
class DayOfWeek extends InOperator {

  /**
   * {@inheritdoc}
   */
  protected function opSimple() {
    if (empty($this->value)) {
      return;
    }
    $this->ensureMyTable();

    /** @var \Drupal\views\Plugin\views\query\Sql $query */
    $query = $this->query;

    $placeholder = $this->placeholder().'[]';
    $fieldexpr = $this->getDateField();
    // For PostgreSQL use EXTRACT (DOW FROM field), result is numeric.
    // For SQLite use strftime("%w", field), result is numeric.
    // BUT : How to tell if these are needed!!
    $lhs = "DATE_FORMAT({$fieldexpr}, '%w')";
    $snippet = $lhs . ' IN (' . $placeholder . ')';
    // Keys are 0..6, to match %w format.
    $possibles = array_keys($this->value);

    $query->addWhereExpression(
      $this->options['group'],
      $snippet,
      [$placeholder => $possibles]
    );
  }

  /**
   * Return an array of day names, keyed by the value of the %w date format.
   *
   * If the 'options callback' is defined, use it to return values, otherwise
   * use the predefined (translatable) versions.
   *
   * Cache the return value in $this->valueOptions for speed.
   *
   * @return array|null
   *   The array of names, keyed by integer 0..6 representing Sunday - Saturday.
   */
  public function getValueOptions() {
    if (isset($this->valueOptions)) {
      return $this->valueOptions;
    }

    if (isset($this->definition['options callback']) && is_callable($this->definition['options callback'])) {
      if (isset($this->definition['options arguments']) && is_array($this->definition['options arguments'])) {
        $this->valueOptions = call_user_func_array($this->definition['options callback'], $this->definition['options arguments']);
      }
      else {
        $this->valueOptions = call_user_func($this->definition['options callback']);
      }
    }
    else {
      // Keys are 0..6 and starting Sunday, to match %w format.
      $this->valueOptions = [
        '0' => $this->t('Sunday'),
        '1' => $this->t('Monday'),
        '2' => $this->t('Tuesday'),
        '3' => $this->t('Wednesday'),
        '4' => $this->t('Thursday'),
        '5' => $this->t('Friday'),
        '6' => $this->t('Saturday'),
      ];
    }

    return $this->valueOptions;
  }
}

Note that the implementation of opSimple has hard-coded use of MySQL. I was unable to find out which DB type this operation is using and therefore adapt to the SQL used by that DB. The builtin 'dateSQL' member of $this is protected and marked views-internal, preventing it being used to identify the db type. I also used the array placeholder feature of Drupal (the ".'[]'" on the placeholder variable) to avoid having to separately quote all the IN values. I also cannot see a way to avoid this operation requiring a sequential search of the db table :(

I switched to using numbers (2) rather than abbrev-names (Tue) because that was more portable between db types and possibly faster. The rest of the code I have inherited/adapted from the drupal.org/project/views_dates:

Add to views_dates.filter.schema.yml:

views.filter.views_dates_day_of_week:
  type: views.filter.in_operator
  label: 'DoW'
  mapping:
    type:
      type: string
      label: 'Type'

Add an entry in views_dates_views_data_alter(), which is :

$data[$table_name][$base_field_id . '_dow'] = [
  'title' => t( '@label as day name', ['@label' => $base_field_label]),
  'help' => t( '@label as day name 0 - 6, representing Sunday (0) to Saturday (6).', ['@label' => $base_field_label]),
  'argument' => [
    'field' => $base_field_id,
    'id' => 'date_dow',
  ],
  'filter' => [
    'field' => $base_field_id,
    'id' => 'views_dates_day_of_week',
  ],
];

Note that, in views_dates.module, entity type 'node' is skipped from adding these new filters - you may wish to change this!


Okay, here is a proper answer to a tricky question.
Documentation
First of all, you should read the following two documents, if you haven't already:

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x
https://www.drupal.org/node/224170

Simple Wildcards
By using % as a path wildcard you are instructing the menu_router matching algorithm to use the path argument as it is (used mostly for numerical arguments). So, following from your comment, yes, it does have a significance. If you write your code like this:
$items['admin/config/mapper/%/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

you are going to get the 3rd part of your path as an argument to your mapper_form_mappings function. Exactly as it occurs in the path.
Auto-Loader Wildcards
Now, if you would use a %NAME type of wildcard, like taxonomy does, you would be triggering the 'Autoloader Wildcards' (a.k.a. 'Wildcard Loader Arguments') functionality. Drupal will try to load an object through a function called NAME_load. In the case of the %taxonomy_vocabulary_machine_name Drupal will try to load a vocabulary using the specified machine name as an argument to the taxonomy_vocabulary_machine_name_load function. The loaded object will then be passed as an argument to drupal_get_form (or any other function defined in your path definition).
Current problem
In your case, your original code:
$items['admin/config/mapper/%tid/edit'] = array(
  'title'            => 'Mapper edit mapping',
  'description'      => 'Add or edit a mapping',
  'page callback'    => 'drupal_get_form',
  'page arguments'   => array('mapper_form_mappings', 3),
  'access arguments' => array('administer site configuration'),
  'type'             => MENU_LOCAL_TASK,
  'file'             => 'mapper.admin.inc',
);

implies there is a tid_load function that will receive the %tid argument from the URL and should return some object to drupal_get_form. This is however not working, since such a function does not exist.
Alternatives using wildcard loaders
If you want to use the 'Auto-Loader Wildcards' functionality, you should do one of the following:

Use an existing _load function, e.g. taxonomy_term_load. Your wildcard should be called %taxonomy_term in this case and the final argument passed to drupal_get_form would be an taxonomy term object.
Use a custom _load function, e.g. mapper_load. Your wildcard should be called %mapper in this case and the final argument passed to drupal_get_form would be whatever your mapper_load function returns.

Best of luck!


Welcome to Drupal, you had just one step more to do that, go to your module list in admin/modules and in Panels package enable Views content panes module then all views exists for using in panels. also it provide a news dispaly in views.

Also you can see this video for more getting involve with views pane


I think this article will be usefull for You because taxonomy is one of entity types:
Working programmatically with fields in Drupal 7

So You should set "entity_types" as taxonomy.


I believe you can use:

$japanese_node = $node->getTranslation('ja');
$japanese_link = $japanese_node->toUrl()->toString();

Adjust accordingly.


You can still embed views in templates, just prepare them in yourtheme_preprocess_TEMPLATE(&$variables), put them in $variables['some_key'] and then display in your template as {{ some_key }}.

I'm starting to look at Page Manager and Panels for a solution. Bringing these modules into the design for a seemingly simple problem does not seem like the correct answer.

I don't see why it wouldn't be. It's possible to do a lot more with just Drupal 8 core than before, but not everything. Using contrib modules is perfectly fine, as long as you try to not add every single module out there to your site.

The only problem is that it is a bit early for many contrib modules unless you know what you're doing and can dig into the code in case you run into issues.


When I want to display a View on certain content types, I make use of the functionality offered by the EVA: Entity Views Attachment module. On the entity's Field Display administration page, you can (like any other field) set the order for outputting the Views' result.

An interesting feature of the EVA: Entity Views Attachment module is that it allows to pass any token generated from the specific entity to the View as an argument.


Adding an image to a media bundle's field

Unless you have a default language setup, Language::LANGCODE_DEFAULT will resolve to x-default.

Either:

Set a default language
Set the property manually, e.g, 'en' rather than Language::LANGCODE_DEFAULT
Remove the line entirely


Show message at every page regardless page content

Why not to write it directly in the template? Or create a Block which you show in the header? or do you need to use the drupal_set_message() Message?

You can use "Drupal is initializing" event at Rules.


Unable to render block in twig after updating Twig Tweak module

It was a docker sync problem. Now with {{ drupal_entity('block','myblockname', check_access=false) }} the blocks are visible.


webform save draft after each field update - ajax error for anonymous user

The save draft functionality has not yet been committed for webform for anonymous users.

According to the post you mentioned, @Stefan in his answer claims he added the functioanlity by incorporating my patch from this issue. (We are testing an updated patch which will be posted to the issue cue within the next couple of days.)


How to alter field values on a display page?

If I need to manipulate the text and/or display based on some PHP logic, I would do it using hook_node_view() in a custom module, not in a template file.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if( $view_mode == 'full' ){
        if( some conditions here ){
            $node->content['field_title_nickname'] = array(
                '#markup' => '
A new nickname title 2x
'
            );
        }
    }
}


In Views, how to allow users to toggle between a grid and list?

If you want to do something like this,

then you can use QuickTabs Module

So, here user can switch from TAB-ONE to TAB-TWO .. so on ..

To implement this, first you have to create View-Blocks and then you have to create Quick Tabs by using QuickTabs Module

Here is one Video Tutorial to create QuickTabs.


Add user's role as a class to all user links

I don't think you can do it with username_alter. You can only modify the user name string in there. Its probably better to use preprocess. In your theme template.php. Do something like this:

function YOUR_THEME_NAME_preprocess_username(&$variables) {
  // Username is linked, use the link_attributes to inject the class or any other attribute
  if (isset($variables['link_path'])) {
    $variables['link_attributes']['class'][] = 'SOME_CLASS';
  }
  // Username is NOT linked, maybe do something else or nothing
  else {
    $variables['attributes_array']['class'][] = 'SOME_CLASS';
  }
}


I recreated the date field settings on a clean install of drupal. I installed/enabled views, ctools, and the date api. I enabled the date popup widget and created a dummy content type. The popup and textfield widgets for the date field do NOT auto update but the select list does. I guess this is how it is designed. Back to the drawing board on this one. the popup module could possibly be modified to allow auto updating.


Screenfly alternative for testing Drupal 8 sites

With Google Chrome CTRL + SHIFT + I also known as right click >> Inspect

Once the Developer Tools is open, then CTRL + SHIFT + M or click the 2nd icon

With Responsive, you can resize to whatever you want by dragging the right border


How can I have a field value that is the sum of other (decimal) field values?

This question is tagged with Views, so I'm just going to go out on a limb and leave this here just in case: Views Calc

  This module adds simple calculations to a views table. Requires the
  Views module.

  You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
  in theme makes the view look more spreadsheet-like (right justifies
  numeric fields, shades calculated columns and rows, and underlines
  calculated rows).


You can do this in Views as you said with Contextual Filters.

In your view click "add" next to Contextual Filters and in the modal check "Content: Has taxonomy term ID (with depth)". Then click "Add and Configure" and you will see the "Depth" option.  In the case of your color example above your depth would be 2 and when passing "Colors" to the view it would return all the nodes you bolded.

If you want the whole depth if it has great grandchildren and so on you would need to set the depth higher to account for the number of levels of your taxonomy hierarchy.  For your example and passing "Colors" as the argument, a depth of 0 would return no nodes, 1 would return "Cerulean, Slate and Mustard", and 2 would return all of the nodes as mentioned above.

Passing the other Colors as arguments would behave in the way you desire.


How to subscribe to notifications or alerts via RSS feeds?

You can create custom feeds using the views. This can contain any fields as you want. And use all the filters, relationships and contextual filters to get the exact feed that you are looking for. The you can place feed link where ever you want it to be seen. This would be done using blocks or may be simply by adding it to the page.


Allow user to select which registration type on Entity Registration module

I haven't use the Entity Regisration module for registration but for my suggestion. You should use the Profile2 module for that purpose. It allows you to:
- Create many type of user profiles
- The link for registration of each kind of users (Must use the Profile2 Registration Path module)
- The custom fields for each kind of users


I can't translate the text  in a form select list

There seems to be a problem translating strings with "<" and ">" in them, which is odd, but anyway:

http://drupal.org/node/348130
http://drupal.org/node/663156

If it's a Views related problem, at admin/build/views/tools you can change Label for "Any" value on optional single-select exposed filters: to - Any - (instead of <Any>) and translate that.


How can I hook into entityforms being submitted?

Entityforms are - as the name suggests - stored as entities. So you can hook into hook_entity_insert(), or hook_ENTITY_TYPE_insert(), having the inserted data as parameter (the entity will be an object):

/**
 * Implements hook_entity_insert().
 */
function MYMODULE_entity_insert($entity, $type) {
  if ($type == 'entityform') {
    // Do your stuff here.
  }
}

or

/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function MYMODULE_entityform_insert($entityform) {
  // Do your stuff here.
}

You could also utilize rules to define custom actions on submission, as the entityform submission triggers the entityform_submission rule.


You should wrap you javascript to user $ for jQuery, since it does not automatically refer to jQuery in Drupal 7. Try like that:

(function ($) {
  // Your code here
  $(document).ready(function() {
    // ...
  });
})(jQuery);

Reference: Managing JavaScript in Drupal 7


Submenu item linked to anchor in parent's content

Try:

Special menu items

Menu Firstchild


Generate unique barcode for each registered user

Enable the barcode module.
Goto: admin/config/people/accounts/fields
Add a barcode field and configure as you like
Towards the bottom of: admin/config/people/accounts, Modify the email to include the barcode

Another option: Commerce Event Tickets, This sounds a lot like what you need.


If you don't mind to use Views module, you can configure any list of revisions. You also can add filter/sort logic, pager, configure access and much more useful things.

You always can export your solution with Views export or with Features module and reuse it on other Drupal sites.

More information about Views: http://nodeone.se/en/node/20


Not a module, but you can add a custom validator that parses the string that the user put in for URL to see whether it contains the expected strings, e.g.

if (strpos($url, 'facebook.com') === 0) { ... }

Note the triple-equals is necessary with strpos because otherwise "found at position zero" (return value of 0) is falsey, and so is "not found" (no return value).


Limit entity reference options base on taxonomy tag

I did something like this recently myself.

Your Person content type should have two entity reference fields, one to a Building, and a second to a Department. A Department also has an entity reference to Building.

Use a hook_form_alter to target the Person form.
In that function get a list of the Departments and their Building references, and attach it to the form along with a reference to a custom Javascript library. (Note that you'll have to use the proper machine name for your content types and fields.)

$departments = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'department']);

$department_data = array_map(function($department){
    return $department->field_ref_building->target_id;
}, $departments);

$form['#attached']['drupalSettings']['dept_bldg_info'] = $department_data;

$form['#attached']['library'][] = 'my_module/my_module.library_name';

The library file will look something like this:

Drupal.behaviors.chartInfoHierarchicalSelect = {
  attach: function (context, settings) {
    // Apply to the HTML page context & the person forms.
    if (context.location || context.id == 'node-person-edit-form'|| context.id == 'node-person-form') {
      let building_inputs = jQuery('[name$="[field_ref_building]"]'),
        department_inputs = jQuery('[name="[field_ref_department]"]');

      building_inputs.each(function () {
        // Ensure initial load has proper limits.
        updateDepartments(jQuery(this));
        // Update on change.
        jQuery(this).change(function () {
            updateDepartments(jQuery(this))
        });
      });

      function updateDepartments(building_input) {
        var selected_building = building_input.val();

        department_inputs.each(function () {
          var opt_val = jQuery(this).val();
          if (opt_val != '_none' && drupalSettings.dept_bldg_info[opt_val] == selected_building) {
            jQuery(this).prop('disabled', false);
          }
          else {
            jQuery(this).prop('disabled', true);
            jQuery(this).prop('selected', false);
          }
        });
      }
    }
  }
};

Then when you select a building, you should see the appropriate departments get enabled/disabled.


How to call external api to pull data into json format?

It depends on what you wish to do with said data.

If you are looking for a purely code approach, you could do something like:

$response = drupal_http_request($url);
$result = json_decode($response->data);

If you want a Rules based approach, you could could use the Rules HTTP Client module, which allows you to do essentially the same as the above code but via the Rules UI.


Can the 'update' module be made less aggressive?

As far as I can tell there's nothing about visiting the modules admin page (or any other admin page) that would invoke a check for update data.

Drupal 6

For Drupal 6 the work is done by _update_refresh(), which is inadvertently called from several places within the update module itself. Those of note include:

update_cron() - called only during a cron run.
update_status() - page callback, only invoked when visiting the update report page.
update_requirements() - invoked when you visit the status page.

Since none of those are called for every admin page, and Drupal 6 doesn't have auto-cron (you also mentioned in the comments you don't have poormanscron installed), it doesn't seem like any of the core functions will be the culprit.

There's no way to unset hook implementations for specific modules in Drupal 6 (there is in Drupal 7, see below) so short of editing the module file directly I don't think there's anything you can do about that.

Drupal 7

The work is done by update_get_available(), and that function is only called from 4 places by core:

update_cron() - called only during a cron run.
update_manager_update_form() - page callback, only invoked when visiting the update manager page.
update_requirements() - invoked when you visit the status page.
update_status() - page callback, only invoked when visiting the update report page.

If the update is happening on any other pages than those listed above it's either caused by a contrib/custom module, or (more likely) because you have auto-cron on, and the cron run is being invoked. There might be more to it than that but I can't find anything looking through the core code.

As far as the status page goes, you could remove the update module's implementation of hook_requirements() from the cached list of hook implementations, effectively stopping the check from happening when you go to that page. It means you won't ever get that particular line in the status report, but if you're ok checking for updates manually then this won't be a problem.

The way to do this is to implement hook_module_implements_alter() in a custom module:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'requirements') {
    unset($implementations['update']);
  }
}

Either version

You can slow the frequency of update-checks down a bit by setting the update_check_frequency variable to something longer than standard. The variable contains the number of days that need to pass before the update data is checked again.


Have a look at the quicktabs module. You could use it to embed views in each tab, based on your required filter options there. For example, you can pass a contextual filter option to the quicktab for a single view display to show that content only.

Alternatively, the better_exposed_filters module may provide some options for you, such as a list of links, instead of a select box.


Feed Import Products ( Commerce ) and Products Category ( Node Page )

The following CSV template and Feed Import settings will import 1 Product Node with multiple Product Entities being referenced.

Step 1 - Creating The CSV

The following example provides the title and product_variation headers...

title: Mapped to the Node Title field in Feed Import

product_variation: Mapped to the Commerce Product Referenced field. Field limit should be greater then 1, so multiple entities can be imported.

title,product_variation

Product Example,"product_sku-1|product_sku-2"

Step 2 -Import Node

The "|" is used to create a unique entry using the Feeds Import Explode plugin.

The Feed Tamper product_variation field should have a single Plugin called Explode with the String separator set to "|".

Essentially, the Feeds Tamper Module will prepare the column values into an array, so Drupal can handle the request all awesome like :)


You have two approaches.

You could create a non cacheable block, that will check a session_variable, if a timer is set and the time is passed. If is has, it will render something, else it will be invisible. The will create the pop up on page refresh.

Alternative you can use a javascript and use setInterval to check if the time has passed and then display a popup. You would then have to add the javascript info on page load.


How do I remove white space from Bartik?

First, you should not attempt to manually override and of Drupal's core files (or any other module or theme for that matter) because your changes will be overwritten during updates. So do not search for the CSS and attempt to alter it.

Make a copy of the bartik theme instead, move it to sites/all/themes and rename the folder and the .info file. Finally alter the info file to give your theme a new name.

All Bartik lay-out code can be found in layout.css. So you will have to modify widths and margins there.

Finally, I wanted to make you aware of the Responsive Bartik theme which is already slightly wider for widescreen monitors, but also optimized for mobile phone usage. You might find it usefull to use that instead, or use it as a base theme for your modifications.

Update for Drupal 8

You have the core/themes/bartik/css/layout.css file where you have to alter the max-width for wide screens:

/**
 * Container
 */
.layout-container {
  max-width: 860px; /* <- This is the default width. */
  margin-left: auto;
  margin-right: auto;
  box-sizing: border-box;
}
@media all and (min-width: 851px) { /* <- Bigger than this means it is a wide screen */
  .layout-container {
    max-width: 1290px; /* <- This is the max-width for wide screens. */
  }
}

Most of the CSS properties are defined in percents and so they should scale along.


Use Ajax on Exposed Filter of a View but NOT on the pager of that View

I'm sure you've found a solution / workaround for this by now, but this thread came up while I was faced with the same issue, so I figured I'd share the solution that worked for me.

All I did was simply remove Drupal's AJAX event handler from the pager links using jQuery's unbind method, e.g.:

$('.pager a').unbind();

With the event handlers removed, the pagination links fall back on the HREF URLs contained within the anchor tags.


Site migrated to the new server with PHP 7.2 and I can't log in

We found the problem. The site was using HTTPS on the production server and HTTP on the test server, and we had set php_flag session.cookie_secure On in our Apache config. HTTPS wasn't in use, so no cookies were sent, so no logins would work properly. Setting this to Off worked wonders. Thanks for pointing me in the right direction, folks!


When multiple aliases are available, Drupal uses the most recently created (as determined by the pid column in the url_alias table).

I don't know an easy way to change this behavior.  You could try manually altering the pid value in the database.  Also consider if using a redirect is a better solution than aliasing.


hook_page_alter and trying to change the '#theme_wrappers' property

As I commented above, the issue was that I was missing the & before $vars in this line:

$element = $vars['page']['sidebar_first'];

It was not creating a reference so it wasn't actually setting my '#theme_wrappers' property.