ThemeKey rule; how to target IMCE pages On my Drupal 7 site, I noticed that the IMCE popup loses its action buttons and all functionality when I'm using Adminimal as the admin theme:

In the Known Issues section of the IMCE project page, it mentions using the ThemeKey module if there is a conflict with your custom theme. Here are the ThemeKey rules it says to write:

drupal:path = %token
drupal:path:wildcard token * imce

When I do this, the IMCE buttons are, in fact, back in place (yay!)... BUT the entire site, both public pages and administration pages, are also displayed in Garland (boo!).

How can I force just the IMCE popup window to render in Garland?

As is my nature, I was totally overthinking this. Here's what I had to do in ThemeKey:

First, for the File field:

drupal:path = imce-filefield/%

Basically, this is matching the first section of the URL path with imce-filefield and then whatever else comes after it is matched with /%.

This solves the problem for file/image uploads. The IMCE file browser used in the WYSIWYG editor (in my case, CKEditor) has a different URL path, so its interface is still broken. That one is simply:

drupal:path = imce

So far so good...


User having issue with site being redirected to home page from every link We have a drupal 7 site hosted on a linux machine. One of our users claims they get redirected to the home page from every link they click on the site. I'm not personally having this experience with the site nor is anyone else I work with. The user hasn't given us any more information, but I'm wondering if you guys have any idea what might be going on here?

I found this thread but it seems to be mostly a Windows-based issue: Why does my drupal 7 redirect me to the home page from any link?. Plus I have clean URLs on and like I said it works fine for everyone else.

Thoughts?

It is possibly an issue with a cookie. Have that user try to use another browser to check if the same problem occurs with that browser.

Or just delete the session cookie in the browser being used, then check if the issue is resolved.


Open Layers Views - Separate Data on Page and Block I have a typical OpenLayers Locator proximity search on Drupal 7. I can search a map for my locations and that works great.

I also have a Product content type that is referenced to my locations. What I'd like to do is to display a table of products on my page AND a map of their corresponding locations.

How can I display two separate data sources on a single page?

I just added a relationship to the Products entity in the view and then added the Product fields in the View. I then excluded most of the location data. This gave me a Products page with a map of locations!


Attach library to custom form I'm building a custom module (say 'mycalc') with a custom block with a custom form inside.
Now I want to attach a library to the form and add some styling and live manipulation.

I created the mycalc.libraries.yml like this:

myform:
  version: 1.x
  css:
    theme:
      css/mycalc.css: {}
  js:
    js/mycalc.js: {}
  dependencies:
    - core/jquery

I added the js/mycalc.js and css/mycalc.css files with few basic lines.
Then in the src/Form/MyCalcForm.php (where is set the MyCalcForm class), i edited the buildForm method adding this just before the return():

$form['#attached']['library'][] = 'mycalc/myform';

But there's no js nor css loading.
What's wrong? Please help!

You need to attach library in your hook_form_alter():

/**
* Implements hook_form_alter().
*/

function <YOUR_MODULE_NAME>_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

    /*Attach library, for Blazy implementation you will need
       $form['#attached']['library'][] = 'blazy/load';
    */
    $form['#attached']['library'][] = '<YOUR_THEME_NAME>/<library_name>';
    $form['#attached']['library'][] = '<YOUR_MODULE_NAME>/<library_name>';
    /*Pass even variable from this function to JS settings*/
    $form['#attached']['drupalSettings']['<YOUR_MODULE_NAME>']['<route_name>'] ['variable'] = 'PHP Value To JS';

    return $form;
}

If you pass variable with above mentioned method - $form['#attached']['drupalSettings']['<YOUR.... then that variable will be available in your JS file.

(function ($, Drupal, window) {
  Drupal.behaviors.helpers = {
    attach: function (context, settings) {
      'use strict';

       console.log(settings);
       console.log(settings.variable); //Should log variable value
    }
  };
})(jQuery, Drupal, window);

Add javascript to form by module


Watermarking an image that is not in the Drupal filesystem using image_style I get an image through the ImageMagick PHP extension because I don't want to start the PHP exec() function. This works.

But I'm not managing to create a watermarked image using image_style because this image is not in the Drupal file system.

How can I do this?

As you've probably already seen about theme_image_style():

  This function does not work with images outside the files directory nor with remotely hosted images. This should be in a format such as 'images/image.jpg', or using a stream wrapper such as 'public://images/image.jpg'.

There's a beta release of a module called Imagecache External which claims to solve the problem:

  Imagecache External is a utility module to allow you to use imagecache(D6)/image derivatives (D7) with external images.

With that module installed your use of theme_image_style() would be replaced with something like:

print theme('imagecache_external', array('path' => $path, 'style_name'=> 'thumbnail'));


How do I correctly setup caching for my custom API routing? I have custom module with some routes which return JSON, for instance terms of a vocabulary.

routing.yml

mymodule.terms:
  path: '/api/terms/{vid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyModuleController::getTerms'
    _title: 'Terms'
  requirements:
    _permission: 'access content'
    vid: '^(foobar|barfoo)$'

Controller:

public function getTerms($vid) {
  $response = $this->jsonifyVocabulary($vid);
  return $response;
}

private function jsonifyVocabulary($vid) {
  $request = \Drupal::request();
  $lang = $request->query->get('lang', 'en');
  $output = [];
  $taxonomyManager = \Drupal::entityManager()->getStorage('taxonomy_term');
  $terms = $taxonomyManager->loadTree($vid, 0, 1, false);
  $response = CacheableJsonResponse::create($output);

  debug(1);

  foreach ($terms as $term) {
    $term = Term::load($term->tid);
    if ($term->hasTranslation($lang) && $lang !== $term->language()) {
      $term = $term->getTranslation($lang);
    }
    $entry = [
      'tid' => (int) $term->id(),
      'label' => $term->getName(),
    ];

    // $response->addCacheableDependency($term);
    $output[$vid][] = $entry;
  }

  $response->setData($output);

  $cacheMeta = (new CacheableMetadata())->addCacheContexts(['url.query_args:lang']);
  $response->addCacheableDependency($cacheMeta);

  return $response;
}

Thanks to this answer I know how to actually add the URL params as a cache context, but the

debug(1);

always gets called, I guess I just somehow have to tell Drupal that this JSON response's cache should relate to that route...

I don't use the core's REST module on purpose since I find it hard to configure to output exactly what I need.

This is all you need to set up caching for a response:

  $response = CacheableJsonResponse::create($output);
  return $response;

If you use a response that implements the CacheableResponseInterface it will be cached indefinitely.

Cache tags

When you add a list of taxonomy terms you have to add these tags:

  $list_tags = $this->entityTypeManager()->getDefinition('taxonomy_term')->getListCacheTags();
  $cache_metadata->addCacheTags($list_tags);

  foreach ($terms as $term) {
    $cache_metadata->addCacheableDependency($term);
  }

This will invalidated the cache entry when the terms are modified in the database.

Cache contexts

When you use a query parameter add this context:

  $lang = $request->query->get('lang', 'en');
  $cache_metadata->addCacheContexts(['url.query_args:lang']);

This will vary the cache by the query arguments.

Cacheable metadata in a response

To put all this together create at the beginning of the controller an empty CacheableMetadata object:

  $cache_metadata = new CacheableMetadata();

While building the content collect the cache metadata for all dependencies you use as described in the two examples before and then add the metadata to the response at the end of the controller:

$response->addCacheableDependency($cache_metadata);


How can my eCommerce site only showcase products without an Add to cart option? I want my Drupal eCommerce site to only show products which contain only product name, description, PDF file.

I don't want price & Add to cart options. Is there any possibility in Drupal?

Yes, there is a possibility. You can achieve that by using the Views module.

Create a content type for Products (say products) or you can also use default content types Basic Page or Article .

Add fields whatever you want to show for products (say description, file for PDF).

Create a View for to display the Product content type nodes (products)

  You need Views if

  You like the default front page view, but you find you want to sort    it differently.
  You like the default taxonomy/term view, but you find you want to    sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain    type.
  You like the idea of the 'article' module, but it doesn't display    articles the way you like.
  You want a way to display a block with the 5 most recent posts of    some particular type.
  You want to provide 'unread forum posts'.
  You want a monthly archive similar to the typical Movable    Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts
  for that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.


Overriding field.html.twig in my module I'm writing a field formatter and I need to override the default field formatting. I've already implemented themes for the items itself, but I can't get my theme to work for the field container.

I've set #theme in the following code, and my field-image.html.twig is found by Drupal and processed:

class ImageGalleryFormatter extends ImageFormatter {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items) {
    $elements = parent::viewElements($items);
    foreach ($elements as &$element) {
      $element['#theme'] = 'imagegallery_format';
    }
    $elements['#theme'] = 'field_image';
    $elements['#attached']['library'][] = 'imagegallery_formatter/light-gallery';
    return $elements;
  }

}

But it doesn't actually work correctly, I don't get any content for {{ item.content }}. This is the core of my field-image.html.twig:

{% for item in items %}
   <div>{{ item.content }}</div>
{% endfor %}

I suspect that I didn't implement hook_theme() correctly, I tried a few variants, but none worked.

function imagegallery_formatter_theme() {
  return array(
    'imagegallery_format' => array(
      'variables' => array('item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL),
    ),
    'igimage' => array(
    'variables' => array(
        'style_name' => NULL,
        'uri' => NULL,
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
      ),),
      'field_image' => array(
        'render element' => 'element',),
  );
}

The first two themes work, for those I simply copied the variables array from existing code. The third one doesn't work, and I couldn't find any existing code I could use as a template. I tried to define the variables instead of using 'render element', but I don't know how to define the items variable there. I tried setting it to NULL or an empty array, but nothing did work. When I put a variables array in hook_theme, I get simply four empty divs, with the render element array I get a single empty div.

What am I doing wrong here, and how do I override this theme correctly in my module?

I managed to track down the place in core where the code for this specific theme is located, it was in core/includes/theme.inc and not in the field or system module where I previously searched. Copying from there did work in the end, using render element in hook_theme() is correct, but I was missing an important preprocess function.

I defined the following function and called the original preprocess function from there:

function template_preprocess_field_image(&$vars, $hook) {
    template_preprocess_field($vars, $hook);
}


How do I ensure new dependencies added to the info.yml of an existing enabled module are picked up? I've added
dependencies:
 - core/jquery
 - core/drupal

to mymodule.info.yml
(where mymodule is my module name).
How do I ensure Drupal "sees" these new dependencies?
For example, can I clear the cache, drush cr ?
Or is there another drush command to run or something else to do?
When does Drupal read the info.yml file? When module enabled - yes - but what other times?
I would prefer a command to get it to read that file rather than uninstall my module and reenable my module as this could be inconvenient with regard to config/content needing to be re-setup.
Thank you.
Background
I'm working on solving a problem where anonymous users see Uncaught ReferenceError: Drupal is not defined in console, based on a solution  that adds the dependencies I mentioned above: Anonymous Users See Uncaught ReferenceError: Drupal is not defined In console.
Potentially related: jQuery not Loading for “Anonymous” Users

I think you are mixing dependencies to modules with dependency to libraries. Your code adds a PHP module dependency to core/jquery, and I don't know any module of this name.
(When in module.info.yml)
If you want to add a (JS or CSS) library dependency, use the libraries: key and not dependencies:
(When in module.libraries.yml)
Remember that just defining a library does not automatically load it, you still must add it in module.info (or load it dynamically)


Possible explanation for error and site crashing randomly without any provocation? I have a multilingual client that "suddenly and randomly" started suffering errors and a site crash.

The client assured us they "have not touched the site since it went live." And, more or less we can confirm that given that we have not updated the site on their behalf, as we are the the only ones with update privilages.

Has anyone had their multilingual site "just randomly crash" after months of being live with no problem?

This is the error message. Has anyone seen this before?

  WD php: PDOException: SQLSTATE[42S22]: Column not found:
  1054 Unknown column 'ml.language' in 'where clause':

  SELECT ml.*, m.*, ml.weight AS link_weight FROM {menu_links} ml
LEFT OUTER JOIN {menu_router} m ON m.path = ml.router_path
WHERE  (ml.menu_name IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3,:db_condition_placeholder_4)) AND (ml.link_path IN (:db_condition_placeholder_5)) AND (ml.language IN (:db_condition_placeholder_6, :db_condition_placeholder_7));
Array (
  [:db_condition_placeholder_0] => 1cf698d64d1aa4b83907cf6ed55db3a7f8e92c91
  [:db_condition_placeholder_1] => navigation
  [:db_condition_placeholder_2] => management
  [:db_condition_placeholder_3] => user-menu
  [:db_condition_placeholder_4] => main-menu
  [:db_condition_placeholder_5] => node
  [:db_condition_placeholder_6] => und
  [:db_condition_placeholder_7] => ja
)

  in i18n_menu_init() (line 829 of sites/all/modules/i18n/i18n_menu/i18n_menu.module).

Make sure the i18n_menu module is enabled,

e.g:

drush en -y i18n_menu

i18n_menu has i18n_menu_install to add that language field to the menu_links table on install, and an i18n_menu_uninstall to drop it on uninstall.


When should I use the Url::fromRoute method instead of "new Url" I'm finding that these two PHP snippets yield the same result:

$arr['query']['confirm'] = 'y';
$text = t('Click here.');
$url = new Url('my_route.import', [], $arr); // Three arguments.
$link = Link::fromTextAndUrl($text, $url)->toString();

and

$arr['confirm'] = 'y'; // No "query" key.
$text = t('Click here.');
$url = Url::fromRoute('my_route.import', $arr); // Two arguments.
$link = Link::fromTextAndUrl($text, $url)->toString();

Is there any reason to prefer one approach over the other?  Which is the more typical approach?  Is there some general PHP rule of thumb that might apply, such as... always use a method on the class instead of instantiating an object with "new" whenever possible?

From the documentation for the Url class:

  In most cases, use Url::fromRoute() or Url::fromUri() rather than
  constructing Url objects directly in order to avoid ambiguity and make
  your code more self-documenting.

So, generating a new Url object from a static method is preferred.


How do I change the uploading image file name How do I change the image name while uploading through a file uploading field? In drupal 8 whenever I add an image to a file field, it automatically uploads the image file to my S3 bucket. I need to change the image name before uploading because I need to list my image names with a specific pattern. I searched the internet but couldn't find a hook for that auto image uploading.

If you're uploading a file I'm assuming it's within a form, right? You could add a submit handler function using form_alter() (or override the submitForm() method) and change the file's name using the $form_state object's setValue() and getValue() methods I'm sure.


How to add link in user menu which is available for loggedin users in drupal I want to add link for member area in user menu which is only available for logged in user.Please let me know how i can do this.I am using Drupal 7.

I have taken the easy way out on this one with all my projects. I have two menus, one for logged in users and one for logged out. This works because I can set the 'logged out' menu block to show only to anonymous users, and then I can set the logged in for only authenticated users (in block settings). The solution works great with no custom programming needed!


Drupal Form API submission to create node I have created a custom form in my module using Form API, the problem is it's kind of huge form (it consists lots of fields and fieldsets), I wanted to save the form as node after submission. I can create content type and map those fields, but the form is huge. I am looking for alternative way to do this  and by the way I have "Taxonomy terms" in my select list in my forms, I want them to be preserved as well while saving in node.

Thank you.

If you want to save the form as a node you have to add all the fields to the node type, because otherwise the database won't have tables to put all the data in.

Then, if the form you have made maps directly to the node type, then there really isn't any need for you to have a custom form, just use the normal node add page.

If you then want things to look or function a bit differently you could form alter the form to tweak things and get them the way you want them.

That is the approach I would recommend (without actually knowing what you are trying to achieve, so I am making assumptions).

The alternative is to stick with your custom form, but also make a custom database table to store all the data and enter the data into that, but then you miss out on all the modules that are already out there that provide extra functionality for nodes, you have to write your own integration with views if you want to use that, etc.

You could also do a custom entity type or use the data module, but the trouble you would go to doing this is pretty similar (or even more so) to what you would have to do if you just set it up as a node type.


How do I create a static block programmatically? I want to create a static block using a module. I do not want to use the Views module to create a block. Could anyone explain me how to create a static block programmatically?

I have already checked the example modules in Drupal, but it didn't help me much. I have started Drupal module development every recently and I am struggling to do this.

The important hooks in the Block example module are hook_block_info() and hook_block_view(). The info hook defines your block in the system and the view hook creates the output (html) for your block.

Every module, including yours, will have at least a .info file and a .module file. Drupal.org has some more documentation about .info files that you may find helpful when getting started with modules. Yours really just needs the name and core entries.

The .module file is where you'll implement your hooks. First, implement hook_block_info(), replacing 'hook' in the function name with the name of your module, e.g., my_module_block_info(). It should look something like the following.

function my_module_block_info() {
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

Then, implement your hook_block_view() hook to define the static content.

function my_module_block_view($delta = '') {
  // The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'your_block':
      // Create your block content here
      $block['subject'] = t('Title of first block (example_configurable_text)');
      $block['content'] = 'Your block content, or the result of a function that returns the content';
      break;
  }

  return $block;
}

Once you have that in place, you can put your block in any region as you would any other block in Drupal.


Rules - send email when users role changes to x I need to send an email when an admin changes a users role to role x. The email should not be sent if the users role is already role x and 'save' is pressed on the user page.

I have set up a rule:

Event: After updating an existing user account

Actions: Send mail

This works fine. Then I add a condition of type 'data comparison' account(updated user):roles with the operator 'equals' and the data value 'role x'. But for some reason the email now never sends when I change the user role to 'role x' and resave. I'm confused about why this is not working.

Then once this is fixed I assume I'll need to negate the condition that the account(unchanged user):roles equals 'role x'

Arpitr got me on to the correct solution for this. Here is the code that you can import:

{ "rules_update_user_role" : {
"LABEL" : "Update User Role",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "user_update" : [] },
"IF" : [
  { "user_has_role" : { "account" : [ "account" ], "roles" : { "value" : { "7" : "7" } } } },
  { "AND" : [
      { "NOT user_has_role" : {
          "account" : [ "account-unchanged" ],
          "roles" : { "value" : { "7" : "7" } }
        }
      }
    ]
  }
],
"DO" : [ { "drupal_message" : { "message" : "Changed User!" } } ]

}
}

I like the way arpitr used a drupal message for testing if the rule had worked - i didn't realise you could do this.

It looks like the mistake I might have been making was to use the condition of type 'data comparison' and then try to drill into it to get to the user role rather than just using the 'user has role' condition. I think when i had tried previously to use the 'user has role' condition it failed because I made the used 'account:roles' rather than just account.

Hope this helps someone else.


can't upload files from computer in any wysiwyg editor When I want to upload an image from an editor it only allows me to insert a URL and the ability to browse and upload a file is missing.
So there's something that behind all the wysiwyg editor that is preventing me from doing this and honestly don't know where to start looking for this.

Tried FCKeditor, CKeditor, jwysywig and TinyMCE and in all those cases I can only insert a URL but not upload from hard drive

There's a tutorial I found on youtube here. At 0:19 you'll see 4 tabs called 'Image Info', 'Links', 'Upload' and 'Advanced' respectively.
So my problem is the 'Upload' tab is missing from my editor as well as all other editor where this upload function is supposed to be.

The IMCE project provides upload capabilities to a variety of WYSIWYG editors. Check the project page for the appropriate way to install it for your particular editor.


Aggregation CSS loads old files I'm a little exhausted and don't know where to look anymore.

After checking "aggregate and compress CSS-Files" it seems that Drupal is loading old files.

So far I tried:

Clearing Cache (of course)
Deleting the aggregated files from "sites/default/files/css"
Reloading page to re-aggregate the css files

Unfortunately Drupal is still loading the old files.

Where is Drupal getting these old files from and how to delete or refresh them?

These aggregated CSS and JS files are generated by drupal_build_css_cache() and drupal_build_js_cache() functions when the hash of the content changes (based on the sha256).

If clearing cache didn't help, to force removal of cached files, you can remove the following variables: drupal_css_cache_files, drupal_js_cache_files.

Using drush, it's:

drush -y vdel drupal_css_cache_files && drush -y vdel drupal_js_cache_files

See also: Aggregated CSS/JS file names, when regenerated?

Other thing to check is drupal_stale_file_threshold variable which may prevent removing the old files via drupal_delete_file_if_stale(), if it's set to high.

Read more at drupal_build_css_cache() API docs page:

  The cache file name is retrieved on a page load via a lookup variable that contains an associative array. The array key is the hash of the file names in $css while the value is the cache file name. The cache file is generated in two cases. First, if there is no file name value for the key, which will happen if a new file name has been added to $css or after the lookup variable is emptied to force a rebuild of the cache. Second, the cache file is generated if it is missing on disk. Old cache files are not deleted immediately when the lookup variable is emptied, but are deleted after a set period by drupal_delete_file_if_stale(). This ensures that files referenced by a cached page will still be available.


drush sql-sync doesnt extract gzipped sql I run the following command from a script:

drush -v sql-sync @tmp.stage @tmp.coe | tee ./sql-sync.log

My @tmp.stage server is Drush 7.0 and @tmp.coe servers is Drush 6.2.0

An SQL dumpfile is created locally rsynced to the destination server and attempted to be imported by mysql without first uncompressing. Is there a workaround? The source and destination servers have gzip installed.

Log Output

You will destroy data in server1/tmp and replace with data from 2016_tmp_mirror.
Do you really want to continue? (y/n): Include /var/www/2016/tmp/vendor/drush/     [notice]

Executing: mysql --defaults-extra-file=/tmp/drush_jUBS0A --database=2016_tmp_mirror --host=localhost --silent  < /tmp/drush_H19MvV
Calling system(mysqldump --defaults-extra-file=/tmp/drush_QRO7xg  2016_tmp_mirror --host=localhost --no-autocommit --single-transaction --opt -Q  | gzip -f > /home/dgurba/drush-backups/2016_tmp_mirror/20160407200242/2016_tmp_mirror_20160407_200242.sql.gz);
Include /var/www/2016/tmp/vendor/drush/         [notice]
You will destroy data from webuser@server1:/tmp/2016_tmp_mirror_20160407_200242.sql.gz and replace with data from /home/dgurba/drush-backups/2016_tmp_mirror/20160407200242/2016_tmp_mirror_20160407_200242.sql.gz
Do you really want to continue? (y/n): y
Calling system(rsync -e 'ssh -T' -akzv --exclude=".git" --exclude=".gitignore" --exclude=".hg" --exclude=".hgignore" --exclude=".hgrags" --exclude=".bzr" --exclude=".bzrignore" --exclude=".bzrtags" --exclude=".svn" --include="sites/mysite.foo.com/" --include="sites/all" --exclude="sites/*" --stats --progress --remove-source-files /home/dgurba/drush-backups/2016_tmp_mirror/20160407200242/2016_tmp_mirror_20160407_200242.sql.gz webuser@server1:/tmp/2016_tmp_mirror_20160407_200242.sql.gz);
sending incremental file list
2016_tmp_mirror_20160407_200242.sql.gz

         32,768   1%    0.00kB/s    0:00:00
      2,591,074 100%   26.52MB/s    0:00:00 (xfr#1, to-chk=0/1)
Number of files: 1 (reg: 1)
Number of created files: 1 (reg: 1)
Number of regular files transferred: 1
Total file size: 2,591,074 bytes
Total transferred file size: 2,591,074 bytes
Literal data: 2,591,074 bytes
Matched data: 0 bytes
File list size: 0
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 2,584,839
Total bytes received: 42

sent 2,584,839 bytes  received 42 bytes  469,978.36 bytes/sec
total size is 2,591,074  speedup is 1.00
Calling system(mysql --database=bar --host=localhost --user=foo --password='*****'  < /tmp/2016_tmp_mirror_20160407_200242.sql.gz);
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\8B

In Drush 6, the sql-sync command on the source system composed bash commands, and executed them on the remote system as needed via ssh.

In Drush 7, the sql-sync command on the source system uses drush_invoke_process to operate on the remote system. Drush 6 did not support the gzip features that Drush 7's sql-sync command requires.

You don't specifically mention if the system you are running sql-sync on is Drush 7 or Drush 8 or something else, but Drush 8 is substantially similar to Drush 7 vis-a-vis sql-sync implementation.

You should be able to use gzip to send sql dumps to @tmp.coe, but only if you use Drush 6 on the source. Drush 6 is no longer supported, but I believe it also supported transfer between two remotes. You should therefore be able to install Drush 6 on your local system, and perhaps name it drush6 and use it only for this purpose.


Send an email from Drupal interface? How can I send an email from the D7 UI to specified email addresses?

I want to type in some text, type in some recipient addresses, and click send to send it from the site's address.

An easy way could be using Rules and a custom content type.

The content type should have a title which can be used as the email title, a body for email body, and a field to hold email address(es) (or perhaps a reference field to site users or roles).

Then configure a new rule. Select new content event, add a filter to restrict to defined content type, then as an action select send email. Map the proper inputs and you are done.


How to redirect Add to Cart link to product page? I am working with E-Commerce module of Drupal 7. I want to redirect Add to Cart button link to product page only those products which have attribute otherwise I want to add product direct to cart.

Using Drupal Rules Module:

To redirect directly to checkout after a user clicks 'add to cart'

Admin -> Configure -> Rules -> Add New Rule
Give it a title of 'Add to Cart - Redirect to Checkout'
Set React on event to: After adding a product to the cart
Add new Action - set this to 'Page redirect'
Give it a value of 'checkout' and save.

Now when users click your add to cart button, they will be taken directly to checkout.  Alternatively, you can send them to /cart by change the value in step 5.


use PHP library in Custom Controller I have a custom module and in its controller i am using 'namespace + classname' format to included QRCode library (which is in root/vendor/).

I have used composer to install library

Now I am trying to use this library in custom controller

namespace Drupal\product_display\Controller;
use Endroid\QrCode\QrCode;

But I am getting 'class not found error'

Error: Class 'Endroid\QrCode\QrCode' not found

Class doesn't autoload.

Did you tried dump-autoload command too -

composer dump-autoload

Ref: https://getcomposer.org/doc/03-cli.md#dump-autoload-dumpautoload-


How to automatically send a push notification when content is created? I have set up and configured the Push Notifications module for a site. But, I want to automatically send a Push Notification to all the mobile devices registered in the site when content of an specific content type is created. Can this be done?

I have called the content type "alert", and the user that can send alerts doesn't have access to the administration console, where the push is sent from.

Use the Rules integration of the Push Notifications module. Refer to the issue "Add support for Rules module" for more details on this (issue status = needs review ...) and also use the appropriate patch from that issue.

For the "event" part of such rule to be created, just use "After saving content", limited to (= Rules condition) content type "alert".

If you have to still install the Rules module, you'll discover tons of other use cases to also be resolved by the same Rules module (possibly complemented with the Flag module soon ...).


Drupal 8: Node form submit/update - how to redirect to a custom page with an code-based approach different than hook_form_alter() I have Drupal 8 installation, with a custom content type.
I would like to redirect to a specific page after node form submission.

What I have tried so far:
Using hook_form_alter() and it works, but that's not the point here.

What I want to achieve:
Delivering the same functionality in a new OOP code based way.

What I have found so far:
https://www.thirdandgrove.com/redirecting-node-pages-drupal-8

This example shows the replacement for the old hook_init().

Update 1:
Rules module can achieve the desired functionality.

Update 2:
Node_save_redirect module can achieve the desired functionality.

Update 3: A possible answer
https://www.foreach.be/blog/how-manipulate-forms-drupal-8
can someone with enough D8 experience actually confirm if that's actually the official way of doing things ?

Regards,
Oleg

While the other solution is perfectly valid, I mark this answer as accepted since it comes closer to what I was looking in first place - the new way to alter forms.

Eventually the solution can be found right here:
https://www.foreach.be/blog/how-manipulate-forms-drupal-8

In summary (quoted from the article):
1 ) The first step is to write a service that intercepts the original UserLoginForm and directs to the adapted form

2)  Changed the route to return the adapted NewUserLoginForm instead of the original UserLoginForm

3) The new form extends the old form and inside the buildForm method you add in the beginning

$form = parent::buildForm($form, $form_state);

This step was missing in the example tere


How to resolve File to Patch issue? We are trying to apply a patch to a core module using Applying patches after updating Drupal core to 8.5.6. When running patch -p1 < patchname-issuenum-version.patch command, we get the following.

We tried entering /core/modules/some/path/file.php but that did not work. I ran the command from the /core/modules/some/ directory, which is the module's root folder.

How do we resolve the File to Patch issue?

$ patch -p1 < patchname-issuenum-version.patch
(Stripping trailing CRs from patch; use --binary to disable.)
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/core/modules/some/path/file.php b/core/modules/some/path/file.php
|index cb2e5754a..12354789 11111
|--- a/core/modules/some/path/file.php
|+++ b/core/modules/some/path/file.php
--------------------------
File to patch:

You need to run patch -p1 < patchname-issuenum-version.patch from the directory containing the core directory, not from core/mdoules/some/ or core/modules/some/. (I take core/mdoules/some/ is a typo in the question body.)

Patches for Drupal core are created from the Drupal root directory, so when you apply a Drupal patch, you need to change directory to that one.


access denied when viewing profiles of other users I am having a hard time finding out why non admins (and anonymous users) are having
"access denied" errors when looking at Drupal-7 profiles of other users.

The "View user profiles" permission is checked.

My user's profile page is a panel, but the 'access denied' errors even if the profile is not a panel.

Any idea? Please help.

Additional Information:

Using a code inspired by Yuriy Babenko's answer, and filterning for uniqueness, I see the following pemissions are denied when user 163 views the profile of user 174 (goes to /user/174) :

access administration menu
access administration pages
access all views
administer block classes
administer blocks
administer contexts
administer less
administer media
administer menu
administer user relationship
administer users
administer views
bypass node access
execute php code
view any private_notification content
view own unpublished content
view the administration theme

I don't see anything related to user access...

The nice Access Denied Backtrace module gives the following backtrace, but how to interpret it?

Array
(
    [ 2: drupal_deliver_page()] => Array
        (
            [file] => includes/common.inc:2564
            [args] => Array
                (
                    [0] => 3
                    [1] =>
                )

        )

    [ 1: menu_execute_active_handler()] => Array
        (
            [file] => includes/menu.inc:532
            [args] => Array
                (
                )

        )

    [ 0: main()] => Array
        (
            [file] => index.php:21
            [args] => Array
                (
                    [q] => user/174
                )

        )

)

HOTFIX: Adding the following code before line 820 of user.module temporarily solved the issue:

if (arg(0) == 'user' && is_numeric(arg(1)) && is_null(arg(2)) &&
    $string == 'administer users' ) {
  return TRUE;
}

But how do I find why the 'administer users' permission to view other user profiles?

Impossible to say exactly without having access to your site, but something ON the profile page is causing this.

Do this (assuming you're on Drupal 7):

Open /modules/user/user.module
Scroll down to line 820 (which should be: return isset($perm[$account->uid][$string]);)
Immediately above that line, add this code:

.

if (!isset($perm[$account->uid][$string])) {
  echo 'denied permission: ' . $string . '<br/>';
}

Reload the page as a user that's getting Access Denied, and you'll get a printout of all permissions the current user got denied - one (or more) of them will be the culprit.

Don't forget to remove the code changes once you've found the issue.


How do I add a custom template to my feature? I have a feature with a few views. How to I add a custom template file to it?

Edit: Based on sheena_d and schnippy's suggestions, here is my entire .module code. (It is still not working)

<?php
/**
 * @file
 * Code for the Nigel Gallery feature.
 */

include_once('nigel_gallery.features.inc');

function nigel_gallery_init() {
  drupal_add_css(drupal_get_path('module', 'nigel_gallery') . '/nigel_gallery.css');
}

$theme_registry['template_file'] = array(
  'template' => drupal_get_path('module', 'nigel_gallery').'/templates/views-view--gallery-content.tpl.php',
  'type' => 'module',
);

For either content-type or views templates, you're going to need to manually add these to your features set since ctools exports doesn't handle these. In your features folder (ex. testfeature), you want to create a subfolder for templates:

/testfeature
    testfeatures.features.inc
    testfeatures.info
    testfeatures.module
    templates/

and then copy all of your custom templates into this folder. Then in the testfeatures.module folder, you just need to use hook_theme_registry_alter to add your content-type templates in:

function testfeatures_theme_registry_alter(&$theme_registry) {
    $theme_registry['template-file']['path'] = drupal_get_path('module', 'my_feature')."/templates/";
}

For views templates, you should have more success using a hook_theme function, ex:

/**
 * Implements hook_theme().
 */
function nigel_gallery_theme() {
  return array(
    'views-view--gallery-content' => array(
      'variables' => array('view' => NULL, 'options' => NULL, 'row' => NULL),
      'template' => ' views-view--gallery-content',
      'path' => drupal_get_path('module', 'nigel_gallery'),
    ),
  );
}


How to add the datepicker jQuery UI element to Highcharts in a Drupal site? I am creating a Highstock (Highcharts) page in a Drupal site and I cannot seem to add the datepicker element. I have successfully implemented it in a non-Drupal environment here:

https://jsfiddle.net/MrSnrub/g7u14p10/

...but when I try to migrate it to a Drupal module, it fails. As I understand it, both jQuery and jQuery UI are installed by default in Drupal, is there a specific version that I need to worry about?  When I load up Firebug, it does not give me an error about the datepicker, so it must be interpreting it correctly, but when I load the page and click on the textbox, no datepicker appears. I have jquery_update module installed, and I'm running Drupal 7.  Here is my relevant Highstock JavaScript code:

$('#div-highstock-container').highcharts('StockChart', {
  chart: {
    renderTo: 'div-highstock-container',
    events: {
      load: create_new_legend
    }
  },

  // ...

  series: seriesOptions
},
function(chart) {
  // apply the date pickers
  setTimeout(function() {
    $('input.highcharts-range-selector', $('#' + chart.options.chart.renderTo)).datepicker()
  }, 0)
});

HTML:

PHP (in hook_page):

drupal_add_library('system', 'ui.datepicker');
drupal_add_js('
  jQuery(document).ready(
    function() {
      jQuery( ".highcharts-input-group" ).datepicker({
        autoSize: true
      });
    }
  );
', 'inline');

Do I need to call the datepicker() method in the PHP code or in the JavaScript code at the end of the highcharts() object creation function call, or both?

UPDATE: I changed the PHP code to the following, but the datepicker is still not showing:

drupal_add_js('
  (function ($) {
    Drupal.behaviors.addHighStockDatepicker = {
      attach: function(context, settings) {
        $( ".highcharts-range-selector" ).datepicker();
      }
    }
  })(jQuery);
', 'inline');

If I change the element from ".highcharts-range-selector" to "#div-highstock-container" the datepicker does appear in the main container (therefore, I know I am loading the jQuery library datepicker file successfully), so why does it not appear when I try to apply it to all elements with class "highcharts-range-selector"?

The datepicker was being displayed, it was just hidden by the Highchart. Adding z-index: 9999 !important; to the .ui-datepicker CSS solved it.


Dynamic menu with latest Article in drupal7 I'm a bit new to Drupal environment. I'm trying to develop a demo site for CMS application. Now I'm facing a difficulty to create a dynamic menu for showing taxonomy-wise latest Article. Can I do it with any existing module (Muchomenu, OM Menu etc.,)

Thanks....

I am sure there is a module do to something like that, but you could also create your own.

You could use hook_menu() to query for the items you want and return the correct menu structure. You would need to also make sure the menu cache is rebuilt on a node save.

hook_menu should return an array of menu items, often these are pretty static however there is nothing wrong with these arrays being dynamically generated.

So you can query the node table to get a list of nodes you want, loop through these items and dynamically create an array which contains the correct menu items.

very roughly:

function example_menu() {
  $result = db_query('select * from node where ...'); // put in your own select items and where clause
  $menu = array();
  while ($row = db_fetch_object($result)) {
    $menu['my_path/' . $row->nid;] = array(
      // See hook menu docs for what to put here.
    );
  }
  return $menu;
}


Move fields on User edit page between pages I am using Simple News, which changes the user/1/edit page by adding a new "Newsletter' Page" that is at user/1/edit/simplenews ("1" can be any userId). This page has a Newsletter option field.

I would like to move this option field so it is on the main user/1/edit page.

How can I do this?

I have created my own customer user-edit template (tpl.php), following the instructions here.
The template effects both user/1/edit and user/1/edit/simplenews.

I can print out the Newsletter option field with <?php print drupal_render($form['subscriptions']);?>. But the field only prints out when the user goes to   user/1/edit/simplenews. On user/1/edit it disappears.

Neither are pretty but, you could customise SimpleNews so that it includes the correct form data on the page you want (instead of creating its own local menu entry), or use hook_form_alter() with a custom submit and validation handler on the user edit form to update the db properly - you should be able to steal the code from simplenews for the validation and submit, that way it will update the db the way it was intended. If you go for the former, new updates to simplenews will be difficult to deal with and if you go with the latter however, be aware that future updates to simplenews may break this functionality if they change table names, etc.


Drush cc gives only two options even when I am in root folder I am working with drupal 8, MAMP version 3.5, and drush version 8.1.3. I have installed drush globally and when I enter drush st it gives me complete information and shows that drush is installed but when I run drush cc, it gives me only two options

cancel
drush

whereas, it is suppose to give me many options. I am in a root folder of the site I am working on .i.e. /Applications/MAMP/htdocs/mysites/mysite. My OS is OSX on macbook pro, just in case if this is mac specific issue.

Done with this step as well:

sudo ln -s /Applications/MAMP/tmp/mysql /var/mysql

Not sure what else to look into, can you anyone please guide? I am new to drush, terminal and mac

Use drush cr (container rebuild) rather than drush cc (clear cache)
for drupal 8.


Start page count from 1 with views pager Is there a way to start the page count from 1 instead of 0 using views pager? Maybe using aliases or some module?

By default, the first page is displayed with the URL parameter ?page=0, the second page with ?page=1 and so on. The pagination works good, but in my opinion it would be more coherent having the page one for the url with the parameter ?page=1, the page 2 with ?page=2, etc.

I found a similar question here, but it's about Drupal 7 and I'm on Drupal 8:
Views pager - start paging from 1

Another discussion here: https://www.drupal.org/node/1818040, but without a solution.

To change it just on the UI, you can adapt the number in template_preprocess_pager in your theme's .theme file.
Something like:
function template_preprocess_pager(&$variables) {
  foreach ($variables['items']['pages'] as $key => $value) {
    $variables['items']['pages'][$key]['text'] = $key +1;
  }
}

To change the query params, you could use hook_url_inbound_alter and hook_url_outbound_alter to manipulate the queryparams, but this was D7.
In D8 you would need to go in this direction to manipulate them: How do I implement the equivalent of hook_url_inbound_alter()?


"Cannot use string offset as an array" I am theming a node for a specific content type and split the theme into whether the node is being displayed as a teaser or full. This error only comes up when you view the full node.

  Error: Cannot use string offset as an array in XXXXXX/node--event.tpl.php on line 100

The node displays fine as a teaser, which makes this error even more confusing as the problematic line is used during teaser display. The code below is the one for the teaser part of the template.

  <?php if ($teaser): ?>
  <div id="node-<?php print $node->nid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

        <h2<?php print $title_attributes; ?>>
      <a href="<?php print $node_url; ?>"><?php print $title; ?> -

        <?php print(substr($node->field_date[und][0][value], 0, -9));?>

  <div class="content clearfix"<?php print $content_attributes; ?>>
     <?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      //*********LINE100**************
print($node->body[und][0][safe_value]);
    ?>

      <?php print $links; ?>

  <?php endif; ?>

If you get that error, it means that $node->body is not an array, but a string. In that case, PHP would take $node->body[und] as a string offset, and you could not use $node->body[und][0][safe_value].

To notice that both und, and safe_value are considered from PHP two constants, but Drupal doesn't define those constants. In that case, PHP would use as value of the constants und, and safe_value, the values of the strings 'und', and 'safe_value', but you should not rely on that.


How can I bulk add existing commerce products to a display node? pretty simple, i want the ability to add more than one existing product at a time to a node. i am already using bulk product creation to help me create all the variations of the product quickly. but then after that, i have to add them 1 by 1 to the display node. i would love the ability to just add a product range by product ID or something.

entity reference view widget module solved my problem. it basically allows you to replace the add existing product button with a view. just customize the view to select any range of existing products you want and add them to the display node. saved my a boatload of time.


Javascript in Drupal I was following this post on drupal.org - https://www.drupal.org/node/3075055
But I'm not getting the same result. I'm not experienced at all in javascript so maybe I'm missing something. Do I need to indicate where is my js file? The name of the js file is important?
My module code below:
function draws_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'bets_node_form':
      $form['field_possible_returns']['und'][0]['value']['#process'] = array('my_custom_process');
      break;
  }
}

function my_custom_process($element, &$form_state, $complete_form){
  $element['field_possible_returns'] = array(
    '#type' => 'textfield',
    '#size' => 8,
    '#attributes' => array(
      'readonly' => 'readonly',
      'tabindex' => -1,
    ),
  );
  return $element;
}

The name of my module is draws.
My javascript file (in the same folder of the module file):
(function ($) {
  Drupal.behaviors.draws = {
    attach: function (context, settings) {
      alert('Its working!');
      $('.field-name-field-bet-value').on('keyup change', function (){
        var bet_value = $('.field-name-field-bet-value input').val();
        var odd = $('.field-name-field-odd input').val();
        var result = (odd * bet_value).toFixed(2);

        $('.field-name-field-possible-returns input').val(result);
      });
    }
  };
}(jQuery));

Here are the field names of my content type bets:

Thank you.

Do I need to indicate where is my js file?

Of course, js files do not auto magically get loaded.
You need to tell Drupal about them, There are various ways, see Adding JavaScript to your theme or module.
function draws_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'bets_node_form':
      $form['field_possible_returns']['und'][0]['value']['#process'] = array('my_custom_process');
      // Load JS File
      $form['#attached']['js'] = [
         drupal_get_path('module', 'draws') . '/draws.js',
      ];
      break;
  }
}


Routing multiple params / paths to single method I'm attempting to create the following routing :

/app/{type}
/app/{type}.{format}
/app/{type}/{limit}
/app/{type}/{limit}.{format}

I would like all of these routes to route to a single method. Do I need to declare a route for each of the paths and params ? Does the ranking of the routes also matter ? e.g do I have to place

  /app/{type}.{format}

first before

  /app/{type}

?

Yes, you need to define a route for each path.

The order should not matter, it will put them all in the router table and then "order" them by the best match first.


Problem with specialchars/tokens sent by email with rules module I'm using rules module in D6

I have an encoding problem in the email's body sent by a rule while using tokens:

Name : [node:field_company_nid-title]

In the email, it appears like that:

Name : L&#039;entreprise exemple

With php it works :

echo htmlspecialchars_decode( $string )

but i'd rather to use tokens !

Thank you for help

The good way is to use the -raw output :

[node:field_company_nid-title-raw]


Drupal form_state sanitization I'm new to Drupal and I am doing some module development for a Drupal 7 install.  I've done development outside of Drupal and normally its best to always sanitize user input.  I've seen different opinions of the matter but from what I have picked up is dont use form_state['input'] but what about form_state['storage'] or form_state['value'].  I'm seeing some people say the API does the sanitizing and others say always sanitize.  Can anyone explain to be best practice?

The values in $form_state['values'] are all sanitized.

The values in $form_state['input'] are the raw unsanitized form values.

$form_state['storage'] is usually only used on multistep forms to keep data for other form steps.

Where possible always use the values from $form_state['values'].

See this post for more information: Avoid using data from $form_state['input']

To quote that linked article:

  The Form API's drupal_validate_form() and _form_validate() functions
  take care of populating a safe set of data in $form_state['values'],
  using sanitized data from $form_state['input'].


Views exposed filter selection I want to use view to show car parts.

I have 2 exposed fields (car manufacturer and car part like doors light etc)
The view work nice but what i want is to have a way for example when user click at the first list (example Audi) to show if there is any part in the another list for parts.

Ex.
In Audi i have only Doors and not lights
When user select from first list Audi the list for part only show Doors.

So if Audi only have nodes for Doors will show in second exposed filter only the Doors option.

Drupal 7 views 3

From what you're describing it sounds like you need Faceted search. I'm not sure if Views filters can give you the functionality you're looking for.

Have a look at the Search Api module, it provides faceted search widgets which behave the way you described.

https://drupal.org/project/search_api


Print created menu directly in a page I have created a menu like france menu. I just want to print it using print_r statement. Is it possible? I know menu block is there. But i don't wanna use it.

Try this:

$menu = menu_navigation_links('menu-your-custom-menu-name');
print_r (theme('links__menu_your_custom_menu_name', array('links' => $menu)));

Source: How to print a menu in Drupal 7 ? and the next comment is also useful: printing custom secondary menu when the user is logged out.

Changelog for Drupal 7: Use #theme='links_MODULE' or #theme='links_MODULE_EXTRA_CONTEXT' when adding links to a render array.

Edit: new version using menu_tree()

$menu = menu_tree('main-menu');
$menuhtml = drupal_render($menu);
print_r($menuhtml);


Menu settings does not change menu I have created a new menu called new-menu.  I go to Admin > Structure > Menus > Settings

And I choose "New Menu"  for the "Source for the Main links" option.

However, on my site, it still shows the Main Menu links (instead of New Menu links).

What am I missing?

Note: I am running a custom "Drupal core" from my university, and I've never worked with Vanilla Drupal, so I'm not sure if something is missing that should be there.

You need to change the menu under Structure > Blocks. Find the Main Menu block that is active and click its "Configure" link. The third option is Menu... change this to dropdown to your new-menu.


What to do with hidden files in Drupal 8 minor core upgrade? Step 3 of https://api.drupal.org/api/drupal/core!UPGRADE.txt/8 says

  Also remove all of the files in the top-level directory, except any that you added manually.

it doesn't exclude or include hidden files explicitly, so my logic would say 'all' includes hidden files.

later it says

cp -R drupal-x.y.z/* drupal-x.y.z/.htaccess /path/to/your/installation

which does not copy any hidden files except .htaccess.

This would suggest not to delete the old hidden top level files. On the other hand the new version/patch of Drupal 8.y.z comes with (new?) hidden files.

So my question is: what is the correct way to handle top level hidden files other than .htaccess while upgrading Drupal 8?

TL:DR;
You should delete all files hidden and not hidden that you didn't place there yourself.

Drupal core has a lot of hidden files, which are used when developing Drupal itself (git, lint and possibly more) but none of those are needed or relevant for running a Drupal site in production. They are highly relevant when you are working on Drupal itself.

The only hidden file you need for a production site is the .htaccess, if you have more than that they are safe to delete.


How to conditionally load a javascript or css? I just got assigned to a project that requires bug fixes. It is not a bug, but the client is asking us to reduce size of our site's compressed javascript.

I found out that the compressed js' size is around 500kb, which is pretty big. I think it is that big because Drupal loads all the javascript from all the enabled modules. The problem is that there are scripts that I don't use on my homepage or other pages.

What would be a good solution or workaround for my issue? One thing I can think of is to turn off compreconditionally disable modules in my template...but...is that okay or even possible?

What your looking to do is remove extra JS or CSS files, correct? AdvAgg can do this for you.
hook_advagg_js_pre_alter()
hook_advagg_css_pre_alter()
are the hooks you want to implement. Then inside of the hook you can use the arg() function to figure out what page your on.

$args = arg();
if (   isset($args[0]) && $args[0] == 'node'
    && isset($args[1]) && is_numeric($args[1])
    && !isset($args[2])
      ) {
  $node = node_load($args[1]);
  if (!empty($node) && $node->type == 'page') {
    // Do awesome stuff to the JS/CSS array.
  }
}

See advagg_js_cdn_advagg_js_pre_alter() for an example on how the hook is used. Also be aware of drupal_is_front_page(); it might be useful.


Can't sort by date in view I have the simple view to display a list of nodes of a particular type. But I can't get it to sort by post date! I tried over and over, ascending and descending and it just won't sort!

I don't know what to do...

In the preview this is the sql statement:

SELECT node.nid AS nid, node.title AS node_title, node.created AS node_created
  FROM node node  WHERE (node.type in ('homepage_feat_video')) AND (node.status <> 0)

There is no sort directive. But I added a sort for sure!

EDIT: discovered that when I change the style to something other than table - it works. but why doesn't it work in a table?

OP asks for D6. For D6 make sure you have the latest version of the date and the views module. Older versions have a bug that tends to "forget" the sort part of the SQL statement.


Drupal 7 node reference field formatter for nid I'm working in Drupal 7 and using the reference module to attach an node reference to another node. I'm then using views to show some of that nodes fields. When I display the field for the node reference, I'm give the choice of formatting it as a title, title with link, or rendering out the whole node. All I really want to be able to do is render out the nid or the node rather than the title. There were a number of modules that did this in Drupal 6, anyone know how to do it in Drupal 7?

Thanks

having trouble creating the patch, here is what I did, added

'node_reference_nid' => array(
  'label'       => t('Nid'),
  'description' => t('Display the nid of the referenced node.'),
  'field types' => array('node_reference'),
),

to the node_reference_field_formatter_info() function also added

  case 'node_reference_nid':
  foreach ($items as $delta => $item) {
    if ($item['access']) {
      $node = $item['node'];
      $result[$delta] = array(
          '#markup' => check_plain($node->nid),
       );
      if (!$node->status) {
        $result[$delta]['#prefix'] = '';
        $result[$delta]['#suffix'] = '';
      }
    }
  }
  break;

to the node_reference_field_formatter_view() function

that's it, hope it helps


Get language path prefix code as contexual filter parameter In Drupal 7, I have a block that shows recent posts which created with views.

I want it to show the translated posts of each language when I click the language switcher to switch the language.

I have two language prefixes (url code):
'en' and 'fa'
mysite.com/en
mysite.com/fa

I set in a contexual filter of that block view to show just the nodes of the specific language by raw value from url set to 1, but it considers the next value of language code as the first parameter.

What should I do to make Drupal consider the language code as the first value?

In Views with i18n there is also a filter available for that matter:

  Content: Language

You can set this to 'Current user's language' in order to filter your content based on the selected language.


Is there a module that can replace tabbed menus with contextual links? The tabbed menus at the top of node with entries like View, Edit, Outline takes too much space for my liking. In my case I also use the Node Clone module which also takes up more space because it uses an action link.

Is there a module to hide the tabbed menu and expand it on demand, or change it to contextual links? I have seen a few examples but they all seem to require changes to existing theme files or modules. Is there one implemented as standalone module?

The Custom Contextual Links module does this https://drupal.org/project/ccl

Jeff Eaton gives a good overview of this module https://www.lullabot.com/blog/article/module-monday-custom-contextual-links

Alternatively, you could theme the existing menu to be styled like contextual links since both use an unordered list, just different css classes that trigger style and javascript behavior.  To do so you could either use a custom module to add the css classes necessary or add your own css rules.


How to change image style using hook_views_pre_render() I am trying to adapt the following Drupal 7 code to Drupal 8, in order to set a different image style to every image in a view:

// Assigns a random style name to each image
function <MODULE_NAME>_views_pre_render(&$view)
{
  if($view->name == 'SOME VIEW')
  {
    $styles = array('thumbnail', 'medium', 'large');
    foreach($view->result as &$result)
    {
      $result->field_field_image[0]['rendered']['#image_style'] = $styles[array_rand($styles)];
    }
  }
}

Right now I have:

function <MODULE_NAME>_views_pre_render(ViewExecutable $view)
{
  if($view->id() == 'SOME VIEW')
  {
    $styles = array('thumbnail', 'medium', 'large');
    foreach($view->result as &$result)
    {
      $image = $result->_entity->get("field_media_image");
      $image->SOME_FUNCTION('#style_name') = $styles[array_rand($styles)];
    }
  }
}

However, I can't figure out what SOME_FUNCTION would be -- There does not appear to be any way to access the render array from an ImageItem object.

I gave up on hook_views_pre_render and wound up meeting my requirements with template_preprocess_image_formatter as follows:

function <TEMPLATE_NAME>_preprocess_image_formatter(&$variables) {
  $styles = array('thumbnail', 'medium', 'large');
  if ($variables['image']['#style_name'] === 'medium') {
    $variables['image']['#style_name'] = $styles[array_rand($styles)];
  }
}


Fetching nid in drupal Here I want to fetch the nid of matching child term id from my content type product_categories.

I used the below code.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'product_categories');
$query->propertyCondition('status', 1);
$query->fieldCondition('field_product_sub_cat', 'tid', $child->tid, '=');
$result = $query->execute();

I execute the above query and it displays correct results.But now I want to fetch the nid, I used below code but its not working.

 $childnid = $result->nid; //Area to explore
//print "<pre>"; print_r ((int)$childnid);
print $childnid;`

can anybody please help me ??

$result is in array of items.

Use this:

$first_nid = NULL;
if (isset($result['node'])) {
   $first_nid = array_shift(array_keys($result['node']));
}


Difference between create new and edit node in form alter I have an alter section for a particular content type. In the form alter how can I find out whether it is create new form or edit form?

With dsm($form) in from alter I can get results with several differences between them. What is the best way to distinguish those from each other?

is this a good way?

    if(isset($form['nid']['#value']))
     'means in edit form'
    else
     'means in create new from'

If you look at the code of node_object_prepare(), which is called from node_form() (the form builder for the node edit/create form), you will see it contains the following code.
  // If this is a new node, fill in the default values.
  if (!isset($node->nid) || isset($node->is_new)) {
    foreach (array('status', 'promote', 'sticky') as $key) {
      // Multistep node forms might have filled in something already.
      if (!isset($node->$key)) {
        $node->$key = (int) in_array($key, $node_options);
      }
    }
    global $user;
    $node->uid = $user->uid;
    $node->created = REQUEST_TIME;
  }

In an implementation of hook_form_BASE_FORM_ID_alter(), it is enough to use code similar to the following one.
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];

  if (!isset($node->nid) || isset($node->is_new)) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}

If the node is new, then the form is creating a node; if the node is not new, then the form is editing an existing node.
In Drupal 8, every class implementing EntityInterface (including the Node class) override the EntityInterface::isNew() method. Checking if a node is new becomes as easy as calling $node->isNew(). Since in Drupal 8 there isn't $form_state['node'] anymore, the code becomes the following.
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state->getFormObject()->getEntity();

  if ($node->isNew()) {
    // This is a new node.
  }
  else {
    // This is not a new node.
  }
}


What are the really use of the ancient Project Application issue queue now that you can promote your own sandbox projects? The Gates are open for Drupal.org Code Contributions, so now you can promote sandbox projects to full projects with releases if you have accepted the git terms of service.

But what is the actual use of the legacy Project Application issue queue (which is now named Drupal.org security advisory coverage applications?

I post this question because I have a module in revision there a some users that says that the code is OK, they made some suggestions and I made the changes until the last comment that says:

  When a node Add is disabled, you should at minimum highlight which
  content type won't accept new content (in fact providing node edition
  instead).

This is a UX change that don't affect the security and don't affect the module functionalities. The module works fine without this. And now the module is promoted to full project this is an impediment to approve the module in the new Drupal.org security advisory coverage applications queue?

What are now the procedures to go ahead wit the revisions?

Disclosure: I'm the maintainer of the module Only One. I'm not looking for promotion, I just want to know how to finish the review process.

Apart from your actual question, you also posted a comment which contains this:

  ... the project is promoted, but now how can I obtain the shield?

Not sure if it will be a complete answer to your question, but your scenario here seems a variation of the question about "Why has my security shield for my new module on Drupal.org been removed?". Your variation now seems to be "Why has my security shield for my new module on Drupal.org not yet been added?" (or why is it not visible yet).

Here is part of my answer in that related question:

  You need to create an official release, for at least 1 version of Drupal core that is supported. In your case, for D7, like a 7.x-1.0 version of your module. Shortly after doing so, your module will have the security shield.

I'm not sure (yet) about how long that Shortly actually may take, but I also noticed that on the revisions page of OnlyOne the most current timestamp is 13 Mar 2017 at 22:32 CET (which is less then 24 hours ago). Moreover, on its project page there is also Last modified: March 14, 2017 (which is today ...). But it could well be that with only a little patience (like until tomorrow?), you will automagically get the shield that you're looking for.

Update

Debugging is the art of taking away all possible causes ... about a day later it appears that for your module "a little patience" is not the solution (the shield still doesn't show up). Sorry.


In which contrib file/function should a class_alias() statement be placed so that it is always processed, regardless of the url being served? To main backwards-compatibility I need to define two class aliases in my contrib module. Both of the source and target classes are within the same namespace within my module's namespace.
I placed the class_alias( ) statements at the top of my_module.module in open code, not a function, and this works for everything in the module, and also mostly for everything everywhere. I have created a second module which uses the original classes to check this. The second module has the first as a dependency. This works most of the time, however, there are a few places where I get a 'class not found' error, meaning that the alias statements have not been processed. For example, when viewing a few admin urls e.g admin/config/regional/language
So is there a better place than my_module.module where I can put the class_alias( ) statements, such that they are always processed?
My fall-back solution would be to re-create the two original class files, in the original locations, and each of them have the class alias statement, so that autoloading finds them. But that's a bit untidy and they will cause confusion as they are named incorrectly. It would be nicer to be able to have the two alias statements somewhere, and not have two nearly empty files left around.

So is there a better place than my_module.module where I can put the
class_alias( ) statements, such that they are always processed?

Put class_alias() in the class file (after the use statements before class {} or at the end of the class file).
*.module files are not loaded by the class loader, they are included later in the kernel bootstrap process.


How could I do a FULL OUTER JOIN in drupal? How can I do this code in Drupal? I cannot find how this code is writing in Drupal.

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;

Dynamically it would look like this:

$q = db_select('table1')
  ->fields('table1', array('column_name'));

$q->addJoin('FULL OUTER', 'table2', NULL, 'table1.column_name = table2.column_name');

Which will give you

SELECT table1.column_name AS column_name
FROM
{table1} table1
FULL OUTER JOIN {table2} table2 ON table1.column_name = table2.column_name

Or you can run any SQL string with db_query():

$sql = <<<SQL
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
SQL;

$result = db_query($sql);


Programmatically created nodes are shown only after re-saving I'm creating a lot of nodes programmatically in a custom module. These nodes are showing up on admin/content and in a default view display (unformatted/fields), but not in a calendar view display. Only if I open and resave, those nodes will be shown in the calendar view.

Why is this happening? All nodes are published.

SOLVED: I was using a timestamp for the generated dates, but it needed to be a string like: "1967-01-15T00:00:00". I needed to look up the values in my database directly, devel / dpm() did not show a difference.


Global php view for conditional profile image I have tried to configure a view for a user listing.
In this view only few fields from the user entity will be shown. In the user entity I have a boolean variable. If the boolean variable is TRUE ("1") the real profile image should be shown, otherwise the default image for all users should be shown.

In order to implement it I have added a views field of type Global: PHP.  In the field's code I wrote:

$file = file_load($row->picture);
if(isset($row->field_primum) ) {
if($row->field_primum == "1") {
print theme('image', array('path' => $file->uri));
else ($row->field_primum == "2") {
print();
}
}
}

However it runs only on the first user and not for all users in the display. Do you have any idea why?

Thanks
zanet

It's possibly the result of syntax errors.

This is where you can see the benefits of well formatted code.

If you format your code like this it becomes more obvious that you have errors in your code (I assume $row->picture actually is a file ID):

$file = file_load($row->picture);
if (isset($row->field_primum)) {
  if ($row->field_primum == "1") {
    print theme('image', array('path' => $file->uri));
    else ($row->field_primum == "2") {
      print();
    }
  }
}

Problems I can see now are:

There you can see that the else actually has no if statement because it is inside the second if statement.
The else also shouldn't have the condition. If it needs the condition then use elseif.
You mention that the field you are using is a boolean field, in which case the values will be 0 & 1, not 1 & 2.
The second print statement should be printing a string so the string should be wrapped in quotes.
You are incorrectly using the a tag to print an image. You should use an img tag for images and an a tag for links.

I would think it should be more like this:

if (isset($row->field_primum)) {
  if ($row->field_primum) {
    $file = file_load($row->picture);
    print theme('image', array('path' => $file->uri));
  }
  else {
    print('');
  }
}

Note that I also moved the file_load() call inside the if statements because there is no need to load it if you aren't using it.


Variable_get question default value in form So I am reading Drupal Development Pro 7 and have stumbled upon something I am a little bit unsure about to do with the variable_get function & form element. I understand it retrieves a stored value from the database and the second parameter is a default value if it cannot find anything in the database matching that form element.

My question is what does the second parameter do in this example below.

foreach($types as $node_type){
    $options[$node_type->type] = $node_type->name; //access the $node_type object and store specific properties from the node_type object in $options array
}

//Checkboxes on Form
$form['annotate_node_types'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Users may annotate these content types'),
    '#options' => $options,
    '#default_value' => variable_get('annotate_node_types', array('page')), //when using the system_settings_form, the name of the form element must match the key of the variable_get ie $form[] = variable_get('$form[]', '') Always form_element name
    '#description' => t('A text field will be available on these content types to make user-specific notes.'),
);

The #default_value for a 'checkboxes' element must be an array rather than a single value (so you can have multiple default values selected).

All that code does is provide the default value wrapped in an array, so that it conforms to what the 'checkboxes' element type is expecting.


How to alter body of contact form? When submitting a message in my site contact form in Drupal 8.x
I have printed a message

print_r($message['body'][1]);die;  //in my modulename_mail_alter(&$message)

I get the following message

Drupal\Core\Render\Markup Object
(
    [string:protected] => Message

   Test Message

     First Name
               Rahul

     Last Name
               gaikwad

)

How can I change the body content of the email.

Alter how exactly? You can cast the markup object to a string, then you can change the string or completely replace it.

Also check out the default integration that the contact_storage module has with swiftmailer to allow sending mails as HTML. That might get you much further than trying to change this string.


8 - How to configure system link I'm new to drupal, I'm trying to change the link structure and still did not get.

For example, when I create a basic page, it uses a standard link "node/drux"

but I want the link to be the title of the page, without having to create an alternative URL.

How can I change this structure?

You're looking for Pathauto I think. It allows you to define patterns for how the aliases should be created automatically.


How to make nodes to be aware that they were added to menu programatically I'm adding nodes to menu programatically by custom PHP snippet in Rules. The problem is that nodes aren't aware of this - so the option "Provide a menu link" is unchecked in them, even if their menu-item exists. I cannot find anything relevant in $node object. How to fix this?

My code is:

$node_path = "node/" . $node->nid;
$node_alias = drupal_get_path_alias($node_path);
$menu = menu_load_links('main-menu');

foreach($menu as $key=>$value) {
    if($node_alias == $menu[$key]['link_path'] || $node_path == $menu[$key]['link_path']) {
        return;
    }
    if($menu[$key]['link_title'] == $node->field_rok['und'][0]['value'] && $menu[$key]['link_path'] == "<nolink>") {
        $menu_year = $menu[$key]['mlid'];
    }
    if($menu[$key]['link_path'] == "archiwum") {
        $archiwum_plid = $menu[$key]['mlid'];
    }
}

if(!isset($archiwum_plid)) {
    return;
}

if(!isset($menu_year)) {
    $item = array(
        'link_path' => '<nolink>',
        'link_title' => $node->field_rok['und'][0]['value'],
        'menu_name' => 'main-menu',
        'plid' => $archiwum_plid,
        'hidden' => 0,
    );
    // menu_edit_item_validate(array(), $item); Drupal doesn't recognize this function in this place (Rules), don't know why... :/
    $menu_year = menu_link_save($item);
}

$item = array(
    'link_path' => $node_alias,
    'link_title' => $node->field_numer_w_roku['und'][0]['value'] . '/' . $node->field_rok['und'][0]['value'] .' (' . $node->field_numer['und'][0]['value'] . ')',
    'menu_name' => 'main-menu',
    'plid' => $menu_year,
    'hidden' => 0,
);

// menu_edit_item_validate(array(), $item);
menu_link_save($item);

menu_rebuild();

Got it - I had to use drupal_get_normal_path($node_alias) on path added to menu. I hope that will be helpful for someone.


Enabling "entity translation" disables term translation in Drupal (name and description) i want to translate taxonomy terms and their description text.
When I enable the module "entity-translation" and check "Taxnomie-terms" in admin/config/regional/entity_translation, the terms and descriptions get synchronized. Means: If I enter the German termname and description and switch to english and change it there, it also changes on the german translation.

The lables show:

Name (all languages)
Description (all languages)

And I don't know how to change that. Ideas for solving my problem welcome!

Ad documented on the Entity Translation project page: "Title module allows to replace entity labels with fields to make them translatable." With the Title module you are able to replace the non-Field title and description properties taxonomy terms with Fields translatable with Entity Translation.


Running asynchronous PHP code I have Drupal server with a REST API using services and rest_server (that's just background, I don't THINK that applies to this problem at all.) I'd like particular API calls to only report back that the request was received, but then go on to do further work in PHP.

To me, this seems like a thread/fork solution, but I can't seem to find a viable solution using PHP/Drupal. The first (and from the looks of it, easiest) thing I came across was the pcntl_fork() function. But, as it looks like that's not viable:

  It is not possible to use the function 'pcntl_fork' when PHP is used
  as Apache module. You can only use pcntl_fork in CGI mode or from
  command-line.

  Using this function will result in: 'Fatal error: Call to undefined
  function: pcntl_fork()'

(And, indeed, when I try using function_exists() through command line, it's there, but when run in PHP through Drupal it says function is undefined. I'm reading some stuff on how to install it/recompile PHP with it, but would prefer if there were a method that didn't involve changes to the server.)

Other than that, I'm coming across solutions such as creating a queue to run with cron jobs, creating convoluted menu items, or a whole background processes... thing. All I want is for some arbitrary code to be run off on its own. Does anyone have a suggestion that they feel works best with with Drupal?

(Also, I don't know what to tag this as--I tried thread or asynchronous but those don't seem to exist--so feel free to tag.)

A request to a REST API should just return required data and end. If you want to do asynchronous tasks do not reuse request threads, use cron tasks.

If you want to get independent from Durpal cron use your own drush command executed by a system cron. So, you declare a drush command that makes whatever asyncrhonous tasks and then declare a system cron that runs drush on that command.

If you need to prepare data for that command (for example, if some REST API functions generates data that must be processed asynchronously) you can use Drupal Queues. When the API is called add a new element to a certain queue that will be later processed by the drush command.


Compute values to display on the user profile page based on other user profile field values I've added fields to user profiles:

subscriber (yes/no)
guest subscriber (yes/no)
print subscription expiration date
online subscription expiration date

On the user profile page, I want to display things like:

Because you are a guest subscriber, your subscription never expires.
Your subscription will expire on date1 [the later of the print and online subscription dates]. Please renew by date2 for uninterrupted service.
Your subscription expired XX days/XX weeks/XX months ago on date.

These are some examples to give the idea. I need to look at profile field values before the profile is displayed, do some computing, and then add additional, display-only fields to the page or modify the value of existing fields that are displayed on the page.

All I need is a clue about the approach. I already have a custom module, so using something similar to hook_form_alter will do nicely. I've read about 20 posts, but none that seem to match.

You can make use of hook_entity_extra_field_info() . Below is the following code snippet which you can use in your module:

/**
 * Implements hook_entity_extra_field_info().
 */
function my_module_entity_extra_field_info() {
  $extra = array();

    $extra['your_entity']['your_content_type']['display']['my_own_pseudo_field'] = array(
      'label' => t('My own field'),
      'description' => t('This is my own pseudo-field'),
      'weight' => 100,
      'visible' => TRUE,
    );
  }

  return $extra;
}
And you can use hook_ENTITY_TYPE_view
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function my_module_your_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('my_own_pseudo_field')) {
      $build['my_own_pseudo_field'] = [
        '#type' => 'markup',
        '#markup' => 'This is my custom content',
    ];
  }
}

Please replace the entity and entity type with your requirement. Since it is only for the display this code snippet will work . Clear the cache you will find this field in manage display section .


Overriding a specific display doesn't work I created a view in Drupal 8 with 2 displays. I want to keep a display content view mode as teaser and the other as featured (custom), but when I change a display it updates the other display as well.

It's easy to miss if you're always clicking on the | Settings link of an Option.

Options can be set to apply to All displays or you can override for each Display separately This attachment (override).

But you have to click on the Option itself and not its "Settings" link to see that Dropdown.

You clicked on the "Teaser" or the "Featured" Settings link of your Show Option, but there is no Dropdown to override there.

You have to click on the Content link first, Override through the Dropdown for this Attachment only and Apply (this display). Then you can change the Settings for the Option if you have to. It will only apply to the current Display.

You can change the original Display Option to what you want and Apply to all displays, that one doesn't have to be overridden, unless it makes sense for that particular case.


Field template for display mode of referenced paragraph I have a custom field field_platform (referencing a the custom paragraph type platform) and a template for my field: field--field-platform.html.twig. Is there a way to override this for a specific display mode of the referenced paragraph type? I have a mode named cover_view for the custom paragraph type platform I want to override the field template for.

I found Field template for display mode but the template suggestion is for the display mode of the content, not the referenced paragraph.

Drupal 8.5.6, Paragraphs 8.x-1.3

Thanks in advance!

Implement hook_theme_suggestions_alter like in the other answer and you can find everything you need in the $variables.

The following snippet will add the template suggestion for the view mode of the referenced paragraphs. Note that this will probably only make sense as long as you use only one paragraph type OR all multiple paragraph types have the same view mode configured.

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_field_alter(array &$suggestions, array $variables) {

  $element = $variables['element'];

  if ($element['#field_type'] == 'entity_reference_revisions') {

    foreach ($element as $key => $value) {
      if (is_numeric($key) && isset($value['#paragraph'])) {

        $paragraph = $value;
        $suggestions[] = 'field__' . $element['#field_name'] . '__paragraph__' . $paragraph['#view_mode'];
      }
    };
  }
}

Seems you can implement that from you theme's *.theme file as well.

I guess the same logic works for any entity (node etc.) reference as well.


Override taxonomy_term_uri Is there a way to modify the behavior of taxonomy_term_uri() in a custom module for D7? I am not able to do so by definining THEME_term_uri(), and I wouldn't like to alter the original Taxonomy module.

I managed to override it. I found out that 'taxonomy_term_uri' is defined in taxonomy.module's taxonomy_entity_info() function, so I added a hook that alters it:

function MODULE_entity_info_alter(&$entity_info) {
    $entity_info['taxonomy_term']['uri callback'] = 'MODULE_taxonomy_term_uri';
}

function MODULE_taxonomy_term_uri($term) {
    // change the path...
    return array(
        'path' => 'taxonomy/term/' . $term->tid,
    );
}


Rendered entity reference field (list-group) disappears, when user can't access the referenced items. Why? I have been trying to find the reason for this problem for a few days now... without any luck. Which is why I would like to ask for help here...

In a nutshell: I'm working on a simple LMS and have defined a content type Course that contains an entity reference field field_lessons, which refers to another content type Lesson. In the template file node--course--full.html.twig I'm using the following code to render a "table of contents" in the sidebar:

...

  {{ content.field_lessons }}

...

In addition I'm using a template file field--node--field-lessons--course.html.twig for rendering the field:

...

  {% for item in items %}
    {% if (item.viewaccess) %}

    {% else %}

    {% endif %}

        {{ item.title }}

      ...
    {% if (item.viewaccess) %}

    {% else %}

    {% endif %}
  {% endfor %}

...

(Note that I deliberately left out a few insignificant details in the code: These are marked with "...".)

So, depending on whether the current user can access a single lesson (I'm using the variable item.viewaccess, which depends on hook_node_access() and is set in hook_preprocess_node()), each lesson is rendered as active or disabled list-group-item. So far, this works perfectly.

Something weird happens, however, as soon as all lessons are locked for the current user: In this case, none of the lessons gets rendered and the whole table of contents (i.e. the whole  block) disappears.

I'm totally stumped at this point. Can anyone offer an idea as to why this happens?
Any help would be much appreciated.

FWIW :

The entity reference field formatters that are in core use the method getEntitiesToView() (From class EntityReferenceFormatterBase) to load the referenced entities.

This method honors entity access :

$access = $this->checkAccess($entity);
// ...
if ($access->isAllowed()) {
  // ...
     $entities[$delta] = $entity;
    }
//...
return $entities;

so yes, it seems normal that nothing is rendered.


How do you change the core forum module to only show a certain depth? I am using the core forum module. If I have this forum structure:

- A1
 - A2
  - A3
- B1
 - B2
  - B3
- C1
 - C2
  -C3

I want it to show A1, B1 and C1. As well as A2 and B2. But not A3, B3 and C3.

I checked the forum-list.html.twig file, but before I start hacking away, I was wondering if there isn't a more obvious hook of some sort I could use to do this?

If you want to change list of forums using hook try hook_preprocess_HOOK something like like

function MYMODULE_preprocess_forum_list(&$variables) {
// dump here forums and search for the forum you want to remove and unset it .
 dpm($variables['forums']);
}


Drupal 8 Configuration API - cant access variables I have made a simple example to practice using the configuration api in drupal 8. I created the following twitter_pull.credentials.yml file in the config/install folder:

oauth_access_token: "12345"
oauth_access_token_secret: "67890"
consumer_key: "54321"
consumer_secret: "09876"

and flushed my cache. In a custom block, I pulled in the configuration

$config = \Drupal::config('twitter_pull.credentials');

and when I did a dpm

dpm($config);

I did not get a null result. However, when I tried accessing a property:

drupal_set_message($config->get('consumer_key'));

now the result was null. Even when I tried using a configuration object which already exists

 $enabled = \Drupal::config('system.maintenance')->get('enabled');
dpm($enabled);

it still returned null. What am I missing here?

EDIT:
If it helps anything here is the full code:

namespace Drupal\twitter_pull\Plugin\Block;
use Drupal\block\BlockBase;

/**
 * Provides a block for executing PHP code.
 *
 * @Block(
 *   id = "twitter_pull_tweets_block",
 *   admin_label = @Translation("Twitter Tweets")
 * )
 */
class TweetsBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    $config = \Drupal::config('twitter_pull.credentials');
    $enabled = \Drupal::config('system.maintenance')->get('enabled');
    dpm($enabled);
    dpm($config);
    drupal_set_message($enabled);
    return 'this is a block: ' . $config->get('consumer_key');
  }
}

To elaborate on @dawehner's answers, default configuration is not cached.

It is only imported when you install a module. After that, if you make changes to default configuration, the only way to add it to existing installations is to write an update function that adds it manually.

During development, there are modules like Configuration development, that can automate that process, but they will obviously not be present on any productive installations.


Change Content region width when Sidebar has content? hello i have what i feel is (hopefully) an easy problem to solve. Basically i have my regions defined which is fine but i have my sidebar that i want to display on the right of the content region. if the sidebar has blocks the 'Content' region should gain a class that adjusts the width to allow the sidebar to display, if no content in sidebar then the content region should display in full width.
In the page template i have this so far

<?php if ($page['sidebar_first']): ?>
         <aside id="sidebar-first" role="complementary" class="sidebar clearfix">
           <?php print render($page['sidebar_first']); ?>
         </aside> <!-- /#sidebar-first -->
         <?php endif; ?>
         <?php if (!empty($page['sidebar_first']): ?>
         <div class="content-region-sidebar-sibling">
         <?php print render($page['content']); ?>
         </div>
         <?php else: ?>
           <?php print render($page['content']); ?>
         <?php endif; ?>

yet the line for
       <?php (!empty($page['sidebar_first']); ?>
continues to return TRUE whether the region has content or not..
i need to know how to fix this syntax so that if my sidebar region is with blocks, the content region will receive the class assigned(which is how i'm editing the width) and will not get the class if there is no sidebar blocks active on that page. Can anyone help?

$page['sidebar_first'] is an empty array when you have no content in that region. So it is defined and the condition

if ($page['sidebar_first']):

is true even if you have no block in the sidebar. So

print render($page['sidebar_first'])

gets executed and, after the rendering, $page['sidebar_first'] will look something like

array(
  '#printed' => true,
  '#children' => '',
)

meaning that it's no longer empty and the condition if (!empty($page['sidebar_first']): will be met in any case. You may want to rewrite your code to something like

      <?php if (!empty($page['sidebar_first']): ?>
       <aside id="sidebar-first" role="complementary" class="sidebar clearfix">
         <?php print render($page['sidebar_first']); ?>
       </aside> <!-- /#sidebar-first -->
       <div class="content-region-sidebar-sibling">
         <?php print render($page['content']); ?>
       </div>
     <?php else: ?>
       <?php print render($page['content']); ?>
     <?php endif; ?>


Only enable SSL for specific websites (Aegir) So Aegir has a manual page on SSL.

I need to enable for one website. I enable SSL for the server and then require the certificate on that website.

But now, if I go to any other website on the same server and try the address with https://, it will present that incorrect certificate and a big error message comes up.

How can I enable SSL only for that one website I need and disable it completely for other sites?

You have to create a separate IP address for each site that uses SSL.  If you only have one IP address on the server and you assign it to SSL then the whole server is essentially using SSL.

So, solution is to assign a new IP address to the server and use that when you setup SSL for a site.

More info from this link: https://groups.drupal.org/node/74248

  all non-ssl sites will use the first ip address in the list.

  When a site has SSL enabled, it associates an IP address with the certificate it uses.
  Both the SSL and non-SSL versions of all sites using the same SSL certificate will use the assigned IP.

  You can only host as many SSL certificate addresses as IP addresses you have on the server.

  The site node also now provides you with the list of IP addresses the site is running on.


Can I change the default URI scheme in media.variables.inc? The default URI scheme is public://, and I want to change it.

So, can I override the following code contained in media.variables.inc?

define('MEDIA_RESOURCE_URI_DEFAULT', 'public://');
define('MEDIA_TYPES_DEFAULT', '*');

What should I change at MEDIA_RESOURCE_URI_DEFAULT and MEDIA_TYPES_DEFAULT?

Changing the code in a third-party module is never a good idea: All the times that module is updated, you should download the new version, edit it to change the code you altered, and update the copy used in your site. This means that, in Drupal 7, you could not use the Update manager module to automatically download, and update, the copy of that module.
If then the module code is changed not to use those constants, you should look at the new code, and see how changing it.

Those constants are probably used as defaults for Drupal variables. If those variables can be altered using the settings page of that module, then altering the constants is not necessary.

There are other ways to alter the output of third-party code:

If the module is using those values for a form field shown in a form, another module can alter that form by implementing hook_form_alter(), and associate a different value to that form field.
If the module is using those values in a theme function, another module can override the function used for that theme function, implementing hook_theme_registry_alter(). In Drupal 7, it is also possible to implement hook_preprocess() to alter the variables passed to that theme function.
If the module is using those constants to set a variable used in a preprocess function, another module can implement hook_preprocess() to alter that variable.