User picture not showing, after moving from localhost to prodution I have moved my site from localhost to the web hosting, and in the web hosting, the user picture have been lost and the users cannot upload new photos. But in the localhost everything was working nicely

When i inspect the "lost picture", i get this path: MY_SITE.com/sites/default/files/styles/thumbnail/public/pictures/MY_PICTURE-5-1375807631.jpg?itok=eQN27TLT

I'm getting crazy with this. Is there any sugestion? Thank you

You might find that updating the permissions on your files folder is necessary. Depending on your server configuration you may need to run chmod -R 770 ~/public_html/sites/default/files (assuming the path to your files folder) or use 777 as your permissions string.

Beyond that, ensure that when you moved to production you deployed an entire copy of the site including all the files.


What is the best way to restrict website's direct access through node urls? How can I prevent a node from being accessible on its own page, through node/xxx, but still be accessible through node description eg: /homepage?

I tried using the Rabbit Hole module, which restricted the page access through nodes/xxx. But it is restricting access even through the node's descriptive path. I don't want people having some knowledge of Drupal to play around with the website by typing in node-IDs.

So what is the best way to achieve this?

Using the Rules module you can implement a rule that looks similar to this:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

It assumes you'll have a node with a path like no_access (which is where a user trying to use node/xxx will be rerouted to). Feel free to adapt to any other path that fits).

The above rule does not (yet) take into account to only apply the "action" for selected user roles. E.g.: you may want such paths to be used (allowed) anyway for roles like 'administrator' or 'content-editor'. But for anybody a bit familiar with the Rules module, that is a straight forward "Condition" to add.

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function. Then further edit/refine to make it fit in your own environment (eg the "Sorry, ..." message to be shown.

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


how to use more then one content type filter in same views in drupal 7? I have two content types animal and fruits.
In animal content type fields description .
content type = animal

conditions:

date = 2015
user = login
If a record exists that satisfies the above 2 conditions:

show description..

Then the system should then get the “body” data field value  from the content type “fruit” where the following 2 conditions are satisfied:

•   “Type” date field value = “apple” AND
•   “Title” data field value = “appple is my fav”.

then body show "
for ex : some content like fsdf lfdjldf

You need to add both the content-type inside Filter Criteria.

Click on the "Add/Or, Rearrange"
Create new filter group


Change target type of entity reference field in update hook In an update function, I'm trying to change the target_type of an entity reference field, following the approach outlined on https://www.drupal.org/node/2535476). The previously used target entity type (its class) has been removed from my site (I'm removing it as part of the update).

Something like this in the update function:

$field_storage_config = FieldStorageConfig::loadByName('entity_type', 'field_name');
$field_storage_config->setSetting('target_type', 'new_entity_type');
$field_storage_config->save();

When I call $field_storage_config->save(), I get a fatal error saying the previously used target type (the one that's been removed) no longer exists. It seems that the save() method eventually calls \Drupal\Core\Entity\EntityTypeManager::getDefinition for the removed entity type, leading to the fatal error.

Any way to get around this, so I can switch the target type from the removed entity type to an existing one in my update function?

I dealt with this issue a few months back in the jQuery Colorpicker module. I was converting all fields of one type (jquery_colorpicker), to fields of an entirely different type (colorapi_color). With the update of the module from 8.x-1.x to 8.x-2.x, I intended to remove the the original type/plugin (jquery_colorpicker). Then in the update script I intended to loop through each field on every entity type, and if it was jquery_colorpicker, change it to colorapi_color. However deleting the plugin led to the same issue you are running into, where I was getting an error about mistting the field type that I had removed.

In the end to get around this problem, I took a different approach altogether. I left the definition plugin file for the jquery_colorpicker field in the file system, but marked it as deprecated:

/**
 * Provides the Color field.
 *
 * @FieldType(
 *   id = "jquery_colorpicker",
 *   label = @Translation("Color (deprecated)"),
 *   default_formatter = "colorapi_color_display",
 *   default_widget = "colorapi_color_widget",
 * )
 *
 * @deprecated as of Jquery Colorpicker update 8200. Will be removed in Jquery
 *   Colorpicker 8.x-3.x, and/or 9.x-1.x. Running
 *   jquery_colorpicker_update_8200() requires the existence of this field type,
 *   however the field type is obsolete after that update has been run. As such,
 *   if the schema version is equal to or above 8200, the field type is removed
 *   from the list of field types in jquery_colorpicker_field_info_alter().
 */

Link: https://cgit.drupalcode.org/jquery_colorpicker/tree/src/Plugin/Field/FieldType/JqueryColorpickerColorItem.php#n9

Then I set the system to remove the field type from Drupal's list of field types when the current installed version of the module is 8200+:

/**
 * Implements hook_field_info_alter().
 *
 * @deprecated as of Jquery Colorpicker update 8200. Will be removed in Jquery
 *   Colorpicker 8.x-3.x, and/or 9.x-1.x.
 *
 * @see jquery_colorpicker_update_8200()
 */
function jquery_colorpicker_field_info_alter(&$info) {
  // Running jquery_colorpicker_update_8200() requires the existence of the
  // jquery_colorpicker field type, however the field type is obsolete after
  // that update has been run. As such, if the schema version is equal to or
  // above 8200, the field type is removed from the list of field types.
  if (drupal_get_installed_schema_version('jquery_colorpicker') >= 8200) {
    unset($info['jquery_colorpicker']);
  }
}

Link: https://cgit.drupalcode.org/jquery_colorpicker/tree/jquery_colorpicker.module#n45

With the above code, before the update is run, the version will be less than 8200. Any time the system builds the list of field types, the jquery_colorpicker field type is available, meaning that when the update script is run, the field type is still available, so you won't get the error about it missing.

After the update has been run, the version will be 8200 (or greater), and therefore the jquery_colorpicker field type should no longer be available. Therefore it is removed from the list of field types.

If/when version 8.x-3.x of the module is released, I will remove the jquery_colorpicker plugin file altogether. For now, it's still in the codebase, but deprecated and unused.


Custom Options Value of Views Grouped Filter? How do I change the select values of a Views groups filter?
By default, they are 1,2,3...
Default

<select>
<option value="all">all</option>
<option value="1">Group A</option>
<option value="2">Group B</option>
</select>

Desired Result

<select>
<option value="all">all</option>
<option value="mycustomname">Group A</option>
<option value="mycustomname2">Group B</option>
</select>

I just did something similar for some data I'm exposing in Views for my custom module (it's kinda the same process no matter where views is getting its data).

To do this in the most efficient/easy way possible, you should create your own filter handler.

For a really simple example:

<?php
class custom_handler_filter_countries extends views_handler_filter_string {
  /**
   * Shortcut to display the exposed options form.
   */
  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'select',
      '#title' => t('Countries'),
      '#options' => function_that_returns_options_you_want(),
    );

    return $form;
  }
}
?>

Then, in your module's .info file, add the file containing this class (in this example, 'custom_handler_filter_countries.inc') to the .info file's files array (files[] = includes/custom_handler_filter_countries.inc).

To make your particular view use this views handler instead of the default handler, you should be able to change the handler in hook_views_pre_view(), I think. (On my particular site, since I defined the views data table myself, I just set my custom handler for fields that needed it. For your site, since the normal handler is already defined by Address Field, you need to override the filter handler.

This discussion may also have a possible solution:

Custom Options Value of Views Grouped Filter?


Why does my admin page appear corrupted after using Backup and Migrate? I recently restored a site backup using the Backup and Migrate plugin. Now my admin toolbar looks like this.
Flushing cache does nothing. How can I fix this?

If you forget to preserve the file permissions when restoring a backup, you'll run into this. Make sure you use tar's p flag when you extract the backup file. Run drush ws to see watchdog error logs and you'll find permission errors like this:
------ -------------- ------ ---------- ---------------------------------------------------------------------------------------------------------------------
  ID     Date           Type   Severity   Message
 ------ -------------- ------ ---------- ---------------------------------------------------------------------------------------------------------------------
  3436   26/May 18:43   php    Warning    User warning: mkdir(): Permission Denied in Drupal\Component\PhpStorage\FileStorage->createDirectory() (line 145 of
                                          /home/public/core/lib/Drupal/Component/PhpStorage/FileStorage.php) #0 /h

Fix the file and directory permissions, then rebuild the cache with drush cr and you should see:


Provide Menu in Module I am looking for a way to provide a whole menu (no menu items) within a module. I could find many ways how to do that in D7, but I really would like to da that in D8.

You put the menu in the folder config/install of the module.

An example from the devel module:

/config/install/system.menu.devel.yml

id: devel
label: 'Development'
description: 'Links related to Devel module.'
langcode: en
locked: true

Then you can place the menu link items for this menu in *.links.menu.yml in the root directory of the module.

Edit:

As mentioned in the comment from @mradcliffe, some background info might be helpful. Menus are configuration entities. The storage of the configuration is for performance reasons in the database, but they were at the beginning of D8 in yaml files. If you sync the configuration to the harddisk you will find the configuration in a set of yaml files. You can put any of these yaml files in the config/install folder of your module. But you have to remove the uuid line, because the uuid is only valid for the installation you have exported the yaml file from. The menus are in system.menu.*.yml.


How can I show only terms from a certain vocabulary in a view summary? I have a View that has a contextual filter for Taxonomy terms... I have selected that if the parameter is not given just show a summary, but I want that summary to show only terms of a certain vocabulary... is that possible?

UPDATE: Just to be clear. I'm selecting nodes that has two fields that points to different vocabularies, so in the summary the view is showing all the terms form both vocabularies, I just want to show the terms that are only on one of them.

I was looking for the same thing. I found my answer here: http://drupal.org/node/1243488#comment-4843640

It's not very intuitive, but it works.


Move timezone field in user/%/edit field I want to move timezone field in user/%/edit form. I have used$form['#weight'] in hook_form_alter() and $page['#weight'] in hook_page_alter(), but not working.

The next snippet should work

<?php

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    $form['#after_build'][] = 'MYMODULE_user_profile_form_pre_render';
  }
}

function MYMODULE_user_profile_form_pre_render($form) {
  $form['timezone']['#weight'] = -10;
  return $form;
}


Using path aliases how to identify node IDs from database and based on these IDs how to publish them? I have a content type called article. For this content type, I unchecked the "Published" checkbox under the publishing options tab.

I have 30000 nodes I changed to unpublished. Among those, I want to publish 900 records. I have the node URLs.

Using the path aliases, how to get the node IDs? Once I have the node IDs, how can I publish those nodes?

You can use drupal_get_normal_path() to get the node/id-paths for each of them.

Then you can use the following code to publish them.

// Load the node object.
$node = node_load($nid);
// Set the status property to 1.
$node->status = 1;
// Re-save the node.
node_save($node);


Widgetkit Drupal alternative Is there module that will enable user to create galleries and than embed them into article content, and display them in lightbox fashion?

For example, I can create a gallery in some UI, configure it (set gallery type, transition effects etc...) and than get gallery ID which I can use to embed it in article with some shortcode:

Some text...
[image_gallery ID1]
Rest of the text
[image_gallery ID2]
...
...

I have searched through drupal repositories and on google and didn't find anything like it. So I'd like to know if someone knows better or do I have to implement that functionality from scratch?

Check out the Photowall project to see if it matches your requirements out of the box.

From the project page:

  Provides a Photowall (like Google) format for displaying images, using the JQuery Photowall plugin.

There is a nice demo showing what it does at the  JQuery Photowall link.

If it is not advanced enough for your tastes, I have another idea:

Since most of the power of the YooTheme Widgetkit for Joomla and Wordpress is provided by Javascript that runs in the browser and that should work just as well when it is launched from Drupal instead of Joomla/Wordpress, it should not be too hard to adapt the Drupal module Photowall to make use of the YooTheme Widgetkit Javascript plugin, instead of the JQuery Photowall Javascript plugin (but it will obviously require some custom development).


How to print the raw value of a custom user field in comments I want to print a custom user field of the commenters. It is an Link field (https://www.drupal.org/project/link). Some users have that field completed and other not.

I've read a lot of posts  related to this and tried several solutions. The only code that seems to nearly work OK is the following (found in https://drupal.stackexchange.com/a/129222):

<?php print render(field_view_field('user',user_load($comment->uid), 'YOUR-CUSTOM-USER-FIELD'));?>

The field shows, but there are 2 problems:

1) It causes 2 errors of "Strict warning: Only variables should be passed by reference en include() (line 73 of .../templates/comment.tpl.php)."

2) It shows the entire field, including its label and the complete link with the settings of the field. I only want the "raw" value of the field, the text that users introduce in the field.

Thanks for your help!

You can use the field_get_items() to get all values for this field, after use field_view_value().
Example below:

// user_uid_optional_load() will load the user object with all custom fields

$account = user_uid_optional_load($comment->uid);

$items = field_get_items('user', $account, 'field_name');

// as a example I'm using the number 0 as delta
$value = render(field_view_value('user', $account, 'field_name', $items[0]));


Multi-site vs Large Single site for Intranet Whenever I look at "Should I use Multi-site?", it always seems to depend on the use case. (I am using Drupal 7)

I have been developing a company's Intranet on a single Drupal install and it is getting larger and larger.

I have about 75 Content Types and over 500 fields.

The reason for the Drupal site having so many Content Types is to give each department access to manage nodes within specific content types. (Using Content Access).

There are also additional Content Types for workflows that are using with Rules.

I feel the greatest performance hit when managing fields on a Content Type.
Other than that, the site still runs smoothly.

In a situation like this where there are going to be so many more fields and content types added, does it make sense to use Multi-site instead? Or is it perhaps the specs of my Server that are causing the slowness?

It is convenient having everything on one site since I can have a unified Dashboard, not have to re-make the User groups/roles on multiple sites, etc.

In this use case, is it worth converting my structure to a Multi-site setup?

Another alternative you may want to consider is to start using the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various types of roles used by the Group module, refer to my answer to "What are the various roles supported by the Group module?".

And because Group also integrates with the Rules module, you could probably transform your workflows related rules toward Group equivalents.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Forms - Clone form with different url + theme I have a content type which can be created by admins and regular authenticated users.
Now i would like to create a separate form url like /city/create for authenticated users instead of the standard admin url /node/add/city.

I try to achieve to have two urls for the same form with two different layouts.

Could you guys point me in the right direction?

You can create path(url) alias for this. Using alias the same url will be called.
Regarding theme you can alter form with some condition to assingn different theme.
e.g.

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
 if(SOME_CONDITION){
  $form['#theme'] = 'FORM_THEME1'
 }else{
  $form['#theme'] = 'FORM_THEME2'
 }
}


Why is drupal spitting out urls like entity:/node-1474 instead of /node-1474 So for the longest time I was using the following line of code to get urls instead of relying on drupals raw output. The main reason being I need an <a> tag to wrap several elements.

{{ item.content['#paragraph'].field_home_slider_button_link.0.value.uri }}

Inside of a field.

For a quick minute I contemplated just removing the entity:, however I'd really like to understand what's happening here and if there's a way to tell drupal I want the actual url in either twig or some setting?

You have to use .url instead of .uri, like this:

{{ item.content['#paragraph'].field_home_slider_button_link.0.url }}

I don’t think this works on older versions of Drupal 8, so if it doesn’t work you can try this:

{{ item.content['#paragraph'].field_home_slider_button_link.0['#url'] }}


Add class-element to a link though a module (or can I implement theme_link in a module instead of in a theme)? I'm the developer and maintainer of a module on the Drupal website. It implements an API so that a certain third party service can be easily integrated in Drupal.

I'm currently having the following problem: I need to add a class-element to the logout link. So my module has to arrange that all the these links Log out becomes the following: Log out

For the logout link in a menu it's easy, I have to implement hook_menu_link_alter().

However, I also want to catch all occurences where somebody is using l("Log out", "/user/logout"). The latter function calls theme_link, so if I would implement that, I think it could solve my problem.

So my questions are:

Can I implement theme_link in a module? If so, can somebody tell me how to do this?
Is there another way in which the above could be accomplished by means of a module?

What I understand is that you want to have a class in every link that comes on the site.
I believe, you can achieve this by skinr module - https://drupal.org/project/skinr, which not only adds up classes but also provides you UI to achieve the same.

Also, in module, you can try this.

/**
 * Implements hook_preprocess_HOOK
 */
function MODULENAME_preprocess_menu_link (&$variables) {
  if ($variables['element']['#original_link']['menu_name'] == 'main-menu') {
    $variables['element']['#title'] = '<i class="icon-' . _sanitize_words($variables['element']['#title']) . '"></i>' . $variables['element']['#title'];
  }
}

The above could should work, Worked for me atleast :)


How do I alter the order used to load JavaScript files? I created a libraries.yml file with the following content.

highcharts:
  css:
    theme:
      highcharts/css/highcharts.css: {}
  js:
    highcharts/highcharts.js: {weight: -400}
    highcharts/modules/exporting.js: {weight: -29}
    highcharts/modules/data.js: {weight: -28}
    highcharts/modules/drilldown.js: {weight: -27}
    js/hc.js: {weight: -1}
  dependencies:
    - core/drupal
    - core/jquery

hc.js is my custom JavaScript file content. I set its weight to -1 to make it the last used file, but after clearing the cache and refreshing the page, I still JavaScript error because the order used to load the JavaScript files. (hc.js is loaded before highcharts.js).

Do I need to change the content of the libraries.yml file?

I'd set it up like this:

highcharts:
  css:
    theme:
      highcharts/css/highcharts.css: {}
  js:
    highcharts/highcharts.js: {weight: -400}
    highcharts/modules/exporting.js: {weight: -29}
    highcharts/modules/data.js: {weight: -28}
    highcharts/modules/drilldown.js: {weight: -27}
  dependencies:
    - core/drupal
    - core/jquery

charts:
  js:
    js/hc.js: {}
  dependencies:
  - mymodule/highcharts

Then add the library mymodule/charts.


db_select returns empty array, BUT the raw query returns records...? I've written a query to get records that start column is later than a given time. Take the following:

$q = db_select('timetable_slot', 's')
    ->fields('s')
    ->where('str_to_date(s.start, \'%H:%i\') >= \'15:24\' ');

    print_r($q->__toString());
    /* SELECT s.* FROM timetable_slot s WHERE (str_to_date(s.start, '%H:%i') >= '15:24' ) */

$result = $q->execute()
    ->fetchAll();

print_r($result); /* [] */

$result comes back as an empty array.
If I run the generated SQL manually I get the results I expect, any reason why drupal is returning an empty set?

I've also tried:

db_query("SELECT s.* FROM {timetable_slot} s WHERE (str_to_date(s.start, '%H:%i') > '15:24')")->fetchAll();

This also returns empty, even though the query works in a db client.

Thanks

It's impossible to troubleshoot such a query without access to your environment.

The Devel module has a query inspection tool (Display query log in the Devel settings). that can assist you in determining what query was sent to your database. Use that to determine the exact query sent to your DB and  how it differs from the query you're sending to your SQL client.


How to remove "Drupal" from title of page? Now I have this:

Here i found information how to change this text to anything else:
https://www.drupal.org/forum/support/post-installation/2016-09-20/change-site-title-in-drupal-8

I tried:

But it doesn't help.

Drupal is 8.4.2

And it works on 8.0.6

Drupal by default will put the site name at the end of the page title but specific themes might change this.

if you want to override this your best bet is to use https://www.drupal.org/project/metatag module and override appropriate settings

There is a setting for first page or for all content types or specific content types; it very configurable.

Or you might do it programmatically in your THEMENAME.theme file:

function THEMENAME_preprocess_html(&$variables) {
    $variables['head_title']['name'] = "Another Name";
}

To take away the | you have to create a new html.html.twig template in your custom theme and modify (copy paste it from the theme you are overriding)

    <title>{{ head_title|safe_join(' | ') }}</title>

to something like this

    <title>{{ head_title|safe_join('  ') }}</title>


How to set up a View in Drupal that shows recent posts relative to post date of node it is on? I want to set up a View that shows all the nodes that were updated within 7 days of the node that is being viewed

So if the node being viewed has a post date of January 15, 2014, I would see posts that were published between January 8-15, 2014.

I know there is a contextual filter involved, but it eludes me how to do this so the date used is relative to the node it is being viewed on.

No idea if possible in Views, but I created a custom block to achieve this.

function relative_posts_block_info() {
  $blocks['relative_posts'] = array(
    'info' => t('Relative Posts'),
  );

  return $blocks;
}

function relative_posts_block_view($delta = '') {
  switch ($delta) {
    case 'relative_posts':
    $block['subject'] = t('Block Title Goes Here');

    $node = menu_get_object();
    $formatted_date = date('m/d/Y H:i:s', $node->created);
    $start_date = strtotime('+2 weeks', strtotime($formatted_date));
    $end_date = strtotime('-2 weeks', strtotime($formatted_date));

    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'story')
    ->fieldCondition('taxonomy_vocabulary_1', 'tid', $node->taxonomy_vocabulary_1['und'][0]['tid'])
    ->propertyCondition('created', array($end_date, $start_date), 'BETWEEN')
    ->propertyOrderBy("created", "DESC")
    ->propertyCondition('status', 1)
    ->range(0, 25)
    ->execute();

   $block['content'] = '
';

  foreach($entities['node'] as $obj) {
  $node = node_load($obj->nid);
    $block['content'] .= '
' . l($node->title, "node/" . $node->nid) . '
';
  }
  $block['content'] .= '
';

   break;
 }

 return $block;
}


How can I disable the form confirmation message? I'm referring to the green box that informs the user that they have successfully submitted their form.
In particular, I'm wondering if I can remove it without writing any php. Is there anything in the admin interface?

There is no option in Drupal's core that gives you the ability to disable messages but there is a module for that: disable_messages.

Still, I like this approach, which uses drupal_get_messages function implemented in hook_form_alter:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  // Define the $form_id for the form which you want to suppress messages for.
  if ($form_id == 'hide_messages_form_id') {
    $form['actions']['submit']['#submit'][] = 'my_module_submit';
  }
}

/**
 * My custom submit handler.
 */
function my_module_submit($form, &$form_state) {
  // Hide drupal 'status' messages. Equally use 'error', 'warning' or 'NULL'.
  drupal_get_messages('status');
  // Or display your own message.
  // drupal_set_message(t('My message.'));
}


How to remove the RSS feed icon form the content listing pages? I need to remove the syndication icon because I'm either not going to syndicate or I want to do it my own way.

If it's just the feed icon you need to kill, you could always just comment out or delete the line:

<?php print $feed_icons; ?>

from page.tpl.php?


Block link with active class I've created couple of blocks from the Drupal UI.

These blocks has unsorted list with links to the other pages.

They act like a sub menus located into the sidebar region and visible to specific pages.

Here's an example for a block called fruits that have a couple of links:

Apple
Orange
Mango

The Drupal menu system or Superfish module generates active class on the links based on the URL location. How can I do that with these blocks, so let's say a user clicks on the link Apple and when the new page loads, the Apple link will have a active class, so it will look like this:

Apple

I want this, so I can set a CSS for active link.

It needs to be done with PHP. If you use the l() function to generate your links, they will automatically get the active class if you are the page to which the link is linked to.
To do this you would need to enable the PHP filter, but this filter is both recommended against, as well as non-existent in Drupal 8, so it would be better to create a block through code and use that instead of enabling the PHP filter.


How to add 'title' attributes to breadcrumbs links? I'm currently using Crumbs module for creating breadcrumbs on my website. I added 'short title' field to nodes and show its content in breadcrumbs instead of much longer node titles. This makes breadcrumbs shorter and much prettier however it is sometimes difficult for users to understand links destinations as I often use abbreviations as 'short titles'. Would be nice to add the full node titles to the breadcrumbs' links (they will be shown on hover as a guide for users). I haven't found any solutions to achieve this so far. Any ideas?

You can use hook_menu_breadcrumb_alter().
I think it is

$item['localized_options']['attributes']['title'] = 'The title';

Play around and report here if this works!

It is called from crumbs_CurrentPageInfo::breadcrumbItems(), with some useful data with each trail item.

However, this added data is only available if Crumbs is active. Your module with the hook_menu_breadcrumb_alter() implementation may no longer work correctly if you disable Crumbs.


How to query only specific id's in a custom source plugin I have 40/1040 source product_id's I need to ignore in one migration, so that I can put them in their own separate migration. I can exclude and include them in the yaml files, but it's a bit ugly and I would rather do so in the custom source plugin because doing this in the yaml is not performant as they are all queried in both.
I can exclude the 40 from their own yaml this way:
process:
  variation_id:
    -
      plugin: skip_on_value
      source: product_id
      method: row
      value:
        - 1
        - 2
        - all the way to 40

I can include only the 40 in another yaml this way:
process:
  variation_id:
    -
      plugin: skip_on_value
      not_equals: true
      source: product_id
      method: row
      value:
        - 1
        - 2
        - all the way to 40

But I would rather set a string of product_id's to include/exclude (I'm guessing in the public function query()??) because when I run the smaller migration (the 40) there is no need to query and ignore the other 1000 variations.
I created a copy of the source plugin so that I could use a distinct plugin for each of the 2 migrations. Here is the plugin that I am currently using for both:
use CommerceGuys\Intl\Currency\CurrencyRepository;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity;

/**
 * Gets Commerce 1 commerce_product data from database.
 *
 * @MigrateSource(
 *   id = "commerce1_product_bundle",
 *   source_module = "commerce_product"
 * )
 */
class CommerceProduct extends FieldableEntity {

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return [
      'product_id' => t('Product variation ID'),
      'sku' => t('SKU'),
      'title' => t('Title'),
      'type' => t('Type'),
      'language' => t('Language'),
      'status' => t('Status'),
      'created' => t('Created'),
      'changed' => t('Changes'),
      'data' => t('Data'),
      'commerce_price' => t('Price with amount, currency_code and fraction_digits'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['product_id']['type'] = 'integer';
    $ids['product_id']['alias'] = 'p';
    return $ids;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('commerce_product', 'p')->fields('p');
    if (isset($this->configuration['product_variation_type'])) {
      $query->condition('p.type', $this->configuration['product_variation_type']);
    }
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $product_id = $row->getSourceProperty('product_id');
    $revision_id = $row->getSourceProperty('revision_id');
    foreach (array_keys($this->getFields('commerce_product', $row->getSourceProperty('type'))) as $field) {
      $row->setSourceProperty($field, $this->getFieldValues('commerce_product', $field, $product_id, $revision_id));
    }

So I'm asking how to exclude an array of 40 product_id's in one plugin, and then only include an array of 40 product_id's in the other plugin.
Should I do this in the public function getIds(), the public function query(), or the public function prepareRow(Row $row)?
My guess would be in the public function query() But I would like to know the best way, and why.

This was quite easy by adding a $query->condition() to public function query() using IN and NOT IN in dynamic queries
This worked to exclude certain id's:
$products = [1, 2, 3,];
$query->condition('product_id', $products, 'NOT IN');

This worked to include only certain id's:
$products = [1, 2, 3,];
$query->condition('product_id', $products, 'IN');

I was then able to clean up the yamls, and only query the stuff I wanted.


How to load paragraph entity on node object? I'm using paragraphs in my content type. I've created a paragraph type and added content. Now I want to load the paragraphs in a foreach. But nothing's showing up. $paras is empty:

$node  = \Drupal\node\Entity\Node::load(1);
$paras = $node->get('field_paragraph')->referencedEntities();

$paragraph = $node->field_paragraph->getValue();
// Loop through the result set.
foreach ( $paragraph as $element ) {
  $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
  $text = $p->field_name->getValue();
}


Views removes style attribute in "Rewrite Results" I've got screenlists for videos and I need to put them into the div tag to as a background and then change bacgkround position with JS to show the preview. I've downloaded Image URL Formatter for this purpose and added code to "Rewrite Results" field of the field in my view:

But there is no such attribute "style" in rendered html of the page. Does Views module block it?

Yes, Views does block style attribute for security reasons. Class attribute is allowed.

Here's one long discussion about it https://drupal.org/node/853880 and some other ideas for workarounds Add style attribute to view fields.


Image upload not working for "AUTHENTICATED USER" Media module is awesome! But I can not understand why AUTHENTICATED USERS are unable to Upload images from CKEditor( http://drupal.org/project/ckeditor ) module.

I have set permission: Import media files from the local filesystem for the AUTHENTICATED USER, but still the uploader doesn't seem to work, except for the admin!

Here is a screenshot showing the Media Module inline uploader works with CKEditor while logged in as Admin:

Here is a another screenshot showing the Media Module inline uploader do not working with CKEditor while logged in as AUTHENTICATED USER:

Please give me ideas to fix this.

Do not give your authenticated users the Import media files from the local filesystem permission. It's actually different functionality that could open you up to security risk.

Looking at media_media_browser_plugin_info(), we can see that in order to use the upload plugin, the user has to either have the Edit media or the Administer media permission. Likely you'll want to assign the former.

I'll file an issue to correct that the import permission is misleading, and improve the description of the Edit media permission to be clear this is necessary to upload files in the browser.


How to embed a node's NID in the title of a node? I know the Automatic Nodetitles module exists, but it is only for Drupal 7.

Is there a method of automatically assigning the title with the NID upon clicking submit? I know that the NID doesn't exist until the submit button is hit. How would one embed the NID in the title?

What hook would one use?

You need to do two step:

Step one: auto generate the title and hidden form. use hook_field_widget_form_alter() with code

function MY_MODULE_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  $bundle = $form_state->getFormObject()->getEntity()->bundle();
  // You can check with other bundle
  if ($field_definition->getName() == 'title' && $bundle == 'page' && $element['value']['#default_value'] == '') {
    $element['#required'] = FALSE;
    //hidden title
    $element['#type'] = 'hidden';
    $element['value']['#required'] = FALSE;
    // Set default value
    $element['value']['#default_value'] = 'Default Title';
  }
}

with step one you can cross submit form.

Step two: Override new title with default value. Use hook_node_insert()

function MY_MODULE_node_insert(Drupal\node\NodeInterface $node) {
  if ($node->bundle() == 'page') {
    $new_title = 'New title ' . $node->id();
    $node->setTitle($new_title);
    $node->setNewRevision(FALSE);
    $node->save();
  }
}


Views query alter for specific node/content type My idea are instead of update the views
name to the custom code one by one. I like to apply to same content type, but
I don't know the syntax.

 function myModule_views_query_alter(&$view, &$query)

   if(($view->name == '?????????'){

}

I would get the node/content type "myArticle" for node table as following code

$content_type = $wrapper->type->value();

but how can I update $view->name to $views->node->type ? I try print_r the $view but not fully understand the syntax  to access the field. Not sure if I went in the wrong direction. Please advise.

If You only want to display data for specific roles to specific persons then you can use Global php in views to filter your results, Just take "User: Roles (Roles)" in your field as excluded and use its token in Global PHP field.example

if([roles] == "admin"){print [your_field_token_name];}
elseif([roles] == "your_roles"){print [your_field_token_name];}

You have to download the module of viewsphp to use global php.


Mailchimp Newsletter block position in registration page in Drupal I am just pulling my hair out for the last two days  trying to figure this out but as a new user of Drupal I cannot find the option where to change it. I have installed Mailchimp module in my drupal website and I want to display the newsletter option in the user registration page. It display fine but not in the right position. For some reason the block appears between the firstname and lastname field. I want to place this under email address field above the captcha. Can anyone please help me. I have tried to many things and cleared the cache but no luck.

Ok, you'll need to do this with a custom module and use hook_form_alter and set the weight of the mailchimp list properly.

function MODULE_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == "user_register_form")
    {
        //print_r($form);
        //first name field - use proper name
        $form["first_name"]["#weight"]      = 1;
        //last name field - use proper name
        $form["last_name"]["#weight"]       = 2;
        //email field - use proper name
        $form["email"]["#weight"]           = 3;

        $form["mailchimp_lists"]["#weight"] = 4;
    }
}

You should use print_r($form); or drupal_set_message(print_r($form,true)); to inspect the structure of your $form array and get out the proper names of your fields to use in the hook.


How to add google_tag script to header with custom environment variables? I'm trying to add Google Tag Manager to the <head> of my document.

Unfortunately, the way I'm doing it with an HTML tag render element, the ampersands (&) are being escaped.

function mymodule_page_attachments(array &$page) {
  $config = \Drupal::config('mymodule.config');
  $gtm_id = $config->get('google_tag_manager_id');
  $gtm_auth = $config->get('gtm_auth');
  $gtm_preview = $config->get('gtm_preview');

  /** @var \Drupal\mymodule\AnalyticsUtility $utility */
  $utility = \Drupal::service('mymodule.utility');

  if (!empty($gtm_id) && !empty($gtm_auth) && !empty($gtm_preview) && $utility->isAdminPage() === FALSE) {

    $script = "(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '&gtm_auth={$gtm_auth}&gtm_preview={$gtm_preview}&gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','{$gtm_id}');\n";

    $page['#attached']['html_head'][] = [
      ['#tag' => 'script', '#value' => $script],
      'google_tag_manager',
    ];
  }
}

This results in ampersands in the code.

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&amp;l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl+ '&amp;gtm_auth=testrWktRcmjpViiQKW&amp;gtm_preview=env-6&amp;gtm_cookies_win=x';f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-K53TEST');</script>

There are two modules with Google Tag Manager and they both add the code using hook_page_attachments().

The recommendation for adding JavaScript is to use an external file; yet, the Google Tag Manager documentation recommends adding the script in <head>.

Is there a way to do this with Drupal settings and a javascript file in my custom module? Alternatively, is there a way not to convert the ampersands to HTML entities?

The recommendation for adding javascript is to use an external file

That is not always the case and it is more of a guideline than a hard rule.

There is a way to do what you ask, but you shouldn't because the google_tag module does exactly what you to want to do. It also allows you to include the GTM snippet inline or as a file.


Upload file in system_settings_form in Drupal 6 I have a code that was supposed to upload 2 files:

function lafemme_background_images_form() {

    $form = array();

    $form['#attributes']['enctype'] = "multipart/form-data";

    $form['background_left'] = array(
        '#type' => 'file',
        '#title' => 'Obrázok na ľavej strane',
        '#required' => TRUE,
    );
    $form['background_right'] = array(
        '#type' => 'file',
        '#title' => 'Obrázok na pravej strane',
        '#required' => TRUE,
    );

    return system_settings_form($form);
}

function lafemme_background_images_form_submit($form, $form_state) {

    $validators = array(
        'file_validate_extensions' => array('jpg','jpeg','bmp','png', 'gif'),
    );

    $file_left = file_save_upload('background_left', $validators, '/sites/default/files/lafemme/backgrounds/');
    $file_right = file_save_upload('background_right', $validators, '/sites/default/files/lafemme/backgrounds/');

    if ($file_left) {
        drupal_set_message('Obrázok na ľavej strane je nastavený');
    } else {
        drupal_set_error('background_left', 'Chyba pri uploade ľavého obrázka');
    }

    if ($file_right) {
        drupal_set_message('Obrázok na pravej strane je nastavený');
    } else {
        drupal_set_error('background_right', 'Chyba pri uploade pravého obrázka');
    }

}

But it doesn't work. Form is acting like there are no files selected on submit even if they are. Later I found out that it doesn't work probably becouse of system_setting_form function. In drupal 7 there is a managed_file type of input. But what about Drupal 6? It is possible to upload a file in system_setting_form()?

I found the problem: https://www.drupal.org/node/64984

Drupal 6 won't upload a file if file field is required.

Such an enormous bug. No mention in documentation about that, you have to find it yourself.
Drupal can be really disappointing...


Programming Layout Changes into Theme Templates & CSS Files I've kicked a problem down the road for too long and am now stuck in the fact that I finally need to get it fixed.

I need to program layout changes into the php code so that the right CSS rules can apply to changes based on whether or not the left sidebar and/or the right sidebar is present on the page. In these sidebars are a variety of blocks that I have added to the templates and theme .info file.

So here's an example of my situation. If you need access to my current template files let me know.

So for one page, say I have one side bar the main content area, the css rules would read : Left_Sidebar (width: 33%) and Main_Content (width 66%). But when switching pages, say to one without a sidebar, I want the css rule for Main_Content to be (width: 100%).

I've seen it done on other themes, but this theme is all of my own design. Some examples I've seen are in the "body class" where you see "with-sidebar", "no-sidebar", "two-sidebars" -----

I've tried looking around, but I must be not using the correct terms for what it is I'd like to do. If there is anyone who can help, please let me know! Thank you in advance!

Many existing themes already provide this kind of feature (usually using a preprocess function) so I would recommend looking at a theme like Zen or another popular base theme for examples of varying the page layout with a body class which specifies the overall structure of the page.


How to auto generate biblioographies I currently have a content type called book, where the book has fields: author name, book title, ISBN , publication date, ect.

I'd like to automatically generate a bibliography entry for each book so that users can copy and paste it easily. Is there a module that can do this? I know of the biblio module, but to the best of my knowledge you must directly input the information.

So is there a way to automatically generate a bibliography citation entry for a given book based off of the book's given fields?

You need to look into views https://drupal.org/project/views and you can display your content anyway that you want to display it. There is a small learning curve but displaying content type fields is one of the easiest forms of a view to setup. There are tons of examples setup and disabled by default from many modules so chances are you already have views code somewhere in your site even if you don't have the actual module yet :)
Look at the project page under Resources heading to find documentation and tutorials plus there are millions online with quick Google searches.


Printing regions in html.tpl.php I need to output some regions in the html.tpl.php template since these don't change between page.tpl.php and page-front.tpl.php (just to name two). Basically I want to avoid code duplication.

However there seems to be nothing associated with regions in html.tpl.php, nor I could retrieve anything using drupal_get_region_content (both with and without parameters it just returns an empty array).

Ideas?

I solved like this:

function mytheme_preprocess_html(&$variables) {
    $variables['region_name'] = block_get_blocks_by_region('region_name');
}

and then I could do

<?php print render($region_name) ?>


Can I use my own template for a view mode? I'm creating a cusom module that loads a node  through a view_builder. However, none of the available view_mode display the elements like I'd like them to be, so I'm about to create my own view mode. However, I have parsed quite a few tutorials about view_builders, but none talked about using a custom template (or I missed it)

So, is it possible to use your own template, and how do you do so?

Thank you in advance

The standard way to do this is to create a template in your theme, you can use node--nodetype--viewmode.html.twig . (two dashes between each part).

To use it in your custom module, you'd have to use hook_theme_registry_alter to change the path that it looks in for that theme hook.

function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['node__nodetype__viewmode']['path'] = drupal_get_path('module', 'mymodule') . '/templates/';
}

I don't really see the value of moving it into a custom module though.  It's a standard to keep custom templates in the theme.


Conditional field in node type depending on user profile I have a site with two user profiles (group/single). I have a node type repertoire with a field function which I only need for the profile single (mandatory field). Is there a way to hide this field when a user with profile group is adding a node? I don't want to make two different content types with only one little difference.
Thanks in advance!

If you want to hide a field from particular role via a contrib module, you can try

http://drupal.org/project/field_permissions

or if you're comfortable in code, see

hook_field_access

e.g:

function mymodule_field_access($op, $field, $entity_type, $entity, $account) {
  if ($field['field_name'] == 'field_of_interest' && $op == 'edit') {
    // TODO: some special access check for TRUE or FALSE in $access
    return $access;
  }
  return FALSE; // default deny
}


Converting a form field to multiple submit buttons? I'm not sure how to explain this well in text, but I want to change this:

Into something like this:

In Drupal 8, I have an entity for which the only user-editable field is Score, which is a List (integer) with six possible scores, 0 to 5.
On the edit page, I want users to be able to press a button to assign the score.  There should be one button for each score.
How can I implement something like this?

I would like to suggest is, use  hook_form_alter, create an ajax handler on value change on select list, disable ( remove) submit button.
/**
 * Implements hook_form_alter().
 */
function YOURMODULENAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['YOUR_FIELD_MACHINE_NAME']['#ajax'] = [
        'callback' => array('mycustomSubmit'),
        'wrapper' => 'vote-wrapper'
      ];

      $form['YOUR_FIELD_MACHINE_NAME']['#prefix'] = '
',
      $form['YOUR_FIELD_MACHINE_NAME']['#suffix'] = '
';
    // disable submit button
    $form['actions']['submit']['#disabled'] = TRUE;
 }
}

  /**
   * {@inheritdoc}
   */
  public function mycustomSubmit(array &$form, FormStateInterface $form_state) {
    // YOU CAN DO NODE CREATION HERE,
    \Drupal::messenger()->addMessage($this->t('YOUR SUCCESSFUL MESSAGE'), 'status', TRUE);
  }

and in twig template theme the select options instead of radio, theme them in a button like what you want. ( or even you can  style radio options as button with just CSS)
for reference: Customize Radio Button Appearance with CSS


How can I use drush dd in bash script? In a bash script I use drush site-set @foo_alias to simplify subsequent drush commands.
I would like to compile my SaSS files using compass compile $(drush dd my_theme).  However, for this case I have to explicitly specify the alias as in compass compile $(drush @foo_alias dd my_theme).
Otherwise, I get an error message:

You need to specify an alias or run this command within a drupal site.
Target 'my_theme' not found.

Is there a bash syntax that obviates the need for the alias in the drush dd command?

There are several ways to specify which Drupal site Drush will target; the alias is probably the simplest.

The second option is more verbose, but it does not require an alias file.  Run:

$(drush --root=/path/to/drupal --uri=http://mysite.com dd my_theme)

You can do the same thing with a slightly different syntax:

$(drush /path/to/drupal#mysite.com dd my_theme)

You can also specify the Drupal site implicitly, by setting the cwd to the folder that contains the settings.php file for your site:

cd /path/to/drupal/sites/default # or /path/to/drupal/sites/mysite.com, as appropriate
$(drush dd my_theme)

A distant fourth option would be to use the site-set command; that would be a bad idea, though, as it uses the current process id to identify the filename that stores the current Drupal site.  If your bash script created any subprocesses (e.g. by wrapping sections of the script in parenthesis, using $(), using backticks, etc.), then commands inside the subprocess will "forget" the currently set site.

For example, the following script will only print the site that was set once; the portion of the script inside parenthesis fails to find the set site:

drush site-set @foo_alias
echo "process $BASHPID"
drush ev 'return drush_sitealias_site_get();'
(
  echo "subprocess $BASHPID"
  drush ev 'return drush_sitealias_site_get();'
)

In a script, you are better off putting the site specification into a variable, and explicitly use that variable with every invocation of Drush.


exporting a field from dev to production My custom module creates a content type which has fields. I want to export config so that other developers/production can use it.
I run

drush config-export --destination=/tmp/myconfig

from /tmp/myconfig I take the following files:

field.field.node.CONTENT_TYPE.FIELD_NAME.yml   #field instance
field.storage.node.FIELD_NAME.yml   #field storage
core.entity_form_display.node.CONTENT_TYPE.default.yml
core.entity_view_display.node.CONTENT_TYPE.default.yml

and copy these files to modules/custom/mymodule/config/optional

In the destination machine I run

drush config-import  --partial --source=modules/custom/mymodule/config/optional

The field instance gets imported (I can see it on the content type) but the storage does not, and no table is being created in the database.

Am I doing anything wrong?
Uninstalling and re-installing the module doesn't help.

At Drush Commands something similar is mentioned in the comment of Sebastian Contreras:

  --partial and --source "custom directory" are not working at all after upgrading Drupal 8.3 to Drupal 8.4 and Drush8 to Drush9.
  It does not detect the source with --source and it does not detect the --partial causing lots of removals where they should not happen.

However, did you already try the Configuration Split module? This module allows you to create different sets of configuration stored in multiple directories, and merge them back together when needed/indicated.

I'm using the Configuration Split module mostly to exclude configuration that is only needed in my development environment and not in production (modules such as Devel and Stage File Proxy). If I understand your use case correctly, this module should be able to perform the thing you want.


What are the appropriate configurations for the Subdomain module on Window 7 running XAMPP? I have installed the Subdomain module (v 6.1.7), and I'm configuring a subdomain for testing on localhost.

I have been tearing my hair out for days now, trying to get this module to work on my PC - and I'm still stuck on the settings/configuration stage. I have scoured the web for help in vain, and now I'm appealing for help here.

My vital stats: Win7, XAMPP, Drupal 6, Subdomain 6.17. (I gave up on 6.2 because it turned my links into www.localhost/....)

My site is localhost/ideastar.

Here are the changes I have made:

settings.php

$cookie_domain = '';

Leaving this commented out gives me an error ("The $cookie_domain variable in settings.php is not set".)

Uncommenting and putting in "localhost", ".localhost",  "ideastar", ".ideastar" gives me an "Access denied" error.

It seems to accept "localhost/ideastar" or a blank ' ',  although I don't know if this is the right thing to do.

host

127.0.1.1   localhost  ideastar

(and I can successfully ping ideastar)

http.conf

NameVirtualHost *:80
<VirtualHost *:80>
ServerName ideaster
ServerAlias *.ideastar
DocumentRoot C:/xampp/htdocs
</VirtualHost>

Can someone please help me get past the following errors?

Subdomain Prerequisites

  To enable subdomains on your website, you must first configure the following 5 items. If something isn't working, refer to the suggested solutions and make sure you have completed each step outlined in readme.txt.

  DNS server show/hide details: Not working yet
  test-1.localhost: Failed to resolve
  test-2.localhost: Failed to resolve
  test-3.localhost: Failed to resolve

  It appears your DNS server is not setup to handle wildcard subdomains (*.localhost) for localhost. Edit the DNS zone file or settings for your server to fix.

  PHP caches DNS lookups, so you'll want to restart your web server after making changes to your DNS server to see the results of your changes on this page.

  Web server: Unable to test
  Unable to test Apache settings until DNS wildcard subdomains are working
  Drupal's inbound URL rewriting - show/hide details: Not working yet
  HTTP request to http://subdomain-test.localhost/ideally/subdomain/test resulted in an internal Drupal path of . It should have been ~subdomain-test/subdomain/test
  The custom_url_rewrite_inbound() function in settings.php is rewriting the internal path incorrectly. Did you patch settings.php? See readme.txt for instructions.

  Drupal's outbound URL rewriting - show/hide details: Working
  Drupal API: url('~subdomain-test/subdomain/test') returned 'http://subdomain-test.localhost/ideally/subdomain/test'
  $cookie_domain in settings.php - show/hide details: Set
  The $cookie_domain variable in settings.php is set to ''

I think you have to setup a virtual host in XAMPP having a different IP, like 127.0.1.2 and adjust your host file by adding 127.0.1.2 sub.ideastar.

More here (but in german.)


A commerce fees rule works fine, but is giving the warnings in the log I've enabled the Commerce Fees module and added a rule with the following details:

{ "rules_setup_fee" : {
    "LABEL" : "Setup Fee",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce License Billing" ],
    "REQUIRES" : [ "rules", "commerce_fees" ],
    "ON" : { "commerce_fees_order" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "commerce-order:commerce-line-items:0:line-item-label" ],
          "match" : "book"
        }
      }
    ],
    "DO" : [
      { "commerce_fees_apply" : {
          "entity" : [ "commerce-order" ],
          "fee" : "setup_fee",
          "amount" : "999",
          "currency_code" : "USD"
        }
      }
    ]
  }
}

which correctly adds $9.99 setup fee to a shopping cart when customer selects any product which has the "book" string in its title (or SKU which we try to keep the same). So the whole thing serves its purpose just fine, however unfortunately it also leaves the following traces in the logs:

  Unable to evaluate condition text_matches. Unable to get the data
  value for the variable or parameter text. Error: Unable to get the
  data property line_item_label as the parent data structure is not set.

What am I doing wrong here? Thanks!

You should add a data_exists to ensure that the delta/label you're trying to access actually exists. It looks like line-item-label is a custom property.


I function and menu_link I need to put an id in menu links  i have this code from here https://api.drupal.org/api/drupal/includes!menu.inc/function/theme_menu_link/7.

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

And have found the code i need but am struggling where to place it in the function. This code https://api.drupal.org/comment/45408#comment-45408:

l( t('Refresh Page'), $path . '/getdata', array(
              'attributes' => array(
                'id' => '',
                'class' => 'btn-small btn-primary '
              ),'query' => drupal_get_destination() , 'html' => TRUE)),

    );

Where would it go, i know what i need, but i am having difficulty doing it.

Thanks

You can use this module to place different menu attributes to your menu links:
Menu Attributes

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
You should use this module when

You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site.

You want to give a menu item an ID so you can easily select it using jQuery.

You want to add additional classes or styles to a menu item.

You can also add the ID using theme_menu_link like you were using above, you would place that code in your template.php of your theme.
If you use the Devel module you can print out the $variables array and see the different parts of the array there. You would basically want to use the mlid and the attributes part of the link to build out the ID (see code snippet below).
$element['#attributes']['id'] = 'menu-' . $element['#original_link']['mlid'];

If you need any other information just let me know, thanks!


About the template for poll recent block in drupal 7 I need a template for the poll recent block in drupal 7.  I have tried with block--poll.tpl.php and block--poll--recent.tpl.php and poll--recent--block.tpl.php and I can't see any changes.  What's my wrong?

block--poll--recent.tpl.php will work if you clear your system cache (configuration > development > performance > clear all caches).

Worked for me.

See complete template suggestion list for Drupal 7 here : http://drupal.org/node/1089656


Ajax call failing in Workbench email module I'm having trouble with ajax in the workbench email module. On two nodes (out of hundreds), the ajax call to get a list of users to notify when the publication status changes will fail. The error is "Invalid form POST data". I added watchdog logging, and actually the entire $_POST is missing when the ajax fires. Does anyone know what would cause that?

I can't reproduce this in our development environment. I copied the database down, and the codebase is the same, but the same node works just fine in dev.

I've turned off boost caching on the live site and deleted the cache, and that did not help (although it's a node edit form, so I didn't think caching should matter).

It's consistently happening to the same two nodes, but I can't see anything different about them than the other nodes that work without issue.

One more thing -- I am using the Ajax Debugger chrome extension, and postData is populated in the request object with all of the form data and sent to the server. So it must be something in the drupal_bootstrap to remove $_POST data, but I'm stumped.

Thanks to Clive's suggestions, I logged the request and post data before the Drupal bootstrap kicked in, and found that it was not Drupal causing the issue.

The root cause was two different mod_security violations: PCRE limits exceeded and matching rule 300016 (Generic SQL injection protection).  Increasing the PCRE limit and adding an exception for the SQL Injection rule:

<LocationMatch "/system/ajax">
  SecRuleRemoveById 300016
</LocationMatch>

Just for the record, I got the idea that Drupal might strip out $_POST data from this comment: https://www.drupal.org/node/2209051#comment-8539311  I came across it trying to troubleshoot this issue earlier. Maybe I misunderstood or took it out of context. This was a hard one for me to figure out, and I was grasping for anything that sounded close to my issue. Thanks for the help, Clive!


Showing Taxonomy Terms with Empty Descriptions in Views I'm trying to display a list of terms from a single vocabulary that have blank descriptions. I'm using views, and I've tried to set up some regexes as filters. A simple: [\w] returns all of the non-blank ones. However, when I try to do something like ((?!.[\w]).) which should negate the string, I get some sql errors. I tried filtering with not containing certain words (i.e. any words), and I tried "shorter than" 1, but it seems that the truly empty description fields don't show up on any of these.

Any thoughts?

Try adding this to the filter field for the taxonomy term description in the regex: ^[\s]*$


Proper way to do entity query? I am wondering if EntityFieldQuery is the proper way to do this

SELECT * FROM field_data_field_products JOIN node ON entity_id = nid

I'm wondering if there is a better way then my current db_query way, when dealing with entities.

You are not doing the query quite right.  There are a few things you are missing.

You need to remember that fields can be on multiple entity types, and that entity IDs are not unique globally.  This needs to be part of the JOIN clause.

The other is that there is a deleted column, that represents whether the data item has been deleted or not.  This also needs to be part of the JOIN clause.

You also need to ensure node access rights are maintained for any query against the {node} table.

EntityFieldQuery will take care of all of this for you.  Otherwise, you should use db_select() to build the query, as you can ->addTag('node_access') the query.

Something like this would be a start for node entities:

$query = db_select('node', 'n')
  ->addTag('node_access');

$query->join('field_data_field_products f', 'f.entity_id = n.nid AND f.entity_type = :entity_type AND f.deleted = :deleted', array(
  ':entity_type' => 'node',
  ':deleted', 0,
));

$query->fields('n', array(...))
  ->fields('f', array(...))

You would modify this to use different tables and types for different entities.  If you aren't querying against the {node} table, then you can skip the ->addtag();

If you end up using EFQ, remember that it only returns the entity_ids, so you have to entity_load() the results (or use the entity specific version like node_load()).

Regarding the query, it is a good habit to put your base table first and then join the secondary tables.  This helps with readability.  You should also try to explicitly pick the fields you need and avoid * results.  There is no rule against this, it is just considered best practice by some.


Predefined field collection items in node edit form I have a Products taxonomy with all possible product names offered by the organization, Order content type to place an order and ordering form. Order content type includes field collection with term reference field referencing to Product taxonomy. The case is that I need to predefine field collection items with all possible selected Product terms on ordering form.
Items number = count(Products terms)

I tried to use field_multiple_value_form function to generate items, but in this case I can't predefine default value for field inside field collection item (or can?).

$products_taxonomy = taxonomy_vocabulary_machine_name_load('products');
$product_tree = taxonomy_get_tree($products_taxonomy->vid);

if (is_array($product_tree)) {
  $field_instance = field_info_instance('node', 'field_fc_o_position', 'order_request');
  $field_instance['cardinality'] = count($product_tree);
  $field_instance['type'] = 'field_collection_item';
  $field_instance['columns'] = array();

  $form_state['field']['field_fc_o_position'][LANGUAGE_NONE]['items_count'] = count($product_tree);
  $instance = $form_state['field']['field_fc_o_position'][LANGUAGE_NONE]['instance'];

  $form['field_fc_o_position'][LANGUAGE_NONE] = field_multiple_value_form(
    $field_instance,
    $instance,
    LANGUAGE_NONE,
    array(),
    $form,
    $form_state
  );
}

Question is how to generate empty field collection items on ordering form and default value for select field inside each new item?

Thank you!

I do not think that this will work in the way you wish, since Field Collections are entities rather than normal fields.

It sounds to me like you need to use form_alter to update your input form.

Checkout this link on Drupal.org for one method that might work:
Finally - found a solution... (D7)


How do I ignore a module .git directory? I've got a Drupal 8 installation that I manage with Drush 8.1.2, with nothing in that installation in Git except a custom module I am writing (module directory = location of .git directory = /sites/all/modules/mymodulename).

Whenever I do a drush pm-update it complains about my module:

  Project was not packaged by drupal.org but obtained from git. You need to enable git_deploy module

I don't see how I can follow the suggestion of git_deploy which, as far as I can tell, provides an update source for modules checked out of drupal.org... so how can I let Drush know that my module is a stand-alone Git installation, and stop it from generating that warning every time?

The --lock option to drush pm-update is probably not appropriate, since my module is neither a core or a contrib module, and it doesn't change the warning in any case.  The only thing I've found to make that warning go away is to delete or rename the module's .git directory.

p.s., one thing I noticed later: the warning also goes away if the module is uninstalled: probably because uninstalled modules aren't checked for upgrades.

Your analysis is correct; git_deploy is only useful for projects that are ultimately hosted on drupal.org.  The pm-* commands only operate on drupal.org projects, and have no facility for ignoring projects from other sources.  This is a limitation of Drush; improvements in this area would be welcome.


Is there a way to dynamically apply a CSS to a menu that includes the taxonomy term of the current page For example, if I have page nodes with a vocabulary called "issues", which has terms, such as "budget", "education" and "foreign policies", and there's a menu titled "Information", I want to be able to add a class to that menu link for each page, such as "budget-info", "education-info" and "foreign-policies-info", dynamically.  I assume I can throw in a JS behavior, but if there's a module that does this so the user can manage the class names assigned to each menu, especially that handles tokens and/or PHP so you can throw in part of the current url, that would be better. Note that I don't want to create a menu from taxonomy terms, but a standard item in the main menu with a custom class name applied which is comprised of a combination of a manually supplied name, and a taxonomy term that comes from current node.

Thanks!!

You could probably use Field Formatter CSS Class in some form or fashion, that can add a class to the node based on a taxonomy term, etc.


How to add new content using a content type added after taxonomy access control was installed? I have added some content types to Drupal to store some custom content.
Then I installed the Taxonomy Access Control module to manage the access rights. At this point everything was working perfectly and easily.

Then I added a new content type but when I try to "add a new content", this content type doesn't appear in the list of content types.

Is this because of the Taxonomy Access Control module? Do I have to re install it?

Note: I also flushed the cache and performed "rebuild permissions". It appears in the admin/content type filter. but if i add content, no trace of it.

Have a look at the Community documentation of the Taxonomy Access Control module. Especially what it says about the Global default (within Global and vocabulary defaults), i.e:

  The global default, at the top of the form, determines the grants the role receives for untagged nodes (including nodes with terms that are not in controlled vocabularies). Keep in mind that access is denied by default, so if you want TAC to grant a role access to untagged nodes, set the global default to allow for that grant and role.

See what happens if you adapt this default. If the issue persists, then you may want to perform TAC troubelshooting, possibly even Troubleshooting with Devel.


How to examine existing field values and modify other field in hook_form_alter? I have a content type with a bunch of fields attached.  When displaying the node edit form I want to hide or display one field ( using $form['some_field']['#access'] = FALSE; ) if another field has a specific value.

I am using hook_form_alter() and would expect to find existing field values within $form_state['values'] but this key isn't present even though the form fields do contain existing previously saved field values.

What am I missing ?

Thanks

In node edit form $form_state['node'] contains full node object , from which will get the existing field values.


How do I modify the "has_js" cookie? I have a web application deployed through Drupal 7.43. I need to modify the has_js cookie that is set by Drupal to make it both Http-only and Secure for a site security review.

What are pros and cons of making the has_js cookie Http-only and Secure?

The has_js cookie is set, to indicate JavaScript is enabled, in drupal.js with the following code.

// 'js enabled' cookie.
document.cookie = 'has_js=1; path=/';

The HttpOnly flag makes the cookie not available from JavaScript.
For that reason, it's not possible to set the HttpOnly flag when creating a cookie from JavaScript. It may cause issues if there is code that checks for that cookie to determine if JavaScript or cookie support is enabled.

The Secure flag is used to make the cookie only available over HTTPS, which may cause issues with checking for JavaScript support on non HTTPS pages. Nevertheless, if your site is fully HTTPS, that should be fine.

With that being said, you could look into setting the HttpOnly flag on the has_js cookie server side, by checking for that cookie and updating it to use the HttpOnly flag via setcookie().


Get search to index meta tags keywords? So I am using the Meta tags module and really would love if search would index the meta tag keywords of nodes. How would I go about this?

I can't check it right now, but I guess the following should work:

For each content type (its meta tags you want to be indexed), go to "Manage display".
Add the "Search" display.
Add the metatag field to that display.

Assuming that the metatag module uses fields. If not, you'd have to create a dummy field (comment, if you need that explanation).


Changing the url which the logo links to I'm using Zen Theme 5.x and want that the site logo links non to the front page but another page in my base url, like to a contact page. It seems that I can achieve this modifying the page template file but I don't know how to do it. Could anybody help me with this?

Thank you.

Don't do it.

Linking the logo to the front page has become a de facto standard. Linking it to the contact page would only confuse users who expect to go to the front page, while users who want to go to the contact page would probably not click the logo.

Update in response to the comment below:

In my opinion, a language selection front page is a bad idea. Remember that people come to your site in order to accomplish a task. That task is never to choose a language. Also, consider how you want Google to see your front page.

A better alternative is to serve the front page in a language determined y the Drupal Language Negotiation API and make it really easy for users to switch languages if they want to. Read more about multilingual front pages at HowTo: Different home page (default front page) for each language and Drupal 7: Cracking the multilingual front page nut.

Now, if you still want to change the url the logo and site name link to, enable the THEMENAME_preprocess_page function in your Zen sub theme (you did create a sub theme, right?) and alter value of $variables['front_page'].


How to remove the div surrounding the view block? I created a view block that I added in the navigation bar.

When I inspect my page, I have a div around my block.

How can I delete this div ?

I want to have only :

<section class="views-element-container block block-views block-views-blockmenu-page-utilisateur-block-2 clearfix" id="block-views-block-menu-page-utilisateur-block-2">

Enable Twig debugging as per this https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates
Then, see which template file is currently outputting your block view
Create a new twig template file in your theme with the same name
Copy the content of the original file
Edit accordingly


Adding HTML5 placeholder to all drupal forms I'm trying to add the placeholder attribute to all textfields across my website, but I'm having no luck.

I've created a module that overrides hook_form_alter

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    foreach ($form as $key => $value) {
        if ("textfield" == $value["#type"]){
            $value['#attributes']["placeholder"] = t($value["#title"]);
        }
    }
}

I should tell you that I'm also using the webform module.

Because I'm using the webform module I could just theme the global webform template (webform-form.tpl.php) and put it in my theme folder. No need to complicate things with a module.

foreach ($form["submitted"] as $key => $value) {
    if ("textfield" == $value["#type"]) {
        $form["submitted"][$key]['#attributes']["placeholder"] = t($value["#title"]);
    }
}

I put this at the top of the template file.


Create a view to show a user his or her recent activity I am creating a view that would display the activity of the users. When user 1 is logged in, it would show the activities of user1 only...his node uploads, his comments etc,,,such as:

User1  commented on "Some Artcile"   Time
User1 Uploaded his article "Some BLOG"  Time

How should i proceed. I am using Views3, and Drupal7

Why not just use the  heartbeat or the message module and let them do the heavy lifting for you


Authentication page before loading the main website I am using Drupal 7. I need any user(who has not logged in) to just see the login screen only for authentication before he can traverse the actual website.

How this can be done?I tried to do it using Panels but without success.

You can use this module

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail address.
Allow users to login immediately.
Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
Customize the registration form with two e-mail fields to ensure accuracy.
Optionally redirect the user to a specific page when using the 'immediate login' feature.
Optionally redirect the user to a specific page upon validation of their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a pre-defined interval.
Integrates with the Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example).

Or you can add this code as well:
    global $user
    if ($user->uid  == 0  && $_GET['q'] == 'node') {
      drupal_set_message("Access Denied: Please Login");
      drupal_goto('user/login', drupal_get_destination());
    }


How to add Javascript code into a block I have a Drupal 7 site. I'd like to add Social Media follow buttons
(i.e. Follow us on Facebook, Twitter, Linkedin).
I grabbed some Javascript code from http://www.addthis.com
 which generates these buttons and also links to some analytics services I will be using.
Now I need to figure out how to place the AddThis Javascript code I generated, to a Drupal block. Once it's in a block, it will be easy for me to move around my Drupal site pages.

Why not just use the addthis module rather than adding a block. If you however want to add a block, just go to admin/structure/block click on add block. Paste your script in and select filter type of php code and click save

If you do not have PHP filter in the filter type, enable it under the core module


Feeds importer imports only some of the nodes In D7.59 I have to import .csv file and there are all the mappings prepared for that. The file has 500 records, that will become nodes of a content type "record". There are no nodes of this content type in Drupal before the import (all nodes are deleted). When I start the import after it finishes I get the result, that 334 nodes were created and 266 nodes were updated.

Log does not show any errors by the way.

I presume that there are some kind of feeds cache that has to be cleared, to make sure that it does not think that some of the nodes are still in the site. Can someone tell me what SQL tables I should truncate, or maybe there is another way to solving this?

Feeds keep track of previously imported items in the feeds_item table. This also includes items that were only updated by Feeds, but not originally created by Feeds.

Under normal circumstances, when you delete an entity imported/updated by Feeds, Feeds will delete the corresponding import meta data from the feeds_item table. There can be occasions where this does not happen. These are:

During the deletion of the entity, a PHP fatal error occurred which prevented Feeds from cleaning up the import metadata. Non-fatal errors should not cause this, as Drupal would then perform a rollback of the deletion.
Feeds is disabled when deleting the entity.

Feeds doesn't clean up orphaned items from the feeds_item table. To clean this up, you'll need to execute a query on that table. The id column represents the importer ID and feed_nid the feed node ID (the latter is only used when you have attached your importer to a content type and you need to create a node to import content).

Example query to delete all import metadata for the importer 'my_importer':

DELETE FROM feeds_item WHERE id = 'my_importer';

There is an issue to let Feeds automatically clean up orphaned feed items: https://www.drupal.org/project/feeds/issues/1394320

For more information about the feeds_item table, see https://www.drupal.org/node/1768352


How to use the Rules module to award userpoints to referring users? I am creating a referral program on Drupal. I have almost everything working right except awarding userpoints to users. I want to award userpoints to users after the person they refer to the site becomes a paid member. I have tried severally with Rules but no success.

I am using these modules:

User Referral module to capture referrals.
User Points to award userpoints.
Membership Entity to create paid members.

What I want is to create a rule using Rules that automatically awards userpoints to a user once the person that a user refers to the site becomes a paid member of the site.

Anyone with better knowledge able to help me out here?

Add a field to user registration form that collects the uid of the referring user. Then ask current users to invite other people to the site using a custom URL to user registration form and this URL should include as query parameter the uid of the referring user. Hook the user registration form and fill in the uid of the referrer based on the query parameter. You should hide the referrer field completely. Then you do counts in the database for how many paid users a given uid had invited. The referrer uid in regard to each user is kept in the custom user profile field and becomes meaningful in your situation if the user becomes a paid member.


'Add another' fieldset on a multi-step webform I have a multi-step webform using ajax (I'm using webform steps and webform ajax modules).
The webform contains several pages (i.e education, career and experience).
In education page i have the following fields: degree and major which are placed inside a fieldset.

I tried using the webform add more module but it wasn't working (not displaying) although i followed up several recommendations and i know how it works. You need to specify the number of fieldsets, it doesn't create them dynamically.

Is there any other way for me to use the 'add another degree and major' feature?

I am using Drupal 7 and the Webform module 7.x-4.19.

Try using Field Collection in the form. It got the feature of adding multiple fieldset on the fly.


Drush destination command not recognising I'm able to see the destinations by using the 'bam-destinations' command and below is my script to get an entire site backup from a ftp destination (ID of this destination is 'ftp_destination' and I have entered ftp details through BAM module frontend).

drush archive-dump default http://www.example.com/ --destination=ftp_destination

For some reason it's not uploading in to the ftp location but just creates a backup called 'ftp_destination' in my local PC.

Thanks

Check out the drush documentation here.
There's no mention of ftp, the backup archive is saved locally. If you want to ftp your archive somewhere you will have to handle it separately, archive-dump will not do it for you.


How do you get and submit a webform in React? I am planning to build a Drupal 8 site fully decoupled using Gatsby (a site generator for React). So I will use Drupal only to structure (content types, paragraphs), enter and update all the content and data and use React for the frontend.

The website also needs a (simple) form. I want to use the webform module for this.

But how do you get a Drupal form in React and after submitting send all completed fields to the database?

Whenever I ask for a module it gets closed. You got lucky, I guess?

It seems https://www.drupal.org/project/react_webform_backend together with https://github.com/oikeuttaelaimille/gatsby-drupal-webform provides a solution for React/Gatsby. Note:

  This module only provides basic components (textfield, number, textarea etc.) out of the box. More advanced webform components or composite components should be built as custom components.

And then there's an example.


User photo gallery that another user can view I'm looking to give my user the ability to to have a personal photo gallery that when another user clicks on their profile they can see said gallery?

I know i can create a content type and view, but not sure where to go from there as far as only exposing the necessary photos for a specific user to another. basically a dumb-ed down version of what Facebook has as far as photos.

for some interesting options, take a look at the Album Photos module. I'm not sure if it will do what you're asking OOB, but if you use it, it would change your question so I'll suggest it.

  "Album Photos" is an image album module providing multi-user album
  features. The module development objective is to provide a
  comprehensive image album solution for Drupal.

  Version 7.x-3.x Highlights

  Integrates with core image styles. Uses Libraries API 2.x for
  Jeditable. Built in support for Colorbox. Vote on images with Voting
  API. Comment on images. Built in support for Plupload. Upload multiple
  images with Plupload. Limit the number of albums created per role.
  Reads image exif parameters. Nice presentation of the images. Views
  integration. Support for private file system. Drag and drop interface
  to re arrange photos and albums to sort by custom weight order. Photos
  Access Included as a sub module. Enable this module to control who has
  access to the photos and galleries.

  Create password protected photo galleries. Create galleries with a
  list of collaborators who can edit the same gallery. Create private /
  locked galleries that can only be seen / edited by the gallery owner.
  photo gallery, image gallery, user managed photo albums


Setting secure cookies In scanning a Drupal 7 site with Qualys, we're getting the issue

  150122 Cookie Does Not Contain The "secure" Attribute

Is there a way to systematically add the Secure vs HTTPOnly flag to cookies? Would Secure Cookie Data serve this? If so, how do I test that Cookies are secure?

Moreover, this site automatically forwards to https. The user spends no time over port 80 but instead is directly shuttled to 443. We have an administrator who wants nothing but to see this test passed; regardless of the previous fact.

The Cookie in Question:

has_js=1

Would the following in settings.php be sufficient:

ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);

Which cookie is this? All of Drupal 8's cookies are secure.

The exception is BigPipe's no-JS cookie, see https://www.drupal.org/node/2678628 — but there are no security consequences there.

If that's the one that is triggering this alert, then the problem is clear: your security testing tool is making blanket statements that don't make sense.


How to show a RSS feed button for aggregator node page I use the Aggregator module to display RSS contents. I want to have a RSS button along with the aggregator node, how can I enable or add the button to page?

The RSS icon should already appear automatically on the page. If not, check your theme's page.tpl.php file and make sure it has this line on it:

<?php print $feed_icons ?>


How to get grouping values in views I created a views to show all my products, in each product have a field named "Color", so now I want to group all product has same color.
So now how can I get all grouping values,

For exam we have 6 results but just only has 2 colors : Red and Blue without Black one.

My question is how can I get grouping values in this views (Red, Blue)

$view->some_thing->some_how ?

I want to put those values in View footer for my personal purpose

My View should displayed like this

--- View Content ----
[RED]
Product 1
Produc 2
[Blue]
Product 3
Product 4

--- View footer
[RED] - [BLUE]

Thanks

Add Color field into view.
Now click on formate setting.
Select the Color field as a Grouping field.


Providing menu route parameter values from url Suppose I have the following route in my ej.routing.yml file:

ej.form.user.profile:
 path: '/user/{user}/ej_profile'
 defaults:
   _title: 'EJ Profile'
   _form: '\Drupal\ej\Form\User\ProfileForm'
 requirements:
   _role: 'authenticated'
   user: \d+

Now I want to add a menu based on the above route to Tools menu. So I use the following in ej.links.menu.yml file:

ej.user.profile:
  title: 'EJ Profile'
  description: 'EJ Profile'
  route_name: ej.form.user.profile
  menu_name: tools
  weight: 100

However this gives me an exception saying: Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("user") to generate a URL for route "ej.form.user.profile".

The same works as a task entry. Basically I have a custom form that extends user profile to integrate with a third-party system and I need the user id from the url to fetch appropriate user's information.

How can I have the menu to pick route parameter from the url?

It may not be the best solution, but you could add an additional route and link to that in the menu, this route would link to something like /admin/ej_profile. Then via the controller get the current user information and redirect immediately to the correct profile form.


Why is AJAX pager in Views not recording the history I have a listing of news, used with Views module in Drupal 7. I have activated Use Ajax in advanced section. So now the pager loads the content smoothly, without loading other page. That is nice, but the pager is not recording the history of the browser, so when I hit several pages of the same listing, it loads all the content perfectly but when I hit the Back button of the browser, instead of going to the last page clicked on the listing, goes to a previously visited site, even a different website, depending on my browser history. This happens, aparently, because there seems to be no built-in mechanism to record website history or at least change the toolbar address with "#" so it can have a behaviour similar to what be expected. Is there some way of circumventing this?

I have not used but you can take a look

Statehandler module and History.js module


Is there a way to change how a form button looks? I know how to add a class to a form element and how to add a form submission button, but there are classes that are automatically added to these buttons in my Drupal 8 install.
The form I am editing has two buttons, a submit and a skip button; both the buttons look the same. I would like to add a visual clue to the difference between the buttons. The buttons get an automatic btn-primary class but I want the skip button to have a btn-outline-primary class. If I add that class with '#attributes' => ['class' => ['btn-outline-primary']], the class gets added, but the btn-primary class is still part of the button. The combination of those two classes makes the button text the same color as the button background color, and thus invisible unless you hover over the button.
Is there a way to perhaps not include the button in the template, for example {{ form.actions.skip }} but more verbose? In the sense that takes over some of the Drupal 8 automation?
<button class="btn btn-outline-primary">{{from.actions.skip.something}}</button>

There are two basic ways in Drupal to remove the class, a PHP hook or a Twig template. It's only possible to describe this in a general way because the question doesn't contain details about which theme and templates are in use.
For a PHP solution find out which hook is adding this class and then implement the same hook in your custom theme. If the attributes contain the specific class you've added to the form build, then remove the conflicting class.
For a Twig solution enable Twig debug, find out which template is rendering the button now, and copy it to your theme's templates folder. Then do the same thing as described before in Twig:
{% if attributes.hasClass('btn-outline-primary') %}
  <input{{ attributes.removeClass('btn-primary') }} />{{ children }}
{% else %}
  <input{{ attributes }} />{{ children }}
{% endif %}


What is the mechanism used to control how Drupal pages are rendered? I'm a Java programmer trying to get started with Drupal.  Specifically, I want to be able to create custom pages.  More specifically, I want to understand the nuts and bolts of how this is done (I'm an engineer; it's just my nature)  I have a little PHP experience and I've configured Drupal installations for years.  I'm aware of many of the modules that help make this process easier (such as the Views module), but again--I'm interested in working through the nuts and bolts myself.

I'm not specifically interested in creating new Drupal modules, unless that is the only way to create new pages in Drupal.  My primary interest is in being able to create a custom page.  Let me give a few examples:

I have a db of funny quotes.  I'd like to be able to use Drupal to display a selected quote AND HAVE COMPLETE CONTROL OVER THE PAGE LAYOUT (and again--not using an existing module; I want to understand the inner workings).  Don't ask why I'd want to use Drupal for this, or suggest alternate methods of accomplishing it.  It's a made up example to illustrate what I'm wanting to learn. :-)
This is a less made up example.  I'd like to create a "newsletter" where the site editors can select submitted content and customize layout (all in a custom UI) and then create a page with that content, one suitable for either viewing in a browser or printing.  Sort of a "desktop publishing" concept for Drupal.  Again, don't suggest ways of accomplishing this.  It's an example to illustrate what I'm wanting to learn.

Basically, I like Drupal's permissioning, modularity, and content management but I'd like to learn how to control display (as complete control over display as possible).  The problem is that I don't even know what topics to start learning.  Creating modules?  Themeing?  Something else?  What is the mechanism or system that I need to learn to be able to completely control how Drupal pages are rendered?

Corollary question: does such control (not limited to just a block or region, but including menus, headers, footers, and everything visible on the page) require modifying the Drupal code directly or can it all be done in the theme/module systems?

Aaron is right that you'd likely want to handle much of this at the theme layer. You'd want to familiarize yourself with how drupal handles templates.

As for the actual creation of a page in code, this page does a pretty good outline of a method. I've not done this myself, but it reads correctly.

You'll first want to understand how to build a module. The basics are, you need a mymodule folder, and a mymodule.module file and mymodule.info file. Anywhere you see a resource that says to use hook_some_function, you're going to replace hook with mymodule.

The nuts and bolts of the page above outline:

-- Implementing of hook_menu (in this instance, the module's name is starting_drupal_dev)

/**
* Implements hook_menu().
*/
function starting_drupal_dev_menu() {
  $items['starting_drupal_dev/custom'] = array(
    'title' => 'Custom page',
    'page callback' => 'starting_drupal_dev_custom',
    'access arguments' => array('access content'),
  );

  return $items;
}

-- Using the custom function starting_drupal_dev_custom to define how the page renders

/**
* Custom callback function.
*/
function starting_drupal_dev_custom() {
  $content['raw_markup'] = array(
    '#type' => 'markup',
    '#markup' => '
Hello world
',
  );

  return $content;
}

You could then assign your various database queries to variables in order to render them within #markup.

Again, I've not used this particular method myself, but it seems to me that you could at least use this as a starting point for what you're trying to do. Not sure whether or not you could combine this method with theme templates for layout or not. Maybe somebody else could chime in with regard to that.

As for your final question, NEVER (usually) HACK CORE. Handle everything in modules and themes.