How to configure a different main menu for each language on a multilingual site?

Make sure the i18n Menu Translation sub-module is enabled (it is one of the Internationalization sub-modules).

Edit the menu to be translated, by navigating to admin/structure/menu/manage/main-menu/edit (for the "main menu"). From there it should be possible to select the translation mode you want, e.g. Translate and Localize.

After doing so, when editing a menu link, there should be a new link Translate to actually translate the menu entry. Refer to the Multilingual Guide for (way) more details.

Miltilingual sites are really fun in D7 (way better then it was in D6, and D8 promises to become more easy to configure). Typical variations (with similar solutions) of this "menu" topic are:

translations of blocks, which requires the Block Languages (i18n_block) submodule to be enabled.
translations of taxonomies, which requires the Taxonomy Translation (i18n_taxonomy) submodule to be enabled.


How to list nodes posted in current month?

Add a filter criteria Content: Post date and select Is greater than or equal to, value type An offset from current time and value -1 month.

Screenshots:


Relationships block other content type from showing

Solved by adding :title filters and setting both to not empty. Also set second filter (default, not referenced) for a separate group under OR setting.


Use the Subuser module. This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.


You can follow document.

The $P$ is the so called hash type identifier which indicates that the
hash is a portable Phpass hash. The string after that consists of salt
and a hash. The portable Phpass hashes can be migrated to Drupal 8
as-is. When the user logs in to your Drupal 8 site for the first time,
Drupal will re-hash the password. The salted hash used in this example
is for a password 'test'.

If the source system was a PHP based application that used crypt() or
password_hash(), these hashes should work as-is and they can be
migrated 1:1 like in the Phpass example above. When the user logs in
to your Drupal 8 site for the first time, Drupal will re-hash the
password.

Here is my example convert old pass using md5
<?php

namespace Drupal\my_module;

use Drupal\Core\Password\PhpassHashedPassword;
use Drupal\Core\Password\PasswordInterface;

/**
 * Provides custom password hash comparison for migrated passwords.
 */
class MyModulePasswordService extends PhpassHashedPassword implements PasswordInterface {

  public function check ($password, $hash) {
    // Check old pass is md5
    if (preg_match('/^[a-f0-9]{32}$/', $hash)) {
      $pwd_sercet = "pwd_sercet";
      $pass_hash = md5($pwd_sercet . $password);
      return ($pass_hash == $hash);
    }
    return parent::check($password, $hash);
  }
}


Search form block only appear for administrarors

Most probably it's about the permissions. Give the users (anonymous user / authenticated user) the search permission (also), which you can do after navigating to admin/people/permissions.


Programmatically displaying a view into a colorbox

Put your view into a div with a wrapper that is hidden (ie, display:none;). Then you can use the following javascript:

$.colorbox({
    'inline' : true,
    'href' : $('.views-view-my-view'),
});

You must replace the 'href' attribute with the appropriate jQuery collection representing your view. Other customisations to the way your colorbox appears can be found here.

If you need some advice on placing a view on your page, here is a clean implementation:

function MODULE_preprocess_page(&$vars) {
  $vars['page']['bottom']['my_view'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'my-view-container',
    ),
    'children' => array(
      '#markup' => views_embed_view(...),
    ),
  );
}

In this case your selector for colorbox would be #my-view-container .view


I need help implementing an ajax block to prevent it from being cached by Boost module

Without comment to the overall approach, but rather to "I do not understand this line," module_invoke() invokes a hook in a specific module with any arguments passed. The snippet you found is for Drupal 6, so that's the major part of the issue here.

$block = module_invoke('statistics', 'block', 'view', 0);

invokes statistics_block('view', 0) which means to view the 0th block of the statistics module, and

print $block['content'];

prints out its contents (so they get loaded into your #info div later on via ajax).

But, there is no hook_block in Drupal 7, it's now hook_block_view (and hook_block_info) so you need something along the lines of...

$block = module_invoke('statistics', 'block_view', 0);

instead to accomplish what you are looking to do.

More information on all of this can be found here:

http://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_view/7

http://api.drupal.org/api/drupal/modules!block!block.api.php/function/hook_block_info/7

Now, if what you are wanting to do is put the contents of a View in this block, you could do something like this one-liner instead of the module_invoke/print above:

print views_embed_view('NAME_OF_THE_VIEW');

with more information on views_embed_view here:

http://api.drupal.org/api/views/views.module/function/views_embed_view/7


How to establish a condition to show another view if the first view has no results?

Try to write a php code, in your view UI, in the textarea for behavior when no result :

print views_embed_view( 'your_other_view_name', 'default');

NB : enable PHP filter module


Delete a feature but keep the content created by it

Features module is a way to export most of the settings normally stored in the database into code. If you delete the feature, you delete the code which deletes everything.

The cool thing about features is you can change the settings for things (views, panels, etc) at any time and those changes get stored in the database. Once they're stored in the database it should be OK to delete the feature (though I haven't tried this myself).

The easiest way to do this would be to go into each item that your feature has and re-save it. For example, if your feature had a view called "News" you can go to Structure > Views > News > Edit. Then click save on that view. If you look at your feature, it should now say "Overridden."

Once everything is overridden, it should be OK to delete the feature. Make sure you do a backup of everything and try disabling the feature first to make sure everything you need doesn't disappear.


Creating menus links for displaying articles with specific tags

You need the taxonomy menu module. Here is a quote about it (from the module's project page):

Transforms your taxonomy vocabularies into menus with ease!
Features:

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules


This is a known Ctools issue - there is a patch at comment #49.


There is no official way to do your own thing in statistics.php, it is on purpose kept as light as possible.

But of course, you can duplicate its functionality and do whatever you want. The whole trick is adding a JS file that sends an uncached POST request to the server. That's the only reliable way to get access statistics for anonymous users, as those requests might be cached by the page cache or an external CDN/Varnish.

Given that you already posted all the relevant code, I'm not sure what you are asking exactly. You even linked to the d.o issue that removed that feature, which links to the change record (https://www.drupal.org/node/1900384), which in turn links to the contrib module that provides similar functionality: https://www.drupal.org/project/better_statistics. So instead of doing it yourself, you could build upon that.


Is there any module that let (selected) users (/roles?) see the Administration pages in read-only mode?

Interesting requirement.

Presumably you could assign the relevant admin permissions to the role, e.g "access administration pages", "administer site configuration" etc..

After that, you could prevent changing any settings with a hook_form_alter, adding the $form['#validate'] handler to form_set_error for non-admin users / users of that role. You could also possibly hide the submit button with a suitable #access check e.g #access => user_access('special permission'); on the button itself.

e.g

/**
 * Implements hook_form_alter
 */
function MODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['#validate'][] = 'MODULE_readonly_admin_access';
}

/**
 * Custom validate callback
 */
function MODULE_readonly_admin_access(&$form, &$form_state) {
  if (path_is_admin(current_path()) && !user_access('admin write access')) {
    form_set_error(NULL, t('Operating in read-only mode.'));
  }
}

It would definitely need a lot of careful testing to ensure no loopholes (e.g services API access, #limit_validation_errors cases) - make sure all bases are covered.


How to unpublish content when form submitted and notify a user by eMail?

The Rules module is, for sure, your best bet for addrerssing this (therefor +1 for this question already ...).

Can you further enhance (edit) your question to explain what you have tried already using Rules? And what worked, or failed, and what the remaining questions are while using the Rules module? I.e.:

which events?
which conditions?
which actions?

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. Possibly also the similar set of 8 video tutorials about the Flag module, often considered as a natural complement to the Rules module.


I had to create a custom hook_tokens function:

/**
 * Implementation of hook_tokens().
 */
function MODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'submission' && !empty($data['webform-submission'])) {
    $node = isset($data['node']) ? $data['node'] : node_load($submission->nid);

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'values:date_field:custom_format':
          foreach ($node->webform['components'] as $cid => $component) {
            if ($component['form_key'] == 'date_field') {
              $replacements[$original] = format_date(strtotime($data['webform-submission']->data[$cid][0]), 'custom_format');
            }
          }
          break;
      }
    }
  }

  return $replacements;
}


How to hide the (-) sign from facet filter block?

There are a couple of theme functions you can use to work with the display of these filters.

theme_facetapi_deactivate_widget($variables)

theme_facetapi_link_active($variables)

In your case, you could place the following in your theme's template.php file to edit the display of the deactivation 'button' of your facet:

function THEME_facetapi_deactivate_widget($variables) {
  return '';
}


Drupal 8 paragraph access in views-view twig file

This is how i solved this ..

--> I added a relationship of the paragraph field and made it as required

--> After that i selected the relationship in the filter criteria section

--> And then i was able to select all the paragraph fields while adding a new field in the view

Hope this helps someone


How to get the list of blocks for the current page?

To get all blocks in an array by region, you can do as follow

// Get the current theme used
$theme = \Drupal::theme()->getActiveTheme()->getName();

// And pass the theme name to get all the regions
$regions = system_region_list($theme, $show = REGIONS_ALL);

// This will give you all the regions in array format
$regions =  json_decode(json_encode(system_region_list(\Drupal::config('system.theme')->get('default'),$show = REGIONS_ALL)),true);

// Loop over each regions
foreach ($regions as $key => $region) {
  // Get the blocks in particular region
  $blocks[$key] = \Drupal::entityManager()
    ->getStorage('block')
    ->loadByProperties([
      'theme' =>  \Drupal::config('system.theme')->get('default'),
      'region'=> $key,
    ]);
}


I am not sure if you can send a mail without any custom coding, but you can definitely do this via custom code.
Refer examples module, which has an example on how to send mail.


I would start by troubleshooting the horrid White Screen of Death.  Once you find the culprit module/file/function/setting this should be much easier to fix.

You may also want to scope out the Language Dropdown bug list, the i10n_update bug list and the i18n bug list.

If you will post back with details regarding the WSoD I'll do my best to update my answer.


Can a Drupal site design (not just colors, fonts, etc -- template stuff) be replicated over multiple drupal sites?

Just to be able to replicate additional fields that you may add to bundles on a "master" site to several other sites, you may use Bundle Copy.

This project provides export/import support for:

Node types
Taxonomy
User
Field API fields
Field groups

It will only export/import the bundle definition, not the content.

For a more elaborate export/import module that not only handles fields, but whole features, take a look at Features.

From the module's description:

  Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.


Just add the fieldable key and set it to true:

return array(
  'status' => array(
    'label' => t('Status'),
    'plural label' => t('Statuses'),
    'fieldable' => TRUE,
    ...


Location Contextual Filter: Distance/Proximity works for all nodes but one

I did not figure out why this is happening, but I was able to enter the latitude and longitude manually. This solves the problem for the short term, since the client does not add Location nodes often. I'm leaving the question open in case anyone has a clue!


You'll need to hook into the rest server module's formatters. This is untested but I think it'll work:

function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['xml']['formatter class'] = 'MyServicesXMLFormatter';
}

...

class MyServicesXMLFormatter extends ServicesXMLFormatter {

  public function render($data) {
    // This is the default code from ServicesXMLFormatter::render(),
    // manipulate this to add your schema and return the saved doc as normal
    $doc = new DOMDocument('1.0', 'utf-8');
    $root = $doc->createElement('result');
    $doc->appendChild($root);
    $this->xml_recursive($doc, $root, $data);
    return $doc->saveXML();
  }

}


This can be achieved by adding an attribute max

$form['date'] = [
  '#title' => $this->t('Date'),
  '#type' => 'date',
  '#attributes' => [
    'type' => 'date',
    'min' => '-25 years',
    'max' => 'now',
  ],
  '#date_date_format' => 'd/m/Y',
];

Reference: https://api.drupal.org/comment/61733#comment-61733


How to show/hide login block on main page based on button in header?

Your first approach you can consider as best as we won't be actually touching the core Drupal functionality and creating our custom module to tweak the core. You can also have a look at logintoboggan module it may help you to get the drop down effect for login form and login block on click of link once you do the configurations for the loggintoboggan. you may need to additional theming and some jquery code to tweak it more for signup.

Hope it helps.


About list your fields for your content type, I guess that you can use node--NAMECONTENTTYPE.tpl.php in your directory template.

to be more detailed, you can copy/paste to your theme directory the file node.tpl.php (located in modules > node or already located inside your theme directory) and rename it according your content type. for example, if the Content Type is Article the name will be node--article.tpl.php

already inside in node--article.tpl.php you can list the fields with the variable $content using print_r($content); to see the list of the fields that you can use to your node (or if you use Devel module, is best use dsm($content);)

to call each field you can use:

for example I have a field called field_demotext1, then:

print render($content['field_demotext1']);

here is the example of zone in the node--article.tpl.php using dsm($content); to print list of fileds:

  <div class="content clearfix"<?php print $content_attributes; ?>>
    <?php
      hide($content['comments']);
      hide($content['links']);
      print render($content);
      dsm($content);
    ?>
  </div>


Use migrate to populate entity_reference with nid

It was straightforward. I had a typo in my YML file. The correct answer was:

field_recording_link/target_id: recording_nid

The important thing is to set the target_id field, since that is what the entity reference really is.


Try this as per drupal standard

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('body', context).click(function () {
        alert("test");
      });
    }
  };
})(jQuery);

Go through with Managing JavaScript in Drupal 7 for more information


Is there a module to track future revisions of published content in Drupal 6?

In D6, you can do this with Revisioning and Rules.  You may also need to throw views, etc. into the mix.

Revisioning provides the ability to add pending revisions to content types.  You can set it so that you are tracking only one pending revision per node or you can even track revisions of pending revisions.  Revisioning provides actions and events to rules so you can make your own workflow.  It's not as easy to set up as the Workbench module, but I've implemented a similar workflow with these two modules.

There's also the Workflow module but I don't have any experience using it.


adding the field tokens while creating the component

In Rules you need to use - not a _

Try

[node:field-working]
[node:field-remoz]

EDIT

Click on replacement patterns, it will show you all the fields that you can use. Look for your field on the list, and then use the code that is given there, and copy and paste it into the message body.


Display only the last submission per user of a webform in views

I have worked out a simple solution to this - the Views Distinct module


How to import Panel configuration from versionned code


It's hard to tell what you doing from your description. A better description could possibly yield better answers.

One possible problem could be that the form needs to be loaded on the page the it is submitted on. This is required for the validate and submit handlers to be processed.


Hash method not providing password that is stored in database

That's pretty much the point. user_hash_password uses _password_generate_salt, which in turn uses drupal_random_bytes. This means hash returned will always contain randomization and is designed not to return the same result twice. Or at least do it as rarely as possible, because there is 2^(6*8) possible outputs of 6 random bytes.

To test passwords, Drupal uses user_check_password. This function extracts salt from stored password and applies it to the one user provided.

Note that by design Drupal does not have any function that would allow to recreate hashes perfectly, and it's not possible to write one (without using original hash to extract salt, that is). You can get pretty close if you need to, copying logic from  user_check_password, but it is actually better to leave salt changing as much as possible.


The sid won't be available from a validation handler; validation handlers are called before form submission, thus a valid sid for your submission doesn't exist at time of execution.

If you need to call a post-submit webform hander, the webform module provides hook_webform_submission_insert():

function mymodule_webform_submission_insert($node, $submission) {
  // The submission object contains $submission->sid, the submission id.
  print_r($submission);
}


why does commerce pricing rule increase price before decreasing price?

Answer: It doesn't.  The checkout page just makes it look like that because all those line items have already had the discount applied to them and the view does not show that.

So my new questions are:

How to display original price on the product display? (Because only the discounted price is shown to authenticated users)
How to display the original price in the cart and checkout forms?

But original question answered.


Adding Drupal field "subtitle" to page template

I assume you cleared the cache. Your issue is page--content-type.tpl.php override not working. Try to suggest theme hook in THEME_preprocess_node.

Furthermore you need to theme nodes of Happy Day content type, so you must use node--CONTENT_TYPE.tpl.php. For more information visit Theming nodes by content type page.


CKeditor removes iframes in editor after update to 6.x-1.14

In ckeditor.config.js, add config.allowedContent = true; to disable the filtering of HTML elements in the editor.

CKEDITOR.editorConfig = function(config) {
    config.allowedContent = true;
}


How can I pass parameters to a Services endpoint?

You need to use http://domain/api/v2/node?parameters[type]=event_calendar

any of the identifiers need to use inside parameters[]

Also, you can use services views module to expose the data and create new identifiers like type on your own.


How do I change the style used by the "Archive" view to show the dates?

Views haven't supplied an easy way of doing this, but it is possible. To do this you would have to create your own handler and make views use that:

1. Creating own handler

class custom_handler extends views_handler_argument_node_created_year_month {
  function construct() {
    parent::construct();
    $this->format = 'F Y'; // Write your custom format here.
  }
}

2. Making view use your custom format

function module_name_views_data_alter(&$data) {
  // Set the argument to the handler you named above.
  $data['node']['created_year_month']['argument']['handler'] = 'custom_handler';
}

Update.

The custom_handler class or whatever you choose to call it need to go in it's own file. For Drupal 7 the standard is to put it in a dir called handlers which is located in the dir that you specify with hook_views_api, and add the file as include in the .info file (Look at the views module for reference).
For the module_name_views_data_alter you need to replace module_name, with the name of your module.
Clear cache.


How to add extra new term into multiple nodes

Install the Views Bulk Operations module.
Create a view and add a filter to view nodes having term a and b.
add    a Bulk operations: Content field and in the field  settings under    SELECTED BULK OPERATIONS select  Modify entity values.
Save the view and from the Operations list, select Modify Entity
Values.    Choose the term field you want to add the terms to,
and then    select the terms you want to add
Select the Add new
value(s) to    FIELD, instead of overwriting the existing values
check box and Submit the form.


Enable/disable a menu item programatically depending on a variable value

The usual way to enable a menu item only in certain circumstances is to use a custom access callback, in which you would evaluate whether this option is set. So:

'access callback' = 'my_module_access_callback',
...

function my_module_access_callback() {
   return my_module_test_option_is_true();
}

But it's a little hard to be sure if this will work for your case as you haven't given us much to go on.


Theme call for block returning as an empty string

Assuming your template file can be found at theme/block-projectinfo.tpl.php, you just need to change the file property to template in hook_theme():

function generic_theme() {
  return array(
    'block_projectinfo' => array(
        'variables' => array(
            'completionPct' => NULL,
        ),
        'template' => 'theme/block-projectinfo'
    )
  );
}

file is

  The file the implementation resides in. This file will be included prior to the theme being rendered, to make sure that the function or preprocess function (as needed) is actually loaded; this makes it possible to split theme functions out into separate files quite easily.

And refers to situations where you implement a theme_foo() function, rather than a template file.


Referencing a referenced entity's fields on a form

You can use DFV - Dependent Field Values. It's a great module and does exactly what you're asking
The module's page says:

This modules enables site admins and developers to make the allowed values of a field depend on another proviously selected field's value.
You can use views with arguments to let views return the allowed values for a dependent field.

I'm using it myself, it's quite simple to use: you create a view of type Dependent Field Value with a contextual filter, which in your case is the NID of the node in the first field, the team (remember to add the relevant relationship in the view's Relationships section).
Usually you'll want to add two fields to this view, e.g. the home game's NID and the home game's title. After adding the two fields, click on the settings of the  dfv list format. Choose the home game's NID as the Key Field an the home game's title as the Title Field. The view is done!
You didn't explain how is your contact form made, but I suppose that you use webform. So: you just have to go to the second field's settings, check the "Enable dfv settings", choose the parent field (team) and the view you just created.


How to use Drupal to encapsule an external site

If you've, at least, any control on the second web site you can do it with dynamic includes. It works not so bad with the help of an own module.

The idea its to create a module that do a file_get_content() and return it to Drupal that gonna show the content.

But, for it your second web site should have relative paths between his pages, or you will make the change with a regex.

There an example module, no tested.

function mymodule_menu() {
  $items = array();

  $items['inc/%'] = array(
    'title' => t("Include"),
    'page callback' => 'mymodule_include',
    'page arguments' => array(1)
  );

  return $items;
}

function mymodule_include($path) {
  $http = 'http://example.com/';
  // Maybe check if the page is available
  // better to use drupal_http_request for that
  $content = file_get_contents($http . $path);

  // Perform any change in the content before to
  // send it for render.
  return $content;
}


How to remove duplicate nodes in a view with taxonomy relationship (1 node per term)?

https://www.drupal.org/project/views_distinct

use this module and configure the settings in the view Field.

This will remove those duplicates from your view.
do this for the duplicated field items.


Can't update via composer because of lock file

The way I updated is I manually updated composer and set Lightning to 8.1.0 and then ran composer update drupal/lightning.


What is the purpose of entity_keys in ContentEntityBase?

entity_keys are basically an alias for fields. It allows generic code, like the storage backends, to access common fields that have different names, for example the ID. They need write the saved value, so the can't just use id() as most places.

Internally, those keys are also used by generic methods like id(), label(), getRevisionId() and so on, so they work out of the box.

There isn't really a reason that comment doesn't define status. Nothing really uses status, if you search for getKey('status'), there are no matches, while getKey('id') finds a lot.

Node only uses it internally for the isPublished().


How can we catch the acces denied exception?

To catch the access error you can use a symfony event listener:

  If your listener calls setResponse() on the
  GetResponseForExceptionEvent, event, propagation will be stopped and
  the response will be sent to the client.

http://symfony.com/doc/current/controller/error_pages.html#working-with-the-kernel-exception-event

This is an example how to return a GetResponseForExceptionEvent event:

Drupal\Core\EventSubscriber\CustomPageExceptionHtmlSubscriber

public function on403(GetResponseForExceptionEvent $event) {
    $custom_403_path = $this->configFactory->get('system.site')->get('page.403');
    if (!empty($custom_403_path)) {
      $this->makeSubrequestToCustomPath($event, $custom_403_path, Response::HTTP_FORBIDDEN);
    }
  }

For your own Event Subscriber extend DefaultExceptionHtmlSubscriber.

class MyCustomPageExceptionHtmlSubscriber extends DefaultExceptionHtmlSubscriber

See the complete example:

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/EventSubscriber/CustomPageExceptionHtmlSubscriber.php

which extends

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/EventSubscriber/DefaultExceptionHtmlSubscriber.php

You would have to use a higher priority, so that your code will run first.

In most cases it might be easier to configure a url pointing to a custom controller here:

/admin/config/system/site-information

BTW the example code above is how core implements this configuration.


Always best to include the Drupal version you are making use of, for the purpose of the answer will assume its Drupal 7;

So there are two parts to this;

1) The user data upload to drupal; you could make use of the Migrate module; I would think in the very least you would need to set the username and a temporary password to facilitate the first time login instance.

2) To force the user to fill in his details you could make use of the hook_user_login in a custom module implementation to validate that the user's details have been filled in.


I found the answer on a video

Go to 'Edit View'
Click on the field you want to add a CSS class to
Go to the 'Style Settings'
Check 'Customize field HTML'
Check 'Create a CSS class'


How can the admin of a group edit all members default profiles? Is that possible? (Drupal 6 installation)

User Profile Access does not have elaborate access control in the fashion of nodes, so the answer is a custom module that takes over the profile edit page's menu access callback.

Use hook_menu_alter() on user/%user/edit and set 'access callback' to custom_user_edit_access. In that function, run the original access logic to preserve normal behavior, but then add another layer that checks to see if the current user is an administrator in the group and if the active user profile's user is in the group.

For D6, you can either check the user data structure directly, or use the API functions og_is_group_member() and og_is_group_admin().

If you want to special-case the email field to a specific permission once the user has access to the form, that's a case for hook_form_alter() and changing the email field's #access element to use a new permission or an access callback with logic of it's own.


How can I alter node markup from a custom module (not theme)?

This did the trick:
custom.module:
<?php

/**
 * @file
 * Custom module hook implementations.
 */

/**
 * Implements hook_theme().
 */
function custom_theme() {
  return [
    'node__custom_article' => [
      'template' => 'node--custom-article',
      'base hook' => 'node',
    ],
  ];
}

Credit where it's due:
https://www.drupal.org/forum/support/module-development-and-code-questions/2015-06-03/drupal-8-override-template-with#comment-12461953


You could make the same search with a view and add contextual filter to achieve the specific URL pattern and normal field filters to apply other filtration if needed. The view could render the node with the same display that you was going to use for the default search so if you have already built the markup - you don't have to do it again.

Edit:
Also if you want to use the default search api - you could make a facet to filter with the help of the Facet API Module


The classes are only added to the existing ones, they don't replace them. If you want to remove the old styling, you can create a new layout and either add different default classes, or no classes at all.

Adding custom layouts to your theme (Display Suite)

You also might want to consider using Display Suite Bootstrap Layouts. Bootstrap 3.0 layouts are still in dev, but it's worth taking a look.


Probably a hack, but this is how I solved it:

$form['field_brand_selector'] = array(
    '#type' => 'inline_template',
    '#template' => '{{ somecontent | raw }}',
    '#context' => [ 'somecontent' =>
    '
        <label for="edit-field-brand-selector">Brand</label>
        <select class="" id="edit-field-brand-selector" name="field_brand_selector" readonly="readonly"></select>
    '],
    '#weight' => 8,
);

This way Drupal doesn't validate the field I added.


Edited Code -

{% set build = {
      '#type':   'processed_text',
      '#text':    content.field_front_page_description.value,
      '#format': 'full_html',
} %}
      {{ kint(build) }}
      {{ build }}

Or,

{% set build = {
      '#type':   'processed_text',
      '#text':    node.field_front_page_description.value,
      '#format': 'full_html',
} %}
      {{ kint(build) }}
      {{ build }}


If I understand correctly what you want to achieve, you could also try the Boxes module or even Panels and Panels Everywhere.


Why do the facets display the wrong amount of results ?

All that time, I was using the default Search bar from Drupal 8 (which comes with the Search API module).

The thing is, the results in the facets were the ones that were given after Solr handled the search, and not the Search module from Search API.

For basic requests like a few keywords, both search engines yielded the same results, so the facets corresponded to the result, but my configuration of Solr didn't seem to handle double quotes.

In short : Search API handles the double quotes and displays the good results, but Solr didn't handle the double quotes so the facets results were wrong.


Your description makes it sound like you have ajax views enabled which is probably going to be very challenging to get working correctly.

There may be a better backend way to do this, but one way that occurs to me is to fix this on the client side with javascript, by merging lists after ajax finishes loading.

Copy the Bootstrap List Group view display template into your theme's templates folder.
Add a custom data attribute to mimic the text value of the grouping's row title, and attach a custom javascript behavior to do the work on the client side.

{{ attach_library('yourtheme/prevent_duplicate_list_group') }}

  {% for key, row in rows %}

      {% if row.title %}

{{ row.title }}

      {% endif %}

{{ row.content }}

  {% endfor %}

Create a library in yourtheme.libraries.yml to add a JS behavior.

prevent_duplicate_list_group:
  js:
     js/prevent_duplicate_list_group.js

Write some custom javascript logic to look for all instances of the duplicate grouping and move the values from the second list into the first.

I've not used bootstrap views thus don't know the exact dom structure you'll need to work with, but here is something completely untested to get you started.

/**
 * @file
 * Behavior to merge duplicate List Group titles loaded from ajax-enabled views.
 */

(function ($) {
  'use strict';

  Drupal.behaviors.prevent_duplicate_list_group = {
    attach: function (context, settings) {
      $('.list-group-item-heading', context)
        .each(function (idx, element) {
          var title = $(element).attr('data-grouping'),
            duplicates = $('[data-grouping="'+ title + '"]');
          if (duplicates.length == 2) {
            var first = duplicates.eq(0).closest('ul');
            var second = duplicates.eq(1).closest('ul');
            // snagged from https://stackoverflow.com/a/28487699/413538
            // you may need to overhaul this to only walk through
            // list items from the second list up until it gets to a list item that contains an h4 and hide each individual li
            var i=1;
            $('li', first).each(function(){
              $(first).append($('li:nth-child('+i+')', second).clone());
              i++;
            });
            second.remove();
          }
        }
      );
    }
  };
})(jQuery);


The available hooks for Services are documented in the api docs for services

You probably want hook_services_request_postprocess_alter($controller, $args, $result); which allows you to change the array of $result any way you want.


In the Panels UI, every Pane has a little cog. Click it, and menu appears. There is an entry called "CSS Settings". There you can add per pane classes.


How to import a Text File from feeds CSV and map it to a File upload field with multiple values?

It looks like you're on the right track from:
https://www.drupal.org/node/1116130#comment-6827626

I believe you to set it to use an array of values (that's what explode returns). The file type itself, image vs text file, is largely irrelevant as you simply want it to work with a multiple item field.


Show a required textfield when user select only ups shipping service on checkout form

You could try to do this via #states property in form API.

More information about that can be found here:
How to make a form required with states?

Personally i only used it to hide/display form elements, but required/non-required should be possible as well.


How to achieve order fulfillment in drupal commerce like ubercart?

Have you tried https://drupal.org/project/commerce_delivery at all? That appears to be used in conjunction with https://drupal.org/project/commerce_physical_fields and its dependent Physical Fields module.


This is the best advice:
https://stackoverflow.com/questions/8311320/how-to-change-the-session-timeout-in-php

To put it in a Drupal context, you'd have to add a new column to the user table that tracked the last time a user was active and check that on a user hook.


function tag_graphics_form($form_state) {
    $form = array();
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    $form['tag'] = array(
        '#required' => TRUE,
        '#type' => 'textfield',
        '#title' => t('Tag'),
        '#size' => 30,
      );
    $form['image'] = array(
        '#type' => 'file',
        '#title' => t('Image for tag page'),
        '#description' => 'Recommended width for image: 605px'
    );
    $form['description'] = array(
        '#type' => 'textarea',
        '#title' => t('Page Description for SEO')
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save'
    );
    return $form;
}

function tag_graphics_form_validate($form, &$form_state){
  $field = 'image';

  $directory = file_directory_path();
  if (file_check_directory($directory, FILE_CREATE_DIRECTORY, $field)) {
    $validators = array();
    if ($file = file_save_upload($field, $validators, $directory)) {
      file_set_status($file, FILE_STATUS_PERMANENT);
      $form_state['storage']['file'] = $file;

    }
  }
}
function tag_graphics_form_submit(&$form, &$form_state){
  print_r($form_state['storage']['file']);
}


Add role to user after joining organic group with rules

Now your Rule runs after user requests membership. But you should run it after OG membership was approved.
I prepared Rule which adds role “member” after membership was approved or if it was added by admin (auto-approved). Here is export (4 is id of my drupal role “member”):

{ "rules_after_add_user_to_group" : {
    "LABEL" : "After add user to group",
    "PLUGIN" : "reaction rule",
    "TAGS" : [ "test" ],
    "REQUIRES" : [ "rules", "og" ],
    "ON" : [ "og_user_insert", "og_user_approved" ],
    "IF" : [ { "data_is" : { "data" : [ "og-membership:state" ], "value" : "1" } } ],
    "DO" : [
      { "user_add_role" : { "account" : [ "account" ], "roles" : { "value" : { "4" : "4" } } } }
    ]
  }
}

Screenshot:

Tip: you can enable Rules debug (page admin/config/workflow/rules/settings) to see when your rules are executed.


In your route you require CSRF token and your ajax call is missing the CSRF token.
Get a CSRF token from ur drupal site using url "/session/token" and send it with your Ajax request.
But is it wise to do it this way? i don't know.
For making ECK Entity with ajax Post i would use REST resource or make a custom REST resource with basic_auth or cookie authentication, that way you wont need a CSRF Token.


scss isn't parsed by the browser- it needs to be compiled to css... ,Assuming you have already installed ruby and sass, open a terminal window and navigate to your theme's root directory. Then sass --update to compile the styles once or sass --watch to continue compiling as you work.


If you goal is only to change the Cache-Control you can use drupal_add_http_header(). According the documentation this function allow you override an existing header. If you add it in you template.php you'll able to change the header without patch the core function.


How to attach profile type to specific user role?


Go to: YOUR_SITE/admin/structure/block/add and fill the info like this:

In Block body field you must put the code of the badge and go to the bottom of the page to Save block.

Then in the YOUR_SITE/admin/structure/block page search your block, in this case the name is "Best of Houzz badge" then select the region where the block will be displayed (in this case Sidebar first)

Go to the bottom of the page and click in the Save blocks button.

And you will see the block in your site.


See the Multifield module.

  This project seeks to provide a true compound field solution for
  Drupal 7. As much as I love Field collection, it still has to save
  actual entities, and can cause performance problems due to having to
  load all the referenced field collection entities on node, or parent
  entity load.

I am not sure of its compatibility with Features or Search API though.


Please help with this query! Need to get taxonomy terms of related nodes

You already have the {term_node} table joined in your query so I'm pretty sure you should just be able to change your first line to include tn2.tid. Try this:

SELECT DISTINCT n.title, nr.teaser, n.nid, tn2.tid, DATE_FORMAT(FROM_UNIXTIME(n.created), '%M %e, %Y') AS date, f.filepath AS image, cfri.field_related_images_nid as image_id
FROM node n JOIN node_revisions nr ON n.nid = nr.nid
LEFT JOIN content_field_related_images cfri ON (n.nid = cfri.nid AND cfri.delta = 0)
LEFT JOIN content_field_att_file cfaf ON cfri.field_related_images_nid = cfaf.nid
LEFT JOIN files f ON cfaf.field_att_file_fid = f.fid
JOIN term_node tn2 ON n.nid = tn2.nid

WHERE n.status = 1 AND n.type = 'article'   AND nr.body LIKE '%kimberly-clark%' AND     tn2.tid = 143 ORDER BY n.created DESC LIMIT 3


How to make the help text of a content type field collapsible?

Each form element in your input/edit form will be in a div with a unique id, and will have a child division with the 'description' class which contains the help text.

If you know which div's you wish to collapse, it can be done with javascript, following the model for Collapsible Blocks.


How can I watch videos of the presentations from DrupalCon Sydney for free?

For whatever reason, the DrupalCon Sydney videos are on YouTube, not Blip.TV.  The link includes instructions for downloading the videos from YouTube, but if you want them all, it's probably easier to use the torrent.


Brands are clearly taxonomies.
The other two are two product types.
With the help of Commerce Search API you can easily have facets on brands, as well as powerful search.


How to duplicate nodes programmatically?

You can read the values from the original node in an array and create a new node with the data:

$storage = \Drupal::entityTypeManager()->getStorage('node');

$node = $storage->load($nid);

$original_values = $node->toArray();

// assign content type as string, the array causes an error when creating a new node
$original_values['type'] = $node->bundle();

// change title
$original_values['title'] = $node->label() . ' (cloned)';

// remove nid and uuid, the cloned node is assigned new ones when saved
unset($original_values['nid']);
unset($original_values['uuid']);

// remove revision data, the latest revision becomes the only one in the new node
unset($original_values['vid']);
unset($original_values['revision_translation_affected']);
unset($original_values['revision_uid']);
unset($original_values['revision_log']);
unset($original_values['revision_timestamp']);

$node_cloned = $storage->create($original_values);
$node_cloned->save();


Creating a user reference field based on a similar field on a referenced node

Create a view with all users.
Create a relationship of type reverse join to project via the members field.
Create a relationship of type reverse join to issue via the project field.
Add a contextual filter on nid using the second join we created (issue).
Set the view type to "references".
Done :)


How to inherit 'Date' element in webforms?

Webform elements require a Drupal Form API 'Element' plugin and 'WebformElement' plugin.

@see webform_example_element.module


I used Star Rating module. Exactly what I was looking for. In contrast with Fivestar module, it is intended for rating only by the author of the node. Plus no dependencies.
[Thanks to @jimajamma]


How to add additional display (view mode) for all node types?

The programm way from related quedtion should work, but it doesn't, you can try to use the following module: https://www.drupal.org/project/entity_view_mode

  The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities.


How come my view block is not loading using ajax?

I got this working:

gotchas:
1. Had to load ajax_view.js, added this code snippet to theme file, check your view source to make sure ajax_view.js is loaded.

use \Drupal\views\ViewExecutable;
function customthemename_views_pre_render(ViewExecutable $view) {
  if (isset($view) && ($view->storage->id() == 'community_plan_update_news_feed')) {
    $view->element['#attached']['library'][] = 'pager-view';
  }
}

Had to write my own jquery once function in Drupal Behaviors file:

(function($, Drupal, drupalSettings) {
    'use strict';
    // turn off scrolltoTop
    if (Drupal.AjaxCommands) {
        Drupal.AjaxCommands.prototype.viewsScrollTop = null;
    }
    // Write your own jquery once function
    $.fn.once = function(processed_class) {
        if (typeof processed_class == 'undefined') {
            processed_class = 'processed';
        }
        return $(this).not('.' + processed_class).addClass(processed_class);
    };

    Drupal.behaviors.pagerFragments = {
        attach: function(context, settings) {
            var pager_links = $('.tab-content .pager__items li a').addClass("use-ajax");
        }
    };

    Drupal.behaviors.linkClick = {
        attach: function(context, settings) {
            $(".pager__items li a", context).on('click', function() {

                var ajaxObject = Drupal.ajax({
                    success: function(response) {
                        var viewHtml = response[1].data;
                        Drupal.settings.views = response[0].settings.views;
                        Drupal.attachBehaviors();
                        if (response[1].data !== undefined) {
                            $('.tab-content').html(viewHtml);
                        }
                        var ajaxPath = 'views/ajax';
                        var view_info = {
                            view_name: 'community_plan_update_news_feed',
                            view_display_id: 'general_plan_news',
                        };
                        var ajax_settings = {
                            submit: view_info,
                            url: ajaxPath,
                            cache: true,
                            event: 'click',
                            async: true,
                        };

                        Drupal.ajax(ajax_settings);
                        ajaxObject.success(response, "success");
                    },

                });
            });
            // reload sharethis icons
            if (__sharethis__ && __sharethis__.config) {
                __sharethis__.init(__sharethis__.config);
            }
            Drupal.behaviors.animate = {
                attach: function(context, settings) {
                    $(document).ajaxStart(function() {
                        $('.tab-content').fadeTo(200, 0);
                    });
                    $(document).ajaxSuccess(function() {
                        $('.tab-content').fadeTo(200, 1.0);
                    });
                }
            };
        }
    }
})(jQuery, Drupal, drupalSettings);


Setting the default value for a text field as a variable in Form API

You don't need to use user_load($user->uid);. You already have a complete object inside global $user; variable. And don't forget PHP is not a natural languages. You can't just put whitespaces where you want them. In method call or property access, there should be no spaces around ->, it should be right next to object, and property should be right after arrow.

This line is sufficient for me:

'#default_value' => $user->mail,


Display suggested search result on search page if search result is empty

The Search API Spellcheck module might be a starting point. It interfaces with the Search API Solr module.

Hope it helps,


Override a theme template variable with a module

Taking the lead from @Alfred Armstrong above and my colleague, this ended up working!

In mytheme.theme

function mytheme_preprocess_page(&$variables) {
  if(!isset($variables['var1'])) {
    $variables['var1'] = 'defaultvalue1';
  }
}

In mymodule.module

function mymodule_preprocess_page(&$variables) {
  $variables['var1'] = 'myvalue1';
}


How to programatically remove parent form taxonomy term?

taxonomy_term_save() treats null as "do not change parent", and 0 means "this term does not have any parents". Also, property is named parent, not parents. Change

$term->parents = null;

to

$term->parent = 0;

and you're done.


How to specify the order of Javascript calls?

If you want to enforce the order of your scripts, declare them as libraries via hook_library() and list one as dependency for the other.


How do I replace a comma with a line break using feeds tamper?

The problem is to do with single quoted strings and double quoted strings

'\n' !== "\n"

So when you enter \n in the settings it's getting passed to the preg function as a single quoted string and in php there's no safe way of changing the string from a single quoted to a double quoted string.

https://stackoverflow.com/questions/5241748/php-convert-single-quoted-string-to-double-quoted

Solved this using a plugin,

first make a custom module that adds a ctools feeds_tamper plugin directory

/**
 * @file my_feeds_tamper.module
 */
/**
 * Implements hook_ctools_plugin_directory().
 */
function my_feeds_tamper_ctools_plugin_directory($owner, $plugin) {
  if ($owner == 'feeds_tamper') {
    return 'plugins';
  }
}

Then within that module directory create the plugins directory and add the plugin code

/**
 * @file plugins/comma_to_newline.inc
 * replaces commas with comma linebreak on import
 */

/**
 * defines the ctools plugin
 */
$plugin = array(
  'form' => 'comma_to_newline_form',
  'callback' => 'comma_to_newline_callback',
  'name' => 'Comma to new line',
  'multi' => 'direct',
  'category' => 'Text',
);

/**
 * Even though there are no settings we still need the form
 */
function comma_to_newline_form($importer, $element_key, $settings) {
  $form = array();
  return $form;
}

/**
 * replaces a comma (followed by 0 or more spaces) with
 * a comma and a linebreak
 */
function comma_to_newline_callback($source, $item_key, $element_key, &$field, $settings) {
  $field = preg_replace("/, */", ",\n", $field);
}

I could have made a clone of the preg replace feeds tamper plugin, that replaces \n with "\n", for a more flexible (configurable solution)


Display field collection items together with nodes in view sorted by date

I would strongly suggest to move away from field collection implementation. Because, Sub - Events are actually events and should be nodes. Right now they are becoming values of a Single Event by using field collection.

Try considering Entity Reference. Add a reference field called Parent Event to the event content type and make it reference to same content type. Make the field optional so that you can create root Events.

In future, above architecture will provide you lot of advantages. Hope you like it!


Conditional Field on Multiple Selects Module

It work when I use these settings. See screenshots.


Css class for Custom Content type fields

You can use the Display Suite module to control the wrappers of each field or add classes:

Drupal adds a lot of classes already, so you can probably look at the existing markup that Drupal is outputting and style it based on the classes that are already there.


After studying the code in modules/field/text/text.module, I found the missing item: I had to assign my new widget to $element['value'], so:

$element['value'] = $widget;
return ($element);


Search only for the currently active language

There's a really elegant way to do this using the apparently undocumented hook_query_node_access_alter():

function yourmodule_query_node_access_alter(QueryAlterableInterface $query) {
  $search = FALSE;
  $node = FALSE;

  // Even though we know the node alias is going to be "n", by checking for the
  // search_index table we make sure we're on the search page. Omitting this step will
  // break the default admin/content page.
  foreach ($query->getTables() as $alias => $table) {
    if ($table['table'] == 'search_index') {
      $search = $alias;
    }
    elseif ($table['table'] == 'node') {
      $node = $alias;
    }
  }

  // Make sure we're on the search page.
  if ($node && $search) {
    $db_and = db_and();
    // I guess you *could* use global $language here instead but this is safer.
    $language = i18n_language_interface();
    $lang = $language->language;

    $db_and->condition($node . '.language', $lang, '=');
    $query->condition($db_and);
  }
}

Note: this code is 100% based on the excellent Search Config module.

User's vs Content language

Some sites might have language detection configured to show the interface in the user's preferred language, while the page content is shown based on the URL or content language.

In that case, consider replacing

$language = i18n_language_interface();

with

$language = i18n_language_content();


Main navigiation layout bugs after adding a cart block

Looks like those dots are a content on :before of the anchor tag, to remove them you could add this to your CSS files.

.header-container ul.menu li a:before {
    display: none;
}

This looks like it have been added by Drupal or maybe the theme you are using, i am not really sure, I recommend you read this https://www.w3schools.com/cssref/sel_before.asp to understand more about the before selector.


I would make up a module with a hook_menu in it with a path of "crossdomain.xml".  In the menu callback, figure out your domain and serve up the proper file with the proper MIME type.  Install the module in "sites/all" and enable for each site that needs it.

I also suspect you could handle it in .htaccess with something like

RewriteCond %{HTTP_HOST} ^www\.host1\.com [NC]
RewriteRule crossdomain.xml crossdomain.host1.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host2\.com [NC]
RewriteRule crossdomain.xml crossdomain.host2.xml [L]
RewriteCond %{HTTP_HOST} ^www\.host3\.com [NC]
RewriteRule crossdomain.xml crossdomain.host3.xml [L]


Does the cron using Drush must be setup locally or on the server for the production website

TL;DR You should add it on the server!

Whereas it's possible to add it locally and use a remote alias to run it on the server it would be unreliable (requires your local to be online 24/7) and inefficient.

That said, you can also add "local" aliases on your server for convenience, to avoid adding the --root and --uri flags to the command in your crontab.

You can add any number of Drush aliases anywhere you want; so on your local machine you can have a "foo.local", "foo.staging" & "foo.prod" aliases for your site. And on your staging and production servers, you can simply add "foo.staging" and "foo.prod" so that you can access all of your environments in a cohesive and consistent manner.

The advantage is that if you define an alias "foo.prod" on the production server, you can replace your crontab command with this:
/usr/local/drush/drush @foo.prod --quiet cron

It's customary to have the same aliases set up across all servers for that very purpose.


Current version of Addressfield (7.x-1.0-beta5) supports displaying address components in views as separate fields.


How to create and send an HTML formatted eMail using CSS?

With some experience in that field I must say designing 'nice' html mail templates can be difficult – no matter what system you use to actually send your mail. The reason for this is that there are quite many different email clients – from full blown local desktop computer programms to mobile apps on smart phones and feature phones – and a virtally countless number of online services –– all behaving slightly different. Some email clients do accept css3, some don't interprete css at all, some only accept inline css.

So I suppose you probably either have to start digging into that – or use the methods that are rather 'safe' to use as offered by various services and/or modules.


Region not rendering on views page but works perfectly on regular pages!

From the Blocks settings page at admin/structure/block/manage, go to the configuration for the block in question. In the block's "Visibility settings" section, make sure the "Pages" settings are configured in such a way that the block is not hidden from the View page you are having trouble with.


how do I display both a term view and parent terms view on the same taxonomy term page

Please follow the steps to show content of Parent Term on current Term.

Create a view as block
Add relationship as Parent Term
Add contextual filter as Term ID using the relationship and set it like this
Add filter criteria as Taxonomy Vocabulary using the relationship
Add fields whatever you have in taxonomy and use relationship as well

You can also follow the steps in the pics I've created for you.

You don't need to create a new view to show the content of current taxonomy, you can set manage display. Go to admin/structure/taxonomy/TAXONOMYNAME/display

While if you want to display using view, then create another view and follow these steps:

Add contextual filter as Term ID and set it like this
Add fields of the taxonomy you want to show

Note that we won't use any relationship in this view

Now, go to in the block configuration admin/structure/block and enable these.

I hope this will work for you


update order status after order creation

Use conditional actions to achieve this. Conditional actions are part of Ubercart.


How to efficently use Drupal as a laboratory notebook and information management system?

How do you want to organize your information?  I would use a content type such as 'notebook_entry' with a taxonomy 'subjects' and/or 'projects' that allows free tagging of terms.

notebook_entry should use the body field for the bulk of your content.  You can add additional text/image/file fields for storing related information that can be displayed with the content.

I recommend using views to display your notebook entries.  You can create an argument in your page view with the taxonomy term or terms you've defined for the notebook_entry content type.  This will make the page only display entries related to that term.  You'll have to create a menu block filtered by the taxonomy to access your content.  It will list each of the taxonomy terms as links to your page view that displays your notebook_entries.  Create a list of terms and use the global text field to make a link to the path of your page view including the arguments.


Where does location cck module save the data?

As mentioned, the data's stored in the location table, which is handled by the location API and indexed by location ID (lid). The CCK field stores an lid. If you have access to the node object with the field, then you can access the address fields directly from the node object. If you don't have the node object and want to avoid the cost of loading lots of nodes, you can get the CCK DB details using content_fields($field_name, $content_type_name) and content_database_info($field). Then you can use location_load_location($lid) to get the location. I've just taken a quick look at the source for location_load_location() and note that it might do JIT geocoding (so it might actually write as well as read!). I imagine you won't have any issues with doing a join directly on the location table, but I always prefer to use the API where possible.

There's also the command location_load_locations($id, $key) which looks like it can give you all locations associated with a particular nid or vid, but I don't think that's what you're after.


How to assign a CKEditor profile to a specific field?

CKeditor profiles are assigned to text formats (admin/config/content/formats).

Ckeditor is available for "Long text" fields. When editing the field, you have to choose "Filtered text", so, if a Ckeditor profile is assigned to this format, when creating or editing the node, Ckeditor appears.


Your question is not clear but I think you want to know how to set the right access to the different Roles

Go to your_site/admin/people/permissions
Search from the successful store content type
For Role 2 check the "Create new content" and "Delete own content"
Click save at the end of page

Now users of Role 2 can create and delete their own content.

You can also create a link for Role 2 users to access their own content.

Go to your_site/admin/people/permissions
Search from the Access the content overview page
For Role 2 check the box for Role 2
Click save at the end of page
Create a menu item and add the link as admin/content


Adding content to a page through a module

If the content is always static then you can look into adding it to a theme template file (by creating a subtheme).

Or you could add some php as part of preprocess_node in template.php to append/prepend the text to the content/body array.


Your pretty much there but when calling the field name use the method get()

$uri = $paragraph->get('field_image')->entity->getFileUri();

Then once you have the uri you'll be able to get the full url

$url = file_create_url($uri);


How to print node id in a block in a module?

You can get the ID of the current full-page node with menu_get_object:

$node = menu_get_object();
if ($node) {
  // Do something with $node->nid
}


How can I stop Drupal from tracking or collecting IP addresses?

As mentioned in clives comment you could override $_SERVER['REMOTE_ADDR'] in your settings.php to obfuscate incoming visitor IPs. Drupal's ip_address() function than would return your obfuscated IP to any module that attempts to log IPs (like dblog).
Just be aware that any static or random address would conflict with a part of Drupal's flood control mechanism (the part that blocks IPs after too many failed login attempts; default: 50 within one hour). A static IP would expose you to the risk of locking every user out of the system. A random IP would render it useless.
Hashing the IP should work. The module cryptolog seems to to what you want and takes care of the flood control issue. From its project page:

Cryptolog enhances user privacy by logging ephemeral identifiers rather than actual client IP addresses in Drupal's database tables and syslog.
When Cryptolog is enabled, Drupal 8's \Drupal::request()->getClientIP() and Drupal 7's ip_address() output a 128-bit HMAC of the client IP address (in IPv6 notation), using a salt that is stored in memory and regenerated each day.
Because Cryptolog uses the same unique identifier per IP address for a 24-hour period, it is still possible to do some statistical analysis of the logs such as counting unique visitors per day. In addition, unlike other solutions of setting $_SERVER['REMOTE_ADDR'] to either one static IP address or a completely random IP address, Drupal's flood control mechanisms still function as normal.


How to get name, price and image of product using EntityFieldQuery()

You can now load the product using commerce_product_load($product_id); Then you will see price, fields, etc. You could also put all the product_id's in an array, then load them all with commerce_product_load_multiple($product_ids);


If you're creating links, use l().

$url = 'http://example.com/content/' . $current_node['name'];
$output = l($current_node['name'], $url, array('external' => TRUE));


IMCE stops uploading image in the middle of uploading

I cannot find the string "A file with the specified name already exists" anywhere in the source of IMCE 6.x-2.2.

Looks like the same issue was noted here on Drupal.org and was not part of IMCE

I would recommend updating to the newest version of IMCE in the 6 series to see if this fixes the issue. (Currently 6.x-2.3)


There is a module for Drupal 7 for this called Opening Hours and for 8.x there is Office Hours.


how to use function arg() in drupal to call .tpl files?

If I understand it correctly you are looking for a way to render .tpl.php files on certain paths, this article explains how to do it.

In the article they define only one path and show you how to make sure a .tpl.php is rendered. You can easily adjust the code to make it work with 3 different paths and 3 different tpl.php files.

Hope this helps!


I think you'd be better off creating 2 separate forms for each tab, but if you want one form to handle both you can use the function menu_get_item() to determine the menu path that routed to the form.

  $menu_item = menu_get_item();
  if(isset($menu_item['path']) && $menu_item['path'] == 'user/%/Privacy-Statement') {
    //@TODO: Add form elements specific to privacy tab
  }


Overriding permissions selectively via settings.php/settings.local.php

Permissions are clobbered because Drupal uses NestedArray::mergeDeepArray() to merge overrides with existing config.

For example, if we have this permissions

$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  - 'access content'
  - 'access comments'

and then add

$config['user.role.anonymous']['permissions'][] = 'use browsersync';

to settings.php, the result will be

$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  - 'use browsersync'
  - 'access comments'

An easy way to workaround this would be

$config['user.role.anonymous']['permissions'][9999] = 'use browsersync';

which will result in

$ drush cget user.role.anonymous permissions
'user.role.anonymous:permissions':
  0:'access content'
  1:'access comments'
  9999: 'use browsersync'

But if you need to remove a permission via settings.php, then I honestly don't know how to do it, even with module config overrides system (which has an ability to load original config before providing the override). Maybe overriding the unwanted permission with NULL may work, but I haven't tried.


How can I programmatically create products via REST?

This might need to work around as below

['field_store']['und']['#options'] = Store_array


Missing five core module folders and one enabler

The field submodules are inside the field module folder:

./modules/field/modules/number/number.module
./modules/field/modules/list/list.module
./modules/field/modules/text/text.module
./modules/field/modules/field_sql_storage/field_sql_storage.module
./modules/field/modules/options/options.module

The D7 module overview is at admin/modules. admin/build/modules was in Drupal 6; a lot of the community docs pages are badly outdated, unfortunately.

Finally, the Profile module is deprecated in Drupal 7, and therefore hidden by default.

modules/profile/profile.info:

; The Profile module is deprecated, and included in Drupal 7 for legacy
; purposes only. By default, the module will be hidden from the UI unless you
; are upgrading a site that uses the Profile module to extend user profiles.
; See user_system_info_alter().
hidden = TRUE

It's only there to provide an upgrade path for D6 sites; it can't be enabled on a new D7 site without commenting out that line.

(The reason the module is deprecated is probably that the Fields API has taken over what it used to do, so it's obsolete.)


That sounds like fun.

First, a question: In your example, do you mean that the source page is /blue-work, and you're clicking a link on /blue-work to go to node-1? And you want the destination URL to become /blue-work/node-1 ?

If so, that sounds difficult b/c you'd have an open-ended number of different paths and you'd be telling Drupal to behave differently, paying attention to the tail only (and how is Drupal to know what, exactly, is the tail?). I think it would still be possible, though.

Instead, you could go with what currently works: if you click a link on /source-page to go to /destination-page, then this URL works: /source-page/destination-page.  However, I'd sooner use: /source-page?context=destination-page.

Regardless, you might start with hook_page_alter so you can edit all the links on the source page before it's rendered, adding the source page's url to (the end of) the links.

Then, of course, you're going to have to check the requested URL to get the 'source-page' context and apply it. Perhaps with hook_page_alter again.


I've used the Webform module for this situation in the past.   Just create a name and email component!

  Webform is the module for making surveys in Drupal. After a submission, users may be sent an e-mail "receipt" as well as sending a notification to administrators. Results can be exported into Excel or other spreadsheet applications. Webform also provides some basic statistical review and has and extensive API for expanding its features.


Commerce product fields as optional attributes

You probably want to group products that a similar into the same product types and setup different product types, instead of having a single multipurpose product type that can be turned into anything. The product creator can decide which fields to use by choosing which product type to use. A distinction that will come very naturally for non technical people.


How can one module's template file be overriden by another module?

Rather than outright overriding the theme item implementation (via your hook_theme()), you could use hook_theme_registry_alter() to add your preprocessing function to the theme item.


What causes very long initial visit load times intermittently?

If users experience very long response time for initial visit, but then next visits are fast - then it definitely could be related to the cron (as suggested by Geoff).

Here is a quote from official cron documentation:

  It [internal cron] works by checking at the end of each Drupal request to see when cron last ran and, if it has been too long, processing the cron tasks as part of that request. The two down-sides are (1) cron tasks will only run when Drupal is processing requests; and (2) the 'weight' (processing and memory) of running the cron tasks will be added to some arbitrary unknown page request, which may slow down those requests, and has the potential to exceed memory limits on a complex site.

To prevent this, configure external cron job that will trigger Drupal cron jobs more often that 3 hours (my suggestion is to run external cron every hour).

In addition you can configure internal cron to run less often by configuring it here /admin/config/system/cron.


Altering a form to set it's target to _parent

to change your form you can use hook_form_alter
example

function login_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id=="user_login_block")
    {
         $items[] = '<a id="fpassword" target="_parent" title ="'.t('Request new password via e-mail.').'" href="#">'.t('Request new password').'<a>';
         $form['links'] = array('#markup' => theme('item_list', array('items' => $items)));
    }
}


How to show custom user profile fields in a view?

I fail to understand why anyone would use Profile2 (or Content profile) when users in Drupal 7 are fieldable.

From what I understand from the Profile 2 project page, it utilizes Entity API; you may need to use EntityFieldQuery Views Backend.


Facets: Show more and Show less functionality

Answer:You can select the visible items of the facet on the facet display.
E.g. you can select 3 items to be visible.If the facets items are more than 3,by default will appear a Show more/Show less functionality for the facet.
Hope this is clear.
thanks


Alter a Views query to use "OR" through the user interface

In Drupal 7 (Views 3), it's pretty simple, for regular filters at least:

For regular Filters, open the 'rearrange' (or "and/or, rearrange") window by clicking on the arrow next to 'Add'. From here it's simple and self-explanatory - you put your filters into Filter Groups, and can set each filter group to be 'OR' or 'AND'.
For Contextual Filters, it's a little bit stranger and is currently undergoing development work. Keep an eye on this issue: Document that contextual filters are included in the first 'and/or' filter group . As the title of that link suggests, all your contextual filters are treated as being part of whatever your first Filter Group is, so make sure there is at least one, and edit that as above.

There's talk in that issue of changing this to something more flexible (watch above link), but that'll take time.

(note - talking about contextual filters is relevant to this question because someone closed a question about setting 'OR' on contextual filters as a duplicate and pointed it to this one)

-----UPDATE-----------

That issue closed with just a documentation change, here's a couple of relevant ongoing issues to follow...

Using OR in filters breaks contextual filters
Views AND/OR Contextual filters two ways


How can I consistently see the "renderable" version of a views field?

Use advancedRender(), this is a method in the base class of views fields, which renders an entity field respecting field rewrites and other settings:

$value = $field->advancedRender($row);


No, you should not call any mysql functions at all. You don't mention the drupal version, but in 6, it's likely that you're actually using the mysqli extension and in 7, you're using PDO.

I don't think that a handful open database connections is going to be a problem, they will be automatically closed by the end of the request. So unless you have a long-running process or more than a handful connections you need to make, I wouldn't worry.

If you have either of those, then you might need to care about this, if you're on 7.x, there's an API for this: Database::closeConnection().

On 6.x, you're not so lucky, while you could check global $db_type (see db_set_active()), and call the right function, you also need to pass global $active_db to the function to close the right connection and you can't update $db_conns in db_set_active(), so that will not know that you closed the connection and you can't re-open the connection again.


"drush sapi-i" command which calls drush_backend_batch_process() fails with "Output is empty"

After checking the vendor/bin directory I noticed that the drush script exists but drush.bat or drush.cmd were missing, I mean, for some reason even though I executed the drush sapi-i command using Git-bash, Drupal was still trying to access the Windows type of the file (which didn't exist in the source I copied from Mac).
so creating the below file manually fixed the issue.

drush.cmd file:

@echo off
setlocal DISABLEDELAYEDEXPANSION
php "%~dp0../drush/drush/drush" %*

drush file:

#!/usr/bin/env sh

dir=$(cd "${0%[/\\]*}" > /dev/null; cd '../drush/drush' && pwd)

if [ -d /proc/cygdrive ]; then
    case $(which php) in
        $(readlink -n /proc/cygdrive)/*)
            # We are in Cygwin using Windows php, so the path must be translated
            dir=$(cygpath -m "$dir");
            ;;
    esac
fi

"${dir}/drush" "$@"

Note that the drush script's line ending should be LF (instead of CRLF which drush.cmd needs),
so in Git-bash simply cd to where your script is and run sed -i 's/\r$//' my-script-filename (if your editor can only save with CRLF).


How to include PHP code in welcome email?

Updated :

Use PHP mailer module to send the email in the format of php


Using getThirdPartySetting() to get node type configurations in other hooks

$bundle is the node type (ID), so you can load the node type based on that.

$node_type = \Drupal\node\Entity\NodeType::load($bundle);


Backup and Migrate module - no option to back up files?

There was a module which did this earlier, Backup Migrate Files, but it got obsolete and the code is not merged with Backup Migrate module, and is available with version 7.x-3.0
Make sure you use the latest version of the module.


How to resolve error "Failed to load MailChimp PHP library. Please refer to the installation requirements."?

Here are some steps to troubleshoot this error according to this thread: Issue #2054037 Failed to load MailChimp PHP library. Please refer to the installation requirements. (provided by @rtome, above)

Re-read the instructions in MailChimp module's README.txt
Clear the cache
Ensure Libraries module is installed and is working properly
Ensure Mailchimp library is located at sites/all/libraries/mailchimp
Check your versions:

  MailChimp module 7.x-2.x requires MailChimp library 1.3
  MailChimp module > 7.x-3.x requires MailChimp library 2.04

If MailChimp library updated, reinstall MailChimp module


$this->options and #options of the select element are two different things.

See the separator field of NumericField::buildOptionsForm:

$form['separator'] = [
  '#type' => 'select',
  '#title' => $this->t('Thousands marker'),
  '#options' => [
    '' => $this->t('- None -'),
    ',' => $this->t('Comma'),
    ' ' => $this->t('Space'),
    '.' => $this->t('Decimal'),
    '\'' => $this->t('Apostrophe'),
  ],
  '#default_value' => $this->options['separator'],
  '#description' => $this->t('What single character to use as the thousands separator.'),
  '#size' => 2,
];


How to create node and reference it in Drupal 7?

http://drupal.org/project/noderefcreate

This one is available for D7, and allows you to create & reference nodes within the create / edit form for another node type. Unlike the popups_reference module, it will only allow you to create the extra nodes with titles (no other fields). You could, however, use this and then write a small custom module that uses hook_form_alter() to redirect the user to the edit forms for newly-created nodes to enter the rest of the information.

Not as nice as popups_reference, but it should work.


How to affect kernel request hostname when bootstrapping from custom PHP script

You need to use the HTTP_HOST instead the SERVER_NAME, also you can pass it as $server param to the Request::create()

$autoloader = require_once 'web/autoload.php';
$request = Request::create('/', 'GET', [], [], [], ["HTTP_HOST" => 'whatever']);
$this->kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$this->kernel->boot();
$this->kernel->prepareLegacyRequest($request);

Remember to add the hostname to $settings['trusted_host_patterns']


How to add delete link to recent comments block?

You can override the theme_comment_block(): You can find a good tutorial here: http://www.webomelette.com/theming-comment-block-drupal-7

I instead liked to just replicate the functionality in a Views block, and then styled the block to look the same way. I felt it gave me more control, and I try to avoid hacking up core blocks.


I don't know if there is any shortcut to put the article into Block, but usually I use Views for that. After installing Views Module

create new Views and select content of type Article
Check on Create a Block and Continue and Edit
In Fields, Select the fields you want to display eg: Article Title, Description, etc.
Use the Filter to filter results.

If you want to display only the latest Article, then use Sort by Post Date Desc and in Pager settings display max items to 1 with No Pagination option.

Go to Structure->Blocks and select your theme and you can enable/disable what blocks you want to display and where. If you are unsure about the regions in theme then click Demonstrate Block Regions

This looks one heck of a task, but playing around Views would make you more comfortable with Drupal.


What's the difference between creating a 'Content' or a new 'Pages>>Add Custom Page'?

Structure -> Pages menu link comes from ctools and it allows you to create more complex pages than your basic drupal core ones (Content -> Add Content link). This may include components comming from other modules (Panels, Fieldable Panel Panes, Views Content Panes and many other that intergrate with Ctools).

With Page Manager (and panels in general) you can create more complex versions of a page (or more, if you use the right contexts).


How Webprofiler EntityManagerWrapper overrides EntityTypeManager?

Yes, the module fullcalendar_view is probably asking for the wrong requirement. Services which implement an interface are supposed to be swappable with services implementing the same interface. So if the module has no reason to check for this specific class it should check for the interface EntityTypeManagerInterface instead.


How to combine multiple view result sets, limiting the combined result set

Here's what I ended up doing (not using views). I'm using Panels on this site, and my default view for this content-type is controlled via Panelizer. Since I couldn't find a way to do this with Views, I created a custom panels pane (code below).

Basically, this pane accepts one setting: the number of related events to display. The render callback counts the editor-defined related nodes, and grabs more (if needed) based on shared terms.

<?php

$plugin = array(
'single' => TRUE,
'title' => t('Suggested Events'),
'description' => t('Combines curated suggested events with those related by category.'),
'category' => t('Custom Panes'),
'edit form' => 'MYMODULE_suggested_events_edit_form',
'render callback' => 'MYMODULE_suggested_events_render',
'admin info' => 'MYMODULE_suggested_events_info',
'defaults' => array(
  'events_to_show' => 4
),
'all contexts' => TRUE,
);

/**
 * Edit Form.
 */
function MYMODULE_suggested_events_edit_form($form, &$form_state) {
$conf = $form_state['conf'];

$form['events_to_show'] = array(
  '#title' => t('Number of events to show'),
  '#description' => t('Used to control the number of suggested events shown. Defaults to 4.'),
  '#type' => 'select',
  '#options' => drupal_map_assoc(range(3, 6)),
  '#default_value' => $conf['events_to_show'],
  '#required' => TRUE,
);

return $form;
}

/**
 * Submit callback for settings form.
 */
function MYMODULE_suggested_events_edit_form_submit($form, &$form_state) {

foreach (array_keys($form_state['plugin']['defaults']) as $key) {
  if (isset($form_state['values'][$key])) {
    $form_state['conf'][$key] = $form_state['values'][$key];
  }
}
}

/**
 * Run-time rendering of the content
 */
function MYMODULE_suggested_events_render($subtype, $conf, $args, $contexts) {

  if (isset($contexts['panelizer'])) {
    $nid = $contexts['panelizer']->data->nid;
  } else {
    return false;
  }

  // Grab the Category Term IDs from referenced node.
  $node = node_load($nid);
  $categoryField = field_get_items('node', $node, 'field_category');
  $categoryTIDs = array_column($categoryField, 'tid');

  // suggestedEvents are the events which are selected by the editor.
  $suggestedEventsField = field_get_items('node', $node, 'field_event_suggested');

  if (empty($suggestedEventsField)) {
    $suggestedEvents = array();
  } else {
    $suggestedEventsNIDs = array_column($suggestedEventsField, 'target_id');
    $suggestedEvents = entity_load('node', $suggestedEventsNIDs ); // @returns array of entities
  }

  // determine how many events we need to find
  // based upon the total to display and how many are site-editor-defined
  $relatedEvents = array();
  $relatedEventsCount = 0;
  if (count($suggestedEvents) < $conf['events_to_show']) {
    $relatedEventsCount = $conf['events_to_show'] - count($suggestedEvents);
  }

  if ($relatedEventsCount > 0) {
    // Query for other events that share the referenced categories.
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'event')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->propertyCondition('nid', $nid, '<>')
      ->fieldCondition('field_category', 'tid', $categoryTIDs, 'IN')
      ->fieldCondition('field_datetime', 'value', date('Y-m-d').'00:00:00', '>=', 0)
      ->range(0, $relatedEventsCount)
      // Run the query as user 1.
      ->addMetaData('account', user_load(1));

    $result = $query->execute();
    if (isset($result['node'])) {
      $relatedEventsNIDs = array_keys($result['node']);
      $relatedEvents = entity_load('node', $relatedEventsNIDs);
    }
  }

  $events = array_merge($suggestedEvents, $relatedEvents);

  $block = new stdClass();
  $block->title = 'You may also enjoy...';
  $block->content = '';
  if (!empty($events)) {
    $block->content .= '
';
    $eventsRenderArray = entity_view('node', $events, 'showcase_card');
    $block->content .= render( $eventsRenderArray );
    $block->content .= '
';

    return $block;
  } else {
    return false;
  }

}

/**
 * Admin info.
 */
function MYMODULE_suggested_events_info($subtype, $conf, $contexts) {
if (!empty($conf)) {
  $block = new stdClass;
  $block->title = $conf['override_title'] ? $conf['override_title_text'] : '';
  $block->content = t('Show @events_to_show suggested events.', array(
    '@events_to_show' => $conf['events_to_show']
  ));

  return $block;
}
}


Node ID and node title in panels page URL

Don't try to change the url with panel page manager:

The path pattern is a way to target some page by there route.

1 - If you want to modify the url pattern, use instead the  Pathauto pattern tool with Token. ex: /[node:title].

Once you build your pattern, it will create some alias every time you create a node, but the internal url is still /node/%node, so you have to use this one to target the nodes pages in the panel configuration.

2- Then, if you need to use the node title in a  panel region, you can create a block view with title, and add a the contextual filter on the ID field, by taking is value frome the url.
https://duckduckgo.com/?q=drupal+8+add+contextual+filter&ia=web

3- If you build a pattern like in 1 - with pathauto and token - the resulting alias will be a transliteration of the node title.


How to display products without selling them (or using the typical ecommerce modules)?

The easiest way to achieve this without using "commerce" modules are taxonomy and vocabularies, using the Entity Reference Module.

A  simple workflow to achieve this would be:

1).Create the corresponding Vocabulary with the desired term structure from admin/structure/taxonomy/add, for example:

Wine

Red

Brand #1  etc.

2). Create The Content Type with the desired Fields

3). In the content type, add an "Entity Reference" Field, assigning it to the vocabulary

4). Create your products (Add content)

5). Create Views to customize the display of each page depending on the term level (using filters)


How to show in different positions exposed filters in a View?

Another way to do this is using Panels or cTools Page Manager (comes with cTools, you'll find the Page Manager UI under Structure > Pages in D7). It takes a bit of learning but, like Views, it's very powerful and once you're used to it you won't want to go back. Here's the basic step by step:

Give your view a Context view display. A "Context view" is a type of View Display like a "View block" or a "View page" or an "Attachment view" etc. Create one with the "Add" button at the top of the View edit page.
Load it as a Context in Panels or Page Manager. These are systems for placing content that you can think of as like a smarter, more powerful version of Drupal's Blocks system. The thing that is special about Context views, is that systems built on cTools contexts (like Panels and Page Manager) can load the view early on in the process, analyse it so they know what types of data to expect, and do smart things with that fine-grained data. In the Contexts page for your Page Manager page or Panel, add a context, choose Views, then find the right view.
Choose a layout on the Layouts page. In your case, a "2-column layout" should allow you to create the exact layout you are looking.
Place each part of the view as Content. Because cTools is loading the View as a context, and because cTools knows what Views are and how to make sense of them, it knows exactly what elements of the view it's going to get (unlike a Views block where it can only dump down the whole rendered block as one unit). When you go to Content in the Panels / Page Manager interface, you'll find a 'Views Context' vertical tab with various bits of your view in it, including th exposed flters. You can place each of these anywhere in your view (multiple times if needed), and configure them where appropriate. Some things this allows you to do:

(as per the question) Place each individual exposed filter anywhere you want on the page, seperate to the 'View row' option which contains the View results. For your layout, if you chose a 2-column layout, you can add three exposed filters using the cog icon on the left column, add the fourth to the right column, then add "View row" (no limit or offset in settings page) to get the results of the view. All this is editable: you can drag and drop, disable and enable, edit, add CSS classes, etc
Place the Header or Footer of a view anywhere on the page seperate to the View content
Build sophisticated grids with your Views content, placing the Views Row content type lots of times with different limits and offsets. For example, you can have a column showing the first row with custom classes making it highlighted, then a column showing rows 2-5, then alongside that column a column showing rows 6-10...


Unable to load class \Drush\VersionControl\Backup

I am running the composer provided drush Drush Version : 8.1.15

Drupal 8.4 requires Drush 9, so upgrade your Drush for starters.

composer global require drush/drush:master

  http://docs.drush.org/en/master/install/


How to redirect an anonymous user to the login form after a 403 error?

I've seen that this question was never answered how to do this programmatically. The code actually does work, when placed in an Exception Subscriber:

/src/EventSubscriber/RedirectOn403Subscriber.php:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;

class RedirectOn403Subscriber extends HttpExceptionSubscriberBase {

  protected $currentUser;

  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  protected function getHandledFormats() {
    return ['html'];
  }

  public function on403(GetResponseForExceptionEvent $event) {
    $request = $event->getRequest();
    $is_anonymous = $this->currentUser->isAnonymous();
    $route_name = $request->attributes->get('_route');
    $is_not_login = $route_name != 'user.login';
    if ($is_anonymous && $is_not_login) {
      $query = $request->query->all();
      $query['destination'] = Url::fromRoute('<current>')->toString();
      $login_uri = Url::fromRoute('user.login', [], ['query' => $query])->toString();
      $returnResponse = new RedirectResponse($login_uri);
      $event->setResponse($returnResponse);
    }
  }

}

mymodule.services.yml:

services:
  mymodule.exception403.subscriber:
    class: Drupal\mymodule\EventSubscriber\RedirectOn403Subscriber
    tags:
      - { name: event_subscriber }
    arguments: ['@current_user']


VBO Custom Operation to create pdf of selected nodes detail page

You can achieve this using rules. Import following component & add Rule component in Views bulk operation list as shown in figure below:

{ "rules_create_pdf" : {
    "LABEL" : "Create PDF",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "ACTION SET" : [
      { "php_eval" : { "code" : "$view = node_view($node, \u0027PDF\u0027);\r\n$html = drupal_render($view);\r\npdf_using_mpdf_library_exist();\r\n_pdf_using_mpdf_generator($html, \u0027node-\u0027.$node-\u003Enid);" } }
    ]
  }
}

In order to save PDF files at server use above Rule component & comment two line given below in pdf_using_mpdf.module of function _pdf_using_mpdf_generator. You can find that on line no. 324 & 325 of pdf_using_mpdf 7.x-2.6.

//drupal_goto($_SERVER['HTTP_REFERER']);
//exit;

Figure:


One solution here is is to use template_preprocess_field function. In your template.php add a MYTHEME_preprocess_field function and perform a check on the node's field value to determine a class that you set in the classes_array variable.

function MYTHEME_preprocess_field(&$variables) {
  $node = menu_get_object();

  //Add a new CSS class to field_MYHIDDEN_FIELD
  if($variables['element']['#field_name'] == 'field_MYHIDDEN_FIELD') {

    //Check field_MYCHECKED_FIELD for an empty value
    $new_class = (!isset($node->field_MYCHECKED_FIELD[LANGUAGE_NONE][0]['value'])) ? 'mytheme-field-novalue' : 'mytheme-field-value';
    $variables['classes_array'][] = $new_class;
  }
}


You won't be able to use HTML markup within the label inputs within the Webform module itself, as it most likely cleans out all HTML markup before displaying to the user to prevent XSS attacks etc.

Most likely you'll need to write a small custom module which implements hook_form_alter, which will allow you to change the markup used for the labels.

I'm not actually sure if Drupal will allow markup within the #title attribute of your form elements, so you might need to use the #prefix property instead to add your custom HTML replacement labels.

If this is all Greek to you then you'll probably need to checkout these tutorials:

Creating modules - a tutorial: Drupal 7.x

Hook snippets: hook_form_alter


Exposed Filters View is not functional with Anonymous Users

I got it.

I had LDAP module enabled and that was de-authorizing the access. Had to deactivate it.

Thanks a lot guys.


How can I include radiobuttons to a view's results?

Is it very important to you to have radio buttons exactly like you describe? If not, I can recommend the Views Bulk Operations (VBO) module. VBO is a popular module which allows you to select views rows and perform a certain action on those rows. Each row gets a checkbox and you select the action to be performed with those rows using a select box. Here is a screenshot to illustrate that:

I think VBO is by far the most mature option available to solve your problem. If you insist on having the radio buttons in your view and you don't mind writing code yourself, have a look at Views Form Field (interesting, but no releases yet), or Create the "View as form" style (work-in-progress in the Views issue queue).


change comment form container to textarea

You can make the field plain text in the comment body field settings.

e.g:

http://example.com/admin/structure/types/manage/article/comment/fields/comment_body

  "Text processing" > "Plain text"


Its possible that there is an issue with ImageMagick.

Check your Drupal status report. Does it show any issues? Check the Image Toolkit page at admin/config/media/image-toolkit. Does it show any issues?
Check your PHP error log. More detail or a stacktrace may have been logged there.


Pass a value from a block preprocess hook to a twig template that inserts that block

After a lot more digging and trying things without success, I ended up solving the problem of passing a value from a block's preprocess hook to a twig template where the block is inserted as per my third option above. Here's what I did:

Follow the instructions at http://www.tothenew.com/blog/overview-of-twig-extentions-in-drupal-8 to create a twig extension. This wasn't very difficult, especially since I had already created a custom module. I just had to create a MYMODULE.services.yml file and a TwigExtension.php file as instructed.
In the twig extension file, create functions setTwigValue($name, $value) and getTwigValue($name) using the php $GLOBALS array for storage. Again, the above-mentioned instructions made this pretty easy.
In the preprocess_book_tree hook, count the number of feature articles and then save the count by calling

Drupal\MYMODULE\TwigExtension::setTwigValue('feature_count', $feature_count);
In the node--magazine.html.twig template, get the saved value using

{% set feature_count = getTwigValue('feature_count') %}

I'm happy to learn of better/safer ways to accomplish what I've done. But at least it works and it's pretty clean.


How to hide node webform programatically?

Try implementing hook_node_view.Then you can put your condition on $node->type, access the webform with $node->webform and use $view_mode to load the current view mode.