How to add author's user role as CSS class to comments? Snippet from Bartik's comment.html.twig ( https://pastebin.com/D70cyHNp ):

{{ user_picture }}

{{ author }}

{{ created }}

I want to highlight comments by administrators with CSS so how can I say "if the comment author has the role administrator, add the class "comment_author_is_administrator" to the author variable?

This can be done pretty easily by preprocessing your comments.

But first of all, very important: don't edit any of Bartik's files (or any core files in general). Create a sub-theme, copy the comment.html.twig to your sub-theme's templates directory and edit that file.

Second, depending on your CSS setup comment_author_is_administrator doesn't seem like a legit CSS class. Normally, underscores are not allowed to be used that way. And maybe you can make it a little bit shorter. Maybe just author-administrator.

Finally, simply place the following snippet in you sub-theme's *.theme file and replace MYTHEME with your actual theme name.

/**
 * Implements template_preprocess_comment.
 */
function MYTHEME_preprocess_comment(&$variables) {

  // Get the comment.
  $comment = $variables['comment'];

  // Get its owner.
  $owner = $comment->getOwner();

  // Check for administrator role.
  if ($owner->hasRole('administrator')) {

    // Append CSS class.
    $variables['attributes']['class'][] = 'author-administrator';
  }
}

Alternatively, you could simply append each comment's author role as CSS class like following.

/**
 * Implements template_preprocess_page.
 */
function MYTHEME_preprocess_comment(&$variables) {

  $comment = $variables['comment'];
  $owner = $comment->getOwner();
  $roles = $owner->getRoles();

  // Let's pop the roles array to only
  // get the last (highest) role of all.
  $role = array_pop($roles)

  $variables['attributes']['class'][] = 'author-' . $role;
}


different "no content" message based on taxonomy vocabulary/term how would I change the message:
"There is currently no content classified with this term"
when viewing a term that doesn't have conent asscociated with it?

I see the message is in taxonomy.pages.inc and that I could just edit that line, but that would change it for ALL terms, whereas I'd like to have a custom message based on the taxonomy vocabulary.

Lets' say I have vocabularies:
"countries" message > Sorry no event listed in [country-name]
"sports" message > Sorry no games of [sport-name]

Please keep in mind I am not a coder.

Thank you

Drupal 7 has a default Taxonomy Views display you can use to override the default pages.  Here are the steps:

Install Views, if you haven't already.
Go to Structure -> Views and look for the Taxonomy term view.
In the little button that says "Enable", drop it down and select
"Clone", and create a new name for the view (it defaults to "Clone
of Taxonomy term").  This will make a copy of the Taxonomy view.
Edit the view, and drop down the Advanced tab.  Add a NO RESULTS
BEHAVIOR.
Select Global: Text area.
Enter the text you want to display for no results.

Let me know if you need help beyond this.


How do I change the description of a view? I have some existing views for which I have written a developer guide description. Now I duplicated the views for some other task, Duplication is successful but I didn't find any possibilities to change the description of the view. I check advanced section of the view but not successful.
The only way is to create a new view but it will take a lot of time and I already have it done in the existing views a few changes are required. But the description is different from the existing one.

When you edit a view, on the top right corner there is an Edit view name/description button.


How to display mini panes in specific pages of my site I need to display mini panels only in selected pages.

Where and how should I mention it?

For Example:

In blog listing pages i need to display the panels in right side.

And in it's full view page I should not show the panels in right side.

How can this be done?

There are many ways this can be done.

Blocks are pieces of content which can be placed in specific areas of the page called regions. You can choose where to put these blocks in the block section of the admin

The standard block admin will allow you to put conditions on who can see the blocks and what paths they are displayed or hidden on. However this can get a little difficult to manage with many blocks and conditions.

Many people use the context module for such situations. This allows you to override the standard block admin and define a context under certain conditions (path being one of them) and define blocks which are displayed under these conditions.


How can I insert a block into each page of a view if the page is loaded via ajax? I am trying to insert a SimpleAds block for each page of a View. But pages are loaded via AJAX using infinite pager. How can I insert a SimpleAds block into each dynamically loaded page of results?

You want to add a javascript such one below to either your custom module or theme (would recommend module). This will react on a view that has a class view-infinitestack, so replace it to match yours view.

Where the debugging code is (console.log) you can add whatever JQuery you need. Eg. ajax call to fetch new content and inject it in another div, sidebar, or anywhere else on the page just by using JQuery, etc...

(function($) {
  Drupal.behaviors.events = {
    attach: function(context, settings) {
      $('.view-infinitestack', context).ajaxSuccess(function(){
        // add your js here to refresh a block
        console.log('success');
      });
    }
  };
})(jQuery);


Image slideshow with onclick on thumbnails I am theming a node. I Want the images in the node to be displayed as below:

when I click on the second image second image should be loaded , when I click on third image third image should be loaded and so on.

How can I do this.

You can use the Views Slideshow module.

  Views Slideshow can be used to create a slideshow of any content (not
  just images) that can appear in a View. Powered by jQuery, it is
  heavily customizable: you may choose slideshow settings for each View
  you create.


Display content type through custom template I have been losing quite a lot of time with something that seemed straightforward initially.

I am trying to use a template file(tpl.php) to print a content type with custom html layout.

In template.php I added.

function responsive_bartik_preprocess_node(&$variables) {
  if ($variables['type'] == 'dagens_billet') {
    $variables['theme_hook_suggestions'][] = 'templates/dagens_billet--template';
   }
}

I added a templates/dagens_billet--template.tpl.php but nothing is being printed.
I've added the following test code in there:

<?php print render('Giannisssssssssssssss'); ?>

Any suggestions to make it work?

this is my method for doing such thing and it always works.

create a view of your content type (ct), say ct__view. create a page and rename it to
 page--path_of_view.tpl.php and embed that view inside it at any where you want with this instruction <?php print views_embed_view('ct__view','page');?>. now you can customize its fields output with views-view-fields--ct__view--page.tpl.php


Execute Drupal function in background, maybe with cron, for the duration of a user session It was too complicated description of the task, so let me edit it and simplify: I need a Drupal 7 function (data collection function) to be periodically triggered in the background but only a while a logged in.

Use case is that we need bunch of data from the remote server to display to the user and it takes long time for all the data to be (1) copied from the remote server, (2) upload to local Drupal database and (3) finally to display to the user. So we don't want the user to wait, but to do some other staff and display the data little bit later when it is ready.

So scenario is like this:

User logs in to Drupal 7 website and start browsing pages without any delay.
At the moment when he/she log's in we need to trigger a Drupal function in a custom module that starts to perform steps (1) and (2) in the background. So user again doesn't feel any delays.
When the data is pulled and uploaded to the local Drupal 7 database, the system starts displaying it to the user.

Is it so difficult or impossible for Drupal to trigger a function in the background independently of whatever user is doing on the website only for the period of time while he/she is in the session?

Preface
While doing web development, if user is browsing can only be measured with two methods: 1. User last access time is less than A_PRE_DEFINED_AMOUNT (say 5 minutes) or (more accurately in some cases, as the user might be just reading the same page without refreshing) user's last heartbeat time is less than A_PRE_DEFINED_AMOUNT or or the most accurate, combination of both (js might be disabled on some browsers).
And while doing Drupal development, running a task periodically, means a cron task. but sometimes these tasks are better handled outside of Drupal.
The problem originates from the fact that Drupal does not have an always running server. Usually NodeJS is used in combination for such tasks, and it performs better (usually when resources on the server is limited). When the NodeJS has the data ready, it uploads it to drupal by calling a URL which you have previously defined in a custom module, say http://example.com/my/module/upload/data. It will use HTTP POST to authenticate and send data.
But anyway, here is the pure Drupal solution:
The custom module part:

Create a custom module.
Define a new entity type in your module (recommended) using a project like entityspice, model or plain entity api.
OR just use hook_schema() and define a table for your module in database (though entity is recommended).
Define a custom rule action in your module, when called it should write the current user id (uid) in the table you just defined. If you have created a new entity type you can use the already existing rule create a new entity.
Or just use nodes or a field in user profile but be careful about access checks. It's your call.
Create another rule action, triggered on cron (using rules_scheduler), in this action: fetch user's last access time, if it's more than 5 minutes, fetch the entity we talked about just above and remove it (more explanation on this later).
OR instead of rule action, define a cron task in your module. it should: check user's last access time, if it is more than 5 minutes, remove his/her uid from your custom table.
Or instead of checking user last access time, create a custom JS loaded on every page for logged in users which sends a heartbeat. It is simply done by defining a custom path in your module such as example.com/my/heartbeat/path and fetching that URL using HTTP GET (using ajax) on the server in your custom path's handler function, you should check current user's UID who is sending the heartbeat and update the last access time of the user. (or perhaps create your own entity/table/field for storing last heartbeat time).

Congrats! first part done. now you know if you should process data or stop processing data for user. You know you should while their UID is in your custom table.
The processing of data:
Still this part of question is unclear: who will fetch data? is there a large amount of data, or does it take long for data to become ready? if the former, you might face PHP execution time outs, if the later, you might be fine. Any way, to do it in Drupal, you should create a custom cron task which is again, possible in rules. in this cron task, check every uid which is in the custom entity/table we talked about above and fetch data for, and upload it to local database.
Your cron task should check two conditions: 1. is user uid still in table? 2. is data ready? if 1 is false, cancel fetching data. If 2 is false, just pass for now.
If there is a large amount of data being fetched and user has left the site, you probably won't be able to cancel it as there is no true multi-threading in PHP. how ever there is a register_tick_function which might do the job: if the uid of current task is removed, call die(). I don't know if die() in registered tick function works, however if data is being fetched for other users too, they will be canceled!!
final note:
DO Install Elysia Cron (optional but highly recommended). If you are planning to run cron on short periods it will take the load off of your server drastically.


How to install a specific version of a project with drush I observed that by default "drush dl module_name" installs the latest version possible may it be dev version available.

How can we install a specific version of a project with Drush?

To download a specific version of a project, specify the 'project name', followed by a dash, then the version name. The -y argument answers "yes" to any and all prompts.

The exact 'project name' for a module, is what is included in the URL of the module on D.O., i.e. everything following the last '/' in the URL. So for the Organic Groups module, that would be og, because its URL is https://www.drupal.org/project/og.

As an example, consider something like this:

drush dl og-7.x-1.3

With this command, you download the Organic groups module (replace it with your "module_name"), and more specifically the 7.x-1.3 version of it (replace it with the "version" you want).

You can also specify a development version of a module, as in this exmple (which would download the current 7.x-2.x-dev version of Organic Groups):

drush dl og-7.x-2.x

For many more details, samples, etc, refer to http://www.drushcommands.com/drush-6x/pm/pm-download and/or http://www.drushcommands.com/drush-7x/pm/pm-download.
Or to Installing a specific version of a project with drush.

After you downloaded the specific version, you "enable" the module as per the normal Drupal procedures to do so.

If you want to also enable the module using Drush, then there is no more need to specify the version of the module. To continue the above example, to enable the 7.x-1.3 version of it (after you down;oaded it), use a command like so:

drush en og


Not able to navigate through different sections of administrator page of fresh installed drupal 7.14 At the first instance after finishing installation the link "Go to your new website" directs to the parent directory.
Then I tried with appending "index.php" to "http://localhost/drupal/" it displayed admin home but now Clicking on any link displays the root directory of drupal site.
I am not able to navigate through different sections of administrator page of drupal.

During drupal installation you should be careful of following things;

Download and unzip drupal properly.
copy and paste that into your var/www (for linux) and xampp/htdocs (windows).
Rename the drupal folder to ur project name. Don't make any subfolder.
Make sure there is no spaces during renaming the drupal folder.
After creating database. Doing changes in settings.php run install.php in ur browser.
 If u r using linux give all permissions.


how to create a grid view with only ONE image from nodes containing multiple images? I have Nodes that have an Image field that can have any number of Image Fields. I want to create a Grid View in which I should only a single IMage field (can be the first one or any one actually).

Attached image shows my Views settings that shows multiple images - how do I limit to picking a single image from each node for the grid views display?

(I am in DRUPAL 6)

You can do it easily, by clicking the "Image Field" and check the Group Multiple Values and set show values as 1 and set starting from 0

see the image below


How to display contents which matches the path alias of a content from URL using views contextual filters? I have a content type "basic" and have contents with different URL alias
for ex:

  www.example.com/news/newsletter/title;

  www.example.com/content/title;

both are same type. I need to create a view page and the path for that view page is news/newsletter, In this page I want only the content which having the path alias news/newsletter. How can we get the content?

Thanks.

Views URL alias

  The 'Views URL alias' module allows Views to be filtered by path
  aliases.

  This module is useful if your website uses heirachical paths. It
  allows you to filter and sort a view by URL aliases.


How to render complete page when overriding page--node--add--typename.tpl.php I'm trying to add more buttons to a custom content type form.
I create a page--node--add--typename.tpl.php where I modify the form then render it:

$form = node_add('answer');

$form['actions']['cancel'] = array(
    '#type'   => 'submit',
    '#value'  => t('Cancel'),
    '#access' => TRUE,
    '#weight' => 55,
    '#submit' => array('cancel_button_form_cancel', 'node_form_submit_build_node'),
    '#limit_validation_errors' => array(),
);

print drupal_render($form);

However this only renders the form. Menus and other blocks are not rendered.

THanks.

I think you  would need to return the form, not print it.

return drupal_render($form);

Printing from a function will cease the theme engine which would cause the other parts of the page not rendered.


Print commerce pricing attributes to email receipt Users cannot see what size or color shirt they purchased in the email receipt because tokens won't print the attribute fields provided by Commerce Product Attributes / Commerce Pricing Attributes / Commerce Product Option combo.

User selects shirt size: XL and color: Green
Both fields can be previewed during checkout.
Email receipt received doesn't show any attributes, user cannot check what size/color they ordered.
(All this can be achieved using default CCK fields under product type, but we're using the combination mentioned above for multiple reasons, many products got different option sets to chose from and certain attributes selected adds extra price to total, like eg size: XXXL costs extra $3+ and this cannot be achieved with default fields).

One of the tokens I found is like eg. [commerce-order:commerce-line-items:0:commerce-pricing-attributes] and email on checkout prints it like this:

Product: BK Test

a:1:{s:9:"coveralls";a:8:{s:25:"field_coverall_embroidery";N;s:25:"field_coverall_text_color";N;s:10:"field_font";N;s:16:"field_shirt_name";N;s:16:"field_patch_side";N;s:12:"field_length";s:1:"2";s:21:"field_coveralls_color";s:1:"4";s:19:"field_coverall_size";s:2:"16";}}

Also more tokens available at admin/help/token like eg.: Attributes  [commerce-line-item:commerce-product:field_attributes]  Pricing Attributes field. and combining them with [commerce-order:commerce-line-items:0:commerce-product] won't work, already tried dozens of variations.

E.g. in Order's view page I addded the view Commerce Line Item: Product Attributes and it displays correctly.

How to print this in the email receipt?

<?php

/**
 * Implements hook_token_info().
 */
function mymodule_token_info(){
    $info['tokens']['commerce-order']['line_item_detail'] = array(
        'name' => t('Line Item Product Detail List'),
        'description' => t('List all the Product Line Item Detail of the order')
    );
    return $info;
}

/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();

  if($type == 'commerce-order'){
    $order = $data['commerce-order'];
    $order_wrapper = entity_metadata_wrapper('commerce_order',$order);
    $lineItems = $order_wrapper->commerce_line_items->value();
    $lineItemArray = array();
    foreach($lineItems as $key => $value){
        $line_item_wrapper = entity_metadata_wrapper('commerce_line_item',$value);
        if($line_item_wrapper->type->value()=='product'){
            $product_title = $line_item_wrapper->commerce_product->title->value();
            $quantity = $line_item_wrapper->quantity->value();
            $lineItemArray[] =  $product_title.' x '.$quantity;
        }
    }

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'line_item_detail':
            $variables = array(
                'items' => $lineItemArray,
                'type' => 'ul',
            );
            $replacements[$original] = theme('item_list', $variables);
            break;
      }
    }
  }
  return $replacements;
}

This is the sample code.

You can modify the result you want at hook_tokens().

I hope this will help you.


Include Full Taxonomy Term inside a Content Type? I'm working on a project where we want to pull in the title, description, and an image from selected taxonomy terms and include them in content of a predetermined content type. The content type is already displaying the Term with a link, but I want to display the description and an image along with it.

While I am sure this is possible, I'm not sure what the best method would be to accomplish this. I'd rather not hard-code it into a content-type template.

The content type UI doesn't allow you to render a taxonomy term entity. So, you can solve this one of three ways.

Create all the fields in the taxonomy you need and add the term to the content type via a reference then use the custom code found here: https://stackoverflow.com/questions/12705389/displaying-content-of-term-reference-instead-of-link-drupal-7

$term = taxonomy_term_load('taxonomy_term', array($hotel["und"][0]["taxonomy_term"]->tid));
$view = taxonomy_term_view($term);
print render($view);

Note: In most cases, you will find that you actually do not need to run taxonomy_term_load since the values in the array ['taxonomy_term'] is exactly the same. Therefore you can use:

    $term = $hotel["und"][0]["taxonomy_term"];
    $view = taxonomy_term_view($term);
    print render($view);

Create a taxonomy view and use a contextual filter to limit the view to the nid from URL.
Don't use taxonomy for this. What you're trying to do is display content, not organize content. In Drupal, when you want to display content, you should use a content type. Once you have a content type, you can reference it with an entity reference and display it in a teaser format. You could then add a term reference to THAT content type to limit it by category.


How to work with field collections in $build in hook_entity_view_alter? I have a hook_entity_view_alter() function inside the .module file for a custom content entity type that I am working on. I want to be able to conditionally show or hide fields in the canonical view of the entity based on the value of that field.

Example for a checkbox field: show it in the canonical if it was checked in the form, hide it in the canonical completely if it was unchecked in the form.

I am using unset($build['field_id']) for fields that are not inside field collections, and this is working fine. However, I would also like to use unset() for some fields that are contained within field collections.

I feel like this is probably a pretty simple thing to do and I'm just completely missing it. I've been var_dumping $build for a while and can't figure out what to unset, or if this is even the way to do it.

edit: here is the code I am working on in {module}.module

function {module}_{entity}_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {

  $notAllowed = stripos($entity->get('field_category')->getValue()[0]['value'], "Not Allowed");
  $allowedConditionally = $entity->get('field_maintenance_info')->first()->getFieldCollectionItem()->get('field_allowed_on_maintenance')->getValue();

  if ($notAllowed !== false) {
    if (!$allowedConditionally[0]['value']) {
        //the next 4 lines work with fields defined at the module settings level, not inside field collections - this works!
        unset($build['field_allowed_1']);
        unset($build['field_there_are_multiple_varieti']);
        unset($build['field_variations']);
        $build['title']['#prefix'] = "No ";
    }
  }

  $protein = stripos($entity->get('field_category')->getValue()[0]['value'], "Protein");

  //this is just a loop I had for exploring $build, this outputs string(2) "25" which I am pretty sure is the field collection ID
  //'field_allowed_1' and 'field_serving_settings' are both field collections, the latter nested inside the former
  if (!($protein && !$notAllowed) && !($notAllowed && $protein2 && $allowedOnMaintenance)) {
    var_dump($build['field_allowed_1'][0]['#field_collection_item']->field_serving_settings[0]->value);
  }
}

HOOK_entity_view_alter() works with render elements. That are all array keys, that have no '#' sign.

At the point you are now there are only fields prepared for rendering on the top level, that means the fields, which are not in a field collection.

Fields that are inside a field collection have at this point no renderable output.

To get the render elements of these fields you have to use the hook for field_collection_item:

function mymodule_field_collection_item_view_alter(&$build, $entity, $display) {
   kint($build);
}

Here you will be able to unset fields inside the field collection.


How to hide a field of a content type except when editing? I'm using Drupal 7 and have a custom content type that I've given authenticated users the ability to add and edit. Instead of giving them the ability to delete nodes, I've added a Boolean checkbox titled "Delete?" to the content type that they can check when editing the node. This prevents them from deleting a node without any administrative review. Is there anyway to hide this checkbox when they're adding a new node?

Implement hook_form_alter() and check whether $form['nid']['#value'] is empty, if empty then it is creation else it is update. If creation then hide the  field by setting #access property to FALSE.

UPDATE : Create a custom module and use the following code with needed modification.

Here is an example to hide tags field  in article content type.

function MYMODULE_form_alter(&$form, &$form_state, $form_id){
  if($form_id=='article_node_form' && empty($form['nid']['#value'])){
     $form['field_tags']['#access']=FALSE;
  }
}

Here is a tutorial on how to create a custom module.


Changing the tite of your page to match the title of your tabs I have the following function:

function cvminterviews_menu() {

  $items = array();

  $items['admin/settings/cvminterviews'] = array(
    'title' => 'Interview Schedule Overview',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_overview_form'),
    'access arguments' => array('administer cvminterviews'),
  );

  $items['admin/settings/cvminterviews/overview'] = array(
    'title' => 'Overview',
    'description' => 'Overview',
    'file' => 'cvminterviews_admin_overview.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_overview_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_dateroomsetup_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

This outputs two tabs at the top of the page. However, when I click on each tab, it has the same page title as the parent menu item "Interview Schedule Overview".

Is there a way to set unique page titles for each tab?

You have to call

> 4.6 – 6   drupal_set_title($title = NULL)
> 7 – 8     drupal_set_title($title = NULL, $output = CHECK_PLAIN)

You'll have to change your code around a little

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('cvminterviews_dateroomsetup_form'),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

to

  $items['admin/settings/cvminterviews/setup'] = array(
    'title' => 'Interview Schedule Setup',
    'description' => 'Setup',
    'file' => 'cvminterviews_admin_setup.inc.php',
    'page callback' => '_cvminterviews_admin_page',
    'page arguments' => array(
      'variables' => array(
        'form' => 'cvminterviews_dateroomsetup_form',
        'title' => t('my_title')
      )
    ),
    'access arguments' => array('administer cvminterviews'),
    'type' => MENU_LOCAL_TASK,
  );

function _cvminterviews_admin_page($variables = NULL) {
  if(isset($variables['title'])) {
    drupal_set_title($variables['title']);
  }
  if(isset($variables['form'])) {
    return drupal_get_form($variables['form']);
  }
}

Then do the same thing for $items[admin/settings/cvminterviews'] & $items['admin/settings/cvminterviews/setup']

When you are changing your code, there is one more problem that you will need to aware of.

There will be 2 tabs on admin/settings/cvminterviews,  one that will be active 'Overview' and 'Interview Schedule Setup'.  'Overview' will link to admin/settings/cvminteviews NOT admin/settings/cvminterviews/overview.  admin/settings/cvminterviews/overview will never be called (unless you type that it into the address bar) because it is the default tab set by 'type' => MENU_DEFAULT_LOCAL_TASK.


Redirect to a specific tab in a page after node submit I'm working on Drupal 8.9.6.
I'm trying to redirect users to a particular page after they add a node. I can do that without any problem, by adding the following information in the form's URL:
/node/add/author/edit?destination=/author-list

However, when I try to have a specific tab of the destination page opened, as follows:
/node/add/author/edit?destination=/author-list#tab2

It directly redirects me to /author-list, ignoring the #tab2 part. While if I enter in the browser /author-list#tab2 I get the /author-list page with the #tab2 active without problem.
Does anyone know what could be happening?
Thank you!

Most if not all browsers strip the hash (fragment) and this information is lost so you can't rely on hash being in the URL.
RFC 3986 states:

the fragment identifier is not used in the scheme-specific
processing of a URI; instead, the fragment identifier is separated
from the rest of the URI prior to a dereference, and thus the
identifying information within the fragment itself is dereferenced
solely by the user agent, regardless of the URI scheme. Although
this separate handling is often perceived to be a loss of
information, particularly for accurate redirection of references as
resources move over time, it also serves to prevent information
providers from denying reference authors the right to refer to
information within a resource selectively.

Possible workaround:
Create a hidden input field url_fragment and make sure it passes as a URL parameter (&url_fragment=hashvalue). Have some javascript execute on load of this page and if it finds the url_fragment in the URL make it do a scrollTop and opening of the specific tab.
Here is a question and answer that does the scrollTop if the urlParemeter EXISTS.  You need to modify this script to get the actual value and also click the Tab.


How do I create a multisite with  shared users and nodes? I want to create a multisite with Drupal 7: Every site works separately but users, and nodes must be shared among the sites.

How do I achieve it?

You can change the settings for the access to the database that are contained in the settings.php file used by your Drupal site to something similar to the following one (replace the values between brackets with the correct values for your site):

$databases['default']['default'] = array(
  'driver' => '[Your database engine]',
  'database' => '[Your database name]',
  'username' => '[Your username for the access to the database engine]',
  'password' => '[The password for the access to the database]',
  'host' => 'localhost',
  'prefix' => array(
    'default'   => 'main_',
    'users'     => 'shared_',
    'sessions'  => 'shared_',
    'role'      => 'shared_',
    'authmap'   => 'shared_',
  ),
  'collation' => 'utf8_general_ci',
);


How do I prevent the feed aggregator creates blank nodes when cron is run? I've recently taken over the management and development of a Drupal 6 site and one of the problems plaguing this installation is that blank nodes authored by "Visitor" keep popping up.

I've narrowed the issue down to the RSS aggregator and it seems like the nodes are being created when this runs durring the cron job. Has anyone seen this before? If so how do I go about fixing this? If not, does anyone have an idea where to look in order to resolve this?

Take a look at the Scheduler module. It creates blank nodes if you have some crappy nodes in scheduler table.


How do I disable comment moderation? I want to disable comment moderation and I want to show all comments by default. In the comment settings under content type, I can't find anything for this.
How do I disable comment moderation?

Visit the /admin/people/permissions page. Select the Post comments and Skip comment approval permissions for the roles for which you want to disable comment moderation.


Slideshow with views - Make slideshow title optional Hopefully this is an easy task and I am just too much a beginner to solve it ...

I use a slideshow that can be configured using views. Slideshow uses the following fields: Title, nid, and Slideshow image.

Is it possible to introduce an extra field (checkbox -> boolean) to page/article and then to exclude the title from being displayed if the boolean checkbox is checked?
To be precise; intrudicing the checkbox is easy, but I do not know how to evalute it then to exclude title in slideshow if checkbox is checked.

Yes. Assuming your view is displaying fields (under Format > Show), you'd follow these steps:

Install the views_php module.
Edit your view, adding the fields you wish to display all the time.
Add the boolean field to the view, checking the "exclude from display box."
Add the title field to the view, checking the "exclude from display box."
Add a new field "Global: PHP" to the view. In the "output code" field, enter in the following code:

<?php
$title = NULL;
if ($data->field_field_show_title[0]['raw']['value'] === "1") {
  $title = $row->title;
}

echo $title;
?>

This code assumes your boolean field is called field_show_title. Note that, for whatever reason, $row->field_show_title reports the node ID instead of the value of the field, so I had to dig it out of the data object instead.

Beneath the "output code" field you'll find an "available variables" section which describes the data that views makes available to your PHP snippet.

You may order the fields however you like, of course.


How to change page not found page error message in drupal 8? In my drupal 8 site I want to change my page not found page error message. Recently message showing like this "The requested page could not be found.". But I want show message like this "The requested page "/nvzmx,nvm,zxnv," could not be found.".

Note: my question is not about how to create a custom page for "page not found", instead I only want to change this actual error message.

You can do this by overwriting the route system.404 with a custom controller:

mymodule/src/Controller/MyHttp4xxController.php

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyHttp4xxController extends ControllerBase {

  public function on404() {
    return [
      '#markup' => $this->t('Custom 404 message'),
    ];
  }

mymodule.routing.yml

system.404:
  path: '/system/404'
  defaults:
    _controller: '\Drupal\mymodule\Controller\MyHttp4xxController:on404'
    _title: 'Page not found'
  requirements:
    _access: 'TRUE'

mymodule.install

<?php

function mymodule_install() {
  module_set_weight('mymodule', 1);
}

You have to be sure, that your module runs after the system module, so that you can overwrite the route from the system module. This is why you need to set the module weight to 1. You need to reinstall the module, when you implement this.


How to expose a persistent variable as a field for use in view I have a particular base path recorded as a settings var, and I have a number of Views (v3) that unfortunately have this same value hard-coded as part of its links. These links are rendered using the Rewrite results and Output this field as a link options, and are built from a number of field values.

Problem is I have to configure this on every dev/test/prod site. It would be far better if these links could pull the information from the persistent variable.

A couple ideas:

I have tried defining this value as a bespoke token, but as I expected these View options do not support checking for and rendering Tokens. I was hoping that perhaps using the global fields of the Views Field View module might work. So that I might render a field as Exclude from display and reference it with normal Views replacement patterns. However this failed to render Tokens as well.
I could step into each specific field in question and override with a particular template, wrapping its content in the link and sourcing the variable directly with variable_get. But this would actually be quite involved, and would also remove the primary reason for using Views in the first place — the possibility of live modification.

Is there a better way of using a persistent variable from within a View?

I already have a bespoke module set up, so have looked to see if it is possible to modify the replacement patterns of a view with a particular hook or something; however that hasn't turned anything up so far. My last remaining idea is to hook into the final render of the view and perform a token pass, but I don't know if this is such a good idea or not.

Your instincts are correct (and you're right about the lack of examples too).

In order to add a custom replacement pattern / token, you'll need to extend a Views field handler class and override the document_self_tokens() and add_self_tokens() methods.  You can then instruct a field to use your custom field handler via hook_views_data_alter() (thanks to Daniel Wehner for this info, and very likely the hook itself).

You can see example code from my need for adding a Views field replacement pattern / token.

If you need help adapting it for your need above provide the field or fields you'd like the replacement token to appear for and maybe more on how you'd like to construct it, but if you look at my example and remember to list in your .info the file with your field handler extending class so that Drupal registers it, you'll probably be all set.

(In giving the same answer over here, i also commiserated about the confusing naming of Views rewrite field replacement pattern "tokens" versus Drupal's Token API tokens.)


PHP evaluated in rule works locally but not on remote server I have this code. When I run this on my local server, it works fine but when I run it on the remote server it does nothing. Not even the messages appear. I am using the devel module. Any help appreciated.

drupal_set_message('test');
dpm($node);
// send msg for skills
$arrayofprojectskills = array();
array_push($arrayofprojectskills, $node->field_project_skills['und']['0']['tid']);

$usersprofidstonotify = array();

foreach ($entity_list as $obj) {
    if ($obj->field_skills) {
        $profile1 = $obj->field_skills['und'];
        foreach ($profile1 as $innerar) {
            foreach ($arrayofprojectskills as $oneskill) {
                if (in_array($oneskill, $innerar)) {
                    array_push($usersprofidstonotify, $obj->pid);
                } else {

                }
            }
        }
    } else {
        //drupal_set_message('field skills has no values');
    }
}

$useridstonotify = array();

foreach ($entity_list as $obj) {

    foreach ($usersprofidstonotify as $user) {
        if (($obj->pid) == ($user)) {

            array_push($useridstonotify, ($obj->uid));
        }
    }
}

$arrayofprojectskillnames = array();
foreach ($node->field_project_skills['und'] as $fieldprojinner) {
    array_push($arrayofprojectskillnames, $fieldprojinner['name']);
}

$usersprofidstonotify = array();

$name = dpm($node->name);
$msg = $name;
$msg .= ' has posted a project called ';
$msg .= ($node->title);
$msg .= 'More details:';
$msg .= ($node->body['und']['0']['value']);
$msg .= ' They need the skills of ';
$msg .= implode(",", $arrayofprojectskillnames);
$msg .= 'Can you help them out YEAH!? ';
$msg .= ' If so, please sign up ';
$msg .= 'vid) . '">' . 'here';

foreach ($useridstonotify as $oneuser) {
    privatemsg_new_thread(array(user_load($oneuser)), 'Someone needs your skills', $msg);
}

Please follow below steps to debug.

Enable Rules Debug settings.
Enable the rule you created.
Check the messages given by rules debug messages on rule activation conditions.

Still if you cannot able to find the solution, check the error logs.

You may need to change the format of collecting node values. Using "und" $node->field_project_skills['und']['0']['tid'] is not the right way. You can check below post that explains right way of reading node values.

http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way


How do I print core block or views block in node.html.twig? I'm pretty new to D8, so this might be basic stuff, but I can't find any tutorial how to do it.

In Drupal 7 this is the code that outputs core block in node.tpl.php:

<?php $block = module_invoke('block', 'block_view', '10'); print render($block['content']); ?>

This works for Views:

<?php print views_embed_view('viewname','block_10'); ?>

How do I achieve this in Drupal 8?

In Drupal 8, you don't need (and should not) render in PHP. The rendering is done as late as possible in Twig.

So put the build array of your view in a variable.

function mytheme_preprocess_node(&$variables) {
  $variables['view1'] = views_embed_view('view1', 'block_news');
}

And then render it with {{ view1 }}.

Twig will handle the necessary rendering for all kind of render arrays that are possible in Drupal.

You can use the same for a block. (See the comment from Ivan Jaros.)

$variables['block1'] = entity_load('block', $id)->getPlugin()->build();

The build() method gives you the build array of the entity and you can use {{ block1 }}.


Views: Filter by Year in D8 I'm finding a lot of resources for 7 but not much for Drupal 8.

I'm displaying a content type with a date field in a view. I'd like a dropdown that presents users with a list of years for filtering purposes.

When I add that field as a filter I'm presented with two options:

A text input date, preferably in machine-readable format
An offset from the current date, also text input

Neither of these are very useful in an exposed filter. Is there a way I can filter only on the year using a dropdown?

Perhaps not the most elegant, but I used the following on the date field:


Extra space at beginning of downloaded image I'm using custom code to download images, as I need to check permissions and keep a trace of each download (inter alia).

Here's how I decided to go:

Simple link, triggering an AJAX call of my download page
As it's an AJAX called page, html--ajax.tpl.php is used
Same for page--ajax.tpl.php
My final file force the image download

...and the content of the 3 related files:

html--ajax.tpl.php:

<?php print $page; ?>

page--ajax.tpl.php:

<?php print render($page['content']); ?>

download.ajax.php:

<?php

// ...extra code to populate $path and $filename

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;

  My problem is that I've an extra space in my downloaded image bytes

The downloaded image is corrupted, so I decided to compare its bytes with the original image with xxd, and here's the result where you can see an extra 20 byte at the very beginning:

00000000: 20ff d8ff e000 104a 4649 4600 0101 0000   ......JFIF.....
00000010: 0100 0100 00ff fe00 3b43 5245 4154 4f52  ........;CREATOR
00000020: 3a20 6764 2d6a 7065 6720 7631 2e30 2028  : gd-jpeg v1.0 (
00000030: 7573 696e 6720 494a 4720 4a50 4547 2076  using IJG JPEG v
00000040: 3632 292c 2071 7561 6c69 7479 203d 2037  62), quality = 7
00000050: 300a ffdb 0043 000a 0707 0807 060a 0808  0....C..........
00000060: 080b 0a0a 0b0e 1810 0e0d 0d0e 1d15 1611  ................
00000070: 1823 1f25 2422 1f22 2126 2b37 2f26 2934  .#.%$"."!&+7/&)4
00000080: 2921 2230 4131 3439 3b3e 3e3e 252e 4449  )!"0A149;>>>%.DI
00000090: 433c 4837 3d3e 3bff db00 4301 0a0b 0b0e  C<H7=>;...C.....

I used the same approach as the one described in this post to find the origin the the space. The better I could have is to determine that the space appears in page--ajax.tpl.php :

00000000: 5020 44ff d8ff e000 104a 4649 4600 0101  P D......JFIF...

P is printed before the render(), in page--ajax.tpl.php, and D before my readfile().

Any ideas to helps me to find the origin of this space?

Thanks

Vinodkumar's answer didn't solved my issue, but it pointed me in the right direction.

I still haven't found the extra space, but as Drupal already used ob_start() in bootstrap.inc, I can now call ob_clean() to ensure no extra characters are shown:

<?php

// ...extra code to populate $path and $filename

ob_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;


Omega theme showing 404 on iPhone I have a site on my local server which is served by Apache using virtual hosts. I am using an omega sub-theme. On the desktop everything works fine.  I try to browse to the site via the iPhone by changing the web proxy setting to point to my server. That works and I get to my site via Safari on the phone. Every link I go to on the site gives me a page not found. I'm using views on the site as well.  Looking at the Apache access log I see the entry for Safari that results in a 404 and then Chrome when I browse on my laptop which succeeds.

Any thoughts on where I should start looking for the problem?

octopus.dev:80 192.168.1.106 - - [01/Oct/2012:11:00:52 -0500] "GET http://octopus.dev/ HTTP/1.1" 404 5756 "http://octopus.dev/" "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3"
octopus.dev:80 192.168.1.147 - - [01/Oct/2012:11:01:30 -0500] "GET / HTTP/1.1" 200 7475 "http://octopus.dev/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
octopus.dev:80 192.168.1.147 - - [01/Oct/2012:11:01:31 -0500] "GET /sites/default/files/videos/original/output_file_2.mp4 HTTP/1.1" 206 390 "http://octopus.dev/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"
octopus.dev:80 192.168.1.147 - - [01/Oct/2012:11:01:31 -0500] "GET /favicon.ico HTTP/1.1" 404 661 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.79 Safari/537.4"

I simply needed to install and configure a proxy server and point my iPhone to it.  I installed squid on the ubuntu box via apt and then on the iPhone under the wireless settings pointed it to the proxy.


Can't access module settings (Devel module) I have a module that's enabled and working, but the configuration options won't show.

The module in this case is Devel, which I've used on other sites with no problem.  In this site, whenever I click on 'configure' in the Devel module listing, it takes me to the configuration page, but without a Devel option.

I've cleared the cache and re-enabled multiple times. The module is definitely enabled because I can use functions like ddebug_backtrace().

What else can I try?

EDIT:

I've uninstalled and re-installed the module, and still have no luck. I need an advice on how to trouble-shoot this.

I Think I figured out the culprit, if not the exact reason- I was getting “Allowed memory size” errors on common tasks like enabling modules, and once I remedied that my config screen showed up.

The memory error issue was addressed here.


Turning page titles to links using hook_page_alter() I'm trying to use a hook_page_alter() to change make the title of certain pages a link to another page.

This is the code I would like to alter.

function mashavumodule_page_alter(&$page) {
  // get the user id of the patient
  $user_id = $page['content']['system_main']['nodes'][$nid]['field_user_id']['#items'][0]['value'];

  drupal_set_message(l("View Patient Profile", "user/{$user_id}" ));
}

Currently, I have the link outputting as a system message.

Also as a side note, if there is a more elegant way to get the value of the field_user_id, I'd love to know because typing

$page['content']['system_main']['nodes'][$nid]['field_user_id']['#items'][0]['value']

just doesn't seem right.

I don't think hook_page_alter() is the best place to do this (though I may be wrong), it seems like since you're changing the display of the title it should be done at the theme level.

Personally I'd go for a hook_preprocess_page():

function MYMODULE_preprocess_page(&$vars) {
  if ($node = menu_get_object()) {
    $field_items = field_get_items('node', $node, 'field_user_id');
    $first = array_shift($field_items);

    $user_id = $first['value']; // if 'value' is the column name for your field, it might be 'uid' if you're using a references field, 'target_id' for entity reference, etc.

    $link = l($vars['title'], 'path/for/link');

    $vars['title'] = $link;
  }
}


How can I get Drupal to hide menu items that user does not have permission for? I thought Drupal was supposed to do this (and sometimes it does), but I'm not seeing this behaviour, so thought I'd ask.

My Main Menu contains three manually-added links to useful stuff.

Administration - this one auto-hides; cannot be seen by anonymous users.
Application - provided by a Module. Does not auto-hide, yet the module defines the path as requiring a certain permission that anonymous users don't have.
Documentation - link to a Documentation node type. I'm using Content Access Control and have not provided permission to view this content type for anon users. Should be hidden but is not.

Can anyone explain when drupal hides stuff and when it won't be able to? Obviously there's the "install yet another module" approach that will provide a brute-force fix, but I'm interested in why the behaviour is erratic/unreliable.

Drupal does this using access callback from the menu items.

In the example given:

This was working.
The Application had TRUE for the access callback. As this was not my application, I used hook_menu_alter in my own module to set the access callback for this argument to my own function. This then checked the permission and returned true/false.
The Contact Access module requires rebuilding permissions (/admin/reports/status/rebuild) after any changes.


Form submit is not firing on large form I have an old D6 site. I created a form with hook_form with very many fields (197 rows * 6 columns = 1182 fields). It works good and form submit works properly.

But when I add a new, 7th column to the form and the fields number becomes 1379 the form submit is not firing.

I do not see any errors or warnings, php memoty limit is set to 256M and post max size too. But submit handler simple does not fire.

What can be a cause?

Increase max_input_vars in your PHP environment as Clive suggested in the comment.

Another indication of this problem is the form validate handler won't trigger either. Unless you have E_WARNING set in the php.ini error_reporting setting the form will silently fail and run the form hook again.


Schedule a push notification I need to schedule a Push Notification, as in the push notifications module, every predefined set of time (e.g. every week). Looked into the Rules module, but could not find a way to program a rule based on time.

Is there a way to do this?

The module rules_scheduler present inside rules module is giving you what you need.

Details of implementation are here:

https://www.drupal.org/node/2720421
https://www.drupal.org/node/1300068


How to add java script in a content type: article or blog or basic page I need to add following kind of java script and html element in one of my computer programe coding tutorial article:

what I want to add a java script + html to create a text box to add function to copy the text inside the box on mouse click. (I know the code and html for that, but I was unable to paste that here)

I am looking to do it through: content tab in administrative tab: add content:  article: new article creation form in full html option.

Please let me know how to do it in drupal 7: by article or blog creation form or if there is any other easy way to do it.

Thanks.

You can add javascript in template file using hook_preprocess_page() function.

<?php
function mythemename_preprocess_page(&$vars, $hook) {
  if(arg(0) === 'node' && arg(1) === 'add' && arg(2) === 'article') {
    drupal_add_js(path_to_theme().'/js/events.js');
  }
}
?>

Other solution is that you can use theme function.

function theme_content_type_node_form($form) {
  drupal_add_js(...);
  return theme('node_form', $form);
}

This just calls the default theme function for the node add form after adding the js. As the theme function is called even the form is cached, this works nicely. You also need to implement hook_theme to make this work.


How can I add extra information for each term reference? I'm trying to create a content type that matches a product. The product can be made of several thing in different percentages:

Eg.

material 1:
    material 1.1: 5%
    material 1.2: 0%
    material 1.3: 20%
material 2: 75%
material 3: 0%
material 4:
    material 4.1 0%
    material 4.2 0%

I've built the materials hierarchy using taxonomies.
How can I add a parameter to a taxonomy so I can do this?

I've tried using Field Collection, but the problem I encountered was the inability to work with Solr

There are two options:

Create own module based on taxonomy. Most flexible, but also most complicated. That's what I would do, if I had time and motivation to play.
Use Field collection - create a collection of term and percentage fields, and make this collection (not individual fields in it) multivalue. Warning: I know of no easy way to make sure your percentages adds up to 100%. I know how to do it easily in custom module.... see point 1.


Why do so many classes define a ::t() method? I've encountered MANY methods substituting the translation function — forms, entities, plugins... What is the point when there is the global t() function that has exactly the same code

return \Drupal::translation()->translate($string, $args, $options);

as the methods do?

The point is unit testing. You can extend the class and override t() or just create a mock out of it. Global functions are not available during PHPUnit runs and in general just a pain.

Since this became so popular let me link the relevant handbook page on global functions and unit tests.


Equivalent of OnSessionStart for drupal I am looking for the equivalent or at least a way to run a snippet of code only when the session starts and at now other time do i want this code run.  Can anyone help me with this?  Ive looked around and cant seem to find an answer and all i read about is how drupal is not good with sessions.

What im trying to do is:
Retrieve a value from the URL when the session starts and set a couple variables and cookies according to that variable.  I need to use those cookies throughout in order to retrieve correct results.

I guess you should use hook_init as it's the first hook called right after Drupal setup sessions.


How can I add classes to the rendered "body" field on a content type? Preface: I don't often work with Drupal, so I may not be using the correct terminology or fully understand the stack. Please bear with me, I'll do my best to be as clear as possible.

I want to filter the rendered output of the primary "Body" field on a "Basic Page" (or "Article," any content type really) to add some classes to various elements. This would be the field labeled "Body" at /node/add/page. I'd like to achieve this using DOMDocument in my .theme file, but I'm having trouble figuring out what the correct "hook" is to tie in to.

So ultimately the goal would be a function something like the following (which is partially psuedo code):

function my_theme_body_alter(&$content) {
    $DOM = new DOMDocument();

    $DOM->loadHTML(mb_convert_encoding($content, "HTML-ENTITIES", "UTF-8"), LIBXML_HTML_NODEFDTD);

    $anchors = $DOM->getElementsByTagName("a");

    foreach ($anchors as $anchor) {
        $existing_classes = $anchor->getAttribute("class") ? $anchor->getAttribute("class") : "";

        $anchor->setAttribute("class", "button {$existing_classes}");
    }

    $content = $DOM->saveHTML($content);

    return $content;
}

To be absolutely clear, I want to modify the output (on the front end) of this field:

What is the name of the hook I'm looking for, or how can I locate it myself?

note:I have tested it in my machine and it works 100%

the Hook_preprocess_node is gonna be executed before the rendering of any node of any content-type, you have to apply your logic here but be sure to apply it only of the body field exist otherwise you'll get an error if some content type doesn't have this field, then inject the updated dom into the node.html.twig template using the $varaibles that has been passed by ref to the current hook:

<?php
/**
* Implements  hook_preprocess_hook
*/
function test_preprocess_node(&$variables){
 // 1. Getting the current node.
 $node = $variables['node'];

 //2. Apply this logic to all nodes that have a body field
 if( $node->hasField('body')){

   //3.Get the body field
    $body = $node->body->value;

    //4.Apply som logic on the body field
     $body = updateBodyDom($body);

   //5.injecting the result into the node template (ex: node.html.twig)
   $variables['body'] =  $body ;
 }

}

function updateBodyDom($body){
 $DOM = new DOMDocument();

 $DOM->loadHTML(mb_convert_encoding($body, "HTML-ENTITIES", "UTF-8"), LIBXML_HTML_NODEFDTD);

 $anchors = $DOM->getElementsByTagName("a");

 foreach ($anchors as $anchor) {
   $existing_classes = $anchor->getAttribute("class") ? $anchor->getAttribute("class") : "";
   $anchor->setAttribute("class", "button {$existing_classes}");

   //kint($anchor-> getAttribute('class')); die();
 }

 $content = $DOM->saveHTML( );
 return   $content;
}

in your templates folder create node.html.twig, to render the
injected body :

{{ body }}


Reusing code in .module and .inc files I plan to develop a module (say M2) that uses a pre-existing module(M1) as a soft dependency.  In short there are a number of functions that I can reuse from M1 in my module M2...

other than specifying M1 as a dependency in M2's .info file what other steps do I need to take to re-use M1's functions.. also since these aren't classes but functions so how can I inherit them ?

using module_load_include() function only includes the .inc file... but then what about the .module file of M1 ?

If M1 is enabled, the .module file will be included on every page load anyway. And if M1 is a dependancy of M2, M1 will definitely be enabled if M2 is enabled.

It's only the other files (.inc, etc.) that might contain extra functionality that you'll need to load explicitly with module_load_include().


Make block appear on some pages but not others How can I tell a block to appear on user profiles, like /user/1, but not on other pages where the beginning of the path is the same? So for instance, if I have a view set up at /user/1/articles, or user/1/messages, how can I tell the block to appear in the main user profile but not on the articles or messages pages?

I believe your only option is to use a PHP snippet to set the visibility.

Under Visibility settings select Pages on which this PHP code returns TRUE (experts only) copy and paste the snippet below.

<?php
if (arg(0) == 'user' && !arg(2)) return TRUE;
?>

For this to work you would also need to enable the PHP filter module.

Note that it's not generally recommended to use the PHP filter, but in some cases it might be the easiest solution.


How do you automatically perform several back-to-back migrations in a set order? I am using the Migrate module to transfer 400,000 items to a new Drupal 7 site.  I had a lot of problems in my first attempt because the database table was too large to import in one go.  To get around this problem, I created several (around 100) smaller migrations which each did a piece of the migration.  This works fine (so far) but the migrations must be done is a specific order.  I would like to set up something that will run each migration, one after the other, in a set order.  The entire process will take several hours, and I would like to set it up and let it run on its own.  How can I do this?

Also, if there is a way create a single migration that can break down one big table query into several smaller queries, I would like to know about it.

Here is a sample of my module activation code (note, the big 400,000 table is not referred to here):

function mig_contacts_enable() {

    for ($i=0; $i<10; $i++) {
        $index = substr((1000+$i), 1);
        Migration::registerMigration('ProspectImport', "prospect_import_$index", array('rank' => $i));
    }

    for ($i=0; $i<1; $i++) {
        $index = substr((1000+$i), 1);
        Migration::registerMigration('CustomerImport', "customer_import_$index", array('rank' => $i));
    }

    for ($i=0; $i<1; $i++) {
        $index = substr((1000+$i), 1);
        Migration::registerMigration('CustomerContactImport', "customer_contact_import_$index", array('rank' => $i));
    }

...

When you activate a migration module that contains multiple migrations, they are installed in alphabetical order.  This is the order that they are executed in when you use the UI or:

drush mi --all

I have added a single letter as a prefix to my migration.  This allowed me to arrange my migrations as needed.


Send mails in an asynchronous process I'm using drupal_mail() to send mails from the HTML formatted content.

It takes more time to send mails. Actually, Mail is triggered while the form submission after the save logic.

To save the page loading time, how can I send emails in an asynchronous process?

As far as a pre-built solution goes, you can try the Background process module, which would theoretically allow you to do something like:

$handle = background_process_start('drupal_mail', $module, $key, $to, ...);

Beyond that Drupal has nothing to help, so If you don’t use that module, just approach this as a general PHP task. The options and difficulties for async/background processing in PHP are very well documented around the web.


Views - Display grouped dates per node I have a Committee content type which has multiple meeting dates.

I'm trying to get a View that shows multiple Committees and meeting dates.  Basically, like so:

Committee A
1/1/2012
2/1/2012

Committee B
1/2/2012
2/2/2012

Instead I get:

Committee A
1/1/2012

Committee A
2/1/2012

Committee B
1/2/2012

Committee B
12/2/2012

I have tried Group Multiple Fields, but the checkbox does not stay checked after I save.  Any pointers much appreciated.

Thanks!

There is a bug in the Date module.  Found this in the Issues queue:
Group Multiple Value functionality is broken, patch for review
in http://drupal.org/node/1086100
The patch in #2 there worked for me.  Hope it gets rolled in, but in the meantime hope this saves someone else some time.


Message contextual filtering I have been trying out the Message module. I am using it to send notifications to users' profiles whenever a node of a certain content type is added (a simple hook_node_insert() in combination with Message::create()). These notifications are displayed in a view block on the user's profile page (this block is an alteration of the base Message View. Let's say these are nodes whose content type is Event, and each of these nodes has a taxonomy term reference field called Event type (e.g. Sports, Conference, Concert, etc.).

Let's say that a user only wants to be notified about events for which the value of the Event type field is Concert. In the user form, I have provided a field which contains checkboxes for all of the different event types (its a list of all of the terms that come from the Event type vocabulary). Whenever a user visits their profile page, they should only see notifications for the event types they've selected.

I haven't been able to find a solution for how to implement this either at message creation or through some sort of view block hook. I am now trying to do it through Views filters/relationships.

To make the long story short, my view block contains a list of Message type entities, each with an event_type field that references a single taxonomy term. Every user entity on the page has a event_notification_preferences field which is basically an array of taxonomy terms selected by the user.

What I would like to do can be explained through an example. Let's say the view contains three messages, each with a different event_type field (Sports, Conference, Concert). The currently logged in user's event_notification_preferences array contains only one reference (to the Concert term).

How can I filter the view to display only those messages whose event_type field is relevant (i.e., it has a corresponding match in the event_notification_preferences array, in this case Concert)? Is this possible?

In case it helps someone - I solved the issue by creating a view block of Messages, then I:

Added a relationship with the Taxonomy term referenced from the event_type field.
Added a relationship with the User using the event_notification_preferences field.
Added a contextual filter for User: User ID and got the default
value from the currently logged in user.


How do I pull in a group of term descriptions instead of their names? I am using a taxonomy to categorize content of type "lesson plan" by subject. Each lesson plan can belong to multiple subjects.

In a view where I display these lesson plans, I would like to have a field that lists all of the term's descriptions, rather than their names.

I followed these steps to pull in Taxonomy term: Term description instead of Content: Subject (where Subject is the name of the vocabulary) in the view.

However, in the Rewrite Results area, [description] only pulls in the first term's description, instead of all of them.

How do I get all of them?

One quick way to solve it with code would be to add a custom field formatter:

function MYMODULE_field_formatter_info() {
  return [
    'taxonomy_term_csv_descriptions' => [
      'label' => t('Taxonomy term CSV descriptions'),
      'field types' => ['taxonomy_term_reference'],
    ],
  ];
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = [];

  if ($display['type'] == 'taxonomy_term_csv_descriptions') {
    $descriptions = [];

    foreach ($items as $item) {
      $descriptions[] = check_markup($item['taxonomy_term']->description, $item['taxonomy_term']->format);
    }

    $element[0] = ['#markup' => implode(', ', $descriptions)];
  }

  return $element;
}

That will give you a new formatter to use for taxonomy term reference fields in Views or the Manage Display pages for content types.

If you go with this solution you can remove the relationship to the Taxonomy Term from your View.


How to add custom field to content view? I would like to add to my main content view in drupal 7 (the one with the path /admin/content) a custom field called "mobile friendly".
This field should tell the user if the current node is mobile friendly. The values should be "yes" or "no".

The values theme selves are in special dedicated table which has 2 columns: the first is "nid" and the second is "mobile_friendly" (which is either "1" or "0")

I would like this field to be sortable and and i would like to filter by it also.

i have looked in the Drupal docs but didn't understood how to do it.

Can someone give me please an example in code or refer me to some close example?

Thanks in Advance

View module doesn't have access to the custom tables by default, but you can fix it using hook_views_data function. More information you may find here http://www.sitepoint.com/exposing-tables-views-drupal-7/


Drupal AJAX forms & commands I have a form updating with AJAX on select element change. Easy so far. The problem is that I need to return the form & also an ajax command at the same time.

If I need the form, I just return the $form array and if I need to return an ajax command I use return array('#type' => 'ajax', '#commands' => $commands);. Both works just fine.

The problem is that I don't get it how to combine both of them in the same return object.

Any ideas how can I do that?

As a backup solution, I'll do it this way:

$form['#suffix'] = '<script type="text/javascript">some_function_to_do_what_i_need();</script>';
return $form;

this should work.


retrive data from drupal not working What I tried

    $sql="select * from project_status where node_id=".$vid." and ".  strtolower($field_progress_flags)."!='' and ".  strtolower($field_progress_flags)." IS NOT NULL";
    $query=$sql;
    $array = array();
    $result = mysql_query($query);
    while ($object = mysql_fetch_array($result)) {
        $array[] = $object;
    }
    mysql_freeresult($result);
    echo "<pre>";
    print_r($array);

the actual sql query is  select * from project_status where node_id=385 and draft!='' and draft IS NOT NULL

here am not getting any data
what am doing wrong here?

After some R&D got the solution as follows:

$sql="select * from project_status where node_id=".$vid." and ".  strtolower($field_progress_flags)."!='' and ".  strtolower($field_progress_flags)." IS NOT NULL";
$result = db_query($sql);
while($record = $result->fetchAssoc()){
        $data[]=$record;
}

and its works for me


Decoupling Drupal 7 from Ubuntu/Debian package management I'd like to decouple my Drupal 7 installation from the OS package management.

This is because Ubuntu's current LTS version (14.04) has Drupal 7.26, imported from the Debian packages at the time of release - it's now fixed at that version and they won't move to a later one.

Some security fixes have been backported, but not necessarily all. This is mostly due to policy issues with regards to software versions within the Ubuntu project, so the best solution is to reinstall my Drupal instance so that it's not under the control of the package management system.

I've been looking for information on this for a few days now, and can't find much of use.

I have the Backup and Migrate module, so can use that. I also have drush installed (albeit, ironically, via package management).

I can't get drush to update Drupal at all. My experience here (remembering back to Drupal 6) is that the Ubuntu package management has set some kind of flag that means Drupal doesn't check for updates for itself, only for modules & themes. "sudo drush up drupal" results in "specified project not found" for the drupal project.

Drush is updating modules and themes OK, just not core - so I believe I can probably install via drush.

My current plan is this:

Perform a backup (drush bam-backup)
Stop apache (service apache2 stop)
Remove the packaged version of Drupal (apt-get remove drupal7)
Install Drupal (drush dl drupal)
Restart apache (service apache2 start)
Restore the backup (drush bam-restore)

Does this look OK? Will I need to do anything between steps 4 & 6 (like set up the website system again)? Or am I approaching this the wrong way entirely?

If the site were mine I would first test the database against a new installation before I destroyed the old site.

I have never used the bam module so I do not know a lot about that.  What I would do is dump the DB (drush sql-dump > site.tld.data.sql or something like that).  Restore that backup to a new database and install the latest release of Drupal 7 and attach that to the restored database.  With the new code base you will need to run drush updb to get all the SQL updates to your older database.  The issue you are really going to face is modules.  How have you installed modules for your existing site?  Manually?  If you have just copy your sites/all/modules (or wherever they may be) to the test Drupal instance.

Of course you could do all of this locally on a dev machine without touching your site if you have that setup (Linux Desktop?).

After I got a warm fuzzy with the database being OK to run on a manually installed Drupal you could then attack your site and replicate the process.  Again I am unfamiliar with the BAM module.


How do I choose a database? I am NOT a developer or DB guy but a webmaster who has manipulated mysql successfully for several wordpress sites. I know how to use the command line tool and also to run things via phpmyadmin. I know how to perform basic administrative mysql functions and occasionally to make a custom query.

I am setting up a  drupal7  site on a VPS where I will already have a wordpress-mysql instance. But it occurred to me that there's nothing really stopping me from installing another db -- postgresql, SQLite, MariaDB. I am less interested in power than ease of use -- but obviously better performance would be welcome. I would probably need some management tool with a web interface. As I said, I wouldn't expect to be doing a lot of DB work; just the routine maintenance and rescue operations that occasionally are necessary.

The site should be a low or medium traffic site with not a lot of writes, but probably a lot of reads. There would probably not be enough traffic to do load balancing or clustering. (It's for a magazine site).

Is there any rule of thumb for which db to choose? Sticking with mysql seems to the obvious and easy solution; I'm just wondering if there's any reason to think differently in 2013.

Well choosing a database for your site depends on many ways,
I prefer MySQL to keep it quite simple.

MySQL is preferable PHP sites because:

Drupal 7 now comes with default table engine which is InnoDB(advantages over MyISAM) for
MySQL
MySQL has choice of table types for better read performance.
Drupal has PHPMyAdmin Web Interface for MySQL.
WAMP,XAMP comes with MySQL so it makes life easier when you use MySQL
Drupal's much better tested with MySQL

http://drupal.org/node/37268


Would a cached page be considered, solely by definition, RESTful? I'm thinking about how to explain the definition of a RESTful interface and am wondering if a cached page in Drupal would, purely by definition be considered RESTful: http://en.wikipedia.org/wiki/Representational_state_transfer#Constraints

Obviously if I wanted to setup a truly RESTful interface I would use Services or Fago's RestWS modules.

But by definition if the page is cached in D7 (thus there is no state information) is there a difference in definition between returning an xml or json endpoint and cached html page? Would the fact that there is javascript on the page create a state that would make it by definition not RESTful?

Again this is purely intellectual so thanks for any of your thoughts.

If a page is cached or not is in my opinion completely irrelevant. Page caching is transparent to the user and the content, he doesn't know if it is and once the cache expires, he might get something different on the same page. A page could for example be a view that randomly displays a node. Enabling page caching (and the node only switches e.g. every 5 minutes) doesn't change anything.

RESTful is about having a 1-1 mapping between an URL and a resource (or maybe better: a representation of that resource, e.g. a different format). IMHO, it doesn't matter if..

authorization is necessary to have access to that resource (anon vs. authorized users)
Only a part of that resource is visible (e.g. someone with additional permissions might see more information)
If the displayed information changes, as long as it's the same resource on the same URL (e.g., a node could have an access counter that increases every time you view it.)
If there is some sort of caching involved, either page or partial caching.


Redirect rule doesn't contain all the query parameters I`ve set up a Rule to redirect a user after log in.
The Rule works redirecting the user to the URL specified, but it doesn't contain all the query parameters after "?".

This is the URL value:

user/login?destination=node/4?cid1=[entity-fetched-household:0:contact-id]&cs1=[entity-fetched-household:0:hash]&cid2=[account:civicrm-contact:contact-id]&cs2=[account:civicrm-contact:hash]

But the user is redirected to the following one:

user/login?destination=node/4?cid1=[entity-fetched-household:0:contact-id]

just containing the first query parameter cid1.

I've checked the other parameters, cs1, cid2, cs2, contain the correct values.

This is the export of the Rule:

{ "rules_add_parameters_to_url_related_to_contact_id" : {

"LABEL" : "Add parameters to url related to contact id",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "path" ],
"ON" : { "user_login" : [] },
"DO" : [
  { "entity_query" : {
      "USING" : {
        "type" : "civicrm_contact",
        "property" : "display_name",
        "value" : [ "account:civicrm-contact:household-name" ],
        "limit" : "1"
      },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched_household" : "Fetched entity" } }
    }
  },
  { "redirect" : { "url" : "user\/login?destination=node\/4?cid1=[entity-fetched-household:0:contact-id]\u0026cs1=[entity-fetched-household:0:hash]\u0026cid2=[account:civicrm-contact:contact-id]\u0026cs2=[account:civicrm-contact:hash]" } },
]
  }
}

Any help will be really appreciated.

That's the way drupal_parse_url() parses your URL. If you think this is wrong, you can escape your & characters and file an issue in the core Drupal issue queue.

$ drush php-eval 'print_r(drupal_parse_url("user/login?destination=node/4?cid1=[entity-fetched-household:0:contact-id]&cs1=[entity-fetched-household:0:hash]&cid2=[account:civicrm-contact:contact-id]&cs2=[account:civicrm-contact:hash]"));'
Array
(
    [path] => user/login
    [query] => Array
        (
            [destination] => node/4?cid1=[entity-fetched-household:0:contact-id]
            [cs1] => [entity-fetched-household:0:hash]
            [cid2] => [account:civicrm-contact:contact-id]
            [cs2] => [account:civicrm-contact:hash]
        )

    [fragment] =>
)


How do I index a custom added field? When I create a new content or update existing content gets index immediately on solr search api index.
But I have added custom field to search index using entity_info_alter I have added custom field.
The custom field gets updated on Solr only on cron job runs. I want it to update when I create/update any content.

How it can be achieved?

I think this is the expected behavior: Content is marked to index when you update it, and the next cron run will reindex your items.

You need to enable the checkbox "Index items immediately" for this to be a immediate operation. Be aware this is a costly operation.

If your field type is custom, you might need to expose the value you want to entity API. Check out how to do this in Describe field properties to make custom fields work with Entity Metadata Wrappers.


How can I access untranslated field values in a translated view row? If you add the title field to a view you can use the token title__raw as a pattern. I just created a custom field for use in view named dossier_status and I need to create something a like dossier_status__raw token. The reason is that the status can be translated to different languages but I need the status always in english to use it as a css class. How can I accomplish this?

For the moment I have another field named dossier_status_machine_name (with the status always in english) But I think that this is not the best approach.

It seems not to be possible to access untranslated field values in a rewrite token pattern for text fields. You can get the untranslated value from the field in a template by using the row entity and getting the untranslated entity {{ row._entity.getuntranslated().field_dossier_status.value|clean_class }}, but using templates in Views I would avoid if possible. So this may be a better approach:

Static

Supposed that there is a limited number of CSS classes, in most cases CSS is static, use a field field_dossier_status of the type list (text) with a allowed values list:

dossier-status-class-1| Dossier Status Class 1
dossier-status-class-2| Dossier Status Class 2
...

You can translate the second part of the allowed values in Translate content fields.

Now if you access the raw value from this list field in a Views token pattern __value you get the untranslated first part

and this result:

Dynamic

If the CSS is dynamic you can use a dynamic method for the allowed values, see Dynamic Default and Allowed Values for List Fields in Drupal 8, which btw. gave me the initial idea for this answer to the question you asked some days ago. You could even parse the dynamic CSS for the classes it provides and fill them in the allowed values list.


"Page cache maximum age" is set to "no caching" but the block seems to be cached I have a Drupal 8 standard installation on Azure. I wrote a block that uses PHP to load external content; I added a timestamp to the block as well. Under Page cache maximum age, the site is set to no caching. When I refresh the page, the timestamp doesn't update telling me it's not attempting to reload. If I manually clear the cache, all is good and the timestamp updates.

Why would this be?

As I mentioned before, these blocks are loading external content. Ideally I could set it so that these blocks alone wouldn't be cached. Is this possible?

To disable caching of the block add this to the php code:

  $build['#cache']['max-age'] = 0;
  \Drupal::service('page_cache_kill_switch')->trigger();

This is a similar question Caching of blocks for anonymous user


Adding/deleting from data tables I have a few data tables on my site. If I login as the admin and go to the page where the view of the table is located, I can click Edit Item and change that one entry. However, I can't find how to add new or delete entries that are there.

When I'm looking at my data table screen I can see this:

TITLE         - NAME         - NUMBER OF ROWS
Example Title - Example Name - 41             - View

However, when I click View, it basically just refreshes the page and doesn't let me view the table. This happens for all my tables. If I'm at the Data Table Management page, I can do everything that is listed there (edit the table itself, claim/disown, schema, etc), but there's no option on this page to edit the data in the table. It says I should be able to do that from the Data Table Content Page. I realize I can edit these entries directly from the database, but the hope is to give an admin user of the website the ability to manage this data table without giving them access to directly edit the database itself.

Any suggestions or possible alternative solutions that I could use?

The data table must be marked as a Drupal Entity -- then the columns of the table may make use of the Field UI to allow an edit page per entry similar to a node_edit form.

Otherwise, you may be able to use the Editable Views module to make a table redition of your Data table -- whose cells are editable values. In this case you will likely still need to make the whole table a drupal entity.

The Data module is an API module to adopt/destroy SQL tables into Drupal. It's not really designed as a phpmyadmin replacement for a site.


Notification when a shopping cart is abandoned How to create a notification when a shopping cart is dropped ?

I wish that the user who has not completed his / her order, receives an email 1 day after, to tell him that he has a basket in progress.

I think this should be possible with the "Rules" module.

Thank you

I'd start by trying the existing Commerce Abandoned Cart Notification module. This module was specifically designed to send abandoned cart notifications.

This module allows you to notify your customers by email about their abandoned their cart.
Abandoned Shopping Cart mailings generate more than 55% more conversion compared to regular email campaigns. –SeeWhy research (2011)
Features

List your customers abandoned carts
100% integration with Commerce VBO
Edit the notification email directly from the Rule component


config-import error: These entities need to be deleted before importing I have two Drupal environments with the same system.site:uuid

In the main Drupal I export the configuration with command:

drush config-export deploy -y

In the destination drupal I import the configuration with command:

drush config-import deploy -y

But I have this error

  Entities exist of type Shortcut link and
   Default.
  These entities need to be deleted before importing.

And:

  Unable to install the mytest theme since
  it does not exist.

My test was a test for create subtheme, but then I delete mytest form drupal. And I don't know what it exports now, and, placeholder I don't Know what is it

I followed this article And I have the same issue of this comment

For:

  Entities exist of type Shortcut link and Default. These entities need
  to be deleted before importing.

You need delete the entities of type short-cut, you can do with drush:

drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'


Update field collection programatically - backend different to frontend I know there are other questions similar to this, but I'm having a specific problem. I'm trying to programmatically update a field collection (from it's fid only). This appears to work when printing out the values on the frontend, but when editing the node that the field collection is attached to, the fields within the collection are empty, but the collection itself is there.

// Unset and start afresh
unset($node->field_composition[LANGUAGE_NONE]);

foreach($fids as $fid){
  $comp = entity_load_single('field_collection_item', array($fid));
  $comp->field_chemical[LANGUAGE_NONE][0]['target_id'] = $id; // These values are derived elsewhere and are correct
  $comp->field_weight[LANGUAGE_NONE][0]['value'] = $value; // These values are derived elsewhere and are correct
  $comp->save(TRUE);
  $node->field_composition[LANGUAGE_NONE][] = array('value' => $comp->item_id);
}

node_save($node);

I assume the problem is to do with revisions - as the data is correctly saved somewhere - else it wouldn't appear on the front end. How to solve this?

Well, as always happens I found the answer just after I posted the question:

// Unset and start afresh
unset($node->field_composition[LANGUAGE_NONE]);

foreach($fids as $fid){
  $comp = entity_load_single('field_collection_item', array($fid));
  $comp->field_chemical[LANGUAGE_NONE][0]['target_id'] = $id; // These values are derived elsewhere and are correct
  $comp->field_weight[LANGUAGE_NONE][0]['value'] = $value; // These values are derived elsewhere and are correct
  $comp->save(TRUE);
  $node->field_composition[LANGUAGE_NONE][] = array(
    'value' => $comp->item_id,
    'revision_id' => $comp->revision_id // ADDED REVISION ID HERE!
  );
}

node_save($node);


Path to theme within a module / jQuery context? I've written a custom D7 module as a companion to a theme I've contributed to drupal.org and in the module, I effect output of the logo image with some basic jQuery as such:

$("li.purple").click(function () {
$('#logo-img').attr('src', '/sites/all/themes/mytheme/images/logo-purple.png');
});

$("li.green").click(function () {
$('#logo-img').attr('src', '/sites/all/themes/mytheme/images/logo-green.png');
});

etc...

Now this works fine but ideally I'd like not to have to hard code the theme path as above, it would be great to have a variable instead.

I did some searching and found a drupal docs page, "Pass the theme path to javascript", but I can't really make heads or tails of it within the context of what I'm trying to do. There's a preprocess function on the aforementioned docs page that supposedly can tell jQuery what the path to the theme is but I don't quiet understand the usage in terms of actually creating a theme path variable.  So from this:

function my_module_preprocess_page(&$vars) {
  drupal_add_js('jQuery.extend(Drupal.settings, { "pathToTheme": "' . path_to_theme() . '" });', 'inline');
}

I need to extract the path variable and put into this:

$("li.green").click(function () {
$('#logo-img').attr('src', pathToTheme + '/images/logo-purple.png');
});

... However, I get this error:

Uncaught ReferenceError: pathToTheme is not defined

... so I'm just struggling how to get this to work or if it's even possible.

Use Drupal.settings.pathToTheme.

$("li.green").click(function () {
 $('#logo-img').attr('src', Drupal.settings.pathToTheme + '/images/logo-purple.png');
});

Also, theme_preprocess_page(&$vars) should be in template.php as your_theme_preprocess_page(&$vars);

Good idea to not hard code the theme path, that path structure wouldn't work for all set-ups.


Difficulty adding a parent menu link I'm creating a custom module in Drupal 8.4.4. I put several menu links under the Development menu.

scrape.scrape_form:
  title: 'Scrape'
  parent: system.admin_config_development
  route_name: scrape.scrape_form
  description: 'Scrape content from ccad.edu'
  weight: 10

scrape.scrape_images_form:
  title: 'Images Scrape'
  parent: system.admin_config_development
  route_name: scrape.scrape_images_form
  description: 'Scrape images from ccad.edu'
  weight: 20

...

This is working fine, but now that whole menu is getting a bit too long.

I wanted to wrap up all of my links under one 'header' link under the Development menu.  I added this at the top of mymodule.links.menu.yml:

scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  route:<nolink>
  menu_name: scrape.migration
  route_name: scrape.migration

But when I try to rebuild the cache, I get this error:

The website encountered an unexpected error. Please try again later. Symfony\Component\Routing\Exception\RouteNotFoundException: Route &quot;scrape.migration&quot; does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName()

How can I make a new, non-navigable parent link under Development, to put my custom links under?

Edit 4k4's comment is correct, but my parent link is very small and greyed out.

scrape.migration:
  title: 'Migration'
  description: 'Migration functions'
  parent: system.admin_config_development
  menu_name: scrape.migration
  route_name: <nolink>

How can I get a full-height, dark-font header link?

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

mymodule.links.menu.yml

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

mymodule.routing.yml

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

You might have to adapt the path/permissions accordingly.


How can I create a custom module that can be reinstalled without throwing an error? I'm creating a custom module based off of Bootstrap Paragraphs, with a bunch of configuration files for custom paragraph types.
The configuration includes a bunch of field.storage. files, which AFAICT result in tables being created in the underlying MySQL data store for the respective fields.

The module is under active development, and I often need to reinstall it to pick up new changes.
Whenever I uninstall it and install it again, I get the error

  Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "'field_config' entity with ID 'paragraph.custom_component.custom_component_field' already exists." at /var/www/html/core/lib/Drupal/Core/Entity/EntityStorageBase.php line 425, referer: http://localhost:2345/admin/modules.

My best interpretation of this error is that the MySQL store already contains this table, so it can't be created.
Sure enough, when I access MySQL, the tables are there, even after module uninstallation.
Elsewhere, I've seen people say that in Drupal 8 uninstalling a module should cause all traces of the module to be removed, but that doesn't seem to be the case for me.

How can I set up my component so that it will delete the fields from the store when I uninstall it? Is there a better approach I should consider?

What I've tried

Overriding hook_uninstall() in the module file and adding the following code

\Drupal::configFactory()
  ->getEditable('field.storage.custom_component.custom_component_field')
  ->delete();

Renaming the config/install directory to config/optional
Purging configuration using the "Purge Configuration" tab available from the Easy Install module

You can make your config dependent on the module by adding this to the relevant config file(s):

dependencies:
  enforced:
    module:
      - module_name

When your module is uninstalled, the config will go with it. You probably want to delete any content and field instances in hook_uninstall as well.


Page Title outputting leading/trailing whitespace within H1 My Drupal 7 site is printing out leading and trailing whitespace and a line break within the page title <h1>. The following is an exact copy and paste of the HTML that's being delivered to the browser:

<h1 class="title" id="page-title">
                I am a Page Title               </h1>

Not too big of a deal as most browsers know to ignore whitespace... except Chrome for Windows... where it's making the last word in the page title wrap to the next line (I confirmed this by deleting the whitespace in Chrome's web inspector):

Why is it doing that? Is there a fix? I can think of a handful of ways to trim the the whitespace using Javascript (can it be done with CSS?), but I'd rather fix it at the source.

In the page.tpl.php file, the page title bit looks like this:

                <?php print $title; ?>

Simply removing the trailing/leading whitespace (tabs and new lines) from the code, did the trick:

<?php print $title; ?>

(Thanks to @sareed and @slawrence10 for the comments that jogged my memory as to how to deal with this!)


Role based content publishing Content created by Role A should not be published and only moderator should be able to publish it.
Content created by A should publish automatically.

How can this be accomplished in Drupal?

Cheers

That's a very broad question so I can only really give a very broad answer. There are two options that I know of for this type of workflow:

The aptly named Workflow module

  The workflow module allows the creation and assignment of arbitrary workflows to Drupal node types. Workflows are made up of workflow states. For example, a workflow with the states Draft, Review, and Published could be assigned to the Story node type.

A combination of the Workbench and Workbench Moderation modules

  Workbench provides overall improvements for managing content that Drupal does not provide out of the box.

  Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.


Display all associated tags from content page I have found many similar questions, but not quite the right way around. I have a large number of tags that are associated with multiple content pages. When viewing these content pages you can only see the parent term, and not its children terms, which are equally as important. How can I display the entire list of terms, and not just the parent term in a content view?

If you are using D7 then check this lovely module for displaying child terms after rendering. Taxonomy display child terms.

You can look into Taxonomy Display module too.


Changes to Input Formats not saving: Default instance field is required When trying to make any changes to any text format, when I click "Save" Drupal returns an error message: "Default instance field is required." and the changes are not saved. Screenshot: http://awesomescreenshot.com/0ff38my7f7 (Drupal version 7.30.)

Can anyone suggest what could be causing this?

I was getting this error because of qTip filter (https://www.drupal.org/project/qtip) which had a required field that wasn't visible on the text format page because qTip filter wasn't selected. The required field was still part of the form (visible in source) even though it was invisible in the rendered page.


Date popup form field doesn't show the default value correctly I am creating a custom form with "date_popup" form fields.
The only issue I have is that the default_value for the date popup form field shows only the first digit of the year, not the whole date.

Can anyone help with this?

Clive was absolutely right: The default value MUST be set using the date format "Y-m-d", such as with date('Y-m-d', $date).

The difference is that I used "Y-M-d" instead of "Y-m-d" for #default_value.


Can you force users to put all new content in at least one Organic Group? In Drupal 6, I would like to make sure users always add their Group content nodes to at least one Organic Group. I have a module that enforces a maximum number of groups, but I don't think it does a minimum.

The site is entirely groups-based and I don't really want people posting outside of a group.

I could certainly write a module for this if one does not exist, or it might be as simple as a form_alter() function.

In admin/og/og search the "Audience required" setting, and change it from optional to required, if you don't need it for administer accounts also.