How to exclude an item from a view if it appears in another view on the same page?

So you have 2 views: "Promoted News", and "Latest News" View.

To exclude any view results ('items' as you call them) from "Latest News", add a 'filter' in that view with as criteria the opposite (negation) of the 'filter' criteria that are used in your "Promoted News" views.

E.g. if "Promoted News" is implemented with a filter like "published to frontpage", then in "Latest News" the filter o be added should be "NOT promoted to frontpage".

Note: If you're new to Drupal, you might also want to review the set of 30 video tutorials about the Views module to become more familiar with the Views module.


Adding lines to themename.libraries.yml is not enough to add the JS, you just declared a library doing this.
Now if you want to use that library on all your theme pages, you need to add in themename.info.yml
libraries:
  - themename/webform

But if you just need to attach the library to your forms, you can use  the hook_form_alter, target your webform ids and write
$form['#attached']['library'][] = 'themename/webform';


Find the total dollar amount spent by shopper in Ubercart, using Views?

Ugh, I found that Ubercart does have this already built-in, at this URL: admin/store/customers/view. Oh well, better late than never!


Using the menu API, how do I get only the enabled links?

Set onlyEnabledLinks() on the menu tree parameters:

$parameters = new MenuTreeParameters();
$parameters->onlyEnabledLinks();
$tree = \Drupal::menuTree()->load('main', $parameters);


Question in the title: Hook fires before current_user service can identify current user

The menu discovery process is not that dynamically, only runs when you clear the cache or make changes that need a rebuild. So the current user while rebuilding the menu has nothing to do with the current user of a request when the menu is displayed.

I want to make a menu link disappear when a user doesn't have permission to use it.

About the question behind this, what do you not like about the default behavior? Drupal doesn't show menu items the user has no permission for. If you want to do more adjustments probably the best place is in preprocess.


Fuzzy Search in Drupal 7 gives no results

In the Fuzzy Search index, make sure the Fuzzy Search processors are enabled, and that they are processed last. The Fuzzy Search except processor should be last, with the settings processor immediately before it. You may need to enable the Tokenizer processor as well, and that should be before the Fuzzy processors.

Reindex after saving the changes.


Views field cache tags does not invalidate the views cache

Although there are Views plugins which use CacheableDependencyInterface, I'm not sure it is the right way for a field plugin, because a field renders content and a cache tag of rendered content belongs in the render array.

This was discussed in this issue for block plugins. Don't know if this here or in the other issues for blocks is a core issues, because you can see in both core modules the effort to collect plugin cacheable metadata, or Drupal assumes, that all render arrays fulfill the requirements outlined in the docs:

  "It is of the utmost importance that you inform the Render API of the
  cacheability of a render array"

Anyways, an easy fix is to put the cache tag in the rendered output of the field.


automatically reference user to node by date field

Use the computed field module for this. This lets you add your own conversion logic into the field (using PHP) that will be processed on entry. So download and enable the module, then add a field for your horoscope, then in the settings field, you want to add your PHP logic, ex (roughly):

$date = new DateTime($entity->field_profile_dob[LANGUAGE_NONE][0]['value']);
$month = $date->format('m');
$day = $date->format('d');
if (($month = 1) && ($day < 21)) {
    $answer = "some sign";
} else if .. etc.

That will take some time to write that logic. You might be better off putting this in a module then leaving it in the settings. There are dozens of examples in the documentation that should help you get started on this.


Composer install dependency error drupal/drupal dev-master

I ran into the same issue. My issue was related to upgrading to a new Drupal core minor version (ex: 8.6 to 8.7). If that's not the case for you, then my steps may be unnecessary.

I was able to resolve it by removing the core directory of Drupal. Then run composer update drupal/core --with-dependencies. I believe the issue stems from the core/composer.lock file having conflicts with what you are trying to install.


rules_invoke_component() - Getting the value of the Provided Variable

From the "Tiny book of Rules":

Invoking components programmatically

Rules components are handy tools for allowing site builders to customize their own actions and
conditions. If you are writing a module that allows site builders to set custom conditions (or
actions), you can let them set these up as Rules components and then evaluate selected components
programmatically. This works in a way analogous to invoking events, by using
rules _invoke_component() .

The first argument is the (machine) name of the component, and any subsequent arguments are
variables sent to the component.

// Included somewhere in your custom module.

$component name = $settings [' rules component name'];

// Any variables provided from the component are returned from its evaluation.

$result = rules _invoke_component ( $component_name, $var 1, $var 2 ) ;

So the last 2 lines in the quote above should answer your question.


The download button is actually rendered from a twig template found at /views_data_export/templates/export-icon.html.twig. This means that you can override it in your theme by copying that file to /themes/YOUR_THEME/templates/export-icon.html.twig and modifying it to what you need.
You can of course put that twig file into any subdir of /templates/ that makes sense to you - e.g. /templates/views_data_export/export-icon.html.twig will work as well.


Why is the chart button missing when trying to create a chart using Easychart?

Have a look at the Easychart support request "Installation on Drupal8". It contains varioous hints about what might be the cause of your issue, such as in these comments in it:

nr 3: You need to install embed & entity_embed to get the chart buttons.
nr 8: I ... didn't have Libraries API module installed.
nr 8: It appears to look for ec.min.js. The Easychart library that drush installed for me didn't have ec.min.js , but copying ec.full.min.js to ec.min.js makes it all work

Note: I added the hyperlink here for the Libraries API (it's the commonly used one, there is no Easychart specific variation of it ... at least not that I'm aware of).


Remove the special characters (like %20) from URL

Please take a look at transliteration module. Together with pathauto you could get better urls. But i don't know how well this works with chinese characters.


Not quite sure, whether I got you right. Here's my guess:
Depending on which theme you use, it may be that it is not a problem with the menu template. In my case, the (main) menu was configured to show only one level in the block settings.

I found out by chance, here is how to change it:

Go to https://<yourdrupalpage>/admin/structure/block
on the respective menu block item (e.g. main menu) click configure
adjust the number of visible menu levels to your needs

that should to the trick


Custom module error, does'nt show on the page

Error in hook_menu implementation ! See right code below.

function registerme_menu() {
  $items['registerme/newform'] = array(
    'title' => 'Registration Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('registerme_newform'), // Should be array !
    'access callback' => TRUE,                    //array('access content'),
    'file' => 'registerme.newform.inc',
    'weight' => '-2',
  );
  return $items;
}

function registerme_newform($form, &$form_state) {

}

function registerme_newform_submit($form, &$form_state)
{
  dsm($form_state);
}
function registerme_newform_validate($form, &$form_state)
{
// Some validation to be done on fields.
}

Clear menu cache before checking !


How do I modify email headers when using Rules to send mail?

You can still use hook_mail, you just need to identify the key for the rule or rules you want to override. The key is set in the rules_action_mail() function $key = 'rules_action_mail_' . $name . '_' . $element->elementId(); where name is the rule name and element id is the numeric id for the rule. You need to make sure your custom module has a higher weight that the rules module in the system table of your database.


How can you have Composer install the site in the project root not in web/?

If the server you are using uses public_html as document root, and not web as drupal/recommended-project expects, you need to follow what reported in Using Composer to Install Drupal and Manage Dependencies.

  If you want to modify some of the properties of the downloaded composer.json before composer install is executed, use the --no-install flag when running composer create-project. For example, it is possible that you want to rename the subdirectory 'web' to something else.

  To do that:

  Run composer create-project drupal/recommended-project my_site_name_dir --no-interaction --no-install
  Change directories to my_site_name_dir and edit the composer.json file to suit your needs
  Run composer install to download Drupal 8 and all its dependencies.


Prevent caching some selected parts of a html page

Checkout ESI. In short you need to AJAX load that block if you don't wish for it be be cached for logged out users.


Is there any way to generate url alias instead of this taxonomy/term/%/faq, in views

Pathauto just allows you to generate the URLs automatically so I believe you would still have the issue.

You will need something like https://www.drupal.org/project/path_alias_xt to extend the alias functionality to the other subpaths like the node/%/edit, taxonomy/term/%/faq etc.


Views Filter to display field only if it matches a certain value

Example: I have a field name called "Product". Add FILTER CRITERIA. Filter choose content and search Product. Save the views and click the recently added FILTER CRITERIA. You will able set a setting like Product = Book.
This will appear if you choose Autocomplete

This will appear if you choose select


Fatal error: Cannot redeclare MYTHEME_preprocess_user_picture()

Change function signature with 'function bartik_preprocess_user_picture(&$variables)' and put this function in template.php. Don't forget to clear the cache.


Page title and body field of specific page

If you must do this in twig only, you can use the drupal_field() function provided by the Twig Tweak module.
For example, to print the title of node 2:
{{ drupal_field('title', 'node', 2) }}

Or to print the body field for node 2 using the field's configuration from the teaser view mode:
{{ drupal_field('body', 'node', 2, 'teaser') }}

Or to print an image field with custom formatter settings:
{{ drupal_field('field_image', 'node', 2, {type: 'image_url', settings: {image_style: 'large'}}) }}

I'd probably aim to create a custom view mode here and then print the whole view mode as one chunk with the drupal_entity() function. For example:
{{ drupal_entity('node', 2, 'my_custom_view_mode') }}


What are the alternatives to the Calendar module?

Well, in my recent experience is not yet ready to production, but it depends on your needs. Maybe most of this is because the "partner" module, date, has lots of issues now.
I suggest you test both: Calendar and FullCalendar. The Calendar module is more powerful and flexible, but if you need a simple calendar, FullCalendar is ready to go now.


Sounds like an incomplete or partially failed install. Delete all the tables in the database and try doing a fresh install.

Try performing the install with Drush so you can see in real time if there are any errors when writing to the database (look under "Quick installation with Drush"): https://www.drupal.org/documentation/install/developers

Also make sure you're running PHP 5.3+ and MySQL 5.0.15 or higher with PDO: https://www.drupal.org/requirements


Google Analytics configuration setting for Drupal multisite (domain and submain)

As Kiamlaluno states, this is likely caused by the fact that the module only allows one UA, while you are trying to track two domains. According to the GA module documentation it can be overridden using code like this in settings.php:

<?php
// Override Google Analytics Web Property ID per hostname.
// Hostnames need to be lower-case!
switch ($_SERVER['HTTP_HOST']) {
  case 'www.example.com':
  case 'www.example.net':
  case 'forum.example.net':
    $conf['googleanalytics_account'] = 'UA-123456-2';
    break;

  case 'www.example.org':
    $conf['googleanalytics_account'] = 'UA-123456-3';
    break;

  default:
    $conf['googleanalytics_account'] = 'UA-123456-1';
}
?>

Documentation can be found here


You also need to provide the actual menu config entity as default configuration in config/install. Note that test.menu.listown is not a valid menu name, they can't contain dots only alphanumeric characters and dashes.

I'd recommend to prefix all default configuration with your module name, so that they're unique. Something like mymodule-something.

And, try to follow coding standards and conventions. For example, always use camelCase for class names, like TestBlockMain in TestBlockMain.php.

And last, avoid calling render() yourself whenever possible. You can just return a render array from a block.


entity_load_multiple returns empty array although an eitity lives in the database?

comment_load_multiple will only load a comment if the node and the user linked to the comment both exist.

You can see this in the code for CommentController::buildQuery where it does an INNER JOIN on both the node and user tables. Note that if you trace through the execution of comment_load_multiple you have to pass in the RESET argument (or clear the caches before hand) otherwise you will get the cached result, and will never make it into CommentController::buildQuery.

Now the reason CommentController::buildQuery does an INNER JOIN rather than a LEFT JOIN (and the reason I didn't add this as an answer straight away) is that you are not supposed to be in a situation where you have a comment that does not have a node or a user.

You can see this because:

The code for comment_save clearly expects the associated node and user to be set ;
The comment module implements hook_node_delete, and always ensures that comments are deleted when a node is deleted ;
The comment  module implements hook_user_delete, and always ensures that comments are deleted when a user is deleted.

So the problem you are seeing suggests your database is somewhat inconsistent. This could happen if you deleted nodes or users without using the proper API, though it could happen for other reasons (eg. sometimes when dumping and re-saving MySql database you might loose the entry for the anonymous user - it has id 0, and must be in the database users table).

Another note: If this is the only issue affecting the loading then you can get the comments that won't load by doing an SQL query:

SELECT cid
FROM comment
LEFT JOIN node ON node.nid = comment.nid
LEFT JOIN users ON users.uid = comment.uid
WHERE (node.nid IS NULL)
      OR (users.uid IS NULL)


Second managed_file upload field fails with "An unrecoverable error occurred"

I'm the OP: This is not a full answer, but a fix:

Forcing the session to start with $_SESSION['something'] = 1; in the form build seems to cure this problem.

If you can provide better answers please do.


Using background images formatter for taxonomy in views

If you have not disabled Add default classes under Style Settings of image field then you can use views_field_FIELD_MACHINE_NAME class to play with css.

For example If you have a field with machine name field_book_category_icon then after adding this field to your view you can get a class views-field-field-book-category-icon on front end when ever you render that view on your page.


When I should create a new permission in my custom module?

If you are creating a custom module for a client-only (or yourself), then you can do whatever is appropriate for the situation.

When creating a contrib module, you have to consider that you probably don't know all of the potential uses.  In general, I would make your own permission; typically as a project reviewer, this is something I point out as part of peer review.

I do not see too-many-permissions as a problem.  In fact, I see it as a benefit.  When I build sites for clients, I try to build out roles that can stack (users can have multiple roles) and roles have the minimum permissions needed to meet the needs of that role.

One common complaint about Drupal is that it is too complicated.  By using roles and permissions, you can limit what users can do, and minimize the complexity to exactly what they need to do (no more, no less).  When you gang up tasks into a single permission, you may give the option to people to do things that they may not need or want to do.

Another way to look at this, is that permissions can be used as a security method to limit what uses can do.  They can also be used by an organization to limit what users need to do as part of their job function.


I am not sure if I got you right,but if you want to call a form on a menu item.Here is view for that
Implement

  hook_menu() - to build custom page page callback - return your custom
  form here

Some sample code

function mymodulename_menu() {
  $items = array();
  $items['custom-menu'] = array(
    'title' => 'Your Custom Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodulename_custom_form'),
    'access callback' => TRUE,
    'access arguments' => array('access content'),
  );
  return $items;
}

function mymodulename_custom_form() {
  $form = array();
  // your custom form code goes here
  return $form;
}


Give permissions to a non-admin user for custom rules components

You can set permissions on rule component page in fieldset at the page bottom.

There is an option "Configure access for using this component with a permission."


Allow users to upload files and attach to specific nodes

In a word, No.

At least not the way you are asking the question...

You need to be thinking about node types as well as just A, B, C & D.

I would look into the views module (tutorial here).

This would mean you could upload your files to nodes of a particular type, and then create several views that display different files uploaded based on your custom parameters.

It's a bit hard to be any more specific based on the broadness of your question.


How to display all the terms of a vocabulary with a list of the items associated to the term below in a view?

It sounds like you are looking for a glossary view.  There are many tutorials on how to do this, ex: https://www.ostraining.com/blog/drupal/glossary/

... after rereading, you may actually be looking to create a view of all terms in that is grouped by parent id. There are different ways to do this. Take a look at:

Grouping Taxonomy terms by their parents
https://www.konordo.com/blog/show-taxonomy-terms-grouped-taxonomy-parent

These talk about D7, but the same should work in D8


How can I keep a record of user email addresses when users update their email address?

The first thing that came to mind is Drupal's revision feature. Out of the box, Drupal let's you keep records of what changes are made to nodes over time. Users are a different entity, but the User Revision module aims to provide the same functionality. This Lullabot article explains it pretty well. You could give it a shot.


Ubercart shipping quotes silently fails on server migration

Ok, I eventually traced the issue back a module called "UUID", which is required by Node Export.

Disabling UUID module solved my issues. The errors in the rules UI (admin/config/workflow/rules) simply went away.

Would love to know more about why this is. I don't need node export at the moment so it doesn't matter to me.


How To customize user account creation form

You need to use user_register_form instead of user_register.

Try using it like this :

$items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'responsive_bartik'). '/templates',
    'template' => 'templates/user-register-form',
    'preprocess functions' => array('responsive_bartik_preprocess_user_register'),
);

Now create a user-register-form.tpl.php in your themes template folder.


How to add different GTM snippets per environment?

In my opinion adding a GTM snippet should be handled by a module, and not theme dependent. The GoogleTagManager can be used to accomplish this.

In your settings.php file you can indicate which snippet to use:
$config['google_tag.settings']['container_id'] = 'GTM-000000';

When you want these snippet variants stored in you version control system, in that case every environment should have some kind of indicator allowing to implement something like:

if ($_ENV('ENVIRONMENT') == 'dev') {
    $config['google_tag.settings']['container_id'] = 'GTM-000000';
} elseif ($_ENV('ENVIRONMENT') == 'stage') {
    $config['google_tag.settings']['container_id'] = 'GTM-AAAAAA';
}

Another option to indicate which snippet to use depending on the current environment (i.e., Dev, Stage, QA or Production), is to use the Configuration Split module. This module contains functionality to create conditional splits.


Custom variable in custom block template

After long hours of searching and trying I finally found a solution.
Not really sure why but it seems a naming convention has to be respected.

I changed the name of #theme and templates to start with module name, here the name is custom_blocks.

src/Plugin/Block/FrontAppsBlock.php

/**
 * @Block(
 *   id = "front_apps_block",
 *   admin_label = @Translation("Front Apps Block"),
 * )
 */
class FrontAppsBlock extends BlockBase implements BlockPluginInterface {

  public function build() {
    return [
      '#theme' => 'custom_blocks__front_apps',
      '#app' => 'test value',
    ];
  }

}

custom_blocks.module

function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'custom_blocks__front_apps' => [
      'variables' => [
        'app' => null
      ],
    ]
  ];
}

templates/custom-blocks--front-apps.html.twig

Hello: {{ app }}

Base Label: {{ label }}


How to make a callback funciton to a drupal behaviors funtion

You could assign mySwiper to a property within the behavior.

(function ($) {
  Drupal.behaviors.modulenameSwiper = {
    attach : function (context, settings) {
      if ( location.pathname != '/en/imce' || location.pathname != '/fr/imce' ||              location.pathname != '/it/imce'     ) {
        mySwiper = this.get();
        $('.swiper-container').each(function (){
          mySwiper.instances[mySwiper.index] = new Swiper ($(this)[0],{
            mode:'horizontal',
            loop: false,
            slidesPerView: 'auto'
          });
        });
      }
    },
    /**
     * Returns an object with Swiper instances and highest index.
     */
    getSwipper : function () {
      if (this.mySwiper === 'undefined') {
        this.mySwiper.instances = new Array();
        this.mySwiper.index = 0;
      } else {
        this.mySwiper.index++;
      }
      return this.mySwiper;
    },
  };

  $(document).ready(function () {
    console.log(Drupal.behaviors.modulenameSwiper.getSwiper());
  });
}(jQuery));


you have to write alter function for your form then you may attach fields from another entity by using field attach form function here is a example for loading profile2 fields form elements

 global $user;
         $profile = profile2_load_by_user($user,'profile');
        field_attach_form('profile2',$profile,$form,$form_state,'und');


I am trying to use AJAX with Drupal 6. How do I determine the URL I am trying to contact?

The URL you use is the one that delivers you the data you want.  If you want to grab the server time you can create a short PHP script that gets the info and then make that info available to JS using Drupal.settings.

For example:

// Create the array that is required by drupal_add_js()
$server_time = array(
  'serverTime' => date("h:i:sa"),
);

// This is what makes the variable available to JS
drupal_add_js(array('time' => $server_time), 'setting');

Then, in your.js:

var time = Drupal.settings.time.serverTime;


Entity registration, register to more event from one form in event detail

Install VBO module, create a entity view with checkboxes. See the Rules sections here. You can use that rule in VBO to register them automatically to the Events they selected.


The default Drupal Bootstrap 3 subtheme has all the required LESS files, which includes the overrides.less file. This file, and all others, is rendered into the style.css file by the LESS processor HOWEVER this can change if your processor is wrongly configured, so make that the first thing to check. Then check that your theme .info file is only referencing the css/style.css file and not any other css files.

https://www.drupal.org/node/2052931


The has_js cookie has been used by the Batch API. Without this cookie, or when JS is disabled in the client browser, the batch API will give you a WSOD.

See $_COOKIE['has_js'] must die.

If your service endpoint is dealing with the Batch API internally, then you will have this problem.


Calendar view doesn't display node titles upon first view, but will after Prev/Next are pressed

Well, I did a comparison between our development server and production server via drush pml | grep Enabled | grep -i views on each server. I noticed that for some reason I left views_rss enabled on production but not development. After drush dis -y views_rss and drush cc all && drush cron, things appeared as normal.


You can't easily manually insert a user record. The password is not an MD5 hash, it a salted SHA-256 hash.

You hopefully made a backup, you should restore that. From there, you should consider to use drush, which is the by-far easiest way to log in, with drush uli to generate a one-time login link or drush upwd, to set the password of a user.


How to have nodes online but not as a separate node number?

You can't disable the node entity's canonical path easily, but you can serve a 403/4 for requests to the pages instead.
The simplest method for that is probably the Rabbit Hole module

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.


Display images of a specific content type in a lightbox when vocabulary is clicked

If I were you I would create a "Kitchen Type" content type and then edit the image field to allow unlimited amount of images. Then add a taxonomy field to "Kitchen Type" assigning a taxonomy term to each.

Create a new view which pulls all "Kitchen Type" content types and add the Taxonomy Field and Image field to the display. Views allows you to style individual fields by its tpl naming convention. If you go to the "theme" option in that view you will see a set of file names to place in your theme to style individual fields. You will need to style the image field by looping through the image array and output html which conforms to the lightbox2 convention like this:

This should display each set of images for each kitchen type right under it. Once one image is clicked it should open up a lightbox with arrows to go to next image.

Hope this helps or at least points you in the right direction!


How to give anonymous users access to only certain nodes?

You can use the Rules module for this.

Here is a prototype of a rule (in Rules export format) to get you going:

{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "some\/path1",
                  "some\/path2"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/something",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed for Anonymous users.",
          "type" : "warning"
        }
      }
    ]
  }
}

Adapt the paths in it to fit your own needs, to reflect all the paths that anonymous users should not be able access. And for any access module you have enabled, allow access for anonymous users also (any paths that fit in the Rules Conditions will be blocked by the above rule, while any path that does not fit can be accessed by anonymous users). Obviously, using the "negate" facilities or Rules, you could also rework this prototype rule so that you only specify the paths allowed for anonymous users.


I think you should create the field as suggested in 3 regardless of which method you choose for authorizing users to view content. Your first suggestion seems reasonable.
I would personally opt for method two, and use the Page Manager in Ctools. PM is a tool however, and as such requires both understanding and configuration to do what you ask.
Your third option, hiding in the theme, seems wrong however.


I would do this from my custom module. I would create a men path and a page callback which renders the block.

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
    $items = array();
    $items['my/block/path'] = array(
        'title' => 'Block As A Page',
        'page callback' => 'mymodule_block_as_page',
        'access callback' => TRUE,
    );
    return $items;
}
/**
 * Page callback the path for my/block/path
 */
function mymodule_block_as_page(){
    $block = module_invoke('module_name', 'block_view', 'module_delta');
    return $block['content'];
}

If you go to the path my/block/path, you will see your block as a page/node.


Modify custom module's setting.yml without reinstalling

You can try the module config_sync, there you can update the site's configuration from your custom module.

afaik there is no official way to update configuration from an updated module.


PDO exception for Entity Reference Module

The reason is here:

[…] ON na.nid = node.nid WHERE (nid IN (:db_condition_placeholder_0)) […]

Can you see the nid after the WHERE keyword, it has no identifier and therefore PDO does not know how to handle it. You must prefix it with the correct table name (or assigned shortcut). Either na.nid or node.nid should do the trick.


How to print a variable set in my custom module's inc file in node-contenttype.tpl.php

To get a variable to a custom node.tpl.php you need to do this in MODULE_preprocess_node(&$variables) usually this is done in your template.php file located inside your themes directory, however, because you are calling a private function _taobao_get_page(), I think you need it inside your module.

Something like

MODULE_preprocess_node(&$variables) {
   if ($node->type == 'mycontenttype') {
      $variables['linkz'] = X;
   }
}

Now you can call $linkz inside your tpl.php file


How do I create a full project from a sandbox project?

You need to have your account elevated to be able to promote a project to full status, meaning you have to go through the project application process if you have not already.

https://www.drupal.org/node/1011698


How do I get only one result using db_query()

If you wish to fetch only one result you could use fetchField with db_query to fetch the result, e.g.:

$zip_code = db_query("SELECT zip from {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city))->fetchField();

You could also fetch the values retrieved from the query's returned result source using options like fetchObject() similar to methods of conventional PHP (mysql_fetch_object) coding like using and get results.


Drupal Form API submission to create node

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

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

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

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

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

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


How to create a automatic Field value number to display in the lable for an custom content type: Itinerary e.g Day 1, Day 2

Using computed field you could do this.

Install computed_field module
add a field into the content type you want to count the field for, and then in the display code box add this (field_slect is the field you want to count)

$display_output = sizeof(field_get_items($entity_type, $entity, 'field_select'));


Install the Commerce Extended Quantity module and then implement a HOOK_xquantity_add_to_cart_qty_prices_msg_alter():
https://github.com/drugan/commerce_xquantity#an-item-added-to-your-cart-message-alter


How can I conditionally reference an entity?

Use Entity reference module to insert the references of the existing users to the content type.

  This project provides D7 versions of the 'node_reference' and
  'user_reference' field types, that were part of the CCK package in D6,
  at functional parity with the D6 counterparts.

For the rest of the users, you could use a textfield.


Why block id is generating with encrypted id

Views block deltas aren't encrypted, they just use an MD5 hash. The reasoning is thus:

  block.module has a delta length limit of 32, but our deltas can unfortunately be longer because view names can be 32 and display IDs can also be 32. So for very long deltas, change to md5 hashes.

That comes directly from the comments in views_block_info(), which then goes on to run this loop:

foreach ($keys as $delta) {
  if (strlen($delta) >= 32) {
    $hash = md5($delta);
    $hashes[$hash] = $delta;
    $items[$hash] = $items[$delta];
    unset($items[$delta]);
  }
}

Which, as the comments suggest, make sure that the delta is a maximum of 32 chars.

You can try implementing hook_block_info_alter() to implement your own naming convention (it might work, I haven't actually tried it). But the 32 char limitation imposed by the block module is set in stone at the database level so you'll have to take that into account.

If you do that you'll probably need to hook into some other parts of views as well, so that it knows how to process the new block deltas you've given.

As kiamlaluno points out in the comments, you could actually control this at a higher level by making sure that your view's name + display ID together don't exceed 32 characters.

I'm not sure exactly why you want to change this delta, but in my experience the most common reason is so that you can target a specific block with a template file.

Just in case that is your use case, this is a snippet I use in projects to level the playing field so-to-speak.

function MYTHEME_preprocess_block(&$vars) {
  if ($vars['block']->module == 'views') {
    // Add some template suggestions that are a little easier to manage than
    // the default dom id added by views.
    $delta = $vars['block']->delta;

    $found = FALSE;
    if (strlen($delta) == 32) {
      $hashes = variable_get('views_block_hashes', array());
      if (!empty($hashes[$delta])) {
        $delta = $hashes[$delta];
      }
    }

    list($name, $display_id) = explode('-', $delta);
    $vars['theme_hook_suggestions'][] = 'block__views__' . $name .'__' . $display_id;
  }
}

This will let you create a file named like block--views--viewname--displayid, regardless of the delta length limit imposed by the block module


How do I get a field translated in Drupal 8

You can get a specific translation with $translation = $entity->getTranslation('de'), then you can use $translation exactly the same as $entity.

Usually, you don't want to get a specific translation, but the best translation that is available for the current language, for that, use getTranslationFromContext():

 $translation = \Drupal::service('entity.repository')->getTranslationFromContext($entity);


Loading third party PHP SDK library from a custom module drupal 7

Use libraries module to load 3rd party dependencies (easier way), or composer manager to load composer package (better way).

Here you can find some details and examples how to start with libraries module.


There are a couple ways you can do this. The easiest way and probably the way you will end up doing it is in your view you need to change the format to a table and then output as fields. It sounds like you are outputting a rendered entity instead of the fields. Then under theme information you will see the available templates that you can overwrite.

The one you will want is under Style. Notice the naming convention. For a view named test and a block the view would be views-view-table--test--block-1.tpl.php.

Create this template and put it into your theme folder and clear your cache. Inside that template you have access to the $rows variable that will contain all of your output.

<?php
dpm($rows); // If you have devel module enabled see your rows;
?>

This should then allow you to style your HTML as needed.

I would advise against this unless you have a special need. A better way to do this would be to use Display Suite in which you can create your own view mode and manage the fields like that. I wont go into detail on how to do that but research would be good to see if it is a good way to go for you.


Shipping method and shipping service from a placed order

Since shipping_method is an entity reference field, you can call $order->shipments->entity->shipping_method->entity, to load the shipping method entity.

The shipping service is not an entity, but just a text field, so you can get the value by using $order->shipments->entity->shipping_service->value.

Hope it helps!


Display different menu links based on page/theme

You will need to mange the links in 2 different menus. for example Main Menu for all website links and Blog Menu to have the links related to Blog pages.

Disable the Main Menu and the Secondary Menus from your theme settings.

Now goto blocks pages and configure the main menu block scroll down to bottom

under Show block on specific pages

select All pages except those listed and type blog/*

now save this block configuration and goto configure Blog Menu scroll down to bottom and select Only the listed pages and type the same in texarea ( blog/* ) and save the block configuration.

Now depending on your URL pattern it will display your required menu.


How can I theme an image inside a field formatter

I'm no expert on field formatters in D8, but are you opposed to using a preprocessor? If not, have a look at template_preprocess_image_formatter. It looks like that is where you would prepare your own variables for use in the image formatter template. Cheers -


How to Add a quertystring to a link using jquery

You've got nothing to hook onto for that second attr() as you're not storing the result of the jQuery call in a variable.

I'd advise using a loop instead:

$('a[href^="/mypath/"]').each(function(index, element) {
  var newAttr = $(element).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(element).attr('href', newAttr);
});

That will catch any link on the page that matches the path selector.


Conditional field display in node template

You wrote that you are using Twig conditions to selectively print fields, but they show up twice now. This most likely is, because your template still renders the entire content variable somewhere like {{ content }}.

You can easily avoid the fields being rendered twice by using the without Twig filter. Locate the {{ content }} part in your template and alter it to

{{ content|without('field_video', 'field_image') }}


How to display a new taxonomy term on a select box using Webform?

The error was I was adding a new vocabulary, not a new taxonomy term to the existing vocabulary.


Use this:

// Make sure we are on the term page
if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
  print arg(2);
}


Why doesn't drush check for updates of dev versions of my modules installed by composer?

Drush relies on information written by the Drupal.org package manager to determine whether or not updates are needed to modules or core.

If you use git to install Drupal modules, then you may also use the git-deploy module, and it will add the information needed for Drush to do the update.  Git deploy also works for modules installed via Composer using git; Composer uses git to install when using the --prefer-source directive, or when the module version installed is a development version.

If you use the Composer option --prefer-dist, then Composer will install the tarball packaged by drupal.org, which is why git-deploy is not needed in most cases for stable modules.

Note that there is a bug in git-deploy that prevents it from working when the path to the Drupal root contains spaces. There is a patch to fix this problem available in the git-deploy issue queue; see #2672166.


How to load certain old submission value into webform?

Long story short:
I wrote a custom webform element that takes an argument that gets updated via AJAX and queries the database.
Long story:
As in my comment, adding the "Webform View" module worked besides the wrong version number in the project description for the dependencies.
But it didn't help.
So, here are a few learnings along the way that might be interesting for people with similar challenges, followed by the final solution.
I was able to create a view that outputs the value_old that I need, when I provided the previously selected ID as an argument.
But:
While there is a webform element that shows views and takes arguments, it doesn't work with a token as an argument to reload it's content, when there is a (new) value for the token.
It is even not possible to split it up into several pages, such that there is already a value for the token, when the user proceeds to the next page.
I needed a webform element that gets recalculated, when the form changes, but gets its information from the database.
So, I created a new webform element in a custom module.
I took the „Computed Twig Element“ as a starting point.
But instead of doing a computation, I took the input value as an argument for querying the database for my value_old.
In theory, it would have been possible, to use the view from above, as long as computed values in this view are stored in the database.
If they aren't, querying the view will run out of memory.
In my case, there are some additional requirements to the rights management.
Therefore, I tried different querying mechanisms.
In this custom field, it was possible to query the database directly and to query the view.
I also tried the Webform Query module.
But something in there seems broken, because this module produced a query with a wrong name in it, as soon as I started querying for ordered results.


How do I test the methods or hooks implemented in .module file using PHPUnit?

No, PHPUnit is not for testing functionalities written in class files. Quite the opposite, PHPUnit in Drupal can be used to test hooks, functions, and classes implemented from modules.
Drupal core itself has tests for hooks, for example the InfoAlterTest class that tests hook_system_info_alter().

How to write tests is described in Automated tests. Without a specific use-case, I cannot give more details on testing hooks, except saying that functional tests that do not test web output, which is the case for most of the hook tests, the test class needs to extend \Drupal\KernelTests\KernelTestBase.

References

Types of tests in Drupal 8
An Overview of Testing in Drupal 8


How do I programmatically update pathauto paths for an entity?

You could use the pathauto.generator service provided by Pathauto:

\Drupal::service('pathauto.generator')->updateEntityAlias($entity, 'update');


How to obtain raw field value from db table in a view?

One of the last things Views does when it renders a view is to process all the fields raw data and format them according to settings, then theme according to the default or your own custom views templates.

So, if the 'Output format' options in field's settings on the view don't provide what you need, you can get the raw values - before formatting & theming - like so:

Install Views PHP so you can run code from within views fields, arguments etc.
Check the "Exclude from display" option on the fields you want 'raw' to stop them appearing in the output, but still ensure they're in the view data.
Add one "Global: PHP" field for each field for each hidden field.
In the "Output code" at the bottom of the field settings on the new Views PHP field, add something along the lines of print $row->field_you_want_raw.

Since you've got full PHP in these new fields you can format, tweak and merge any raw field data you need.


What does rebuilding content access permissions do?

There's a quote in the comments on this post that puts it nicely:

  Drupal maintains a table of who can access what; this needs to be rebuilt when a new module affecting user access is enabled.

Think of it as a cache-clear for node access data, except that it's quite complicated so needs to be run as a batch job rather than all at once (e.g. on a cron run).

Since node access is a sensitive issue it's also not wise to rely on scheduled jobs to make the necessary changes, hence why this is all done in one go.


It was a caching issue. This is my final code to cleanly hide all contextual links except in layout building mode:

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;

function mymodule_page_attachments(array &$page) {
  $routeName = \Drupal::routeMatch()->getRouteName();
  if (!in_array($routeName, ['layout_builder.overrides.node.view', 'layout_builder.defaults.node.view'])) {
    $page['#attached']['library'] = array_diff($page['#attached']['library'], ['contextual/drupal.contextual-links', 'contextual/drupal.contextual-toolbar']);
  }
}

function mymodule_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $routeName = \Drupal::routeMatch()->getRouteName();
  if (!in_array($routeName, ['layout_builder.overrides.node.view', 'layout_builder.defaults.node.view'])) {
    unset($build['#contextual_links']);
  }
}

For the caching issue:
The changes above most likely will (after cache clearing) remove all contextual link entries, but leave an empty placeholder like

 in your rendered HTML. To get rid off those empty divs, go to your browsers Developer console > Application > Session storage and clear all keys starting with Drupal.contextual. After clearing them, the empty placeholder divs are gone too, no more CSS hacking needed.


taxonomy terms view with custom alphabar (for Spanish)

I've been reading some documentation about
character settings in mysql, and I have found a solution, I don't know if it's the right way for drupal, and it would not interfere with the taxonomy modules at update time in some way, I hope somebody could comment on this....
Anyway I just changed at the taxonomy_term_data table the collation of the "name" field to utf8_spanish_ci


How to setup reCaptcha to appear on the registration form?

In the CAPTCHA Points tab, you need to click on the enable button.


Do not use standard (as you said in a comment).

Use testing and then create only what you need in the test. That's the main thing to speed up your tests.

They are still rather slow, but that should help.

Another thing to consider is to avoid having many test methods. Each runs in a completely new, isolated environment. A trick that is often used is to have a single testAll() method and many doTestSomething() methods, then they are faster by almost factor count(test methods), since set up is usually by far the slowest part.

You can also run tests in parallel with --concurrency 8 (nummber of cpus is a pretty good value for concurrency)


This was a change that was introduced in Drupal 7.20, which addressed a denial of service vulnerability:

  Drupal core's Image module allows for the on-demand generation of image derivatives. This capability can be abused by requesting a large number of new derivatives which can fill up the server disk space, and which can cause a very high CPU load. Either of these effects may lead to the site becoming unavailable or unresponsive.

From the release notes:

  The security fixes in this release change all image derivative URLs generated by Drupal to append a token as a query string. ("Image derivatives" are copies of images which the Drupal Image module automatically creates based on configured image styles; for example, thumbnail, medium, large, etc.)

Drupal 7.21 revised this a little:

  Drupal 7.20 fixed a fundamental security flaw in the Drupal core Image module and therefore introduced incompatibilities with a number of contributed modules and sites (see the Drupal 7.20 release notes). To help mitigate the effect of these changes, an optional image_allow_insecure_derivatives variable was provided, which sites could use to turn off the security fix.

  Drupal 7.21 adds additional security protection for sites that use this variable. Although they will still not receive the full benefit of the security fix, they will now have protection against the most damaging and easiest-to-inflict vulnerabilities that were addressed in Drupal 7.20.


How to change the order of the payment methods in Commerce?

Changing the weight of the Rules for payment methods will change the order on order review page.


setup Drupal with Docker: clone repositories via deploy token

The way I handle this is creating a gitlab auth.json file and with your token and using a volume mount to put it into the container.

volumes:
  - /Users/${USER}/.composer/auth.json:/home/wodby/.composer/auth.json # composer auth

In some instances I've wanted my ssh keys in there as well for certain operations, but shouldn't be needed for a pull off gitlab. This is just as easy.

volumes:
- /Users/${USER}/.ssh/id_rsa:/home/wodby/.ssh/id_rsa # ssh


Best way to get best breadcrumbs for Commerce

You can add breadcrumbs in your page using drupal_get_breadcrumb and drupal_set_breadcrumb function

In template.php

 function THEMENAME_preprocess_page(&$variables, $hook) {

        if(arg(0)=='shoppage'){  //Put appropriate condition
            $breadcrumb = drupal_get_breadcrumb();
            $breadcrumb[1] = l('Shop', 'shop_link');
            $breadcrumb[2] = l('Category', 'category_link');
            drupal_set_breadcrumb($breadcrumb);
        }
    }


The database connection is handled elsewhere, you do not need to write a new connection function in your template file.

You can use this:
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7


How do I use Gitlab server as a central staging server?

Usually, people set up a remote named "upstream" for the source, in this case it would be https://github.com/drupal-composer/drupal-project.git. Remote "origin" should be the git URL of your Gitlab repo. So for you, here is a sample workflow:

The setup:

git remote rm origin
git remote rm composer
git remote add composer https://github.com/drupal-composer/drupal-project.git
git remote add origin https://gitlab.example.com/user1/drupal8-test.git

The result:

$ git remote -v
composer    https://github.com/drupal-composer/drupal-project.git (fetch)
composer    https://github.com/drupal-composer/drupal-project.git (push)
origin  https://gitlab.example.com/user1/drupal8-test.git (fetch)
origin  https://gitlab.example.com/user1/drupal8-test.git (push)

Get upstream files:

git fetch composer
git merge composer/8.x

Adding your own files:

touch myfile.txt
echo "hello world" > myfile.txt
git add foo.txt
git commit -m "Added my file."
git push origin master


Show contextual link for each node on node listing page

If you are building the node listing page using views, you can

Enable contextual links module.
In the fields for the listing, add a field 'Content : Edit Link'. Then select Exclude from display.
Add a Global : Contextual Links field. In the field settings, check the edit link field.
You should be good to go.
You can also add additional field in the context menu if you want.


How to change the label of the "To:" field in the Date Module

If you look further on down in date_elements.inc at line 412 you'll notice:

drupal_alter('date_combo_process', $element, $form_state, $context);

which allows any module to alter what it's created, eg, something like this:

function YOURMODULE_date_combo_process_alter(&$element, &$form_state, &$context) {

  $element['value2']['#title'] = t('expires:'); // this will change that to: to expires:

}

Just realize this simple example will do this for every instance of a combination to/from date, but information to get more specific is contained in $element, $form_state and $context.  For example, the specific field name is contained in $element['#field_name'] and the form_id is in $form_state['build_info']['form_id'].


How to force a dev release of my module?

In the "Release" tab of your project you've a checkbox with "Show snapshot release". If you check it, you should see the dev releases appear.


Drush cim: error "Table xyz already exists"

Like event said, and In my case, this was solved when the drush cr command is entered before drush cim


You probably want this:

$existingUser1 = user_load($uid1);
$existingUser1->field_group_id[LANGUAGE_NONE][0]['value'] = $g_id;
user_save($existingUser1);

You just need to call user_save() on the user object to save the values after you have changed any fields.


How to fix migrate query() that's breaking my migration?

Adding a query to prepareRow() is the way to go:

  public function prepareRow($row) {
    if (parent::prepareRow($row) === FALSE) {
      return FALSE;
    }
    $query = Database::getConnection('default', 'd6source')
           ->select('image_attach', 'ia')
           ->fields('ia')
           ->condition('nid',$row->nid);
    $query->addExpression('GROUP_CONCAT(DISTINCT ia.iid)', 'iid');
    $query->groupBy('ia.nid');
    $result = $query->execute();
    foreach ($result as $r) {
      $iid[] = $r->iid;
    }
    $row->iid = implode (",", $iid);
  }

This has the huge added benefit of not messing up the source row count.


We host a platform in Acquia and we've run into this issue as well. For our needs, we get around it by logging into each webhead and clearing the appropriate cache.

There is an ongoing discussion for this in Drupal issue #2752961.


What other files belong in the root site folder?

The simple answer is: none. The public files folder is an area Drupal uses to store files. It shouldn't be manipulated manually or by non-Drupal processes (unless you're configuring an advanced workflow, really know what you're doing, and can accept the risk that Drupal could theoretically annihilate any "extra" files it finds as it has write perms).

If you're certain the folders you're talking about aren't managed by Drupal, and you don't need the contents, you can assume they're safe to delete.

Obviously you'll need to perform sanity checks to ensure other processes outside of Drupal don't rely on them first. Hopefully your infrastructure is documented (if not, now's the time to start)

FYI You can check whether individual files are managed by Drupal by interrogating the file_managed table.


Is there a module for saving current block setup?

You can try either of these modules (quotes included are from their project pages):

Features Extra:

  ... provides faux exportables (via Features) of several site-building components.

  To export a block, install FE Block, edit your block, give it a "machine name," export it with Features. You can export block settings (region settings, visibility settings, ...) of any block, and the content of blocks created with the Block module from Drupal core.
  The D7 version supports the Block Class, i18n block and Block Cache Alter modules.

Boxes:

  ... a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.

  The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.


That is what done from user_block(), which contains the following code.

  case 0:
    // For usability's sake, avoid showing two login forms on one page.
    if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

      $block['subject'] = t('User login');
      $block['content'] = drupal_get_form('user_login_block');
    }
    return $block;


Adding a base field definition in an update hook - it's not appearing

The problem lies in your display options configuration (reference 4k4's answer to #244122).

Try this:

function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'datetime_default',
        'settings' => [
          'format_type' => 'medium',
        ],
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type' => 'datetime_default',
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

Edit: Don't forget to update your Entity definition as well!


How can I tidy up an auto increment field in a table from within a module?

You should never do that since the IDs are important for addressing to that specific row in other tables. You would never know which modules are also indexed this row with its id. So if you change the ID of a row, you will encounter unexpected things in your installation.


I ran into the same issue

https://www.drupal.org/node/2723061

function my_theme_preprocess_breadcrumb(&$variables) {
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $variables['breadcrumb']) {
    /** @var \Drupal\node\NodeInterface $node */
    $variables['breadcrumb'][] = [
      'text' => $node->getTitle(),
      'url' => $node->toUrl(),
    ];
    $variables['#cache']['contexts'][] = 'url';
    $variables['#cache']['contexts'][] = 'session';
    $variables['#cache']['contexts'][] = 'user';
  }
}

So:

$variables['#cache']['contexts'][] = 'session';
$variables['#cache']['contexts'][] = 'user';
$variables['#cache']['contexts'][] = 'url';

did the trick for me.


It should wrap new comments in a comment-new class already, but if your theme does it differently, you could edit its comment.tpl.php or copy comment.tpl.php from the comment module to your theme and act upon the $comment->new value to wrap it differently yourself.


Is there a Drupal 8 alternative for Inline Entity Form (to create an item while adding a reference)?

You can use the alpha version and the dev version of the Inline Entity Form


How to include fragment (#) in the URL computed by redirect?

The fragment is stored in the options of the url, also the cid in the parameters. So you'll find all information you need in the url permalink() returns:

  $url = $comment->permalink();

  $this->redirect($url->getRouteName(), $url->getRouteParameters(), $url->getOptions());


When exporting a Feature, how can I turn off all page cache related settings?

The variables are named:

cache - Cache pages for anonymous users
preprocess_css - Aggregate and compress CSS files.
preprocess_js - Aggregate JavaScript files.


Can't access default Drupal twig functions

Because of Drupal's granular caching, it is not possible to make the global request object available in templates (at least by default); if a template was used on multiple pages, it would be cached with the data from one page and have incorrect information on any others.

If you require the request information in a particular template, you will need to add a preprocess hook to add the additional variable, and ensure that you add the correct cache tags.

To see what variables are available within a particular template, use {{ dump() }}


Drupal Commerce and large product inventories

The Akademika case study might help. They're at 18 million products right now, regular MySQL database plus Elasticsearch.

You can find the NyMedia team in #commerce on Drupal Slack (or contact them directly).


Create just one .tpl.php file for several nodes?

Here is an example to change the template dynamically on node type with a preprocess function. Of course you can also use this based on nids. https://www.drupal.org/node/1142800


How to create a rule to combine the terms of 2 fields to create a new term stored it in a 3rd field?

My previous answer is based on using Rules Event "View a node of content type Article".
However (as confirmed by OPer after I posted a comment about that, in a comment deleted by a moderator), I think it should be (1) When a node of that content type is created and also (2) When a node of that content type is updated. But (3) when a rules event like "View a node of that content type" happens, I think that should NOT trigger any Rules Action (because viewing should not change any of those values).
Here is a variation of the previous rule, which takes the above into account:
{ "rules_combine_taxonomy_terms_in_a_3rd_taxonomy_for_create_and_up" : {
    "LABEL" : "Combine taxonomy terms in a 3rd taxonomy for create and update",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "DO" : [
      { "drupal_message" : { "message" : "Value of term for Field C has to be set to \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E, i.e. the combination of the value of Field A (= \u003Cstrong\u003E[node:field-a]\u003C\/strong\u003E) and the value of Field B (= \u003Cstrong\u003E[node:field-b]\u003C\/strong\u003E)." } },
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "[node:field-a][node:field-b]" },
          "PROVIDE" : { "variable_added" : { "combined_term" : "Combined Term" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "taxonomy_term",
            "property" : "vocabulary",
            "value" : "vocabulary_c"
          },
          "PROVIDE" : { "entity_fetched" : { "existing_terms" : "Existing Terms" } }
        }
      },
      { "variable_add" : {
          "USING" : { "type" : "boolean", "value" : "0" },
          "PROVIDE" : { "variable_added" : { "new_term_exist" : "New term exists" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "existing-terms" ] },
          "ITEM" : { "current_term" : "Current term" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "text_matches" : { "text" : [ "current-term:name" ], "match" : "[combined-term:value]" } },
                  "DO" : [
                    { "data_set" : { "data" : [ "new-term-exist" ], "value" : "1" } },
                    { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "current-term" ] } },
                    { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E already existed and will be used to automatically set the value for Field C to this term also." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "data_is" : { "data" : [ "new-term-exist" ], "value" : "0" } },
            "DO" : [
              { "entity_create" : {
                  "USING" : {
                    "type" : "taxonomy_term",
                    "param_name" : "[combined-term:value]",
                    "param_vocabulary" : "vocabulary_c"
                  },
                  "PROVIDE" : { "entity_created" : { "term_created" : "Created term" } }
                }
              },
              { "entity_save" : { "data" : [ "term-created" ], "immediate" : "1" } },
              { "data_set" : { "data" : [ "node:field-c" ], "value" : [ "term-created" ] } },
              { "drupal_message" : { "message" : "Term \u003Cstrong\u003E[node:field-a][node:field-b]\u003C\/strong\u003E did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also." } }
            ]
          }
        ]
      }
    ]
  }
}

To import it in your own site (using the Rules UI), use the same trick as in my prior answer.
The difference with my previous answer is (a) another Rules Event and (b) the messages that are simplified now.
Probably most important is that there is no more page refresh needed (you see the result right away).
Demo
Some messages that will be shown, depending on the scenario used:

Update an existing node, or create a new node, with a term for field C that already existed:

Value of term for Field C has to be set to Term A6Term B1, i.e. the combination of the value of Field A (= Term A6) and the value of Field B (= Term B1).
Term Term A6Term B1 already existed and will be used to automatically set the value for Field C to this term also.

Update an existing node, or create a new node, with a term for field C that did not yet exist:

Value of term for Field C has to be set to Term A3Term B1, i.e. the combination of the value of Field A (= Term A3) and the value of Field B (= Term B1).
Term Term A3Term B1 did not yet exist and was created just now. It will be used to automatically set the value for Field C to this term also.

Done ...


Defining a variable in a template_preprocess() function is straightforward:

/**
* Implements hook_preprocess().
*/
function yourthemename_preprocess(&$variables, $hook) {

    $variables['your_variable_name'] = "some value";

}

In your template file, you would just output it directly, for example using the following code:

<?php print $your_variable_name; ?>

I'm not sure this answers your real question, but I could use a little more information. Why are you trying to move the logo/breadcrumbs using a preprocess function? Which theme are you using? If you're moving these around, it is usually easier to just edit the page.tpl.php file in your theme, and work with them from there.


Output a Menu with just needed classes for ul and li,. Nothing more

Try switching the parameters to in_array. in_array takes the needle first and the haystack (array) second.

Edit: unless that was a typo...

Edit

PHP Docs for in_array().

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

  Searches haystack for needle using loose comparison unless strict is
  set.


I think you may need to enable apache mod_rewrite. You can refer this answer as well. To enable mod_rewrite, use the following command:

a2enmod rewrite

Then you need to restart apache for the changes to reflect,

sudo /etc/init.d/apache2 restart

or

sudo service apache2 restart

Refer this page for information about clean urls, this might even help.


Using dd($form_state); within the callback function works beautifully.

On linux you can tail -f /tmp/drupal-debug.txt to see the $form_state in real time. (Or whatever the temp directory for your site is set to, often something like sites/yoursite.com/files/tmp.)

Otherwise, you can find drupal-debug.txt in your systems /tmp/ directory.
http://ratatosk.net/drupal/tutorials/debugging-drupal.html#dd


How can I print article author profile picture?

Put this on top of your node.html.twig or similar template

{%
  set author_pic = {
    '#theme':      'image_style',
    '#style_name': 'thumbnail',
    '#uri':        node.uid.entity.user_picture.entity.uri.value,
    '#attributes': { class: 'authorImg' },
  }
%}

Use this anywhere in the same template you want to output the author image

{{ author_pic }}


How to alter the parameters in the core.services.yml file programatically?

You need a compiler pass:

Compiler passes give you an opportunity to manipulate other service
definitions that have been registered with the service container.

There are some Drupal specifics. An example which calculates a container parameter depending on tagged services is RegisterSerializationClassesCompilerPass. This class is registered in SerializationServiceProvider.
For simple use cases, where you don't need control over compiler pass priorities, you can use the alter() method of ServiceModifierInterface. This will then be executed in a shared core compiler pass ModifyServiceDefinitionsPass.
Example for adding foo to the filter protocols:
src/MymoduleServiceProvider.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Defines a service provider for the Mymodule module.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    $filter_protocols = $container->getParameter('filter_protocols');
    $filter_protocols[] = 'foo';
    $container->setParameter('filter_protocols', $filter_protocols);
  }

}


How to restrict anonymous users to a single product and quantity 1 using Commerce and Rules?

These rules can be used to restrict number and quantity of products available by role.

They can be imported in Rules admin.

Restrict to single product:

Basically, before adding to cart, if anonymous, remove existing products from cart. The effect is only the latest product is added to the cart.

{ "rules_single_product_order" : {
    "LABEL" : "Single product order",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "commerce_cart" ],
    "ON" : [ "commerce_cart_product_prepare" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "commerce_cart_empty" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }
}

Restrict quantity to 1:

On order presave, if anonymous, loop over the line items and set quantity to 1

{ "rules_restrict_quantity_to_1" : {
    "LABEL" : "Restrict quantity to 1",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : [ "commerce_order_presave" ],
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [ { "data_set" : { "data" : [ "list-item:quantity" ], "value" : "1" } } ]
        }
      }
    ]
  }
}

Anon can still view the cart, but they will be restricted to one product and quantity of 1 - a preferable solution here. You could also show a message about the benefits of registering, if required.


Ignore Special Characters from Expose Filter

in hook_form_alter function you can check the expose form and write your below function.

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

return preg_replace('/[^A-Za-z0-9-]/', '', $string); // Removes special chars.
}

assign value to form value array.


Linking External Javascript with drupal_set_html_head

I think all you need to add is $vars['head']=drupal_get_html_head(); after your code above so that the $head variable passed to your page.tpl.php is updated.  If you are doing anything "interesting" with your header, you may need to change that to a .= instead so that it is added to $head instead of just replacing it.


Does drush need to be installed as root?

NOTE The issue described in the Question has now be fixed in the latest Drush version.

No, Drush does not need to be installed as root.

I've submitted Drush pull #2246 to update the current Drush install instructions.

This install method fixes the issue as per Drush pull #2246:

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > /tmp/drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > /tmp/drush

# Test your install.
php /tmp/drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x /tmp/drush
sudo mv /tmp/drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init


In order to add a new block you need to click on the button place block then click again on the place block button base on what block you want to added it.


I placed <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> in  and now my website looks fine in IE.


Print out custom field and footer in newsletter

$node is available within the simplenews templates. htmlmail-simplenews.tpl.php is a generic template that is not simplenews specific.

$body in this context is the mail body, which has been created by combining the simplenews body and footer. Again, within Simplenews, those are separated, but are then simply concatenated together before passed to the htmlmail template.

To get to the node object in there, look at the example templated provided by HTML Mail, which uses $params['context']['node'] and $params['simplenews_source']->getNode() in Drupal 7.


get variable indicating node preview mode (D7)?

The variable that inside node.tpl.php says the view mode currently used for the node is $view_mode, but that variable is not used when Drupal is displaying a preview of the node. To know that, you can:

Check the value of $node->in_preview; when that value is TRUE, Drupal is displaying the preview of a node.
Check that $classes contains the string 'node-preview', such as with the following code.

if (strpos($classes, 'node-preview') !== FALSE) {
  // Drupal is showing a preview of the node.
}

Drupal already shows a message when the user is watching the preview of a node, anyway.

  The trimmed version of your post shows what your post looks like when promoted to the main page or when exported for syndication. You can insert the delimiter "<!--break-->" (without the quotes) to fine-tune where your post gets split.


After your step 1, make sure to initialize the GIT repository, which will add the .git directory, subdirectories and files that store your repository data.

To do so, just use command git init while in your directory sites/all/modules/contrib/cloze.

If you're new to using GIT with Drupal, you may want to look at the community documentation located at Building a Drupal site with Git (+ its child pages).


How to translate !title field is required

To change the field name, you have to translate !name field is required. . To do this, follow these following steps :

Go to admin/config/regional/translate/translate.
Search for the string !name field is required in the String contains textfield.
In search result, change the string for all the languages.
And then save it.

I hope it works.


Loop through entities chosen by Views Bulk Operations

Quoting the VBO Development guide, you can use the aggregate option to get a list of all chosen entities.

  implement hook_action_info()

  aggregate (optional): boolean. If TRUE, all selected objects' IDs
  (oids) will be packed in an array and passed as the first argument to
  the action function, instead of passing each object one by one. This
  is useful to implement aggregate functions that perform a single
  operation on the whole selection set.

Note this guide is only for D6. I have created a D7 version but could not add an aggregate example yet.

However, in your hook_action_info() implementation, set aggregate to TRUE (defaults to FALSE) and VBO will send a list of entity IDs (for you to perform additional related tasks).


How to download the projects within a distribution using git, not just the distribution itself?

There's no direct way to perform this.

This is a sequence that may fit for a dev environment. It is based on --package-handler=wget and drush make. No submodules. Contrib is downloaded to sites/all.

cd /tmp
drush dl commons --variant=profile-only
drush make commons/drupal-org-core.make distro
mv commons distro/profiles
rm -rf distro/sites/all/
drush make --no-core --no-gitinfofile --working-copy distro/profiles/commons/drupal-org.make  distro/sites/all

I used sites/all because drush make wants a non-existent destination, so distro/profiles/commons is not an option. An alternative is to perform the last make in a tmp directory and copy over the profile directory afterwards.

As a side note, drupal.org profiles provide three packages to download: profile-only, core-profile-and-projects, profile-and-projects. See http://drupal.org/node/1867206 for reference.

drush dl provides an option to choose among these three tarballs: --variant=<full,projects,profile-only>. All three options are available for --package-handler=wget whereas for git_drupalorg the only valid option is profile-only, since it corresponds to a single git project.

That said, there's room to implement a more complex workflow to provide (drush dl commons --variant=full --package-handler=git_drupalorg) by using submodules.


Can I safely delete the migrate tables after migration?

Yes. If you're doing a "one-and-done" migration you can remove the tables. Just make sure to:

uninstall the migration modules
remove your relevant migration config
then remove your DB tables once you have no code/config dependant on these tables.

Note, the caveat is you're wiping out your migration history.

The migration framework has an ongoing issue about this topic. These tables are persisted since these they capture migration source/destination metadata. The metadata is important if you have a phased, or ongoing, migration. If your migration project is over, the metadata has no relevance.


If field date is 15 days away from today, change another field value

Hmm.. This sounds like it could be done with Rules and VBO.

Create a VBO view of nodes that match your date requirement using filter date field > relative date. You might also want to filter out nodes that have already been changed.
Create a rule:

Event: Cron or maybe the Rules Once per Day module
Action: Load a list of entity IDs from a VBO view
Action: Loop list
Action: Change / Add field using Set a data value if it's a single value field or Add item to list if it's a multi-value field.

EDIT: As of November 2017, this feature whereby VBO supplies Rules has been a bit broken and requires a patch to work.


The logged requests are clearly attacking the security vulnerability SA-CORE-2018-002. But this is not your main concern now when you've already been hacked, because most hackers close the vulnerability after they take over your site to not get hacked again by other hackers. You probably need to restore your site from a backup before SA-CORE-2018-002 (but then of course go online only after applying the security updates) or if you have no backup available setup the site from scratch, because it's nearly impossible to clean a hacked site from all malicious code and data.

See Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-002 and the FAQ.


Update imported feeds to only get one taxonomy term per node

If data needs to be modified before it is saved use this module : Feeds tamper

For advanced modification use hook_nodeapi in drupal 6 with the insert parameter , with hook_nodeapi load the old node like this :

$old_node = node_load(node->nid);
$node->taxonomy = array_diff($old_node->taxonomy,$node->taxonomy)

So now you are sure that the $node contain only the new value , Hope this  will help


Making tags in Taxonomy-view appear dynamically?

Add Sort Criteria: Global: Random in view

Change the pager limit according to your requirement


How can I programmatically override the title tag from within custom module?

See this question and answer. In short, I think your might be looking for something like hook_preprocess_page().

function mymodule_preprocess_page(&$variables) {
  $variables['head_title'] = t("The new HTML title.");
}


Your theme doesn't support RTL layout.

You need to either RTLize (flip) the CSS of your theme or replacing to a theme that does support RTL.

BT 3.0 doesn't support RTL (though there are plans to make BT 4.0 RTL supportive).

A good Drupal base theme that does support is AdavptiveTheme 8, which is also lighter in code amount.


Several same product with a customizable field

I think I found how to answer to my need :-)

The configuration is done throught the product settings (Commerce>products then select the product to configure and click to edit)

In "Manage display" tab, edit the configuration of the "Variations" Field which is in Format "Add to cart form". Uncheck box "Combine order items containing the same product variation."

Hope it helps !!


Creating an Editor Role and Reusing the Admin Menu and Overlay in Drupal 7

Assuming you have the Administration menu module enabled, under People > Permissions check the following boxes:

Administration menu

Access administration menu

Node

Bypass content access control (note though, this gives the user permission to delete all content; if you don't desire this then you can micro-manage the permission on the individual content types, it's more box checking but also more secure)

System

Use the administration pages and help
View the administrative theme

Those are the core permissions that you need to have in order for a role to view the administration menu as well as menu items pertinent to managing site content.

Now, in order to make sure that the role is more or less secure, I would always uncheck every box whose label begins with "Administer...", as these permissions would be for administration roles.


Date Field Type - Text Field Widget is Gone?

I have a use case where the user needs to be able to copy the date
from another source and paste that value into the date field.

Bootstrap Datepicker
This will allow you to type/paste in and change the date format.

Note: composer won't install the library for you, you have to manually get the /dist folder from github and put in in the /libraries folder. So it has the /libraries/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js structure.

Similar but don't quite do it
Datetime Flatpickr Allows you to change date format, but doesn't allow you to type/paste in.
Bootstrap DateTime Picker Allows you to type/paste in, but doesn't allow changing the date format.
Single Date Time Picker doesn't allow you to type/paste in nor change the time format.


overloading the destination url of privatemsg

Using the Devel module implement hook_form_alter and find your forms $form_id. Then supply a #redirect FAPI attribute like, $form['#redirect'] = 'my-custom-thankyou-page'; and be sure to make your custom page as a drupal Page, module callback, View etc.


Convert Existing Body Fields To CCK Text Fields

Three options spring to mind:

Views Bulk Operations. Safest if the amount of nodes to convert is manageable. You'll probably need to use custom PHP to make the conversion happen though, as the ready-made functionality won't cut your demands.
Custom script where you load each node to be converted, modify the structure and run node_save().
SQL query, either pure SQL or by custom Drupal (Drush) script. First create your content type, then see the database structure. Then select the body text from the table node_revisions and insert it into your field value column for each node.


To add google analytics to every theme,some manual work is required as:-

In your theme's folder ,
select a theme in which you want to add google analytics
open the theme folder and then create a folder for js files
create a js file and include the code provided to you by google for google analytics.
save the file and this way google analytics is installed in your theme.
follow the same procedure for rest all themes.


Figuring out a conditional statement for a specific page

If you are asking how to modify the default page.tpl.php to do something different when a specific path is called, you could just copy page.tpl.php to page-PATH.tpl.php, eg, page-PATH-THAT-VIEWS-USES.tpl.php and then anything inside this new template would be used just for the page displayed at that path.

In your example code, as an example, you could copy page.tpl.php to page-node-250.tpl.php or page-node-429.tpl.php etc and then you wouldn't need any ifs in them with respect to the id="medspecheader" as these templates would only be used when looking at those nodes.

Just realize that the path used is the drupal system path, not any alias, but Views does create such a path for any Views that utilize a Page Display.

Lots more information about template suggestions for Drupal 6 can be found here.

If these don't work for your specific needs, you can also create more templates suggestions for Drupal to use via a hook_preprocess_page() call in your module or theme.

For example, if you wanted the page to display differently whenever a specific node type is being displayed, and you didn't want to hard code in all of the specific node nids, you could do something like this in your theme...

function YOURTHEME_preprocess_page(&$variables) {

  if (isset($variables['node']) && $variables['node']->type=='med_special') {
    $variables['template_files'][]='page-cck-' . str_replace('_','-', $variables['node']->type);
  }

  // any other page preprocessing goes here

}

Now, whenever page displaying a node of type med_special is called up, Drupal will look for a page-cck-med-special.tpl.php file in your theme to display it.


It's a token for generating a random string. When you look into the implementation, you can see it's the result of hashing 55 random bytes with your selected hashing algorithm (the ? part of random:hash:?).

Will it meet your uniqueness needs? Yes.

Since we're talking pseudo-randomness here and the fact that hashing algorithms can produce collisions, there's a possibility of the same string being generated but it's very unlikely (unless you have a massive number of SKUs being generated).

In the unlikely event that Commerce & the AutoSKU don't have the logic to prevent SKU collision (which should be there as its a unique attribute), you can always add more patterns in the token (e.g. UID) to lessen the collision possibility to effectively zero, for the number of SKUs needed by your store.


Override a single JavaScript file from a module

The answer is simply that the libraries-override definition must go in the .info.yml not .libraries.yml:

So in mythemename.info.yml:

libraries:
  - mythemename/global-styling
libraries-override:
  toolbar/toolbar:
    js:
      js/views/BodyVisualView.js: js/views/BodyVisualView.js

If placed logically there, alongside the libraries definition, it works perfectly.

Note that the second 'toolbar' is the library name from toolbar.libraries.yml, other library names in there include toolbar.menu, so if overriding a file from there it would be "toolbar/toolbar.menu:" instead of "toolbar/toolbar:".


Create content of different entity by user programatically

The key is user_id, so presumably the correct code would be:

$post = Post::create([
  'type' => 'post',
  'field_post' => $post,
  'field_visibility' => 1,
  'user_id' => 2,
]);

$post->save();

I changed the var name to $post as it's not a node and you don't want to confuse those two things. I also removed the type as the social post entity type doesn't have such a field.


How to slow down migrate? Cloud Files can't keep up

In your migration scripts you can use either prepare() or complete() (http://drupal.org/node/1132582) and add in sleep(). It's a hacky solution but it should give you enough time between processing each row for Rackspace to catch up.

public function prepare($node, stdClass $row) {
  sleep(30); //wait for 30 seconds
}


How to correctly invalidate a cached node when a menu link content is added/updated/deleted?

The tag you add doesn't exists. You probably want to add the list tag from the menu link content, which is invalidated in all cases when a link item is added, updated or deleted:

$variables['#cache']['tags'][] = 'menu_link_content_list';

But there might be another problem. As I understand your idea is, if you have a cache tag somewhere on the page, the complete page gets invalidated. This is true, but it will not help you. The rebuilt page will contain the cached menu block, if the block has not the correct cache tag on its own. So if you add a cache tag from the menu link to the node you have to do the same vice versa, add a node tag to the menu.

And probably you also need a cache context in the menu block for the visibility.


Read access to user's nodes based for referenced users

That will require custom code.

Here's one way to achieve it:

You'll need to use hook_node_view to get involved when the node is about to be rendered.  Your code should:

Check the node's author and use user_load to gain access to the referenced users
Check to see if the current user (global $user) is in the list of referenced users
Permit or deny the node view, or change how the node displays, depending on the result.


Permanently disable Auto Preview in views?

As seems to always be the case, I stumbled upon the views settings page after posting the question: On admin/structure/views/settings unselect "Automatically update preview on changes."


Pre-Built Theme, how to transfer header to blocks

Essentially you have the User Login & Search Form blocks so you could add the following to your themes' .info file:

regions[login] = Login
regions[search] = Search

Clear the site cache and visit your Blocks page (admin/structure/block) and you should see 2 additional regions. Place the User Login block in the Login region and the Search Form block in the Search region.

In page.tpl.php in your theme, use the following code:

<?php if (!empty($page['login'])): ?>

   Login

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

<?php endif; ?>

<?php if (!empty($page['search'])): ?>

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

<?php endif; ?>

This will give you a starting point and you can start overriding output in your theme by using functions and templates. It should be possible to achieve almost the exact code you're looking for.

You're obviously using Bootstrap, have you tried using the Drupal Bootstrap theme as a starting point?


Views Grouped Filters turns Radiobuttons into Select?

I  came up with writing a simple hook:

 function  MY_MODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id)
  {
    if ($form['#id'] == 'MYFORMID') {
      $form['field_MY_VALUE_FIELD']['#theme'] = 'select_as_checkboxes';
    }
  }


The problem was due to different behavior between mysql 5.6 and 5.7. I thought I had the same environment between production and test but I was wrong. I use a docker image for mysql but didn't specify a version so I ended up with two different versions on the two systems, even though the provisioning looked the same.


How to get a list of entities available in your Drupal?

You can just invoke hook_entity_info() and check the keys:

$info = module_invoke_all('entity_info');
$all_entity_machine_names = array_keys($info);


How to perform calculations using a field from another content type?

You can go for Views Calc or Views Aggregator Plus

This module adds simple calculations to a views table.

You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns.


Drupal7+Omega Theme: How to narrow the 20px gutter between columns in 960 grid?

If you search Google for "Drupal Omega custom grid", you find links like:

Creating and Setting up a Custom Grid for Omega 3.x
How to define my own 960 grid ?

Hope that helps.


How to do field validation during migration?

You can accomplish this using the ::prepareRow() method on your migration class. You'll have access to the source field values in the $row variable. This method is called once for each record being imported, and returning FALSE will skip the row in question.

Example:

function prepareRow($row) {
  if (!validate_my_field($row->my_custom_field)) {
    return FALSE;
  }
}

More info https://www.drupal.org/node/1132582

For Drupal 8 you could accomplish the same by either implementing a custom source plugin with a prepareRow() method. Or by implementing hook_migrate_prepare_row() and performing your validation there.


How to create a CSV file to migrate my Commerce Products with the Feeds module?

You can use the Forena module. Here is a quote from that page:

  ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

  Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

So if you'd install Forena in your "old" site, then these are the steps for creating such CSV files are:

a custom SQL query (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

These steps do not require any PHP coding.

Bonus: instead of CSV format, you also have an option to format it as either XML or JSON. For more details on that, refer to "How to add a link to the CSV download to my module page, for a report created with Forena?".

Alternative: not sure if it would fit your requirements, but you could also use the Feeds integration of Forena. In this case you'd install Forena in your new site, and use Forena to enable Feeds to just go get your data in your old site. Checkout the video tutorial about this topic (specific to this Feeds integration).

For an online demo (prior to installing/testing Forena), checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module).

Disclosure: I'm a co-maintainer (not owner ...) of this module,
I hope this does not violate the site's policy on self-promotion.


Webform conditional calculation depending on selected options count

You have to use javascript for this and multiply the price with the number of days (the number of checkboxes checked).


Views Data Export Not working for current page

It seems issues with the module itself. You can just use view's template file or hook_views_pre_render() rather than attachment.

Append a link after views content or in footer called Export CSV.

Your code will be like this :

print l('Export CSV', 'userexport.csv', array('query' => array('page' => $_GET['page']));


How do I alter the route defined by another module?

Allow views to override existing routing items just uses existing functionality.
If you want to change the information attached to a route, not the menu,
like the actual used controller, or the requirements (permission/role etc.)
you can use an event provided by Drupal:
  <?php

  use Drupal\Core\Routing\RouteBuildEvent;
  use Drupal\Core\Routing\RoutingEvents;
  use Symfony\Component\EventDispatcher\EventSubscriberInterface;

  class RouteSubscriber implements EventSubscriberInterface {

   /**
    * {@inheritdoc}
    */
   public static function getSubscribedEvents() {
      $events[RoutingEvents::ALTER] = 'alterRoutes';
     return $events;
   }

  /**
   * Alters existing routes.
   *
   * @param \Drupal\Core\Routing\RouteBuildEvent $event
   *   The route building event.
   */
  protected function alterRoutes(RouteBuildEvent $event) {
    // Fetch the collection which can be altered.
    $collection = $event->getRouteCollection();
    // The event is fired multiple times so ensure that the user_page route
    // is available.
    if ($route = $collection->get('user_page')) {
      // As example add a new requirement.
      $route->setRequirement('_role', 'anonymous');
    }
  }

  }

Additionally you have to register a service with the tag 'event_subscriber' for this class.