How do I hide Bartik Main Menu on front page from unauthenticated users? I have a private website in which content can only be viewed by authenticated users.  All I want is the login box for non authenticated users.  I am using NodeAccess and also Rules module to do this.  Seems to work fine with one exception.  The pages which should only be visible after login show their links to the anonymous user on the Bartik theme main menu right on the home page.  All menu items appear including those for pages specifically limited to administrator viewing.  True, clicking on them merely brings up the login dialog box so the individual can't see the page, however, I don't want the menu itself to appear at all until the person is authenticated. How do I make the entire menu disappear if unautenticated? Thanks in advance.

In case you are using D7, when you configure your menu block, you have a section called "visibility settings".There select the Roles tab and check the option "authenticated user" under "show block for specific roles". Then click save block.

You can insert the Menu as a block and then use the Visibility > Roles settings to hide it for anonymous users.


New custom content type not showing up in 'Create content' menu I have created some new content types but they automatically don't show up in the 'Create content' menu - what do I have to do to get them there. I am currently logged in as user 1 so it shouldn't be a permissions issue.

I think you are facing the same problem I've experienced. Probably you disabled the navigation menu link "Add Content" and its respective sub-menu items. Then, they won't show up at the path node/add.

See this Q/A: No content type problem


Get node alias in template I create a about-us with Basic Page content type, and with path alias aliased it to \about-us( nid = 2),Now in template file I want to get path alias

{{ 'About Us'|t }}

in Drupal 7 I got it with  url("node/2") but what is equivalent in Drupal 8?
what snippet  I have to use to get path alias of nid 2 in template  file ?

You can use path('entity.node.canonical', {'node': dd.nid}) in the template file.

The markup in the template file would look like this.

{{ 'About Us'|t }}

I haven't tried it, but it should work.

You would have to do it in this way:

$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath('/node/2');

Create this variable in the template file and use this path-alias variable where ever you want the alias of the node.

Source - https://www.drupal.org/node/1853148


Execute user_save() after the form submission handler In my implementation of hook_form_alter() I am using the following code; it executes mymodule_user_form_submit() before user_save().

array_unshift($form['#submit'], 'mymodule_user_form_submit');

user_save() is not executing after that.

What is the problem with this code?

I want to execute user_save() after mymodule_user_form_submit().

function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_register_form') {
    drupal_set_message("Form ID is : " . $form_id);
    //$form['#submit'][] = 'custom_user_form_submit';
    array_unshift($form['#submit'], 'mymodule_user_register_submit');
  }

}

function mymodule_user_register_submit(&$form, &$form_state) {
//code goes here
$form_state['field_magentopass']['und'][0]['value'] = $form_state['values']['pass'];
}

if the code is wrong how can i assign the value to this variable $form_state['field_magentopass']['und'][0]['value']

or this entire method is wrong?
should i go for any other alternatives?

In your code, your submit handler ( mymodule_user_register_submit ) and actual function name ( custom_user_form_submit ) are different.

Also, your submit handler is using

$form_state['field_magentopass']

instead of

$form_state['values']['field_magentopass']...

It should be something like

/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  array_unshift($form['#submit'], 'mymodule_user_register_submit');

}

function mymodule_user_register_submit(&$form, &$form_state) {
  $form_state['values']['field_magentopass'][LANGUAGE_NONE][0]['value'] = $form_state['values']['pass'];
}

UPDATE: OP changed their question to use matching function names. Apparently new $user is saved, but field_magentopass wasn't updated.

Lastly, an alternative approach, based on form_set_value and the #validate handler

/**
 * Implements hook_form_FORM_ID_alter
 * User register form id: user_register_form
 */
function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  drupal_set_message("Form ID is : " . $form_id);
  $form['#validate'][] = 'mymodule_user_register_validate';

}

function mymodule_user_register_validate($form, &$form_state){
  $form['field_magentopass']['#parents'] = array('field_magentopass');
  form_set_value($form['field_magentopass'], array(LANGUAGE_NONE => array(0 => array('value' => $form_state['values']['pass']))), $form_state);
}

You have to generate an user object in your submit function.
pass this object in user_save within same function only.


Optimizing CSS Delivery in Theme I ran my site through Google PageSpeed Insights and got the following message:

Optimize CSS delivery of the following:

First it lists two CSS files I don't recognize in /sites/default/files

Second, it lists my font awesome css which I'm LINKING to from my .libraries.yml file, like so:

font-awesome:
  remote: https://fortawesome.github.io/Font-Awesome/
  version: 4.5.0
  license:
    name: MIT
    url: https://fortawesome.github.io/Font-Awesome/license/
    gpl-compatible: true
  css:
    theme:
      https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-
awesome.min.css: { type: external, minified: true }
    bootstrap/assets/javascripts/bootstrap/transition.js: {}

So my question then is two-fold:

Short of using another module such as Addvagg

1) How can I speed up delivery of the font awesome css?

2) What are those other CSS files and how can I speed up delivery of them?

download the font & css files, don't use a cdn
minify and concat your css, additionally you can use sass & gulp to
do the job for you


What's the "Best Practice" approach for disabling secure pages on local Dev? Wondering what the "best practice" approach would be for disabling secure pages on local dev. I'm running a site on Acquia Cloud and have access to the environment variable AH_SITE_ENVIRONMENT and I could easily do something like:

if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
  switch ($_ENV['AH_SITE_ENVIRONMENT']) {
    // case 'dev':
    //   // do something on dev
    //   break;

    // case 'test':
    //   // do something on staging
    //   break;

    case 'prod':
      // do something on prod
      break;
  }
}
else {
    $conf['securepages_enabled'] = 0;
}

Is that the best approach or is there a better, cleaner way? Also, are there negative implications for filling up settings.php with stuff like this?

It's a best practice to create a settings.local.php file which is included at the end of the default settings.php file. Then within that file you can place whatever logic you want per server as you've done, or make the content of settings.local.php be specific per server host you're deploying too (and keep settings.local.php basically outside of version control).

This is a good practice for Drupal 7 development -- so good in fact Drupal 8 ships with such code in settings.php by default, which you can uncomment to make use of:

/** In settings.php for a drupal 8 site */

/**
 * Load local development override configuration, if available.
 *
 * Use settings.local.php to override variables on secondary (staging,
 * development, etc) installations of this site. Typically used to disable
 * caching, JavaScript/CSS compression, re-routing of outgoing emails, and
 * other things that should not happen on development and testing sites.
 *
 * Keep this code block at the end of this file to take full effect.
 */
# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

It's better to maintain separate site folders if you want different configs depending on the server role. In the simplest set-up, name each folder after the domain. Eg:

sites/
      dev.example.com/
          settings.php
      www.example.com/
          settings.php

If you need a more flexible mapping, you should use sites.php to hold the code used to determine which folder should apply.


Nothing is saved in Account settings When I'm at this page "admin/config/people/accounts" I can't change anything of the settings. So I uncheck a checkbox or typ another value in an input. When I click the save button, the page reloads but the settings go back to the values before.

Anyone who knows the problem? Other pages does save my settings, it only appears on the "admin/config/people/accounts".

I use Drupal 8.

Thanks!

In modules check for the hook_user_admin_settings_alter, check the form action and change it for the modules implementing those function

$form['#submit'][] = 'module_user_admin_settings_submit';

For reference sample forgot_username module

Instead of this
$form['actions']['submit']['#submit'][] = 'forgot_username_user_admin_settings_submit';,

use this
$form['#submit'][] = 'forgot_username_user_admin_settings_submit';

In my case, forgot_username module breaks the account savings.

Reference : https://www.drupal.org/project/private_message/issues/2905184
Patch : https://www.drupal.org/files/issues/private_message-admin_settings_submit_handler_beta18-2905184-3.patch


What does this error mean and how can I fix it? I do not know what this "notice" means:

  Notice: Undefined index: content in ds_render_block_field()
  (line 947 of
  /home/magpie/public_html/mysite.com/sites/all/modules/ds/ds.module).
  Notice: Undefined index: content in ds_render_block_field() (line 947
  of
  /home/magpie/public_html/mysite.com/sites/all/modules/ds/ds.module).

I am tempted to just delete the line but I think it is best to check first and verify that it is not important.

Can somebody help explain how errors like this occur? And how to prevent them and deal with them?

It's a notice, not a big deal to make you worry as it says, there is an undefined line in your display suit module

To check what errors mean, you can use Google.  Here's how.

Search for the error message inside double quotes (" ") but don't search for the whole message, just the part up to the line number (why: line numbers may be different depending on the site and you won't get any hits.)  Searching inside double quotes forces Google to only match pages that have the exact phrase inside the quotes.

In this case, make a search like this:

  "Notice: Undefined index: content in ds_render_block_field()"

The first result is an issue explaining the problem on Drupal.org.

That issue shows that the problem is with the Display Suite module.  If you read through the issue linked above, you will find a link to this issue, which is a bug report.  Reading this issue shows that the bug was fixed in a dev version of Display Suite.  So, to fix the problem, you should be able to update to the latest dev version of the Display Suite module.


How to change a collection field value with presave I'm using field_collection module, and $question is a collection field.

$question->value = 'test';
$node_poll->save();

The above code works for update this collection field value. Problem is this cannot be used for presave.

$question->value = 'test';
//$node_poll->save(); // I removed this since it does not need for a presave.

When I use above code for a presave hook. The value did not change.

How to set a value for this collection field with presave with D8?

This code worked for me need to add  in presave hook
//field collection field
  $item = $entity->get('field_items')->value;

$fc = FieldCollectionItem::load($item);

foreach ($fc as $fckey => $field) {
    if ($fckey == 'field_name') {
      $value = $field->getValue();
      $value = strip_tags($value[0]['value']);
      $summary_value = $entity->get('field_fc_child')->value;
      $entity->set('field_fc_child', $value);
    }
  }


Are there terms to distinguish between the different levels of Drupal Core? "Core" seems to cover over a multitude of things, encompassing all the modules that ship with the Drupal code base.  But there seem to be levels of "core"-ness, and I'm wondering if there is official terminology to distinguish between these. For example:

There is the code that is not part of any module.  Does "core" include this officially?  It's not clear to me.
There are required modules: without these (at least in Drupal 7) you can't really build a Drupal site.
There are all the default modules that are part of Core.  You can turn many of these off without a problem, but they're still considered "core".
There are modules that are turned off by default (PHP Filter) and which may even be considered a bad practice to use under normal circumstances (PHP Filter, again).

If I were naming these levels, I might call them

The Drupal Kernel
Deep Core Modules
(Normal) Core Modules ("Core Modules" would include 2 and 4 as well)
Outer Core Modules

But it seems like Dries may have an official terminology already.  Is there such a thing?

I'm not aware of any official definition of the various levels.

I will however, referring to your suggestions, explain a bit about what levels there are.

The Drupal Kernel is actually a component in Drupal 8, which is a Symfony Kernel
"Deep Core Modules" could be the include files that are not even modules. Some files, for example database.inc, bootstrap.inc and module.inc are so fundamental that core cannot function without them. (There are some more .inc files however that reasonably could become modules, I don't know why they are not)
Core modules then, core parts that are written in the same style as contrib modules, but are still so fundamental that core wouldn't work without them. There's a system module that manages a lot of low level administrative functionality. The node module is (in D7) still required. Field sql storage cannot be turned of either.
Outer Core Modules, are all the other things that are shipped with core because they are commonly used, but not necessary for Drupal to function. The forum, taxonomy terms, the user interface for the field system etc.

Again, I'm not familiar with any official terminology, other than all of it being "Core". When people work on core, I only hear references to the individual "components" of core, as specific in the Drupal issue queue.

When I hear "actual core", I think of levels 1 - 3.

If you can't turn the module off, it's Actual Core. If you can, it's Extended Core.


How do I change the permalinks to #1, #2, #3? I would like to change the comment/forum links to something like:

TOPIC:

#1

#2

#3

Do you have any idea on how should I do this?

Advanced forum provides what you are looking for out of the box (a #number permalink in the upper left corner of the post) among tons of other useful features for a forum.

You could either simply use that module, or you could look at it's template files to see how it's done. The relevant code seems to be in includes/advanced_forum_preprocess_comment.inc and looks like this.

  /* Linked post number */
  if (!isset($post_number)) {
    static $post_number = 1;
  }

  $posts_per_page = variable_get('comment_default_per_page_' . $node->type, 50);

  $page_number = !empty($_GET['page']) ? $_GET['page'] : 0;
  if (!$page_number) {
    $page_number = 0;
  }

  $post_number++;

  $linktext = '#' . (($page_number * $posts_per_page) + $post_number);

  // Permalink
  //  You can erase next 3 lines if you wish to use built-in Permalink.
  //  Template adjusted: $post_link -> $permalink
      $uri = entity_uri('comment', $comment);
  $uri['options'] += array('attributes' => array('class' => 'permalink', 'rel' => 'bookmark'));
  $variables['permalink'] = l($linktext, $uri['path'], $uri['options']);

You can type in your css file something like this:

.comment .submitted .permalink{
    display: none;
}

and no more permalink ;)


Drupal 7 form alter required field is not working when i used field from "Add existing field" I have added two fields in to my custom content type using "Add existing field".

For specific URL, I need to set these two fields as Required.

So I have altered my form and set required condition. After setting it, I have printed the form using devel, these fields are having required settings.

$form['field_name']['und']['#required'] = TRUE;
$form['field_email']['und']['#required'] = 1;
dsm($form);

But required condition is not applied.

That is, I could not see red color required indication as well as its not working in the form submit.

Try

$form['field_email']['und']['0']['value']['#required'] = TRUE;

and if not work then try

$form['field_email']['und']['0']['#required'] = TRUE;

You can use Field Validation module:

  This module adds an extra tab to each field instance, allowing you to specify validation rules for your field instances.

Or use hook_field_validate in you custom module.


How to give custom function in D8 custom field widget class? I have created custom fields using field,field widget and field formatters.
One of the field I have created is a button. What I need is to write the submit handler for that button.

This is my CertfieldDefaultWidget.php

namespace Drupal\certfield\Plugin\Field\FieldWidget;

use Drupal;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
 * Plugin implementation of the 'CertfieldDefaultWidget' widget.
 *
 * @FieldWidget(
 *   id = "CertfieldDefaultWidget",
 *   label = @Translation("Certfield select"),
 *   field_types = {
 *     "Certfield"
 *   }
 * )
 */
class CertfieldDefaultWidget extends WidgetBase {
  /**
   * Define the form for the field type.
   *
   * Inside this method we can define the form used to edit the field type.
   *
   * Here there is a list of allowed element types: https://goo.gl/XVd4tA
   */
  public function formElement(
    FieldItemListInterface $items,
    $delta,
    Array $element,
    Array &$form,
    FormStateInterface $formState
  ) {
      //print_r($items[$delta]->cert_fqdn);
      //exit();

 $element['cert_fqdn'] = [
      '#type' => 'textfield',
      '#title' => t('Fully qualified Domain Name'),
      '#value' => isset($items[$delta]->cert_fqdn) ?
          $items[$delta]->cert_fqdn : null,
      '#empty_value' => '',
      '#placeholder' => t('Fully qualified Domain Name'),
    ];
    $element['privatekey'] = [
      '#type' => 'textfield',
      '#title' => t('Private Key'),

      // Set here the current value for this field, or a default value (or
      // null) if there is no a value
      '#default_value' => isset($items[$delta]->cert_key) ?
          $items[$delta]->cert_key : null,

      '#empty_value' => '',
      '#placeholder' => t('PrivateKey'),
    ];

    // City

    $element['csr'] = [
      '#type' => 'textfield',
      '#title' => t('Certificate Signing Request'),
      '#default_value' => isset($items[$delta]->cert_csr) ?
          $items[$delta]->cert_csr : null,
      '#empty_value' => '',
      '#placeholder' => t('Certificate Signing Request'),
    ];
    $element['cert_crt'] = [
      '#type' => 'textfield',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];
    $element['create_cert_btn'] = [
      '#type' => 'submit',
      '#title' => t('Server Certificate'),
      '#placeholder' => t('Server Certificate'),
    ];

$element['create_cert_btn'] = array(
    //'#name' => implode('_', $element['#parents']) .'_create_cert_btn',
    '#type' => 'submit',
    '#value' => t('Create/Renew Cert'),
    '#callback' => '_certfield_button_action'
        );

    return $element;
  }

} // class
?>

In my certfield.module OR CertfieldDefaultWidget.php file I have a function like as below

function _certfield_button_action(&$element, $form_state, $button){
}

But none of them is called when clicks on the Button .Please help me to find out a solution .

Because this is your custom widget, you don't need to create a custom submit function.

Just add WidgetBase::massageFormValues method to your class:

class CertfieldDefaultWidget extends WidgetBase {
  ....
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // manipulate with $values where $values is an array of your fields defined in your formElement.
    return $values;
  }
  ....
}

I'm not certain, but can't you add a submit handler to $form?

Something like
$form['submit'][] = '_certfield_button_action'


view contents flagged by other users I would like to make a view to select the contents flagged by a list of users.

I tried this:
https://www.drupal.org/node/1191228

but it works only for one user at time. I would need that for multiple users.

In the "uid" contextual filter I tried to set "Allow multiple values" in the "more" area, but when I use more than one user ("uid1, uid2" or "uid1 + uid2"), the view is not ran.

any idea?

thank you

Try to uncheck the "require this relationship" checkbox in the relationships of your view


Extreme slow Views rendering time On my Drupal 7 site I have some heavy performance problems. I found out (with XHProf) that the cause of that problem are some Views. The strange thing is: not the query build time nor the query execute time are to slow, but the views rendering time:

Query build time    4.83 ms
Query execute time  3.29 ms
View render time    1175.82 ms

The view is complicated because it has 7 relations. So that its build and execute time is as long as it actually shows up in the example above, is what one would expect. But the rendering can not depend on the complexity of the query, right? But only on the complexity of the resulting array or something else.
So, my question is, where to start to optimize View render time?

ps.: If the view is cached it much faster. But I have to optimize its over all execution time, when it's not cache or can't be cached.

Views can create real bottleneck for scaling and often cause great head ache by becoming resource hungry if not optimized well. Especially the use of Left Joins instead of Inner Joins, the default pagination in views and features like Distinct are major causes for the same.

The below code is a quick sample implementation which probably could fix the join issue in a view.

/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

Also, check if you can enable views cache. You can set the interval to something based on your update frequency or try to clear views_cache when something is updated on the site.

Use of views_litepager instead of the default page can also help, if you are using pagination in views.

There are several things you can do. You could read this detailed post on the topic for a more detailed understanding.


Change from email id when admin approved user account I want to change  FROM Email id, when admin approved an user account.

Currently it is using admin email id. I want to use different email  and my admin email id will remain same

Any Suggestions

I don't have enough reputation to comment, so I am expanding user1081275's answer -

The message id for the confirmation message you want to alter is 'status_activated'.

You can intercept outgoing mail with hook_mail_alter() in a custom module as described at https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_mail_alter/7

function mycustommodule_mail_alter(&$message) {
  if ($message['id'] == 'status_activated') {
    $message['from'] = "mail@whatever.com";
  }
}

Per user.module, the ids for other messages defined by the User module in _user_mail_notify() are:

 *   - 'register_admin_created': Welcome message for user created by the admin.
 *   - 'register_no_approval_required': Welcome message when user
 *     self-registers.
 *   - 'register_pending_approval': Welcome message, user pending admin
 *     approval.
 *   - 'password_reset': Password recovery request.
 *   - 'status_activated': Account activated.
 *   - 'status_blocked': Account blocked.
 *   - 'cancel_confirm': Account cancellation request.
 *   - 'status_canceled': Account canceled.

Try the settings at "site information", admin/config/system/site-information.


Migrate : user update resets user roles Using the Migrate module, I created an import task that creates and updates user info from a csv file. The update is launched using drush.

drush -l http://localhost.atrium.com mi Utilisateur --update

All the users are updated appropriately but the user roles, which are not in the migration mapping, are reset for every user that's updated.

How can I avoid that and keep the user roles for every account that's updated ?

Thanks !

You can add fields to be explicitly ignored by adding addUnmigratedDestinations to your class:

$this->addUnmigratedDestinations(array(
  'roles',
  'role_names',
));

We added these lines after line 162 in the user.inc file to not reset the user roles ...

    //and keep the roles too
    $old_account = user_load($account->uid, TRUE);
    $account->role_names = $old_account->roles;


Ckeditor strips  tags CKeditor strips the <i> tags, and I can't find where in config.js I can put this code.

CKEDITOR.dtd.$removeEmpty['i'] = false

This is a solution for Drupal 7 and the CKEditor module.

Add an empty space -

<i class="fa fa-drupal">&nbsp;</i>

Use &nbsp; and add style word-spacing, because spacer move content to the left

&nbsp;

Lorem Ipsum is simply dummy text of the printing and typesetting industry.


how to show breadcrumbs only on subpage? How can I show breadcrumbs only when the depth level is more than 2.

i.e.:

home > page > subpage => show breadcrumb
home > page => hide breadcrumb

Additionally I would like to hide 'home' also (and always), but this has less priority in my question.

Thanks for your explanation!

Regards,
Hans

If you are using Drupal 7, then you can use:

Path Breadcrumbs
Context path breadcrumb

  Path breadcrumbs module helps you to create breadcrumbs for any page with any selection rules and load any entity from the URL!

  This is a plugin module for the context module. It takes the request URI part of the URL of the current page (for example /our-company/our-team/steve) and uses this path to build the breadcrumbs.

Your best bet is to use the Custom Breadcrumbs module:

  Allows administrators to set up parametrized breadcrumb trails for any
  node type. This allows CCK-style node types to have Home > User Blog >
  2005 > January style breadcrumbs on the node view page itself, synchronizing cleanly with custom views or pathauto aliases.
  Breadcrumb visibility can be customized via a php snippet.


How do I disable caching for the Forum module or, alternatively, how do I fix caching? I use the normal standard Drupal Forum module with a clean Drupal 8 installation. After I have installed it, I have a problem where "2 new posts" shows for all users. In other words, the /forum page is caching and showing the cached page of one user for the other user.

So I have two options

Disable caching for /forum <--- I don't mind doing this for now, as there aren't many users at the moment so I have time to fix this properly later.
Figure out why this page is caching the way it is. As mentioned, I am using a clean installation with hardly any confirm and this still happens.

Can someone confirm if the /forum page normally does this or if something is probably wrong with my installation? Or maybe I'm missing some setting? Or maybe caching is meant to be disabled for this to work?

Any help would be greatly appreciated!

This documentation is the most suitable for your query: https://www.drupal.org/docs/8/api/cache-api/cache-contexts

Please learn all the details on that page and the other associated page. This may resolve your issue.

Thank you.


Slow Search on Drupal 6.x site with 60.000+ nodes We use Drupal 6 for http://www.boekwijs.nl. But when you search for something (which hasn't been searched for before, in other words; not in cache) it's very slow. At the moment there are 60.000 nodes with CCK fields and taxonomy terms.

What is the best way to optimize this? Are there any modules available? Do we need to use another search engine (SOLR?) or maybe another database structure?

60,000 nodes in the search index is definitely a lot. Not only is it slow and suboptimal to use Drupal's default search with such a large number of nodes, but it is going to progressively put more pressure on your infrastructure as you continue adding nodes.

The solution would definitely be to offload your search to another tool. Two options:

Solr: 60,000 is child's play for Solr. It could suffice you for a lot more even on a commodity machine.
Elastic search: Another tool built on top of Apache Lucene. This one's newer and does not have as many supporting modules for it as Solr does (for Drupal). But it is faster than Solr and can handle concurrent commits much better.

In both these cases, I'd recommend installing the search tool on another server.

It is not not required to go for the other module.

I have developed site IDSA, there are 20,000+ nodes and taxonomy terms etc.
Using database indexing for particular row will also affect the searching functionality.

Have you customize search module or apply any hook_query_alter ? This will also affect the result.


Can you suggest any alternative for Statistics module? We have a pretty descend traffic to our Drupal website, approximately 600 page views per minute. We have enabled the Drupal statistics module for storing the node page views.

At peek traffic hours, we observed a high usage of Disk I/O wait, and we doubt that it is due to statistics module. Please correct me if am wrong. If yes, kindly suggest some alternative method to implement node view counter.

Have a look at the Visitors module. Here are some reports you get from it:

  View pages that have recently been visited.
  View pages that have been hit frequently.
  View pages count per month, day of month, day of week, hour.
  ...

Especially these reports should be what you're looking for (it includes hits for paths corresponding to a view):

Top pages (table with columns Title, Path and nr of Hits).
Recent hits (table with columns Date of visit, Title, Path and User ID of the visitor).

Checkout the above (source) links to get an idea of which data are available.

The demo site contains some sample reports (charts) available to anonymous users also. This demo site also shows some additional blocks with reports also created by the Visitors module module.

You may also want to look at the visitors_schema to get an idea of the data that actually get logged (recorded) by this module.

In case it's not a perfect fit, it's probably a very good starting point for some custom reporting. Either via a custom module that would simply have to query the data maintained by the Visitors module. Or via a straight forward custom report created with the Forena module.

Disclosure: I'm the maintainer of the Visitors module,
and co-maintainer of the Forena module.

An alternative is to use

Google Analytics module
Google Analytics Reports module
Google Analytics Counter module
jStats module

  Statistics module saves data into the database and for a high traffic
  site it can make a large number of writes to the database.

You may want to read this thread - https://groups.drupal.org/node/145294

Hope that helps


Add content to the front page in module I made a module, that outputs the data when the user opens a page /courses

function courses_menu()
{
  $items['courses'] = array(
    'title'            => t('Courses'),
    'page callback'    => 'courses_output',
    'access arguments' => array('access content'),
  );
}

function courses_output()
{
  return "some HTML";
}

How can I add this data to the main page below the node contents?

I would either implement a block or if you are using panels create a content pane.

You could just add a call to your function in your page-front.tpl.php :

print courses_output();

It's not the standard way : you should use a preprocess function etc. but it's straightforward.


drupal 7 Ubercart recurring fee settings tab is blank I get an error
on my screen There are no payment methods configured for orders with recurring fees, enable one from recurring fee admin settings.

I then go to the link
cart/checkout#overlay=admin/store/settings/products/edit/features

Next i try and choose the Reccuring fee settings tab but it is completely blank.

Version of UC Recurring Payments and Subscriptions module is 7.x-2.0-alpha3

I am wondering if down grade will that fix the problem.

You may have to enable the module "Recurring - Hosted Gateways". This should be available under section "UBERCART - RECURRING" in the path admin/modules. In my case this is Paypal WPS.

Once the module is enabled you can see the option at admin/store/settings/recurring. You may also need to enable the required payment methods at admin/store/settings/payment.

You can find the configuration under 'admin/store/settings/recurring'


How do I get entity_type and entity_id from any entity page? Some pages (paths) represent one entity. For example:

The pages at these paths represent one node entity, entity_id (nid) is XX:

/node/xx
/node/xx/delete
/node/xx/edit

The page at this path represents one search server entity (defined by search api module), entity_id (machine_name) is 'apache_solr':

/admin/config/search/search_api/server/apache_solr

How do you load in the basic data about this entity (id and type) when the hook or function you are in doesn't hand it to you?

The standard way to get the current entity is apparently to use menu_get_object($entity_type,$position_of_id_in_url). This, however, assumes that you are coding for just one entity type: you need to state the entity type programmatically, and, even worse, you the human being need to research and hard code in the url position of entity ids that this entity uses.

The closest I can find so far is getting the underlying system uri for the page (e.g. substr(request_uri(),strlen($base_path))), then writing a monsterous switch list based on something like this suggestion, guessing and then hard coding cases for every possible entity you think a site might ever have. But there must be something better than that, right?

While a general solution from core would be best, I'll also accept an answer that depends on common modules like ctools (page manager, contexts, etc), Entity API, Devel, etc.

My immediate need is for edit forms, within hook_field_widget_form(), for a widget that can (with appropriate config and modules) be attached to any fieldable entity type. So, while a general solution would be best, I would also accept a narrow answer that only works within this function or in forms (The id and data that is specific to entity type appears to be buried in $form, but keyed in an entity type specific way, so getting it out of $form seems like a chicken and egg problem).

------------ EDIT ------------------

Seems some people have difficulty understanding the simple general problem. Here's an alternate use case (another seperate but related problem I'm facing). Suppose you have a view that lists some entities. This view sits as a block/pane on pages that can represent one entity, such as a node page or a user profile (or both). You've got a hook set up that reads the views data and looks through the results (foreach $view->result as...). Let's say it's hook_views_pre_render, which means you just have the $view object. You want to do something (say, remove the row or change some field data) if the view results row has the same entity id and entity type as the page does. You've got the logic down to extract this data from the view results, so all you need is to look up the entity_type and entity_id of the page being generated, to make a comparison. That data is in Drupal somewhere. If it wasn't, Drupal couldn't have figured out that it needed to load this view. So how do you get it when it isn't passed to the hook or function you are in?

In Drupal Core, you cannot do this. The relevant issue to add such functionality is here.

What core itself does is always passing around two arguments:

function($entity, $entity_type)

The real answer to this question depends on why you need the data, and at what layer of the API layer cake you're operating.

If you want the entity for a page, you can't do that. A given page could have many entities on it. (Every node, comment, taxonomy... are all entities.)

If you're using hook_field_widget_form(), then you're implementing a field in the Field API, and your answer is in the documentation: Entity type is $element['#entity_type'], and you can't grab the entity ID, since fields implementing the API shouldn't concern themselves with that.

So: Why do you need the entity id?


Calculate percentage based on two fields, one of which is an embedded view I am trying to calculate a percentage based on two fields in my table. I am using views and I have a table which has 2 fields, one field is an aggregation of of all records and the other is an embedded view which has another number - I used the Views Field View module for embedding the field.

How can i get a percentage between these 2 fields. The Math Expression field is not supported in drupal 8 and I have also tried the views_simple_math_field and it didn't help me at all. Please help!

i tried in output code:

<?php
echo count($row->field_a) + count($row->field_a) ;
?>

and the result is:

I modified the view, and used aggregation.

I modified the field a:

I modified the field b:

I modified the field php:

And the code:

And result:

if you want sum two field, you install the module:
https://www.drupal.org/project/views_php

As an example, add two fields in your content "basic pages":

field_a
field_b

I create a content of example: nid = 43

Please create a new view as is the image.

in your field "Global: PHP (php)"
in the section: "Output code".

sum two fields please use the following code

<?php
echo $row->field_a +$row->field_a ;
?>

preview


How do I make a form in Add Content using Drupal 7? I am trying to get my Drupal 7 website working with PHP and an external database. I would like to have user interaction via forms, but all the examples I can find on the web hint that you have to write your own module to do this. I couldn't find a good description of even that process from the ground up. Is there a way to add a form using the standard Add Content -> Article or Basic Page? Is that a bad way to do things? I would like a page that is a form and when the user presses the submit button the same page loads, but now with the data retrieved from the database that was requested.

I'm not sure if you really can do this with it, but have a look on:
Webform

no. I thought you want to do this in your custom module .
 if you not  very skillful in module developing  I suggest you use php block.
enable PHP filter module  in default core drupal module, then create a block  in Home » Administration » Structure » Blocks
put this in body
change nodetype to your optional contenttype you have

  <?php
   module_load_include('inc', 'node', 'node.pages');
   $form = node_add('nodetype');
   $output = drupal_render($form);
   ?>

and in text filter select php filter .save it and in block list put it in your optional region and determine Visibility settings with you optional.


Programatically set the language I'm trying to automate the setup of Drupal multi-site installations as much as possible, we're using each multi-site for a separate country so would like the languages localised for each.

Is there a way to programmatically set the default language? It normally defaults to English. For a Spanish multi-site I would like to set it to Spanish.

The default language seems to be set in SelectLanguageForm.php .Since this happens so early on in the installation process, I can't use hook_form_alter() because no modules, profiles, or themes would be loaded at that point.

The default language will be defined basing on the subdomain where Drupal is going to be installed.

You should consider using Drush (or Bash running Drush) for that. With drush site:install you can set the default language via --locale.

The following command will (re)install Drupal using the expert install profile and set default language to Ukrainian.

drush si expert --locale=uk

Source: https://drushcommands.com/drush-9x/site/site:install/

drush config:set system.site default_langcode en


How to change "add to comment" in comment form? When CCK was not in core, as in Drupal 6, and you selected a node type for comments on other node types, the comment form would say the name of the content type instead of comment. In this case, I want the comment form to say 'Add New Review' instead of 'Add New Comment'. Does anyone know how to do this through a module or configuration?

Create a seperate .tpl file for comment-wrapper named comment-wrapper.tpl.php.

To create a seperate template file for node specific comment wrapper you can create using
comment-wrapper-contenttype.tpl.php copy the code from core comment-wrapper.tpl.php and change the title in the code given below.

While copying from core comment-wrapper.tpl.php don't forget to remove the validation which is meant for forum node types only.

<?php print t('Add new comment'); ?>

You could do it from the comments-wrapper.tpl.php (or check comments.tpl.php too) file in the comments module (/modules/comments)


Use EntityFieldQuery to load by node ID How to use EntityFieldQuery to load the nodes based on available nids. I tried,

$query->propertyCondition('nid', $nid);

and

$query->entityCondition('nid', $nid);

Both of the above didn't work. What would be the right way?

There's no point doing that, use node_load() or node_load_multiple() instead (or entity_load()). EFQ exists to return you the IDs of entities, essentially so you can use them in an entity load function. If you already know the ID beforehand, then using EFQ is a waste of a database query.

To illustrate, if you were to add a nid condition to your query, then these:

->entityCondition('bundle', 'article') // ex. article
->propertyCondition('uid', $uid) // node written by a specific user
->propertyCondition('status', 1);

are all redundant, your query will just be:

$query->entityCondition('entity_type', 'node')->propertyCondition('nid', $nid);

and the only useful data you'll get is the node ID, which you already have.

You only need to pass a node ID to propertyCondition.

$query->propertyCondition('nid', 886);


Alternate way to get form without using drupal_get_form I want to get a custom addto_cart_form in one of (commerce_addto_cart_confirmation) the popup. I used drupal_get_form to get that but unfortunately I cant able get the form on popup. I asked those question here but not get any response also. So now I want is there any alternate solution to get form. refer my old question1 and question2here. Thanks for any suggestion.

I don't belive you that mine work in any places

$form = drupal_get_form('yuor_form');
print drupal_render($form);

You can create block with form and output them where you want, somthing like that

function your_module_form_theme() {
  return array(
      'yuor_form' => array(
          'render element' => 'form',
          'template' => 'your_form',
          'path' => drupal_get_path('module', 'your_module_form') . '/templates',
      ),
  );
}


URL redirect module working fine with nodes not with alias url's I am new to Drupal. I have installed URL Redirect module and tried the following.

Source URL: testwebsite.com/how

Redirect URL: testwebsite.com/how-to-do

Its get stored with node id instead actual URL.

Source URL: http://www.testwebsite.com/node/123545

Redirect URL: http://www.testwebsite.com/node/134566

When I tried to call with node URL its redirecting fine. But when I call testwebsite.com/how it doesn't redirect.

You can use Path Redirect module in your scenario. Module page says :

  This module allows you to specify a redirect from one path to another
  path or an external URL, using any HTTP redirect status.


display a view in admin theme I have a custom view for editing contents for the authors. When I'm logged in as a use with this author role this view is displayed with the 'frontend' theme. But I need it displayed in 'backend' theme.

I absolutely don't know how to get this view displayed in another theme.

Go to Admin -> People -> Permissions & search View the administration theme check the checkbox for author role. Check screenshot below:

You can use themekey. This module allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path


How to hide the "trimmed version" from the preview page? When I "preview" a node add/edit form it shows a "trimmed version" and a "full version". I don't want to show the trimmed version.

The fix suggested for D6 doesn't work for D7. Any ideas?

You tried CSS?

.preview h3 , .preview .node.node-article.node-teaser {display: none}

In my case the content type is an article and worked.

You can use this also:

jQuery(document).ready(function($) {
  $("#console").hide();
  $(".preview h3").hide();
  $(".preview .node-teaser").hide();
});


How to find all views and panels that use a certain field I want to delete a field but I am not sure if there is still a view or a panel somewhere on the site that is still using it. So I want to know if there is any possibility to find all views and panels that use a certain field?

In D7, you can see this for views at least at
/admin/reports/fields/views-fields (Admin -> Reports -> Field list -> Used in views)

(Similarly for content types it is at
/admin/reports/fields/ (Admin -> Reports -> Field list)

Don't know about panels though.

This module may help you Field Tools

It will allow you to see an overview of fields with links to edit single instances, and all instances at once.


Group sub sub theme CSS separately I have a base, sub theme, and sub sub theme. I don't want the sub sub themes CSS to be grouped to CSS_THEME due to support for legacy IE browsers and the issues associated with large CSS files.

$value['group'] = 100 = CSS_THEME = (Theme-Layer CSS)
$value['group'] = 0 = CSS_DEFAULT = (Module-Layer CSS)
$value['group'] = -100 = CSS_SYSTEM = (System-Layer CSS)

Possible to add to this with a different weighting?

$value['group'] = 200 = CSS_SUB_THEME = (Sub Theme-Layer CSS)

Adding CSS to separate group.

  // Add sub sub theme css to separate group.
  drupal_add_css(PATH_TO_THEME/sub_sub_theme.css',
    array(
      'group' => CSS_SUB_THEME,
    )
  );

NOTE: not looking for related answers to legacy IE browser limitations as solutions such as css_splitter are already in place, simply can the above be done or is there a good reason you can't.

May not be the answer you're looking for but have you considered Advanced CSS/JS Aggregation as one of the features is "Prevent more than 4095 CSS selectors in an aggregated CSS file (IE 6-9 limitation)"


Edit account creation message I'm trying to change the message users see after creating an account. It currently says:

Thank you for applying for an account. Your account is currently pending approval by the site administrator.
In the meantime, a welcome message with further instructions has been sent to your e-mail address.

What's the best way of changing this? Would the String Overrides module help? A Rule, perhaps?

Many thanks.

This is exactly what the String Overrides module is for.

If you only need just a couple strings, you can also use settings.php.  See this section:

/**
 * String overrides:
 *
 * To override specific strings on your site with or without enabling locale
 * module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 *
 * Remove the leading hash signs to enable.
 */

You don't want to use Rules, because although you can add a new message with a rule, the old message will still be there as well (which isn't what you want, I assume).

You can change those messages in Configuration>Account settings (admin/config/people/accounts).
There is E-mails section where you can change messages used during account registeration process.


How do I get the content type name using code? I'm working on Drupal 8 and I want to get content type machine name and label. Here is my code:

$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->name;
  $machine_name = $key;
}

I get the following error message:

  Cannot access protected property Drupal\node\Entity\NodeType::$name

Hoe can I get the content type name?

To get a property, there is ConfigEntityBase::get(). Since ConfigEntityBase is a base class for NodeType, you can always use $value->get('name') to get the value of the name property.

To get names of content type you can use below function

node_type_get_names();


Upgrade Commerce Kickstart 1 site with drush From http://www.drupalcommerce.org/blog/9072/updating-commerce-kickstart-2 I learned that it's possible to upgrade a CK2 site using drush.

Is it possible to do a minor upgrade od CK1 using drush dl --select commerce_kickstart and selecting the proper version? I tried and failed.

According to this page http://www.drupalcommerce.org/commerce-kickstart-2/install you should use Drush 8.x-6.x for an upgrade.


Views exposed Filter by date: month OR year If i make an exposed filter with a date-field, i can only select date and month together. Not on year or month. How can i make it by year OR month?

You should be able to add the same filter twice and set one to a Month granularity and the other to a Year granularity. Then you can rearrange the filters and setup an OR grouping and place the year in that one


How can I get translation for a field of custom date I am using the paragraphs module. I have a field which contains a date and time e.g. for events, which is added by an author. For the output I use a paragraph-twig-file and I have this:

<div class="timeline-date">
    {{ content.field_date }}
</div>

In the backend of Drupal I created a custom time "D, d.m.Y - H:i". The output is right e.g. "Fri, 24.08.2018 - 17:14", but my site is in german and not english. So how, can I translate the day of week in german?
In my case this solution is not working

In Twig, you can use built-in translation contexts. I had to output my dates in dutch format. The default formatting was:
{% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F") ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 August 2020

When I use translation contexts, it worked as expected:
{% set date = node.created.value|date("j") ~ ' ' ~ node.created.value|date("F")|t({}, {'context' : 'Long month name'}) ~ ' ' ~ node.created.value|date("Y") %}
// now {{ date }} outputs: 8 augustus 2020

More about translation contexts in Twig: https://stefvanlooveren.me/blog/translate-dates-twig-drupal-8

You need to do something like below screenshot in my case i have translated months of date field in french language.

you have to search for day string for different language like fri ,replace the text for each language in text box then save to path admin/config/regional/translate


How do I change the default value of a field with AJAX? Related to my previous question: Form fields created via Ajax are missing element attributes

I have a date field and a series of text and number fields which need their default values to change based on the value of the date field. I've updated my code so it functions this way:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['date'] = array(
        '#type' => 'date',
        '#ajax' => [
            'callback' => '::dateCallback',
            'wrapper' => 'wrapper',
        ],
        '#default_value' => date("Y-m-d")
    );
    $form['wrapper'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'wrapper'],
    ];

    //insert logic to determine value of a variable called $field1
    $form['wrapper']['options'] = array(
        '#type' => 'fieldset',
        '#attributes' => array('class' => array('options'))
    );
    $form['wrapper']['options']['field1'] = array(
        '#type' => 'textfield',
        '#title' => "Field 1",
        '#value' => $field1
    );
    $form['wrapper']['table'] = array(
        '#type' => 'table',
        '#title' => t('Table'),
        '#header' => array("H1", "H2", "H3"),
        '#attributes' => array('class' => array('custom-table'))
    );
    //insert logic to generate table rows
    return $form;
}

/**
 * Implements callback for Ajax event on date selection.
 *
 * @param array $form
 *   From render array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Current state of form.
 *
 * @return array
 *   Date selection section of the form.
 */
public function dateCallback(array &$form, FormStateInterface $form_state) {
    return $form['wrapper'];
}

There are 2 problems I am having with this:

1) Implementing it in this way, such that the #value property is changed when the date field is changed, technically works, however if the user then chooses to modify any of the textfield values, that is not reflected in the $form_state object and is overridden by whatever #value was last set to in buildForm().

2) I have also tried using #default_value instead, but the value in the field will not update if it already has something in it (which it usually does from the first time #default_value is set in buildForm()). I have seen some threads like this one suggesting to unset the value in $form_state before setting #default_value again, however all such suggestions are for Drupal 7 where $form_state is a completely different data structure.

Is there a known way to do what I am trying to accomplish?

Update: I tried method 2 again by adding $form_state->unsetValue('field1'); before declaring $form['wrapper']['options']['field1'], but this did not change the behaviour.

Method 1 setting #value does indeed make it impossible for the user to input data.

So the method 2 setting #default_value is I think still the best approach. As the old trick from D7, unsetting the value in $form_state, doesn't work anymore, you can try this one:

Create the field in a subkey, which is incremented for each request. Set the property #tree on the first level of the field, so you get back the field value as array [$key => $value]:

$form['wrapper']['options']['field1']['#tree'] = TRUE;

if ($form_state->hasValue('field1')) {
  $key = key($form_state->getValue('field1'));
  $value_field1 = current($form_state->getValue('field1'));
  $key++;
}
else {
  $key = '0';
  $value_field1 = NULL;
}

// insert logic to determine new field value
// but check, if there is user input in $value_field1, that you don't want to overwrite

$form['wrapper']['options']['field1'][$key] = [
  '#type' => 'textfield',
  '#title' => 'Text 1',
  '#default_value' => $value_field1,
];

A solution to append a default value to the field after callback but with option for user to change input:

add the value to field attributes: '#attributes' => array('value' => array($form_state->getValue('option2'))),

        $o = [];
    $form['option1'] = array(
        '#type' => 'select',
        '#size' => 1,
        '#options' => ['a' => 'A', 'b' => 'B'],
        '#title' => $this->t('option 1'),
        '#required' => TRUE,
        '#ajax' => array(
            'callback' => array($this, 'next'),
            'wrapper' => 'option2',
        ),
    );

    if ($form_state->getValue('option1') == 'a') {
        $o = [1 => 'one', 2 => 'two'];
    }
    if ($form_state->getValue('option1') == 'b') {
        $o = [3 => 'three', 4 => 'four'];
    }

    $form['option2'] = array(
        '#type' => 'select',
        '#size' => 1,
        '#options' => $o,
        '#title' => t('option 2'),
        '#required' => TRUE,
        '#prefix' => "
 '
',
        '#ajax' => array(
            'callback' => array($this, 'get_data'),
            'wrapper' => 'data',
        ),
    );

    $form['data'] = [
        '#type' => 'textfield',
        '#id' => 'test',
        '#title' => t("choice") . " " . $form_state->getValue('option2'),
        '#default_value' => $form_state->getValue('option2'),
        '#size' => 5,
        '#attributes' => array('value' => array($form_state->getValue('option2'))),
        '#prefix' => "
 '
',
    ];

    $form['actions']['submit'] = array(
        '#type' => 'submit',
        '#value' => $this->t('Test'),
        '#suffix' => ''
    );

    return $form;
}

/**
 * callback functions
 */
public function next(array &$form, FormStateInterface $form_state) {
    return $form['option2'];
}

public function get_data(array &$form, FormStateInterface $form_state) {
    return $form['data'];
}

public function validateForm(array &$form, FormStateInterface $form_state) {

}

public function submitForm(array &$form, FormStateInterface $form_state) {
    dpm($form_state->getValue('data'));
}


Impossible to add new content I migrated my web to webhosting. There is a problem when I want to add new content, it's not able to add new content with images or files. Do you know where to look to solve it? Does it relate to access rights to directories where Drupal stores those files or is it something else?

When I want to upload an image, it writes:

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access public://image.jpg in file_save_upload() (line 1528 of /web/www/x.y.com/includes/file.inc).
File upload error. Could not move uploaded file.

thank you

review permissions in the /sites/all/files directory. you can test inside files directory, changing permissions to test the correct permissions. for example you, for test, can change to 755 in recursive mode: chmod 755 files/ -R. also review the owner of directory. According my experience, the owner can be a cause.

(According I remember, permission 777 number is the most higher number, but not is recommended).

Please define "it's not able to add new content with images or files" ? was the content save failed or only the image failed to attach ? I suggest you check Drupal status report.


Simple way to add a class to the body when creating/editing an entity In Drupal 8.4, I am trying to add a class to the body (like Drupal 7 had) when the page viewed is a node (or entity for that matter), something like [entity]-[create or edit], so that, when a user is editing or creating a node, a class like page-node-edit gets added to the body classes array.

You can use hook_preprocess_page and check the current route:

function mymodule_preprocess_page(&$vars) {

  $route_name = \Drupal::routeMatch()->getRouteName();

  // This would add a class based on the route.  You'd need the
  // pathauto module enabled.
  $vars['page_classes'][] = \Drupal::service('pathauto.alias_cleaner')->cleanString($route_name);

  // This would add the classes asked for in the question.
  if ($route_name == 'entity.node.edit_form') {
    $vars['page_classes'][] = 'entity-edit';
  }
  elseif ($route_name == 'node.add') {
    $vars['page_classes'][] = 'entity-create';
  }
}

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    user.getRoles()|join(' role-'),
    'edit' in url('<current>')|render|render ? 'page-edit'
  ]
%}


How do I add taxonomy terms and vocabularies to an exportable deployment plan? I'm in the process of developing an installation profile for a new site. We're using Features to export much of our functionality, and are very interested in using the Deploy module integration with UUID to handle the thorny issues stemming from exported content not having the same unique IDs on multiple deployments. Being able to export entities into a deployment plan and import them with Features would be an absolute godsend, and this is working with basic node content from what I've seen so far (I'm familiar with the concept of creating a fetch-only deployment plan and exporting it later).

However, I have a content type that references multiple taxonomies, each with a closed, pre-defined vocabulary. These vocabularies (and their terms) need to be exported, so that they can be referenced by the appropriate fields (for instance, a list of terms representing venues should be selectable from a drop-down). I haven't yet found a way to add these to a deployment plan, despite hearing on the soon-to-be-deprecated UUID Features issue queue that this should be possible. Is there something I've overlooked, or is there a better approach?

I seem to have stumbled my way through to a solution. Vocabularies don't need to be exported via UUID, as they already have their own machine name, but any terms within those vocabularies still need to be added to a deployment plan so they can be exported (inadvertently adding a vocabulary to the plan throws errors).

Using the latest development snapshots (as of March 14, 2012) of UUID, Deploy, Entity Dependency API, Views and Rules, it is possible to stitch together a UI for adding taxonomy terms to a plan. First, a managed fetch-only deployment plan must be created.

Next, a Rules component must be created using Rules, with a taxonomy term as a single parameter and a single action that adds the entity to the selected deployment plan. Note, however, that the current development snapshot of Deploy does not allow you to use Rules to add to a fetch-only managed deployment plan (I had to write a trivial patch that allows this behavior).

Next, one should create a view of all taxonomy terms, adding a Bulk Operations checkbox using Views Bulk Operations. If you have created your Rules component as above, VBO will allow you to select your component as a task to perform on all checked entities.

Now that your form is configured, all that's left to do is visit the view and add the necessary taxonomy terms, and select the relevant components to export via Features. Gotcha: There is no dependency checking in Features after adding the taxonomy terms via uuid_entities. You have to remember adding the vocabulary yourself, or tragedy and error messages will ensue.

For Drupal 7 :

There are a few ways to do this

If you are importing the terms from another Drupal site use Node
export module - drupal.org/project/node_import
If you are planning to export or import from a csv file :
drupal.org/project/taxonomy_csv
If you just want to cut and paste the list (one per line) and add to
a vocabulary : drupal.org/project/batch_add_terms


How do I specify in which database my schema should be created? When using multiple databases in Drupal 7, how can I specify that a table is to be created in a different database on a different server?

By default, when you install a module, Drupal assumes that everything in hook_schema() should be installed in the default database. Is there a way to specify that a table should be created on a different database, or is there some kind of manual workaround I can use?

I have achieved this with the information provided by Berdir. My code looks like:

<?php
function mymodule_schema_otherdb() {
  $schema['mytable'] = array(
    'description' => 'My table description',
    'fields' => array(
      'myfield' => array(
        'description' => 'My field description',
        'type' => 'serial',
        'size' => 'medium',
        'not null' => TRUE,
        'unsigned' => TRUE,
      ),
    ),
    'primary key' => array('myfield'),
  );
  return $schema;
}

function mymodule_install() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_create_table($name, $table);
  }
  db_set_active();
}

function mymodule_uninstall() {
  db_set_active('otherdb');
  $schema = mymodule_schema_otherdb();
  foreach ($schema as $name => $table) {
    db_drop_table($name);
  }
  db_set_active();
}

In Settings.php
$db_url=array('default'=>$db_url, 'sec_db'=>$sec_db_url);
In hook_schema db_set_active('sec_db') will now connect to your another DB , not sure if this is recommended or not try it at your own risk.
And you can make use of db_prefix to query from this secondary DB.
You can make use db prefix in settings.php


Show block in /user/* page, not /user/*/edit From the Drupal 8 administration, I configured a block (block created from a custom module) for display it in /user/* pages.

It works; I see this block in /user/* and /user/*/edit pages.
Now, I want to display my block only from /user/* pages (the view mode), not from /user/*/edit pages (the edit mode).

Can I do that from the Drupal Administration page? I tested it adding "!/user/*/edit" but this has no effect.

If I can't, how can I do that from my custom module?

If you use this module then the exclamation prefix would work to exclude paths: https://www.drupal.org/project/block_exclude_pages

Why don't you try just to hide on the pages you don't want it to be displayed instead of using "Show for the listed pages"? Change the option with "Hide for the listed pages" and add there user/*/edit and every other page where you don't want that block to be displayed.


Redirect to the front page with a different language i have a question about redirecting to a page with a different language. I found this old post for drupal 7 but I doesn't really help me - https://www.drupal.org/node/1280468

Now we are in Drupal 8 and the redirect works like this:

return new RedirectResponse(\Drupal::url('<front>'))

But how can I set the language for the redirect? In my code I have the languagecode like NZ for New Zealand.

You can try this code

 <?php

 use Drupal\Core\Url;
 use Symfony\Component\HttpFoundation\RedirectResponse;

 $language = Drupal::languageManager()->getLanguage('vi');
 $url = Url::fromRoute('<front>', [], ['language' => $language]);
 $response = new RedirectResponse($url->toString());
 $response->send();

Within your controller method:

$url = \Drupal\Core\Url::fromRoute('<front>')->toString();
return new RedirectResponse($url);


Next link on node page based on its taxonomy term So here is what I'd like to achieve:

I'd like to put a Next link to every content of a type, that links to the next content with the same taxonomy term.

So for examle if I have A, B and C products with the term 'clothing' on them, I need a link A product that points to B, one link on B that points to C and so on.

How is this possible to do?

It's only in Alpha but the Treewalk Previous / Next module appears to have that functionality:

  Previous/Next (Back/Forward) links for entity and other pages, that allow to visit them in a sequence.

  Unlike with the existing back/forward module, the sequence of items (entities etc) is not based on a view, but on hierarchical information already present in your site.

  It provides a configurable block with prev/next links based on menu trees. The block is named "Treewalk Prev/Next (Menu)"
  It provides Display suite fields with prev/next links based on entityreference / taxonomy_term_reference fields. The ds fields are named as "Treewalk Prev/Next (...)".

I've never used it but it might at least be a starting point to implement the logic yourself.

You can use the Flippy module for this.

  Flippy is an ultra-simple module that generates previous/next pagers for content types. On the Node type administration screen, you can turn Flippy on or off
  for each content type. It'll generate a unique pager for each content type, so you can page through Articles or page through Blog posts, but you can't page
  through all nodes on the site.


Custom view sort plugin not working only when used in table sorting We have a view of committee memberships (= custom entity). The committee memberships hold references to the committee and the politician and have a field "role". In a view we want to output all committee memberships in a logical order: chairperson first, the vice chairperson, foreperson, spokesperson and member. As you can see alphabetical order is not suitable.
We defined a custom view sort plugin which is playing nice on simple views where the sorting is set in the views configuration. However on a table view when selecting the column for the sorting by role it is not called.
Examples:

https://www.abgeordnetenwatch.de/bundestag/19/ausschuesse/1-untersuchungsausschuss-terroranschlag-auf-dem-breitscheidplatz - the sorting is correct
https://www.abgeordnetenwatch.de/bundestag/19/ausschuesse/1-untersuchungsausschuss-terroranschlag-auf-dem-breitscheidplatz/tabelle#filterbar the committee members are sorted by last name by default (we will change this)... when you click on the last column heading "Rolle im Ausschuss" it should be the same order as the first example. But it is sorted by the key of the role stored in database. "Stellv. Mitglied" has the key "alternate_member" in database that is why these members come first in this table

We defined the plugin in the following way in a class extending EntityViewsData:
$data['committee_membership']['committee_role']['sort']['id'] = 'sort_committee_membership';

The plugin is that:
/**
 * Sort handler for sorting committee memberships by list key position.
 *
 * @ingroup views_sort_handlers
 *
 * @ViewsSort("sort_committee_membership")
 */
class SortCommitteeMembership extends SortPluginBase {

  public function query() {
    $this->ensureMyTable();
    $field_storage = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('committee_membership')[$this->field];
    $allowed_values = array_keys(options_allowed_values($field_storage));
    $formula = 'FIELD(' . $this->tableAlias . '.' . $this->field . ', ' . implode(', ', array_map(array(Database::getConnection(), 'quote'), $allowed_values)) . ')';

    $this->query->addOrderBy(NULL, $formula, $this->options['order'], $this->tableAlias . '_' . $this->field . '_keys');
  }

}

Is there something missing which is needed to implement when the sorting is exposed?!

The problem is that for click sorting it seems that not the view sort plugin is used but the field handler which holds a method clickSort
So here is the solution:
1.) I defined a custom field handler. This can be done in hook_views_data or hook_views_data_alter. I did it in my custom views EntityViewsData extending class:
$data['custom_entity']['committee_role']['field']['id'] = 'committee_role';

2.) Then I defined the field handler class where clickSort can be overwritten.
use Drupal\Core\Database\Database;
use Drupal\views\Plugin\views\field\EntityField;

/**
 * @ingroup views_field_handlers
 *
 * @ViewsField("committee_role")
 */
class CommitteeRole extends EntityField {

  public function clickSort($order) {
    // No column selected, can't continue.
    if (empty($this->options['click_sort_column'])) {
      return;
    }

    $this->ensureMyTable();
    $field_storage = \Drupal::service('entity_field.manager')->getFieldStorageDefinitions('committee_membership')[$this->field];
    $allowed_values = array_keys(options_allowed_values($field_storage));
    $formula = 'FIELD(' . $this->tableAlias . '.' . $this->field . ', ' . implode(', ', array_map(array(Database::getConnection(), 'quote'), $allowed_values)) . ')';

    $this->query->addOrderBy(NULL, $formula, $order, $this->tableAlias . '_' . $this->field . '_keys');
  }
}

After clearing the caching the results in the table are sorted the same way as in the other view. Strange that there is an additional sorting logic in views when a table display is used and the sorting is done via column headers.

A solution could be, to take use of the search_api module.
After you've indexed the entities you want to display in the view, you can create a view based of the indexed items. That way you can get rid of the key, and only use the values. And no programming required.
As a bonus you get all kinds of sorts and facets to play around with.


How do I use Views Global Filter with Geofield 2.x Exposed Proximity Filter? I am trying to set it up so that a views global filter  https://drupal.org/project/global_filter can set the distance and city for the proximity filter for Geofield? What are the steps to do this?

Add a filter that precedes that filter that is not exposed and creates the initial filter you want. Usually you can do this with most views handler filters, so it should work with the proximity filter.


Clear region with menu's per url cache I have a region with menus, a menus displays depending on the url example if on the about page(sitename/about-us), display about menu and links as a sub menu.

It works, but the problem is after navigating through the site a couple of times, the region caches. is the anyway i can clear the regions cache on page reload.

I tried the below in my .theme

   /**
   *  Implements hook_preprocess_HOOK() for block.html.twig.
   */
  function themename_preprocess_block(&$vars) {
    //the menu block id name in the region
    if ($vars['derivative_plugin_id'] == 'submenu') {
      //-- This stops the block being cache in drupal 8
      $vars['#cache']['max-age'] = 0;

    }
  }

also tried

  /**
   * Implements hook_preprocess_HOOK() for block.html.twig.
   */
  function themename_preprocess_block(&$vars) {
    if ($vars['derivative_plugin_id'] == 'theme-block-branding') {
      //-- This stops the block being cache in drupal 8
      $vars['#cache']['max-age'] = 0;
    }
  }

not sure what steps I can follow to achieve the above

Add code below:

class MYCUSTOMBLOCK extends BlockBase {
  public function build() {
    return array(
      '#markup' => '', // the content of your block
    );
  }
  public function getCacheMaxAge() {
   return 0; // No caching gets applied here
  }
}


Simplenews logs out when sending test newsletter I am trying to send a test newsletter through simplenews and it logs me out from my website everytime I hit the send button. I am logged in as admin. I have successfully sent test newsletters before and I dont think it is a permissions issue since I have necessary permissions.
The only thing I changed was install simplenews related modules like simplenews-statistics,etc. I also copied the .tpl.php files from simplenews's module folder to my theme folder.

What could be the problem?

I found out that the problem occurs when I use custom .tpl.php templates. I deleted the statistics module and .tpl.php files from my theme's folder. So, I am using the default .tpl.php files provided by Simplenews and it works.

Now, I need to figure out why I can't use custom template files.

I had the same problem after upgrading to Simplenews 2.x. Turns out there was a conflict with Simplenews Analytics. Once I disabled Analytics, the problem went away.


How can I get a views exposed filter to persist across multiple views? I have 2 separate views that return a set of results for each of my content types. The fields are different, but the filters are exactly the same - Sort by Location / Distance. This Distance / Proximity filter is exposed, and it is set to 'remember' the last entry. I followed the tutorial here http://drupal.org/node/359463 to be able to filter results by distance. It works great.

In views, to remember the last entry, Views uses sessions. But, each view has its own individual $_SESSION variable. That means what I set for one view does not carry over to the next, and even each view can have different values, which is not what I want. Here is a dump of the session after they have been set:

[views] => Array
    (
        [search_pages] => Array
            (
                [default] => Array
                    (
                    )

            )

        [baby_clothes_pages] => Array
            (
                [default] => Array
                    (
                        [distance] => Array
                            (
                                [postal_code] => 11211
                                [search_distance] => 100
                                [search_units] => mile
                            )

                    )

            )

        [baby_gear_pages] => Array
            (
                [default] => Array
                    (
                        [distance] => Array
                            (
                                [postal_code] => 22343
                                [search_distance] => 100
                                [search_units] => mile
                            )

                    )

            )

    )

What I would like to do is create a small module or snippet of code that will simply allow someone to type in their 5 digit zip code and then it update all the values across all my pages with this filter. If it is changed on any page, then it changes it for the rest of the pages as well. It also needs to work so that it affects the results on the next page load so that it correctly shows them filtered.

Here is a snippet of code I was experimenting with to try to set this value, but it's the wrong direction.

 $all_views = views_get_all_views();            // get an array of all views in use on the site

foreach ($all_views['category_pages']->display as $key => $value) {
 //check to see if the structure exists I am looking to modify
if(array_key_exists('postal_code', $all_views['category_pages']->display[$key]->display_options['filters']['distance']['value'])) {

//if so, set its value
$all_views['category_pages']->display[$key]->display_options['filters']['distance']['value']['postal_code'] = '28152';

//try setting the session instead
$_SESSION['views']['category_pages'][$key]['distance']['postal_code'] = '28152';
    }

What's the correct direction? How do I get this value changed? Could it be done in the template.php file with preprocess function? Should I do it in a module, and if so, what do I need to alter?

Very lost at this point. Thanks for the direction!

It sounds like you would need to save the value somewhere. Next when a page load event happens (on any page of your site) you need to load the value into the field. I think you might need to create a cookie to do this.

$view->exposed_input['distance']['postal_code'] = $_SESSION['zipcode_filter']['zip'];

can explain better which are this variables
['distance']
['postal_code']
['zipcode_filter']
['zip']

I have two views, 2 display, page_1 e page_2 with path_1 e path_2;
everyone have own exposed filter (same settings)
on page_1 if I use I have this url
/path_1?filter_identifier_1=18      (when is selected id term 18)

if I change display view url and select exposed I have this
/path_2?filter_identifier_2=18

I have only page variables and name filters and must remember every time that the page change, the previous filter value selected

so code must to be similar at this?

$view->exposed_input['page_1']['filter_identifier_1'] = $_SESSION[previous_page][previous_filter_identifier_value];

$view->exposed_input['page_2']['filter_identifier_2'] = $_SESSION[previous_page][previous_filter_identifier_value];

this if I leave both the exposed filter (first steps for understand how work)

previous_page  how can know this variable ?
(in the example ther are only 2 display, but how when more?)
previous_filter_identifier_value  how can know this variable ? is sufficient write only filter identifier name?

other:seen that I must have only one exposed, how can use $view->exposed_input
for to set the 2nd filter if isn't exposed and not have the filter_identifier ?

........


Validation message on Login form not shown I am using Drupal 7. When ever I visit site.com/user/login I could see my Login form, thats fine. But when I miss to enter any fields say name and click the login button it does not shows the validation error message. Does any one what the actal problem might be?

Thanks

Look at the form id for login form. and then try hook_form_alter() in any custom module.

Add a submit callback or validation callback in which you can check for the empty fields yourself. According use drupal_set_message() to display the error message.

You can make use of a custom validation in the form alter and try to implement things all by your self.


Is this the proper way to alter a path defined in code by another module? I have installed the FAQ module on my site, and it defines the path to the FAQ page in code as 'faq-page'. I would like to make the path be 'mypath/faq' instead. I think I need to create a little module that implements hook_menu_alter(), so that if I upgrade the FAQ module, my custom path won't be overwritten. I think it should go something like the following:

/**
* Implements hook_menu_alter.
* Override FAQ page path defined by the FAQ module.
*/
function MYMODULE_menu_alter(&$items) {
  $items['mypath/faq'] = $items['faq-page'];
  unset($items['faq-page']);
}

Is this the proper way for me to override the path defined by another module?

No, that's not the right way. You are actually looking for aliases. They are provided by the Path module that is integrated in core.

It's possible to do it the way you propose, but it comes with possible side effects and is a little to much for what you want.

Yes,
with $items['mypath/faq'] = $items['faq-page']; you basically create an alias for '/faq-page', so you are not overriding anything.
For what you want to achieve is all you have to do.

The unset($items['faq-page']); instruction is unnecessary, use it only if you don't want that the original path will be a valid one and prefer a "page not found" error if some link still happen to point there.


mod_expires enabled and cache flush I my apache I have mod_expires enabled. My htaccess contains:

<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On
  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

Problem: If I make html change, it is not visible even after flushing all caches in drupal.
Question: Is it possible to setup html expiring to say 1 hour and other things like css/scripts/images to say 1 day?
Thank you.

If you use boost module "flushing all caches" maybe not work. Go admin > configuration and open boost configuration, there a tab named "cache expiration" then undo click "Ignore a cache flush command if cron issued the request." I think this usable for you


How to make a page where two content types are combined It should be a portfolio website. I'm going to place there information about projects I was engaged in and products I designed. The relationships between project and product nodes are those:

--Project 1
----Product 1
----Product 2
----Product 3
--Project 2
----Product 4
----Product 5
----Product 6
etc.

My question. How to create a page where placed all project articles and under each project article there should be related product article teasers. Like on image.

In views you can "Group By" the parent nodes. So if you were using entity references to do the relationship, you would have it as a field in views and group by it.

Are they different content types? How are you relating the children to the parent?

If the default Group By isn't enough, there's a module called Views Field View which can put a view inside a view but that could be a bit unnecessary.

a quick solution could be writing a very simple code. in your .module code in a page call back
take all the data that you want and then group them into an array first that is something like this

$query = "SELECT
nid,
title,
field_data_first_field_table.first_field_table AS first_filed_table,
field_data_second_filed_table.first_filed_table AS second_filed_table
FROM
node LEFT JOIN first_field_table
ON
field_data_first_field_table.entity_id = node.nid
LEFT JOIN field_data_second_filed_table
ON
field_data_second_filed_table.entity_id = node.nid
 WHERE node.type IN(:type);
 $result = db_query($query, (':type' =>array('type1','type2'));
  while ( $data = $result->fetchObject () ) {
  $portfolio_array[$data -> title][$data ->first_filed_table][second_filed_table] = $data ->nid;
 }

in the $portfolio_array you will have that values grouped .you can push this to a theme function (very best) or return that formatted output in the call back function itself.

second method is views module use rlationships to add the fields and then make your theme changes in the correpsonding views


Attach library to a specific page I am developing a custom module in Drupal 8. My custom module include many JavaScript and CSS files which make the site really slow and I don't want them in all pages. I have developed some custom blocks and each JavaScript and CSS library correspond to a block. I want those files on those pages of the site where my custom blocks are visible.

In my last Drupal 8 project, I have done something like the following.

function HOOK_page_attachments(array &$attachments) {
    $user = \Drupal::currentUser()->getRoles();

    if(in_array("administrator", $user)){
        $attachments['#attached']['library'][] = 'module/library';
    }
}

I am not sure how to check which blocks are visible in the page.

If you're using a twig template, you can add it there.

{{ attach_library('module/library') }}

Which is helpful when you want to control whether the library loads before or after the content.

https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

Resolving this doubt: I am not sure how to check which blocks are visible in the page.

block.module have a service that you can invoke:

getVisibleBlocksPerRegion()

https://api.drupal.org/api/drupal/core%21modules%21block%21src%21BlockRepository.php/function/BlockRepository%3A%3AgetVisibleBlocksPerRegion/8.2.x

I think that you can use it to resolve your case.

And in other hands is not the best practice check the use role, maybe will be better check the permissions that you want to check. If you want in the future, that another role can see the block, you cannot do it without grant the administrator role to this user.


How to upload files using the Feeds module? I created a custom content type and I want to upload an XML file using the Feeds module. Can somebody explain how to do the mapping correctly? Should I add a new importer or use a node importer?

I want to perform the upload using an XML file. I have unicode characters in my file.

I am not able to convert it to a CSV file. I have tried converting using Open Office but it is not working.

I find using feeds a bit complicated.

Are there other solutions to upload files into database?

Note: When I try to upload to says no new nodes created.

You need to use Feeds XPath Parser module.

You may need this module if you would like to:

  Import XML or HTML documents into nodes, users, taxonomy terms, or
  regular database tables.
  Scrape webpages like regular feed sources with scheduling, updating, and expiring.
  Extract content from HTML documents to create a semantic data bank or mashup.

Below links will help you to set up.

Feeds XPath Parser, a full-fledged XML parser that utilizes the XPath syntax for scraping feeds.
Importing from XML, from drupal.forhumanists.org.
Drupal 101: What I learnt from hours of troubleshooting Feeds.

I am able to create new node by creating a csv file using google spreadsheets instead of a xml file.I created a new feed importer and mapped the elements of feed to the appropriate fields.


How can I get the page title? drupal_get_title() has been removed from Drupal 8. How I can get the page title in Drupal 8?

If you check the change records you should find the following: drupal_set_title() and drupal_get_title() were removed.

You'll have to read the change notice for all of the info, but here is a starting point:

  drupal_get_title()

  As titles on routes now can be set on various ways (see above),
  drupal_get_title() has been removed. In its place you should call the
  title_resolver service.

  Drupal 7

<?php
  $title = drupal_get_title();
?>

  Drupal 8

<?php
  $request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $title = \Drupal::service('title_resolver')->getTitle($request, $route);
  }
?>

Drupal 8

$request = \Drupal::request();
  // Assuming the Request is $request.
  if ($request->attributes->has('_title')) {
    return $request->attributes->get('_title');
  }


How can I change a user's password? How can I change a user's password from the command line using Drush?

In Drush 9, the command is drush user:password USERNAME "SOMEPASSWORD"; its aliases are user-password and upwd.

In Drush 8 (and earlier) the command is drush user-password USERNAME --password="SOMEPASSWORD"; its alias is upwd.

If we don't know more about drush then we can change password from database in user table . We will edit password and select md5 then we can change password.


Changing node/%/edit title I have created custom content type for upload the details. I have used hook_form_alter to set the node title as "Upload". When I edit the node in node/%/edit the title remains "Upload". I want the title to be "Edit" .How to do this?

Please try this:

function hook_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'form-id') {
   if(arg(0) == 'node' && arg(2) == 'edit'){
     drupal_set_title('Upload Edit');
    }
    else{
     drupal_set_title('Upload'); }

  }
}

Try this..

$node = node_load(your nid);
$node->title = 'new title';
node_save($node);


Clear only CSS/JavaScript cache when files are aggregated When aggregating CSS/JavaScript files using performance page in Drupal 8, drush cc css-js doesn't work, and I've to clear/rebuild all cache.
How do I properly clear/rebuild only the JavaScript/CSS cache?
I want that the filenames change too, so that the browser resets its cache too.

NOTE: I am using the s3fs plugin in order to store assets in an AWS S3 bucket, so if you are not using that your results could differ

This is probably not a suggested method of forcing the system to clear the asset cache, but I was in the same boat and for some reason my file systems got mixed up during multiple edits between local, development, and the live site. For the live site I was only able to get the styles working if the files were not aggregated using the Performance page.

As far as I know, the system will not update the CSS or JS files unless a change has been detected. Aside from going in and making a change to every file I started digging into the database. I found that the file location for the CSS and JS assets were located in the "cache_default" table with a value of something like below:

s3fs:uri:public://css/css_0WFR6_Et4WEJOkLOOpdg4f7EmvMRhsPkSk7KcrPyct4.css

and

s3fs:uri:public://js/js_-YxTfPGZervj7hTx1tF6zyt9ua2DxHPROTbub3I_WRg.js

BACKUP YOUR DATABASE BEFORE GOING FURTHER!
In case you mess anything up, CYA!

I went through and deleted all entries that were a CSS or JS file.
Be careful not to delete the directory reference entries that just
have the JS and CSS folders.
THEN, since I was using s3fs I went into the "s3fs_file" table and did the same thing.
I went back into the Performance page, enabled the CSS and JS aggregation, and saved.
Then cleared the site cache after that. This seemed to re-generate the
CSS and JS assets, re-built the asset table data, and the site was
back to normal!

I did have to dump the DB tables and import into my dev and local environments in order to mimic the new asset names, but this seemed to work like a charm.

SIDE NOTE: I am wondering if there would be some way for Drupal to add a style versioning system? Maybe that we could change the sites CSS versioning after major changes in order to have this done automatically? or maybe this is just something I will need to build my next module for!!

You can run drush ev command to clear css-js cache, check example below:

drush ev '\Drupal::service("asset.css.collection_optimizer")->deleteAll(); \Drupal::service("asset.js.collection_optimizer")->deleteAll(); _drupal_flush_css_js();'

Above sample is taken from here.


Fivestar rating for anonymous user should redirect to login or register When anonymous users tries to rate a node with fivestar rating, they will be asked to either login or register to continue. How to achieve it???

You can use the Rules module to achieve this.

Check out this Great tutorial.


Use responsive images inline I can see that using styles on inline images have been left out for some reason. But when I need to make the site behave a little more responsive.

I have been looking after CKeditor plugins that could select a style for the image being include. But I haven't found any.

I have been looking after at comment on the Drupal 7 Picture module that should be what is the base for the implementation of Responsive Images in Drupal 8. But there is nothing about inline images to find - just old Drupal 7 demos on how it should work.

Any idea how to get responsive images or just a basic image style for images include in inline editor on Drupal 8?

The module Entity Embed will be able to do that. There is now a dev version available, but you better wait for the first alpha/beta-release.

Even longer it will take, until this is in core:

Allow image style/responsive image mapping to be selected in Text Editor's image dialog

This is postponed to drupal 8.1

Until then you can use jquery to move the image from an image field to an empty container in the body. To avoid flicker effects, add a style display:none in the twig template of that specific image field and show it after moving it into the body in jquery.

You can add the class="img-responsive" in  the image tag it will responsive automatically. Hope its will work for you.


Any way to set Drupal theme settings per page? I have a theme which has multiple theme options in its settings page. Is there a way to assign particular theme settings to specific Drupal paths?

For Drupal 7, you can do this by taking advantage of the fact that theme settings are cached by drupal_static(). See theme_get_setting(). I think the same approach would work for Drupal 8 too, but haven't tried it.

// Implement HOOK_init.
// Here we override one of the Bootstrap theme settings.
function MY_MODULE_init() {
  // Only do this if we're actually on the relevant page.
  if ($_GET['q'] == PATH_TO_THE_PAGE) {
    // Override the Bootstrap theme setting 'Smart form descriptions (via Tooltips)'.
    // This because we want to display form input #description as text, not tooltip.
    // This will also affect any other forms on the current page, no easy solution for that.

    // Set the name of the theme we're interested in (the current theme in this case).
    $theme_name = $GLOBALS['theme_key'];
    // Read the setting first to ensure that the drupal_static cache is populated.
    $setting = theme_get_setting('bootstrap_forms_smart_descriptions', $theme_name);
    // Get a reference to the cached settings.
    $cached_settings = &drupal_static('theme_get_setting');
    // Unset the 'bootstrap_forms_smart_descriptions' setting from the cache.
    unset($cached_settings[$theme_name]['bootstrap_forms_smart_descriptions']);
  }
}

I should add, this is arguably a bit of a hack, as it depends on the internals of drupal_static() and theme_get_setting() i.e. not documented API functionality - unless you consider the code to be the documentation :)

You can do this with the ThemeKey Module.

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules. In combination with Drupal's
  theme inheritance you can easily achieve features like:

  individually-styled channels
  a front-page / "splash" screen
  a date/time-selected Christmas theme
  mobile themes for different auto-detected mobile devices
  special themes for "limited" or "old" browsers
  content, user, or role -specific themes
  indicating your environment (production, staging, testing, sandbox, … )
  testing your redesign safely on a live server

  And unlike other theme switching modules, ThemeKey should play well
  with internal and external page caches, like Boost or Varnish, even
  for anonymous users.


Avoid access denied page after user logout I am using Drupal 7. It is good that when user is logged out and again he access the

user/logout

link he is redirected to Access denied page.

Now I want that instead of Access denied page, i want to redirect to the specific page.

Can i achieve it using rules module or i have to write the code for that

What you want is something called 403 redirect to Login:
https://drupal.org/project/r4032login

403 access denied messages will get redirected to the login page. I've used this before and it works nicely.

In Site Configuration > System > Site information you can specify the Access denied path.

Simply give the path to your front page and you will be redirected to front page of the site.


How to make a popup on a node's content using the colorbox module? In Drupal 7, all I had to do to add a popup with colorbox was add the CSS class colorbox to the link to create a nice popup.  Now, using Drupal 8, I cannot figure out how to do this.

I can add colorbox to my fields, but I want to add it directly to the link <a class="colorbox" href"".../a> in the content body, but it is not working.  I cannot figure out how to use inline colorbox either, if that is the solution.

How can I add the popup?

For creating pop-up's in colorbox, you can simply use Bootstrap Modal Window.

Don't forget to include the below ones:
1. bootstrap.min.css
2. jquery.min.js
3. bootstrap.min.js

FULL WORKING CODE:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Small Modal

  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>

          <button type="button" class="close" data-dismiss="modal">&times;</button>

Modal Header

This is a small modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>