Change Log in or register to post comments for content type

Go through this link will give you a nice work around

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

Then, you need to change code: Find your modules/comment/comment.module file, open it in a text-editor (like wordpad or the like), and search for the text you don't want to see on pages. You need to comment out (or delete) a bit of code, something like:
//

 if (variable_get('user_register', 1)) {
//      return t('Login or register to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('Login to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

The added 'return' is just for case, to ensure nothing to show - I didn't test this.

You can either edit the original file (which is quick but unclean, and requires you to redo the change after every unpgrade), or override that function in your theme properly by placing its copy into your template.php file (whole function!), renaming it to "phptemplate_[name]", and changing as needed. I think (not tested!) that it should look like this (added to 'template.php' in your theme's folder / create the file if not existing yet, with

function phptemplate_comment_post_forbidden($nid) {
  global $user;
  if ($user->uid) {
    return t("you can't post comments");
  }
  else {
    // we cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages
    if (variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
      $destination = "destination=". drupal_urlencode("comment/reply/$nid#comment_form");
    }
    else {
      $destination = "destination=". drupal_urlencode("node/$nid#comment_form");
    }

//    if (variable_get('user_register', 1)) {
//      return t('Login or register to post comments', array('@login' => url('user/login', $destination), '@register' => url('user/register', $destination)));
//    }
//    else {
//      return t('Login to post comments', array('@login' => url('user/login', $destination)));
//    }
    return '';

  }
}

But still, you'll probably need to check on every upgrade, whether this copied code is in sync with core's possible new changes.


Migration Issue: New Site won't open -- server doesn't see file that is there

If your files are all under /home instead of /opt you could just setup a virtualhost and point to the /home docroot

e.g, for apache, where www.example.com is your site domain name:

<VirtualHost *:80>
     ServerName www.example.com
     DocumentRoot /home/bitnami/apps/drupal/htdocs
     CustomLog /var/log/apache2/example-access.log combined
     ErrorLog  /var/log/apache2/example-error.log

     php_value memory_limit 256M
     php_value upload_max_filesize 128M
     php_value post_max_size 128M
     php_value max_execution_time "360"

     FileETag ALL

     <Directory /home/bitnami/apps/drupal/htdocs>
         RewriteEngine on
         RewriteBase /

         RewriteCond %{REQUEST_FILENAME} !-f
         RewriteCond %{REQUEST_FILENAME} !-d
         RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

         Options -Indexes
         AllowOverride All

         # Follow symbolic links in this directory.
         Options +FollowSymLinks

         # Customized error messages.
         ErrorDocument 404 /index.php

         # Set the default handler.
         DirectoryIndex index.php

         php_value magic_quotes_gpc                0
         php_value register_globals                0
         php_value session.auto_start              0
         php_value mbstring.http_input             pass
         php_value mbstring.http_output            pass
         php_value mbstring.encoding_translation   0

         # Requires mod_expires to be enabled.
         <IfModule mod_expires.c>
             # Enable expirations.
             ExpiresActive On
             # Cache all files for 2 weeks after access (A).
             ExpiresDefault A1209600
             # Do not cache dynamically generated pages.
             ExpiresByType text/html A1
         </IfModule>
         <IfModule mod_deflate.c>
         # Use mod_deflate to compress text content as required and supported by the client
         # Note that the frontend will automatically gzip content if supported using PHP functionality
         AddOutputFilterByType DEFLATE text/html text/javascript text/css application/x-javascript
         </IfModule>

     </Directory>

</VirtualHost>

<VirtualHost *:80>
    # Redirect non-www to www version of site
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

Add to /etc/apache2/sites-available/example.conf

Then, to enable:

sudo a2ensite example.conf
sudo service apache2 restart


Download file one time only for auth user (Suggestion needed)

Please use the modules tag if you're looking for a module hosted at Drupal.org.

There exist a module named Deep Link.  With 13 installs and no full release in sight, I wouldn't have high hopes for the usefulness of this, but the project page says:

  Deep link module allows the direct access to a specific item of content under certain circumstances and limitations. Such as one-off or time-limited deeplinks.

There is also Expiring Private File Link.

It says:

  This module was created when the need arose to offer a downloadable file to users of a site, without revealing the actual URL of the file itself. It also allows through the permissions system a method of allowing the file to only be available for download to registered users. If enabled, anonymous users will see the same dynamic link as registered users, but when they click on it they are presented with a login dialog informing them they must register to have access to the file.

This is a sandbox for Drupal 7, so its usefulness is even more questionable, but you may still want to check it out.


Creating Image Captions using File Entity module

Exposing file_entity fields in forms

A simple solution to this issue is to change each upload image field's widget type from default 'Image' to 'Media file selector'. Thus throught Media all file fields can be edited.

An alternative solution is File Entity Inline (https://drupal.org/project/file_entity_inline) which exposes the file entity fields as form fields.

Displaying file_entity fields in pages

If file_entity fields are not displayed in the page, test first if they are exposed using Views (field image). If you want to display them in a simple page with image fields already created try to workaround by adding new theme suggestions / template: e.g. file--image.tpl.php

The theme suggestions provided by the File Entity module are:

file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}


How to adjust weight of profile 2 fields

You will have to use the Drupal Form API to achieve that.

You basically need to alter the structure of the form before it gets rendered.

If you are using the Profile2 module, the best way to go about it would be to implement hook_form_profile2_edit_PROFILE_TYPE_form_alter()in a custom module.

You will then need to transform the $form array as needed (change field weights, and field positions).

For example:

function MODULE_NAME_form_profile2_edit_YOUR_PROFILE_TYPE_form_alter(&$form, &$form_state) {
  // Apply transformations to $form
  // e.g. change field weights
  $form['your_custom_profile_type']['place_of_work']['#weight'] = '-10';

  // e.g. copy field into new position
  $form['account']['place_of_work'] = $form['your_custom_profile_type']['place_of_work'];

  // Add a custom pre_render function to prevent the field from showing up again in the form
  $form['#pre_render'][] = 'MODULE_NAME_pre_render';
}

The pre_render function could look like this:

function MODULE_NAME_pre_render(&$form) {
  // Prevent custom field from displaying twice
  unset($form['your_custom_profile_type']['place_of_work']);
  return $form;
}


How do I share views on multisite in drupal 8

Multisite sharing works by using the same prefix for certain tables. It's dark magic, especially in 8.x, with the automatically created entity and field tables.

Since all config is stored in the same table, that's not possible.

You could write a custom config storage controller that stores certain config in a shared table, but that seems like a very crazy idea to me.

Configuration can be exported/imported and probably doesn't change that often. There will also be modules like features and others that will make re-using configuration easier.

I would also strongly recommend to consider other options to share your content. I can't imagine that this works reliably in 8.x.


How can I POST x-www-form-urlencoded data from REST API plugin?

While looking into this, I found this solution to accept form encoded POST data and respond with JSON:

<?php

namespace Drupal\example\Encoder;

use Drupal\serialization\Encoder\JsonEncoder as SerializationJsonEncoder;

/**
 * Decodes form data and returns JSON.
 *
 * Simply respond to form format requests using the JSON encoder.
 */
class FormJsonEncoder extends SerializationJsonEncoder {

  /**
   * The formats that this Encoder supports.
   *
   * @var string
   */
  protected static $format = ['form'];

  /**
   * {@inheritdoc}
   */
  public function decode($data, $format, array $context = array()) {
    parse_str($data, $result);
    return $result;
  }

}

and then add the encoder to the example.services.yml

services:
  serializer.encoder.form:
    class: Drupal\example\Encoder\FormJsonEncoder
    tags:
      - { name: encoder, format: form }

After that, the "Accepted request format" can be selected on the rest plugin config page:

admin/config/services/rest/resource/example_rest_plugin/edit


Take a look at Homebox module.

  Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.


Linking to a php site located in a subdirectory of the Drupal site

Well, I ended up going the JavaScript approach. I don't know how to get around using absolute links to the subsites without doing something pretty hacky, so I created a module that adds a javascript file when NOT in the production environment. The javascript searches all links for hrefs with the production domain and changes them to use the current page's domain.

Hence, in production the module does nothing, but in any other environment it replaces the absolute links.

Not optimal, but a workable solution for my case...


How to change stylesheet ordering of base and child theme?

First of all, if you look into the  section of your code, can you find the css file? If not, it can be that the css is aggregated (in this case you'll find a random alphabetic css file), then clear your cache. If there is no aggregation, and you can't find your file, it is most probably set wrong in your theme.info file.

If the file is there, but not working, check in your browser (via fe element inspect) if and why the selectors are overridden...


Install and configure services module in site A, and on site B you will have to write a custom php post method,

POST http://example.com/rest/user/login

Content-Type: application/json
{
"username":"user_1",
"password":"password"
}

If the response you get from this post method is status 200 then you can verify that the username and password are matching.

Some useful resources:

Services installation doc: https://drupal.stackexchange.com/a/15718

Also found php-curl example here: https://www.drupal.org/node/1334758


Authenticate joomla users to drupal website

I'm not sure on a module based solution, but i would just add a custom form submit function on the user_register_form and then code from there. Success would depend on how you can remotely authenticate with Joomla.


Views report for Ubercart Order product totals for date range?

I found my answer. I used the Views Aggregator Plus module (https://www.drupal.org/project/views_aggregator). I applied "Group and Compress" and "Tally Members" in the "Group Aggregation" column within the Views Aggregator Table options for the SKU field, and I applied "Sum" in the "Column Aggregation" column for the Quantity field. This provided me with the exact result I was looking for.


get taxonomy terms of parent node while in block

You should be able to use menu_get_object() to get the node object if the block is being displayed on a node page. Then, with the $node object you can retrieve terms for the node.

if ($node = menu_get_object()) {
  $query = db_select('taxonomy_index', 'r');
  $t_alias = $query->join('taxonomy_term_data', 't', 'r.tid = t.tid');
  $v_alias = $query->join('taxonomy_vocabulary', 'v', 't.vid = v.vid');
  $query->fields( $t_alias );
  $query->condition("r.nid", $node->nid);
  $result = $query->execute();
  $terms = array();
  foreach ($result as $term) {
    $terms[$term->tid] = $term;
  }
}

Just remember that that if caching is enabled in your block it should be per-page caching, otherwise you could get unexpected results.


modify date token in View to extract only year?

Steps to get the just the year for Delivery Date field

Navigate to /admin/config/regional/date-time/formats page.
Click on Add Format button (/admin/config/regional/date-time/formats/add)
In the Format string text field add Y and save it.
Now add a date type by navigating to /admin/config/regional/date-time page.
Add a new date type and use the the format that we have added in the previous steps.
In the view select the type you want the date to be rendered.

So instead of Rewriting the output, you would directly get the year.

Hope that this will help you.


To test the block style visibility rules, you can use drupal_match_path

For example, in core: block_block_list_alter

  Checks the page, user role, and user-specific visibility settings. Removes the block if the visibility conditions are not met.


Meaning of Error: Cannot redeclare bootstrap_preprocess_region()

This was happening because I'd copied .func.php files from the templates folder of the Bootstrap parent theme into my base theme alongside .tpl.php files. Bootstrap is relatively unusual in that it has files in the templates folder alongside tpl files that will break the site if they're treated like standard theme tpl files.

While the .tpl.php files are to be copied as normal, to override the contents of the other files, you are expected to copy their appropriate contents into your subtheme's template.php file or into a new .func.php file, and substitute your subtheme name for the bootstrap part of the function name.

There's some more information on the theme registry docs page.


Get the name of file from file field before node is saved

try some thing like

function module_node_presave($node)
{
   if($node->type=='article'){

       $file = file_load($node->field_zip['und'][0]['fid']);
       dpm($file->filename);
   }
}


Just checked your issue by upgrading Webform to version 8.x-5.0-beta15. After enabling AJAX on the form and setting the confirmation to either inline or message the confirmation worked as expected. I did needed to clear my cache though.

So try upgrading the Webform module and clear your cache.


Does Page Manager redirect work on alias paths?

Yes panels will read the path alias. I have discovered two related reasons why this problem might be occurring.

Many of my taxonomy terms are two words long. Panels does not have a provision (views does) to convert the spaces to dashes.  The panel redirection variant is not reacting to the URL because it is looking for an argument that does not have dashes generated by %spec:name.
I tried the same redirect using the panel provided by the system /taxonomy/term/%term and it succeeded in placing the redirect path in the URL, although the redirect did not work.  This is because the term name had two words and was inserted with a space in it.

There are several LEARNING Points for me in this answer:

First, I discovered that the actual Drupal path to nodes and terms are fully interchangeable.  I thought that if a URL was using an alias, I was restricted to working with the alias format. The ability of panels to intercept the Drupal name pattern taxonomy/term/%term out of the alias drove home to me the fact that Drupal sees them as exactly the same.

Second, When this problem arose, I thought too big, too fast.  I suspected a bug in the module or a major misunderstanding of how the selections in the form connect to each other to generate the action of the panel variant.  I have had similar problems using views, which also very a complex module.  The problem turned out to be a minor, easily overlooked error.


How to access the links variable from a template?

I have found the solution to this problem. You need to do the following in your template:

<?php $node = node_load($fields['nid']->raw);
global $language;
node_build_content($node, 'full', $language->language);
if (!empty($node->content['links'])): ?>
    <div class="links">
      <?php print render($node->content['links']); ?>
    </div> <!-- /links -->
<?php endif; ?>


Why can't I uninstall a module if I deleted a field type in a content type?

You can try this process
Log into database and ->
Select * from field_config where type = "field_collection"

Delete the rows
Same with field config instance table like
SELECT * FROM field_config_instance where entity_type = "field_collection";

Delete the rows
You can also check.

1.) first remove all the fields inside the Fields Collection.
2.) Then remove the field collection from the content type
3.) Run the Cron
4.) try to disable the module, if you cannot then Go ahead with first query statements above.

Get more details Here.


How do I send a privatemsg to all users that have flagged a node using Rules?

Create a new rule triggered on After saving a new comment`.
No conditions necessary; set them up only if you require something specific.
Actions:

Fetch users who have flagged a node
Loop through those users (argument will be populated automatically)
Under that loop create a new action "Send a message". This will require you to have "Privatemsg Rules Integrations" module enabled.


The version you have should provide an option for the image field Group multiple values and also underneath this you can choose just to show 1 image. Either or a combination should stop these duplicates happening


You need to rearrange text filters - make smiley filter last. If you put it before "strip HTML tags", it will add tags but they'll be stripped.


Adding class to the webform submit button

I think that you have to do something like this (add an array):

$form['actions']['submit']['#value'] = "click to become a member", array('attributes' => array('class' => array('btn'), 'style' => array('CUSTOM STYLE DIRECTLY') ));

I'm not really sure if is there is the right place the you have to add that code, but that generally it's this code:

, array('attributes' => array('class' => array('btn'), 'style' => array('CUSTOM STYLE DIRECTLY') ))


Omega4 supports

<!DOCTYPE html>
<html lang="<?php print $language->language; ?>" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

where you don't have to manually define RDFa.

Beside Omega4 I normally do (usually I use Zen, but you can do this in other themes too):

<!DOCTYPE html>
<html lang="en" prefix="dc: http://purl.org/dc/elements/1.1/">

and define property="http://purl.org/dc/terms/TERMS wherever I use RDFa

Dublincore Metadata Initiative has detailed information about the terms

Drupal7 core has RDF support via rdf_namespaces. The hook implementation is:

function hook_rdf_namespaces() {
  return array(
    'content' => 'http://purl.org/rss/1.0/modules/content/',
    'dc' => 'http://purl.org/dc/terms/',
    'foaf' => 'http://xmlns.com/foaf/0.1/',
    'og' => 'http://ogp.me/ns#',
    'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
    'sioc' => 'http://rdfs.org/sioc/ns#',
    'sioct' => 'http://rdfs.org/sioc/types#',
    'skos' => 'http://www.w3.org/2004/02/skos/core#',
    'xsd' => 'http://www.w3.org/2001/XMLSchema#',
  );
}

so you can simple do <?php print $rdf_namespaces; ?> in your html.tpl.php file where you start <html>.

If you want latest RDF support there is a module for that one too called RDFX.


how to use hook_user_login to catch username and password

The information send in the login form is in the $edit array. You can get this information as follows:

function YOURMODULE_user_login(&$edit, $account) {
  $username = $edit['input']['name'];
  $password = $edit['input']['pass'];
  drupal_set_message("Welcome $username your password is $password");
}


The database connection is not serializable

I experienced this issue after manually deleting some translated configuration files. From then on I was not able to successfully config import anymore without being interrupted with the fatal error from your question.

I then tried to run config import after uninstalling locale, which worked but have also deleted lots of translation from the database. Bad.

I could restore the configs in question and then remove them from the UI before exporting them again. Boring.

So I deleted the original configuration objects from an update function (and thereby also deleted the translations), and afterwards run configuration import again, where the original configs then got restored automatically (as their files still existed) WITHOUT translation.

/**
 * Remove unwanted translations.
 */
function MYMODULE_update_8005(&$sandbox) {

  $configs = [
    'image.style.crop_thumbnail',
    'views.view.user_admin_people',
  ];

  foreach ($configs as $config) {
    Drupal::configFactory()->getEditable($config)->delete();
  }
}

EDIT: Only shortly after I had the same problem again. Again it was a missing config (I deleted manually, don't do that) and took me hours to find out which one exactly. This time it was menu_item_extras which required menu_item_extras.utility.yml. Actually I uninstalled menu_item_extras but maybe menu_item_extras can't be uninstalled that simply. But that's a different issue.

What's left to conclude now is: Did you manually delete some config files prior to getting this error?


How to create a node with submissions of a webform?

Instead of using the Webforms module to create new nodes, it's better to let the users create them directly at MY-SITE/node/add/CONTENT-TYPE. Trying to hack data out of a Webform only makes things unnecessarily more complicated. Hide the toolbar for other users and give them permission to add new content. Lastly, adapt the node form to your needs with a template file and style it with CSS.


How to conditionally attach a stylesheet to a page, preventing anonymous users from getting a cached version?

Related: Cache context drupal don't work.

But your logic is actually depending on the session, and the internal page cache is disabled automatically for users with a session.

So it is more likely that you are having a problem with the dynamic page cache.

Your problem is that cache tags are not about caching multiple variations. They are about invalidating already cached things when something changes. So if you have configuration which override value should load which value, then you'd need a cache tag for that, so you can invalidate it when that happens. Also in 95%+ of the cases, you don't need to make up your own cache tags, but just use the default cache tags for entities, config objects and so on.

What you want is a cache context, either the default 'session' or make your own, that doesn't vary for the whole session content but only your key, whould is more efficient. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts

And you should also read https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays to understand when you need cache tags, contexts, ..


I fixed it by creating a global variable, and then assigning the value of the carousel to it.

var global_jc="";
function slCarousel_initCallback(carousel) {
  global_jc=carousel;
  // ...
}

Wherever I want to use next(), I use the following code:

global_jc.next();


Why does module_invoke() return an empty array for anonymous users?

You are invoking the function bean_block_view(), which contains this code:

if (bean_access('view', $bean) && $bean) {
  $content = $bean->view($bean->view_mode);
  if (!is_array($content)) {
    $content = array(
      '#markup' => $content,
    );
  }

  $return = array(
    'content' => $content,
    'subject' => isset($bean->title) ? $bean->title : '',
  );
}

Looking at the first line of code, you can see the block is only built if the viewer has 'view' access for beans.

So it's a permissions issue of some sort with the beans module. Anonymous users don't have the required permission, so the block is empty.


Editable field in view to display editable form only

I was informed lately that another module fits better my requirements so instead of Editable Views, I had to use editablefields module.

Editable Fields provides you with an editable formatter which allows you to display the field as an editable form only.

Unfortunately it appears to be only on alpha2 for Drupal 7, but seems ok for my expectations.


Can I control what caches are flushed via "Flush all caches"?

If you're using the admin menu module you can selectively target which cache to flush by hovering over the the Flush all cache menu under the home icon. The Class registry and Page and else will wipe out the Boost cache, but everything else will leave it intact.


I did some profiling with a query of 100,000 nodes, fetching the field myfield from all nodes of type mybundle.

Good: A dynamic query with addField()

$connection = \Drupal::database();
$query = $connection->select('node__field_myfield');
$query->condition('node__field_myfield.bundle', 'mybundle');
$query->addField('node__field_myfield', 'field_myfield_value');
$result = $query->execute();
$values = $result->fetchAll();

This runs in about 250 milliseconds.

Bad: An entity query with loadMultiple()

$query = \Drupal::entityQuery('node');
$query->condition('type', 'mybundle');
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$values = [];
$nids = $query->execute();
$nodes = $node_storage->loadMultiple($nids);
foreach($nodes as $node) {
  $values[] = $node->get('field_myfield')->getValue();
}

This took 3 minutes after a few repeated attempts when the cache was fully built. After a cache rebuild, it took more than half an hour.


How do I unhook commerce_kickstart_blog_preprocess_node?

$implementations is an array whose keys are the short name of the enabled modules; $hook is the name of the hook, without hook_ nor the short name of the module.

You need to change your code to the following one.

function my_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'preprocess_node' && isset($implementations['commerce_kickstart_blog'])) {
   unset($implementations['commerce_kickstart_blog']);
  }
}

I assume the short name of your module is my; if it were my_module, then you would need to use the following code, since the hook is hook_module_implements_alter().

function my_module_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'preprocess_node' && isset($implementations['commerce_kickstart_blog'])) {
   unset($implementations['commerce_kickstart_blog']);
  }
}


This sounds like something you could have done in the node template in your theme. You can try to change your theme. If that fixes then your theme is the root cause.


Drush now uses composer for managing external libraries.  You can read about this in the GitHub issue.

If you don't have composer installed, you can follow the instructions on its project page.  Under Linux or OSX, you can do

$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer

which will install it globally.

Once you have done this, you can

$ cd /path/to/your/git/clone/of/drush
$ composer install

This will download all of the external depencencies, and drush should start working.

See the drush project page for details.


How to get a term from the translated term name?

You can try to translate it before pass it to taxonomy_get_term_by_name function, try some thing like

$string= 'De Lema'; // string in not default site language I suppose in French
$default_lang_short = 'un'; // I supposes you default site language is english change it to your default
$en_value = t($string, array(), array('langcode' => $default_lang_short));
taxonomy_get_term_by_name($en_value);


hide result on same node in block (view)

You need to use the contextual filter option here. You can get current page nid using contextual filter as shown in screen shot and can filter out the result.


Using Drupal 7 with APC, Varnish and Memcache, what bins to put in which cache?

Looks ok to me.

What you can try is play around with Memcache options. There is for example a compression flag but it usally depends on the site if it makes sense to enable it because you then have a higher cpu usage to do the compression/decompression.

I also think that page_cache_invoke_hooks flag is not necessary anymore, see http://drupal.org/node/804864. If you don't need those hooks to run then you can set it, but it's not necessary anymore for Varnish to work.

Using APC cache with multiple webservers means that you run into inconsistencies when clearing caches on one server, so if you do have multiple ones, you probably want to use Memcache for cache and cache_bootstrap as well. I've also had stability issues when using APC cache but I did use it for all caches, which might have been the issue.


Any module you distribute must be licensed under the GPL 2.0 or later. You are free to put it up for sale so long as anyone who buys it enjoys the same rights of redistribution - that's just the nature of Drupal's license overall. Anyone who buys your module will be free to put it up on drupal.org and redistribute it at will.


How do I install Drupal Console to my project with Composer?

You should follow the docs on the official Drupal Console repo on how to install it with Composer. Note that the global launcher is not recommended, it is recommended to add it to your project through Composer.

https://github.com/hechoendrupal/drupal-console/blob/master/README.md

# Change directory to Drupal site
cd /path/to/drupal8.dev

# Download DrupalConsole
composer require drupal/console:~1.0 \
  --prefer-dist \
  --optimize-autoloader \
  --sort-packages

Note that the second command is all one command, not four. The \ tells terminal the command is continuing to the next line.


how to implement a data receiver service in Drupal

If you do it the JS part, Drupal part will be quite easy.

Create module with form that handle data transfer to Drupal and submit this form via Ajax https://drupal.org/node/752056

It can be helpful too: Match JSON POST data with custom node fields


How can I automatically visually number each webform component? e.g. 1) ... 2) ... 3)

You could use an entirely front-end solution with CSS counters: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters

I believe components are siblings of each other which would make this quite easy.


Including a file on every page in a module

If the file needs to be included on every page, the correct way is to use PHP's include or require, I don't think the fact that this is in a Drupal site should really make any difference.

I've seen plenty of modules that literally put the following at the top of the module file:

require_once('module.inc');
require_once('test.inc');

If you really want to do it  a 'Drupal' way, you can use module_load_include() (which just wraps around require_once internally), directly at the top of the file instead of inside your page callback. This is what I tend to do normally.

module_load_include('inc', 'MYMODULE', 'MYMODULE.something');

Adding the file in hook_init() is perfectly fine too, I can't think of any justification to use one over the other, it would be down to personal preference.


Get the values of views fields in a Twig template

In the template file (views-view-field), you can use

 {{ row._entity.field_name1.value }} {{ row._entity.field_name2.value }} {{ row._entity.field_name3.value }}

Or, in your theme, in the preprocess function you can overwrite the output:

function your_theme_name_preprocess_views_view_field(&$variables) {
    $view = $variables['view'];
    if ($view->storage->id() == 'your_view_name') {
        $variables['output'] = '
' .
          $variables['row']->_entity->field_name1->value .
          $variables['row']->_entity->field_name2->value .
          $variables['row']->_entity->field_name3->value .
        '
';
    }
}


Homebox column number different on mobile?

Add the following to your css.

@media screen and (max-width:740px){
    .homebox-column-wrapper{
          width:100%!important;
          clear:both;
    }
}


How to programmatically insert and update Field Collection values?

The following snippet (compatible with field_collection 8.x-1.0-alpha1) reuses an existing FieldCollectionItem or creates a new one on demand. The last few lines show how to modify fields inside the FieldCollectionItem.

If one has a field collection with a different name, then it should be enough to replace all occurrences of field_test_field_collection with the custom field collection's machine name.

<?php

// […]

$nodeId = 123;

/** @var EntityStorageInterface $entityStorage */
$entityStorage = Drupal::entityTypeManager()->getStorage('node');

$node = $entityStorage->load($nodeId);
$node->body = 'Body Update: ' . date('c');

/** @var Drupal\Core\Field\FieldItemList $fieldItemList */
$fieldItemList = $node->field_test_field_collection;

// Reuse existing Field Collection.
if (count($fieldItemList))
{
    /** @var \Drupal\field_collection\Plugin\Field\FieldType\FieldCollection $fieldCollection */
    $fieldCollection = $fieldItemList[0];
    $fieldCollectionItem = FieldCollectionItem::load($fieldCollection->value);
}

// Create new Field Collection.
else
{
    $fieldCollectionItem = FieldCollectionItem::create([
        'field_name' => 'field_test_field_collection',
    ]);

    $fieldCollectionItem->setHostEntity($node);

    $node->field_test_field_collection[] = [
        'field_collection_item' => $fieldCollectionItem,
    ];
}

$fieldCollectionItem->set('field_text', 'Last Update: ' . date('c'));

$node->save();

Deleting an existing collection is as simple as: fieldCollectionItem->delete();

Please have a look at the source code of the unit test class Drupal\field_collection\Tests\FieldCollectionBasicTestCase for more information.


i already have the same issue, you have to implement this class to EntityTypeListenerInterface and use the trait EntityTypeEventSubscriberTrait

class SubscriberClassModuleSubscribesToEntityTypeEvents implements EntityTypeListenerInterface, EventSubscriberInterface{

use EntityTypeEventSubscriberTrait;

public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
}

public function onCreate(EntityTypeEvent $event)  {
      //Do things on creation
}
public function onUpdate(EntityTypeEvent $event)  {
      //Do things on update
}
public function onDelete(EntityTypeEvent $event)  {
      //Do things on delete
}

/**
 * {@inheritdoc}
 */
public static function getSubscribedEvents() {
    return static::getEntityTypeEvents();
}

}

and you get to load entity manager in your module.service.yml declaration
    arguments: ['@entity.manager']


How to load paragraphs fields in hook_form_alter to disallow access?

Maybe you can use a preprocess paragraphs function which will target it more easily

function mymodule_preprocess_paragraph__myparagraph(&$vars)
{
    if ($vars['view_mode'] == 'full') {
        $parag = $vars['paragraph'];
        if (SOME LOGIC HERE){
        unset($vars['content']['myfield']);
        $var['field_removed']=true;
    }
}

The key point is to replace __myparagraph with the id of your paragraph

This example show you:

How to access the paragraph object $parag = $vars['paragraph'];
How to handle your logic only for a view mode ($vars['view_mode'] == 'full')
Remove a field unset($vars['content']['myfield']);
You can test the variable field_removed in your twig template to not run the code to display the field (optional)

Oups, it looks like you are asking to alter a paragraph's form...
For this you can use hook_field_widget_paragraphs_form_alter

function maymodule_field_widget_paragraphs_form_alter(&$element, FormStateInterface &$form_state, $context)
{
    switch ($element['#paragraph_type']) {
        case 'myparagraphs':
            $term = $form_state->getFormObject()->getEntity();
            //Check if paragraph is inside a form term
            if($term && ($term->getEntityTypeId()=='taxonomy_term')){
                $voc=$term->bundle();
                //Check if it is the desired voc
                if($voc=='my_voc'){
                    //unset($element['subform']['field_to_be hidded']); //to hide only one field
                    $element=[]; //to hide all the form
                }
            }
            break;
    }
}

Hope this help


Entity Reference lets you do this.

Add an entity reference field.
Target Type: Entityform Type.
If you want to limit the options for a user, you can create an entity reference view for entityform types and select it in the options.
Go to your content type's "Manage Display" and select "Rendered Entity" for the field.
Or for Panels, add a Context>Relationship>Entityform Type from Node.
Add it to the page under Page Content>Rendered Entityform Type.


If I understand you corretly, you need to store other field(s) together with the reference of Manufacturers, right? I think the best way is to add the (a single-value) reference field to Distributor in the Manufacturer content type along with other necessary fields. After that you can create your list with a View.


Drupal views filter exposed with condition fields

If you have planed to use just one vocabulary and you have designed it properly , then Hierarchical Select Module can help you to provide the functionality you expect.


You can pass a second variable to the variable_get() function, which is a default value.

example:

variable_get('background_audio_upload_path', 'path/to/foo.bar');


exporting a field from dev to production

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

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

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

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


Elysia cron stuck in (w) state (wating to be executed)

The "(w)" flag means only that the job is ready to be executed (waiting for the system crontab to start and execute it).

If a job has a rule like "* * * * *" (= execute it EVERY minute), it's quite normal that the "(w)" is always on.

If you use a rule like "* * * * *", assure that system crontab is set to "* * * * *" too. That way you minimize the (w), because system crontab runs every minute too and executes the job as fast as possible.

(However, a little time with (w) is normal and not to be considered a problem).


views-view-fields--taxonomy-term.html.twig

This is the correct template suggestion. For it to work however, the default taxonomy view must be configured to render the content as fields rather than as the content its self.


Services module is what you are looking for. It supports json data. More about the module:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

It also has an extensive documentation.


How to convert a unix timestamp field in views

You can use hook_views_pre_render to change the output of your field..

  This hook is called right before the render process. The query has
  been executed, and the pre_render() phase has already happened for
  handlers, so all data should be available.

  Adding output to the view can be accomplished by placing text on
  $view->attachment_before and $view->attachment_after. Altering the
  content can be achieved by editing the items of $view->result.

function MYMODULE_views_pre_render(&$view) {

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

      // do whatever you want

   }

 }


In either case, the Conditional Fields module sounds like it could help you here... from the module page:

  Define dependencies between fields based on their states and values. Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

The alternative is harder because you'd need to write your own little module that implements hook_form_alter() that can do custom validation and insert a snippet of jQuery to hide/show elements according to the age being 18 or over.


How to show parent terms in view for restricted nodes categorised with child term?

In case anyone has the same issue, I gave up in the end and wrote a custom module since I find views a pain in the ass.

My module uses nested queries which is embarassing, but it's still fast to run (unless you have a massive list of taxononomy terms) so it doesn't matter too much for this purposes.

The module outputs a Drupal block, the content of which comes from this function:

function list_of_resource_tags(){

// Retrieve the logged in user
global $user;

// Select all "Metadata" terms for the nodes the logged in user
// has permission to see
$sql_terms = '
SELECT DISTINCT(term_data.tid) AS term_id, term_data.name, term_hierarchy.parent, term_data.weight
FROM node_access
INNER JOIN node ON node_access.nid = node.nid
INNER JOIN term_node ON node.nid = term_node.nid
INNER JOIN term_data ON term_node.tid = term_data.tid
INNER JOIN term_hierarchy ON term_data.tid = term_hierarchy.tid
WHERE node_access.grant_view = 1
AND node.status = 1 /* Published nodes */
AND term_data.vid = 9 /* Taxonomy terms of "Metadata" vocabulary only */
AND node_access.gid IN (SELECT rid AS roles FROM users_roles WHERE uid = %d) /* Logged-in user is granted permission to these nodes */
ORDER BY term_data.weight';

$result_terms = db_query($sql_terms, $user->uid);

$displayed_terms = array();
$output = '';
while ($row = db_fetch_object($result_terms)) {
    // If tag is top-level, just display and put in array
    if ($row->parent == 0 && in_array($row->term_id, $displayed_terms) == FALSE){
        $output .= '
term_id.'">'.$row->name.'
';
        $displayed_terms[] = $row->term_id;
    }
    // Test if we've already displayed the tags parent, if not, retrieve it
    else if (in_array($row->parent, $displayed_terms) == FALSE){
        $sql_parent = '
        SELECT *
        FROM term_data
        WHERE tid = %d';

        $result_parent = db_query($sql_parent, $row->parent);
        $row_parent = db_fetch_object($result_parent);

        $output .= '
tid.'">'.$row_parent->name.'
';
        $displayed_terms[] = $row_parent->tid;
    }
}

return $output;
}


Theming the default "node/add/content-type-name" content type form will allow you to achieve what you need as these forms are publicly available to users with permission. If the user has permission to create that content type, he will be able to access the page, so either create a link to the page (node/add/content-type-name) or use the default Navigation Menu link "Create Content" to take the user to the node/add page.  Take a look at Theme a CCK Input Form for CCK2 & CCK3 to learn more about theming content type forms.

To remove the configuration fieldsets such as Menu Settings, Publishing Options, Revision Information, etc you really just need to change the permissions for the role.  For example, remove "administer nodes", "administer menu", "administer comments", etc.


You should take a look at References for the linking part, and also Workbench for the moderation part, and lastly Field Permissions to give users access to do the linking.

Create a Node reference field on one content type, to link the child node to the parent (or vice-versa)
Use Field Permissions to grant everyone access to enter/edit the field
Use Workbench to force changes into a new revision which need to be approved.


theme_preprocess_node not working inside of a view

$node = menu_get_object() works only when the page you are seeing has a URL that is similar to node/12, or node/12/view. When you are watching a view, its URL is probably different.

That code is also not necessary, as template_preprocess_node() already initializes $variables['node'] with the node object.

$variables['node'] = $variables['elements']['#node'];
$node = $variables['node'];

If you want to check if the node is being viewed in its own page, you can use the following code.

if ($variables['page']) {
  // The node is shown in its own page.
}
else {
  // The node is shown together other nodes.
}

$variable['page'] is a variable set by template_preprocess_node().

As side note, this is the code used by views_plugin_row_node_view::render() to render a node.

function render($row) {
  if (isset($this->nodes[$row->{$this->field_alias}])) {
    $node = $this->nodes[$row->{$this->field_alias}];
    $node->view = $this->view;
    $build = node_view($node, $this->options['view_mode']);

    return drupal_render($build);
  }
}

node_view() is the function that calls the theme_node() theme function, causing preprocess/process functions to be called.


No, but you can easily make one yourself by implementing hook_theme().


How do I prevent rewritten views field output from having ":" stripped out of the  sizes attribute?

Based on No Sssweat's comment suggestion, I was able to work out a views field template in my custom theme to resolve this question. As I used the twig tweak module to help apply multiple image styles in node templates, I also used it in my views field template in a similar way.

In views-view-field--[view id]--[display id]--[field id].html.twig
(or views-view-field--products--page-1--nothing-2.html.twig in my case):

{#
/**
 * @file
 * Default theme implementation for a single field in a view.
 *
 * Available variables:
 * - view: The view that the field belongs to.
 * - field: The field handler that can process the input.
 * - row: The raw result of the database query that generated this field.
 * - output: The processed output that will normally be used.
 *
 * When fetching output from the row this construct should be used:
 * data = row[field.field_alias]
 *
 * The above will guarantee that you'll always get the correct data, regardless
 * of any changes in the aliasing that might happen if the view is modified.
 *
 * @see template_preprocess_views_view_field()
 *
 * @ingroup themeable
 */
#}
{% set href = path('entity.node.canonical', {'node': row._entity.id}) %}
{% set image = row._entity.field_product_images[0] %}
{% set product_listing_xs = image.entity.uri.value|image_style('product_listing_xs') %} {# requires twig tweak module #}
{% set product_listing_sm = image.entity.uri.value|image_style('product_listing_sm') %} {# requires twig tweak module #}
{% set product_listing_md = image.entity.uri.value|image_style('product_listing_md') %} {# requires twig tweak module #}
{% set product_listing_lg = image.entity.uri.value|image_style('product_listing_lg') %} {# requires twig tweak module #}

No ":" or other items were stripped from the final output.

As a result of the field template, I was also able to remove six hidden field items in the views settings that were used in the rewrite this template now handles.


Any way to have "Path Will Be Viewed" trigger?

If you simply want to restrict the access to the View, you should alter the settings for the View.

Under the access settings, select Role instead of Permission, and select the appropriate role.

However, if you have to use Rules for some other reason, I would create a rule that triggered every time Drupal is initializing. And then, add a condition with custom PHP code. You could do something like

global $user;
$rid = 1;
return ($_GET['q'] == 'my/forbidden/path' && isset($user->roles[$rid]));

and then add an action that redirects the user to another page.


What's the use of the new Star button in the project pages?

Consider this "Star"-facility as a way to "bookmark" specific contributed modules as your "favorites". Some more details about it (from What’s new on Drupal.org? - April 2017):

  Users on Drupal.org may now star their favorite projects - making it easier to find favorite modules and themes for future projects, and giving maintainers a new dimension of feedback to judge their project's popularity. Users can find a list of the projects they've starred on the user profile. Over time we'll begin to factor the number of star's into a project's ranking in search results.

Notes:

Projects that you star-ed are shown to others also. E.g here are your current star-ed projects.
When I look at the views page (without being logged in to D.O), I don't see that "star" (as in your image), I only see the star itself, and the "35". After I log in, I do get a similar Star-image like your question here.


How to create a filter condition autocomplete for entity reference field or normal?

you can change an exposed filter to Select List or Text Box using the following code..

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
        $options = array('your options');
        $form['your field name']['#type'] ='select'; //Use TEXTBOX for text field.
        $form['your field name']['#size'] = null;
        $form['your field name']['#default_value'] = '';
        $form['your field name']['#options'] = $options; //not needed for textbox
    }
  }
}

Another option is use Autocomplete Deluxe for References Module.

Hope this will help you..


Prevent email from being sent using hook_mail?

You can do the access check from hook_mail_alter instead of hook_mail (let it prepare the default message based on parameters, and alter it later) by something like:

function HOOK_mail_alter(&$message) {
  // can add additional check for particular mails here,
  // by checking the value in $message['id']
  if (TRUE) {
    $message['send'] = FALSE;
  }
}

Note: You should clear the cache in order to make the changes effective.


how to force drupal to create tables with ENGINE=MyISAM

The schema definitions can take an argument of 'mysql_engine', which defaults to 'InnoDB', in createTableSql().

In theory you could thus alter all the defined schemas with a custom module, and change the engine.

It's highly questionable to do so though. If you value your site and data, you should NOT use MyISAM unless you understand the difference the two engines.

Switch to a provider that supports InnoDB instead. MySQL itself defaults to InnoDB as of 5.5. I would be very suspicious of any provider that didn't support InnoDB.


Programmatically get webform submitted field values

In recent 3.x and 4.x versions of webform it has an hook based API to allow you do stuff with submitted webform values.

Look at like hook_webform_submission_insert() or hook_webform_submission_update() (if your webform has Drafts enabled for instance the final submission is an UPDATE call with isNew == False and isDraft == False).

The functions take a parameter $submission that is a PHP array of the submitted form values ... You can do whatever you want with them from there.


Views, Grouping by various levels of granularity in a date field?

Well I think I got it.

Step 1: Add two new date formats

I set up two new date formats: Month only and Year only

Step 2: Query the date date field twice under the new formats

Add the Publication Date field twice in these newly created formats

Step 3: Apply the proper grouping to the view

Here's how I grouped it....

And finally, the results

Below, albeit poorly formatted, I have two two years of 2015 and 2014 with sub divided months.

(For some reason, what ever the last grouped field is encapulated in . I tried playing with the formatting but no luck. However, I've worked out my logic here.)


Option 1

I use the Geofield module, which provides a similar function to the Location module.  It provides the concept of a proximity filter.  This allows you to implement views such as "show all nodes within 50km of specified point".  I don't know whether the Location module has a similar function, or whether you might be willing to change modules.  The Smart IP module claims some Views integration but D6 only, so you might need a bit of code to integrate with views.

This approach would not use access control at all - so that if the user specifically navigated by URL to a far away node, they would still see it.

Option 2

If you definitely want access control, then I think you will have to give up exact distances.  You could divide your target area into regions, maybe around 50-500 of them - most simply using a simple grid.  In your hook_node_access_records, you decide which regions are close enough to the node (calculate distance to the region centre).  Finally in hook_node_grants, you need code to take the output of the Smart IP module and calculate which region it is in, and set the appropriate grant.

If you need some more help with the details of either approach, feel free to edit your question to say which approach you prefer, what you have working and where you are stuck.


Anonymous users can't use personal contact forms

Assuming that the anonymous users are not trying to access user/0/contact (which would not be an ordinary case), the reasons why they cannot access the contact for a an authenticated user A are essentially 3:

User A didn't enable the contact form
The setting for enabling the contact form for user A has not been yet saved
The anonymous user sent too much messages

In the first two cases, it's the access callback for the user's contact form that block the access, using the following code. (See the comment before the code.)

// If the requested user has disabled their contact form, or this preference
// has not yet been saved, do not allow users to contact them.
if (empty($account->data['contact'])) {
  return FALSE;
}

In the third case, it's the form builder that returns an access denied page.

// Check if flood control has been activated for sending e-mails.
  $limit = variable_get('contact_threshold_limit', 5);
  $window = variable_get('contact_threshold_window', 3600);
  if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms') && !user_access('administer users')) {
    drupal_set_message(t("You cannot send more than %limit messages in @interval. Try again later.", array('%limit' => $limit, '@interval' => format_interval($window))), 'error');
    drupal_access_denied();
    drupal_exit();
  }

Notice that in last case, the default limit is 5 messages in a hour, and that limit is cumulatively valid for any user sharing the same IP, as flood_is_allowed('contact', $limit, $window) executes the following code.

if (!isset($identifier)) {
  $identifier = ip_address();
}

If you are not seeing any error message from Drupal ("You cannot send more than […]") and the enabled theme or any module is not hiding the error messages, I would assume the users didn't enable their contact form, or the setting to enable the contact form was not yet saved.


You can use Webform Validation. This module includes a lot of validations for webform elements.

Alternatively, you can code your own validation yous adding your validation function to the desired forms. Then use form_set_error to mark wrong element with red border.

Webform puts the fields inside a group, so if you need to mark a field as not valid you must provide the full hierarchy.

For example, for this field in $form:

$form['submitted']['form_contact_data']['form_contact_email'] = array(
...
);

You can mark it as erroneous with:

form_set_error('submitted][form_contact_data][form_contact_email', 'Error message');

In this example the filed is inside two groups: the first, 'submitted' is the main Webform group. The second, 'form_contact_data', is a field group created where I've placed contact data fields for this webform.


Views pager labels translation per context

Use hook_pager() in your theme template.

function YOUR_THEME_pager($tags) {
  echo "<pre>";
  var_dump($tags);
  echo "</pre>";
}


What you're looking for is this:

$form['uid']['widget'][0]['target_id']['#required'] = TRUE;

(Devel is your friend!)

You were on the right track as $form['author']['#required'] = TRUE; will make the "Authoring Information" have a red star (*), but won't make your authored by field required.

Complete code:

function hook_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'your_form_id') {
    $form['uid']['widget'][0]['target_id']['#required'] = TRUE;
  }
}


I don't think the min max would be readily available in the template and you'll have to add it in.

You could use hook_preprocess_commerce_product($variables) and within $variables it will contain the product entity and also all of its variations. You would just need to loop through the variations to work out the min and max price and then add the new value into $variables e.g.

$variables['min_max_price'] = $myvalue;

Then in your template commerce-product.html.twig do:

{{ min_max_price }}

and that should come out with your $myvalue value


What is the recommend process for migrating a Drupal 6 Ubercart site to Drupal 7 / Drupal Commerce?

There are new tools and resources for this:

http://drupal.org/project/commerce_migrate
http://drupal.org/sandbox/rfay/1233708
http://vimeo.com/26775252
http://www.commerceguys.com/resources/articles/215
http://www.commerceguys.com/resources/articles/ubercart-drupal-commerce-1
http://www.commerceguys.com/resources/articles/ubercart-drupal-commerce-2
http://dl.dropbox.com/u/7350603/Importing%20into%20Drupal%20Commerce.mp4


Here is one solution that I came up with after looking around in core's code. It seems to work as expected.

$module_list = module_list();
if (isset($module_list['token'])) {
    unset($module_list['token']);
}
// Reset the list to our new list of modules!
module_list(false, false, false, $module_list);
// Force to regenerate the stored list of hook implementations.
module_implements('', false, true);


Changing the module path on custom install profile

You can get an example in Videola profile:
https://github.com/Videola/videola/blob/master/videola_starter.make - main make file which downloads only profile from github.

Then see main make file with all the modules: https://github.com/Videola/videola/blob/master/videola.make which shows you an example of what you want to do.

projects[admin][subdir] = "contrib"


Creating Nodes Of A Content Type on-the-fly While Creating A Different Content Type

If you are able to use the node reference field from the References module instead of the Entity Reference once the Node Reference Create module might be of some help:

Node Reference Create is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.
When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.

I think the Contextual Administration module might also be useful too; there's some video documentation under the title of "Automatic Node Reference on Node Create" which will probably interest you the most.
UPDATE
You also might want to check out the NodeConnect module, it doesn't append the fields of the referenced node to the original node's edit form but does this instead:

Node Connect expands the node reference (of the references project) auto-complete field by adding a add new content and edit current content button.
The add a new button will all a new node to be added via a node add form and then return the user to the original form.
The edit button will take the user to the edit form of the referenced node, and return them when they are done editing.
Unlike other module that have provide this functionality this module does not use popups of kind, but caches the original forms when switch to child forms. This allows for multiple levels of adding and editing


is the a module similar to data_export_import that includes user roles?

I have never used Data Export Import, so I don't know whether it has special features or functions that you need for your use case.

For the use case of exporting everything (except file and media attachements) from my live site to my dev site, I use Backup and Migrate.

What it does is not in any way "advanced". It just mirrors the entire database, including content (nodes etc.), users and taxonomy terms. All references including NIDs are preserved, and user roles are also preserved.

There is nothing in your question that suggests that Backup and Migrate may not serve your use-case, but I may have overlooked something.


Fatal error while editing and deleting menu items

This error was coming because of responsive menu module.Responsive menu was fetching the parent links using

\Drupal::service('plugin.manager.menu.link')->createInstance($parent);

Adding the condition before calling createInstance will fix this issue.

\Drupal::service('plugin.manager.menu.link')->hasDefinition($parent)

Created a issue on D.o also

https://www.drupal.org/project/1786786/issues/2924229


How to add a "Remove Taxonomy term" option to VBO instead of only "Add taxonomy term"?

You could try to perform a bulk operation using logic expressed in a Rules Component. More details below ...

VBO comes, out of the box, with some predefined (hardcoded) operations that is to be applied to each row selected in the view. The available operations are shown within "Selected bulk operations" when configuring the VBO field. In your case "Add the selected terms" seems to be one of those. While something like "Remove the selected terms" (as per your question) is not included.

However using Rules (Conditions and/or Actions) you might probably get it to work, i.e. by execute a VBO operation which you define using a Rules Component. To get the idea, have a look at the video about Using Rules components with VBO" uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video. This video actually shows how to (also) add a term to a node, so it should be pretty forward to use a similar technique, and perform a remove instead of an add of a term.

Note: to process 100.000 nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


If you have a white page then there is very likely an error somewhere. Check your apache or php error logs. Which could really be any where depend on what platform you are developing on.

Fatal errors won't make it into the database log file within Drupal since fatal errors tend to stop everything dead.


Automatic base URL not picking up https://

Try setting the $base_url on the protocol:

  $base_url = ((isset($_SERVER['HTTPS'])) ? 'https://' : 'http://') . 'www.yoururl.com';


Button that executes php function, or custom VBO action

You can create a menu item that does what you want along the lines of

function YOURMODULE_menu() {

  $items=array();

  $items['sugarme/%'] = array(
    'title' => 'Send this node to sugarCRM',
    'page callback' => 'YOURMODULE_sugarme',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  // other menu items here

}

function YOURMODULE_sugarme($nid) {

   if (YOURFUNCTIONTOSENDTHISNIDTOSUGARCRM($nid)) {
     return 'Sent to sugar';
   } else {
     return 'Send to sugar failed';
   }

 }

which in the very simple form above (no security, no argument sanity checks, etc) creates a path on your system www.yourhost.com/sugarme/#### that will call your function with the nid passed to it.


Boosting by changing bias of ApacheSOLR has no effect

Turns out the solrconfig.xml for Drupal was not properly installed on the SOLR server. Which made it unable to parse the querystring properl with DisMax.


Move my project from public_html/web to public_html

You should be able to change the installer paths in composer.json, which defines where the files are placed:

"installer-paths": {
  "web/core": ["type:drupal-core"],
  "web/modules/contrib/{$name}": ["type:drupal-module"],
  "web/profiles/contrib/{$name}": ["type:drupal-profile"],
  "web/themes/contrib/{$name}": ["type:drupal-theme"],
  "drush/contrib/{$name}": ["type:drupal-drush"]
},

to:

"installer-paths": {
  "public_html/core": ["type:drupal-core"],
  "public_html/modules/contrib/{$name}": ["type:drupal-module"],
  "public_html/profiles/contrib/{$name}": ["type:drupal-profile"],
  "public_html/themes/contrib/{$name}": ["type:drupal-theme"],
  "drush/contrib/{$name}": ["type:drupal-drush"]
},

You can then rename the web folder to public_html and everything should work.


What are the template variables to identify that a page is a term or user?

I think a better way to hide the title on user and taxonomy term pages would be to use a preprocess_page function in your themes template.php. This way you are keeping your page.tpl.php cleaner and separating logic.

/**
* Implements hook_preprocess_page
*/
function MY_THEME_preprocess_page(&$variables) {
    if( (arg(0)=='user' && arg(2)=='') || (arg(0)=='taxonomy' && arg(1)=='term' && arg(3)=='') ) {
        $variables['title'] = FALSE;
    }
}

This will only hide the title on the view pages, but it will still be there when editing content. This is done by checking that arg(2) is empty on user pages and arg(3) is empty on taxonomy term pages as if editing content these would contain the string "edit".

As pointed out by clive the line in your page.tpl.php would need to read:

<?php if ($title): ?>

<?php print $title; ?>

<?php endif; ?>

Once you have added this code then you will need to clear the cache to see the changes.


Serve aggregate CSS/JS files from S3 instead of local storage

It's all explained in the module's README.txt

  This will configure your site to store new uploaded files in S3.
  Files
  which your site creates automatically (such as aggregated CSS) will still
  be stored in the server's local filesystem, because Drupal is hard-coded
  to use the public:// filesystem for such files.
  However, s3fs can be configured to handle these files as well. In
  settings.php you can enable the s3fs.use_s3_for_public and
  s3fs.use_s3_for_private settings to make s3fs take over the job of the
  public and/or private file systems. This will cause your site to store
  newly uploaded/generated files from the public/private file system in S3
  instead of the local file system. However, it will make any existing files
  in those file systems become invisible to Drupal.
  To remedy this, you'll need to copy those files into your S3 bucket.

  Example:
  $settings['s3fs.use_s3_for_public'] = TRUE;
  If you use s3fs for public, you should change your php twig
  storage folder
  to a local directory, php twig files in S3 produce latency and security
  issues (these files would be public). Please change the php_storage settings in your setting.php and choose a directory, out of docroot
  recommended.

  Example:
  $settings['php_storage']['twig']['directory'] = '../storage/php';

  If you have a multiple backends you may use a NAS to store it or other
  shared storage system with your others backends.

Related Question: Serve compressed JS and CSS with S3 as filesystem


How to include a view in a specific region defined in a custom layout?

You can embed views anywhere with php with views_embed_view(). Please refer https://api.drupal.org/api/views/views.module/function/views_embed_view/7


varnish + multiple webheads = files/(css/*.css|js/*.js) missing

This is happening when you have optimization for CSS/JS turned on. These files are generated regarding the context (the page visited by the browser) and so the visitor won't be served some files when the round robin changed the targeted server.

You can configure the round robin to stay on the same server on a per-session basis (see: Pure VCL cookie-based sticky sessions in Varnish 2.1), but generally you should set up a NFS share between your server where you'll put the sites/default/files folder.

Source: Drupal's optimize CSS and JavaScript setting causing problems in multiple server environments.


How do I apply loop into node twig template?

I would use code similar to the following one.

  {% for key, item in content.field_article_main_content %}
    {% if key == 0 %}

{{ content.field_article_main_content[key] }}

    {% else %}

{{ content.field_article_main_content[key] }}

    {% endif %}
  {% endfor %}

If it happens that some values of key start with #, then I would use the following code.

  {% for key, item in content.field_article_main_content if key|first != '#' %}
    {% if key == 0 %}

{{ content.field_article_main_content[key] }}

    {% else %}

{{ content.field_article_main_content[key] }}

    {% endif %}
  {% endfor %}


Drupal module to make html pages of all nodes automatically

The Boost module is the closest thing to 'Drupal as a static generator'.

  Boost provides static page caching for Drupal enabling a very significant performance and scalability boost for sites that receive mostly anonymous traffic.

EDIT: You could also look at the Static module. However it doesn't provide a mechanism to get the files onto a server, you would need to set that up separately.


Overriding a specific display doesn't work

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

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

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

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

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

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


Duplicate field values in views for a custom entity

Setting EntityDefaultViewsController is not really required as entity API sets this by default and yes it does conflict with hook_entity_property_info().

The solution can be found here: https://www.drupal.org/node/1208874 and it is as simple as defining the 'module' property in hook_entity_info().

<?php
/**
 * Implements hook_entity_info().
 */
function entity_test_entity_info() {
  return array(
    'entity_test' => array(
      'label' => t('Test Entity'),
      // Entity API needs to know about your module for the views integration to work
      'module' => 'entity_test',
     ..
?>

Once the 'module' property is defined the entity API will no longer try to guess the property types and follow hook_entity_property_info() implementation.

This same trick also solved errors related to string and array conversions I was having such as:

  strpos() expects parameter 1 to be string, array given in
  entity.property.inc:363


How to use Drupal Commerce to extract all the people who purchased a specific product?

Not 100% sure what you mean with "reports on line items" or "a line item report" (consider refining what actually this means). But since the question is tagged with the reporting tag, maybe you may want to consider the Forena module.

It would probably take a bit of time to achieve perfection, but you'd have all of Forena's xHTML-power available to finetune the ultimate result (report), for things such as:

look-and-feel (styling/theming).
maybe add some charts to it also (using selected data about commerce).
saving the ultimate output (report) in formats such as PDF, DOC, etc.
creating eMail campaigns about selected records.
pulling in information stored in other databases related to this report.

For more details about Forena, 2 types of documentation are available:

Community documentation.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of the current:

Forena documentation - use the link 'Reporting documentation' or visit relative link /reports/help.
Forena samples - use the link 'Reporting samples' or visit relative link /reports/samples (these samples are fully functional, so make sure to experiment a bit with it, such as the drill downs available on the SVG Graph sample).

The newest 7.x-4.x version also includes an amazing (I think) UI for either creating your reports (the WYSIWYG report editor) and/or for creating your SQL queries (the Query Builder).

Here is some more info about the other databases in mentioned above:

Using a SQLite instead of MySQL database: the Forena samples actually get shipped including a (Tiny) SQLite database. Go check it out in the demo site: the data shown there are data contained in the sampledb, which is in SQLite format.
Forena comes with a full suite of Supported database connections ... such as MySQL, MS SQL, Oracle, Postgress or any PDO compliant variation.

Enough reasons for considering giving Forena a try? While doing so, use it's issue queue for any type of support/docu requests you may have.

Be aware: I'm a co-maintainer of Forena.


Calendar as view's pager (passing arguments between views?)

Your two Views should be possible with the Views Field View module:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

or the side by side could be accomplished by integrating the Views into the Panels Module:

  The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.


I figured this out myself..

So the basic idea is that we build the form based on the setting of $form_state['num_names']. The custom submit functions for the "add more" button increment and decrement $form_state['num_names'] and then force a rebuild of the form.
We then iterate over the fields for the product and search for entity reference fields to a commerce option set.
(This takes into account that the commerce_product_option module has been properly configured and option sets have been set.)
We create a new blank option set each time and add a quantity field with an extra key to attach it with the current option set.

For the submit callback,i had to dig deeper into the module and tweaked a bit for these specific attributes.

<?php

 function multiple_option_sets_form_alter(&$form, &$form_state, $form_id) {
if ((strpos($form_id, 'commerce_cart_add_to_cart_form_') > -1)) {
    multiple_option_sets_add_more_form($form, $form_state, $form_id);
    $form['#submit'][] = 'multiple_option_sets_add_more_submit';
}

}

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

$form['field_extra_attributes']['#prefix'] = '
';
$form['field_extra_attributes']['#suffix']= '
';

// Build the fieldset with the proper number of names. We'll use
// $form_state['num_names'] to determine the number of textfields to build.
if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 0;
}

for ($i = 0; $i < $form_state['num_names']; $i++) {

    //lets add all the fields we want in the set
    // Because we have many fields with the same values, we have to set
    // #tree to be able to access them.
    $form['#tree'] = TRUE;

    // Get the current product. Is added in the cart module.
    if (isset($form_state['default_product'])) {
        $product_id = $form_state['default_product']->product_id;
    }
    elseif (isset($form_state['default_product_id'])) {
        $product_id = $form_state['default_product_id'];
    }
    elseif (isset($form_state['products'])) {
        $current_product = reset($form_state['products']);
        $product_id = $current_product->product_id;
    }
    else {
        return;
    }

    $current_product = commerce_product_load($product_id);

    $someFieldIsAdded = FALSE;

    // Iterates the fields of this product. We search for entity reference fields
    // to a commerce option set.
    foreach ($current_product as $field_name => $field) {
        $field_info = field_info_field($field_name);

        if ($field_info['type'] != 'entityreference' || !isset($field_info['settings']['target_type']) || $field_info['settings']['target_type'] != 'commerce_option_set') {
            continue;
        }

        // Do not display our options if this field has been marked as an attribute field.
        $field_instance_info = field_info_instance('commerce_product', $field_name, $current_product->type);
        if ($field_instance_info['commerce_cart_settings']['attribute_field']) {
            return;
        }

        $lang_code = field_language('commerce_product', $current_product, $field_name);
        if (!isset($field[$lang_code])) {
            continue;
        }

        // Create a new blank option set.

        foreach($field[$lang_code] as $key => $data) {

            $option_set = commerce_option_set_load($data['target_id']);

            $values = array(
            'set_id' => $option_set->set_id,
            );

            $option = commerce_option_new($values);

            $form_state['commerce_option'][$field_name][$key+1+$i]['option'] = $option;

            $form[$field_name][$key+1+$i] = array(
            '#parents' => array($field_name, $key+1+$i),
            );

            field_attach_form('commerce_option', $option, $form[$field_name][$key+1+$i], $form_state);
            $someFieldIsAdded = TRUE;

        }
    }

    $form['field_extra_attributes'][$i+1]['quantity'] = array(
    '#type' => 'textfield',
    '#title' => t('Quantity'),
    '#prefix' => '
',
    '#suffix' => '
'
    );

}

$form['actions']['add_more'] = array(
'#type' => 'submit',
'#value' => t('Add more'),
'#weight' => 50,
'#submit' => array('multiple_option_sets_add_more_add_one'),
'#ajax' => array(
'callback' => 'multiple_option_sets_add_more_callback',
'wrapper' => 'ajax-attributes-wrapper',
),
);

return $form;

}

/**
* Callback for both ajax-enabled buttons.
*
* Selects and returns the fieldset with the names in it.
*/
function multiple_option_sets_add_more_callback($form, $form_state) {
return $form['field_extra_attributes'];
}

/**
* Submit handler for the "add-one-more" button.
*
* Increments the max counter and causes a rebuild.
*/
function multiple_option_sets_add_more_add_one($form, &$form_state) {
$form_state['num_names']++;
$form_state['rebuild'] = TRUE;
}

/**
* Submit handler for the "remove one" button.
*
* Decrements the max counter and causes a form rebuild.
*/
function multiple_option_sets_add_more_remove_one($form, &$form_state) {
if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
}
$form_state['rebuild'] = TRUE;
}

function multiple_option_sets_commerce_cart_product_comparison_properties_alter(&$comparison_properties) {
// Force separate line items when the same product is added to the cart from
// different display paths.
$comparison_properties[] = 'field_color';
}

/**
* Cart submit callback function. This is required to create / update
* the option related to the line item.
*
* @param $form Form array
* @param $form_state The form state array.
* @return void
*/
function multiple_option_sets_add_more_submit($form, $form_state){

// Get current product, taking into account different Commerce versions behavior.
if (isset($form_state['default_product'])) {
    $product_id = $form_state['default_product']->product_id;
}
elseif (isset($form_state['default_product_id'])) {
    $product_id = $form_state['default_product_id'];
}
elseif (isset($form_state['products'])) {
    $current_product = reset($form_state['products']);
    $product_id = $current_product->product_id;
}
else {
    return;
}

$current_product = commerce_product_load($product_id);

// Iterates the fields of this product. We search for entity reference fields
// to a commerce option set.
foreach ($current_product as $field_name => $field) {
    $field_info = field_info_field($field_name);

    if ($field_info['type'] != 'entityreference' || !isset($field_info['settings']['target_type']) || $field_info['settings']['target_type'] != 'commerce_option_set') {
        continue;
    }

    $lang_code = field_language('commerce_product', $current_product, $field_name);
    if (!isset($field[$lang_code])) {
        continue;
    }

    foreach ($form_state['values']['field_extra_attributes'] as $delta => $set_id) {

        $option = $form_state['commerce_option'][$field_name][$delta]['option'];

        // Notify field widgets and populate option with values.
        field_attach_submit('commerce_option', $option, $form[$field_name][$delta], $form_state);

        // Check if our option is empty. If yes we shouldn't save anything.
        // Cannot use field_get_items() because it calls field_language().
        $option_extracted = commerce_option_get_valuables($option);
        $ow = entity_metadata_wrapper('commerce_option', $option);
        $empty = TRUE;

        foreach (array_keys($option_extracted) as $option_field) {
            $value = $ow->$option_field->value();
            if (!empty($value)) {
                $empty = FALSE;
                break;
            }
        }

        if ($empty) {
            continue;
        }
        global $user;
        if($delta != 0) {
            $new_line_item = commerce_product_line_item_new($current_product, $form_state['values']['field_extra_attributes'][$delta]['quantity'], $form_state['line_item']->order_id, $form_state['line_item']->data, $form_state['line_item']->type);
            $new_line_item = commerce_cart_product_add($user->uid, $new_line_item);
            //var_dump($form_state['line_item']);
            //var_dump($new_line_item);
            //die();
            $line_item_id = $new_line_item->line_item_id;
        }
        else {
            $line_item_id = $form_state['line_item']->line_item_id;
        }
        $product_id = $current_product->product_id;
        $match = FALSE;

        // Check if the newly created options exist on this line item already.
        // If yes we needn't save anything, commerce will just increase the
        // quantity.
        $query = db_select('commerce_option', 'co')
        ->fields('co', array('option_id'))
        ->condition('line_item_id', $line_item_id, '=')
        ->condition('product_id', $product_id, '=');

        $result = $query->execute()->fetchCol();

        if (!empty($result)) {
            $commerce_option_entities = commerce_option_load_multiple($result);
            $option_extracted = serialize($option_extracted);

            foreach ($commerce_option_entities as $commerce_option) {
                $commerce_option_extracted = commerce_option_get_valuables($commerce_option);
                $commerce_option_extracted = serialize($commerce_option_extracted);
                if ($commerce_option_extracted == $option_extracted) {
                    $match = TRUE;
                    break;
                }
            }
        }

        if ($match) {
            continue;
        }

        $option->line_item_id = $line_item_id;
        $option->product_id = $product_id;

        // Save the option.
        commerce_option_save($option);

    }
}
}
?>


So, I was working on a test for @Mołot to reproduce the clone bug, and I couldn't with a fresh view.

I tracked down the difference :

With the filter Published or admin: the cloned query didn't return anything.
No problem with the simple Published filter.

Don't ask me why.

As @autopoietic said, working with core query_alter_hook wasn't a good idea. I switched to views hook, and got the SelectQuery object :

function mymodule_views_pre_execute(&$view) {
  $query = &$view->build_info['query'];
}

Then I was able to do my sorting.


How can I invoke a drush hook on a remote alias?

If I understood correctly, we had a similar problem with drush < 6.4, drush was not passing the alias to the remote server if root and uri where not specified.

One way to solve it is to define $conf['root'] and $conf['uri'] in your local alias, the other is to use drush 7.


Aggregating JavaScript generates errors and breaks JS functionality

This issue is usually -- but not always -- because someone has written Javascript without adding semicolons in the appropriate places. JS is valid without them but only when there is also a line-end at that point. Many JS preprocessors remove line breaks, so making the JS invalid.

This can be resolved by examining the JS source for missing semicolons and adding them; a good JS IDE will be able to guide you as to where.

Another issue that sometimes occurs is when the JS code has not been properly context-wrapped. Drupal standard practice is to include a function() { js(); code(); here(); } (); wrapper around code blocks because that limits the scope of names to that block; without it, the scope could be global and thus can be interfered with by other blocks of code.

The Drupal solution, which also solves another problem, is to use the "Drupal.behaviours". construct. Check the Drupal JS files for that string for examples.


How do I add typekit fonts to a D8 theme?

For put the library to the header you must user header: true, then:

mytheme.info.yml

libraries:
  - mytheme/typekit

mytheme.libraries.yml:

typekit:
  version: 1.x
  header: true
  js:
    //use.typekit.net/abc1abc.js: { every_page: true }
    js/custom.js: { every_page: true }

js/custom.js:

try {
  Typekit.load();
}
catch(e) {
}


What's difference between node_revision__field_X and node__field_X tables in Drupal 8?

Yes, that is correct. This is the same data structure as in Drupal 7.

It would be possible to write a different backend that only uses one table, there was a project for that for Drupal 7 but I think it never really took off.

See https://www.drupal.org/node/2083451 for a discussion if that's still necessary or not.


Where does the drush installtation command set the PROMPT_COMMAND variable?

The function that changes the .bash_profile or .bashrc file is drush_init_core_init(). The shell script that effectively sets the prompt is $home/.drush/drush.prompt.sh, where $home is the value returned from drush_server_home(). If the file doesn't exist, drush_init_core_init() creates it from the content of DRUSH_BASE_PATH . "/examples/example.prompt.sh", which contains the following line. (See example.prompt.sh.)

export PROMPT_COMMAND='__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "'

There is also the following line, which sets PS1 and that is is commented out by default. (See the comment before it.)

  # PROMPT_COMMAND is used in the example above rather than PS1 because neither
  # Git nor Drush color hints are compatible with PS1. If you don't want color
  # hints, however, and prefer to use PS1, you can still do so by commenting out
  # the PROMPT_COMMAND line above and uncommenting the PS1 line below:
  #
  # export PS1='\u@\h \w$(__git_ps1 " (%s)")$(__drush_ps1 "[%s]")\$ '

As for the error message you see, __drush_ps1() is a bash function used to change the prompt, defined in drush.complete.sh. bash completion/prompt broken explains exactly when and why you get that error. TLDR; in some circumstances, the shell script is not sourced, and the Bash function results not defined.
For what I understand it, the error has been has been fixed in recent versions, though, so you should just need to update Drush to fix the error.


How to go from View to Webform, submit Return to View

Does your views page had a direct url? E.g. www.mysite.com/my-views-url? If so you can just redirect the webform on submit

Edit the webform, select settings tab
Select confirmation tab
Chose either

URL (redirects to a custom path or URL)
URL with message (redirects to a custom path or URL and displays the confirmation message at the top of the page)

Set the url in Confirmation URL to redirect back to your view


How to list the uploaded files (image file) of unsaved nodes?

The short answer is that there isn't really a way to do this.

The longer version is that you could make some SQL to find all candidates. The issue is that you can see if a file is used somewhere (on entites) on the file_usage table, but some files wont be "used in that manor. This means that finding a file "not being used" is not the same as it's safe to delete it.

A solution could be to make a cron job, that only checks images that has just been uploaded, but you still have the issue that you might end up deleting files that shouldn't have been deleted.


Maybe try something like this?

$output = '
';
$output .= '
demo link title';
$output .= '
desc link title'
$output .= '
hot to link title'
$output .= '
';


How to disable javascript validation of html5 URL element?

One way to do this is to simple not use the URL render element.  You can still use its validation, but you replace the URL element with a textfield element.

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {

  if ($context['items']->getFieldDefinition()->getType() == 'link') {
    $settings = $context['items']->getFieldDefinition()->getSettings();
    // If external link, don't use HTML5 URL element, to prevent its annoying
    // pop-ups.  Use a textfield with the backend validation from the URL element.
    if (!empty($settings['link_type']) && $settings['link_type'] == 16) {
      $element['uri']['#type'] = 'textfield';
      array_unshift($element['uri']['#element_validate'], ['Drupal\Core\Render\Element\Url', 'validateUrl']);
    }
  }


How to filter filenames in views based on a match to currently logged username?

If you could use tokens in views filters you could do something like File: name ... contains any word ... [user:name] and that would end up in the sql as file_managed.filename LIKE '%username%' which would be cool. But you can't do that, to my knowledge.

You might achieve what you want using contextual filters having PHP code in both contextual filter and validator, maybe.

That said, depending on how much files and users you have and so on, it might be easier to tag the files with taxonomy terms. That way user wanting to change their username, eg. when they get married, won't brake your system. Also usernames having spaces, underscores, apostrophies etc. wouldn't be an issue.

Edit:

What do you know, this can be done with contextual filters! I don't know how practical or robust or performant this is but here goes:

1) Add a contextual filter of Global: null.
2) Provide some default value, doesn't matter what. For example Fixed value -> 'blaa'.
3) Specify validation criteria -> PHP code

global $user;

$view->query->where = array(
    1 => array(
        'conditions' => array(
            0 => array(
                'field' => 'file_managed.filename',
                'value' => '%' . $user->name . '%',
                'operator' => 'LIKE',
            )
        ),
        'args' => array(),
        'type' => 'AND',
    )
);
return true;

I figured this out with dpm($view). If you have other filters in the Filter criteria, this code will have to take that into account. Tampering with the $view like this is not really future proof, but theoretically possible.


How to restrict node authors from commenting on their own nodes?

You'd want to use hook_node_view_alter() in your theme to unset the comment form if the logged in user is same as node author.

function yourtheme_node_view_alter(&$build) {
    global $user;
    // get the uid of logged in user
    $logged_in_uid = $user->uid;

    // if content type is 'your_content_type'
    if ($build['#bundle'] == 'your_content_type') {

        //get node author's uid
        $node_author = $build['#node']->uid;

        // if logged in user is the node author - unset comment form and remove the 'Add comment' links from node display
        if ($node_author == $logged_in_uid) {
            unset($build['comments']['comment_form']);
            unset($build['links']['comment']['#links']['comment-add']);
        }
    }
}

Also, you can check out Comment Permissions module. It does not offer the functionality that you need, but it provides more granular permissions than core comment module.

  The Comment Permissions module enables control of commenting by user role and by node type. Additional user permissions for selected node types are added to the user access system so you can configure commenting with more control than Drupal core provides.


Reaction rule throws exception when previewing node

I have found a workaround.

It seems that this is indeed a bug in the Rules module. The working solution is from here (although it was originally written for different situation, it fits this case as well): https://www.drupal.org/project/rules/issues/2929588#comment-12385257, and basically suggests to use a different condition:

Rule condition: 'Condition: Data comparison'
Data to compare (switched to data selection): node.type.target_id (Content type ID)
Operator (switched to Direct Input mode): ==
Value (switched to Direct Input mode): your_node_type

I hope this helps somebody.


is there any Function to extract all the view modes for specific node?

The code below will give me the list of view modes

$entity_info = entity_get_info('node');
$list_of_view_nodes = array_keys($entity_info['view modes']);


How can I display existing node content in its node form?

One way that I recently found was by using panels where you can actually place different components in different places. These components would then be either the rendered to-be-translated field beside the translation field. So you could say that this is a solution but I'm not very sure if this is going to require me to do this for each and every role differently or if panels could only be used to kick in only when a specific condition is met i.e. user has 'translator' role.


How can anonymous users be allowed to post while still maintaining content integrity?

I don't think this is possible with rules alone.

You need to alter the submission form in order to capture the verification email address, and you also need some logic to ban spammers and recognise returning visitors.

I am the maintainer of a project named Anonymous Publishing. It looks as if this module does what you want.

It still in development, but a Drupal 7 version has been used at several of my production sites without any issues. Please check it out.

You may also want to look at the answers under this question.


contextual filter for a block view with relationship

I figured it out: the contextual filter should NOT use the relationship, as the Book field is in the Quote content type!

Finally, this worked: contextual filter (field_book : Content) Content : Book set

• Relationship = Do not use any relationship

• When the filter value is NOT available : Provide a default value = Content ID from the URL


How to make content work with and without javascript

This isn't specific to Drupal but its a javascript technique known as 'unobtrusive javascript'. Not knowing how you are displaying the dialog contents, let's assume this simple case:

See Dialog Content

and then somewhere else in your code (next to?) you've got a div with your dialog content set to not display, ex:

Your dialog content here ..

What you want to do is use jquery (you can do this with native javascript but you're using drupal so its already loaded) to bind a click handler to this link. The idea is then that if javascript is not loaded, then the browser will automatically send them on their way. So that would look something like this:

$(".dialog-trigger").click(function() {
   // do your display stuff here,
   return false;
}

The 'return false' statement at the end is key here to making it so that the link won't be followed.


some images not displaying after migrating to local host

The reason you are having the problem is because you have your website on localhost/folders. And you Drupal installation expects your website to be in locahost. So there is to easy ways to solve this problem. Either you move everything up directory and all your files are in the localhost.

cd /Applications/MAMP/htdocs/testwebsite # Move to the website folder directory.
sudo mv * .[^.]* .. # Move everything up one directory.
cd .. # Move to localhost directory.
sudo rm -rf testwebsite     # Remove testwebsite directory.

Or you can created a temporary soft link on your localhost so your Drupal installation can find the sites folder on the localhost.

cd /Applications/MAMP/htdocs/ # Move to the webserver directory.
sudo ln -s testwebsite/sites sites/ # This is going to created the soft link .