Fatal Error HtmlRouteProvider not found?

Unless you’re doing something custom, your classes need to be under ./src to be discovered. By default, MODULE/src/Foo.php is mapped to the Drupal\MODULE\Foo namespace and so on.

Move the two classes out of the root of your module and into ./src, clear cache, and try again.

See PSR4 namespaces and autoloading in Drupal 8 for full details.


Price by multiple attributes in Commerce

It will probably have to be done with custom Rules.  If the price is calculated predictably via different measurements/attributes, you can use the Rules Event of Calculating Sell Price of Product.  Conditions could vary, but a custom Action or Action set is probably going to be needed to calculate the price, and then set the price to the calculated value.

Maybe check out this link for an example of dynamically changing product prices.

http://www.drupalwoo.com/content/blog/drupal-commerce-and-rules-changing-product-price-dynamically


Can I use the Rules module to send mass emails to authors of selected nodes?

If you want to use rules for that, you would have to create your own event: when you add a CCK field. You would then have to write some code to trigger then event when a new CCK field is added, and supply rules with the nodes of that type or whatever data you would need in your rule.

My guess is that the amount of custom coding needed for this to work, would be more than what is needed to just do this yourself in a custom module, with hook_mail. Also you might have problems configuring the rule to do what you need. I haven't tried using an array of data types in rules, so that might make things more complicated for you as well.


I think, content in contact messages is the user input. Then you cannot translate this, because it is not saved to the database. The form itself is config translation, similar to the field definitions in content types.


For webform: Use insert block module as well.
Structure --> block --> Click configure one of the webform you want to add.--> look at the URL

Example: http://localhost/example.com/#overlay=admin/structure/block/manage/webform/client-block-5/configure

Type this "[block:webform=client-block-5]"


It can be done by implementing custom menu callback

/**
 * Implementation of hook_menu()
 */
 function mymodule_menu() {
   $items['media/view/%file'] = array(
     'page callback' => 'mymodule_download_file',
     'page arguments' => array(2),
     'access arguments' => array('access content'),
     'type' => MENU_CALLBACK,
   );
   return $items;
}

/**
 * Page callback for a file to download
 */
 function mymodule_download_file($file) {
   if($file) {
    file_transfer($file->uri, array('Content-disposition', 'attachment; filename='.$file->filename));
   }
   else {
    return drupal_access_denied();
   }
 }


Can I create two sites with a single user login?

The mechanism which you are talking about called SSO (Single Sign On). There are modules in Drupal to achieve SSO but it would depend upon your site setup like whether 2nd site is sub-domain of the first or both are sub-domain of some other etc..

In case one of them second level domain then you can use Bakery. I have used it successfully.

I have heard so much about CAS module too though never used it. You can go through the documentation of the module and find out whether it fulfil your need or not.

You can have a look here on comparison between all SSO modules available in Drupal.

Regarding auto update, I am not sure it can be done easily with any of them. You will have to write your own code maybe.


How do I pass JavaScript variables back to PHP?

Where you implemented hook_menu(), in Drupal 8 you need:

A .routing.yml file containing the routing definition

example.name:
  path: '/example/{variable}'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::content'
  requirements:
    _permission: 'access content'

A controller class for the page callback

class ExampleController {
  // ...
  public function content($variable) {
    // Do something with $variable.
  }
}

What is important is the file structure, which should be as follows, assuming that example is the machine name of the module.

example
The directory containing the module

example.routing.yml
src
The directory containing all the classes

Controller (directory)

ExampleController.php
The file containing the controller

Keep in mind that you can change the machine name of the module, the route name (example.name), and the name of the class implementing the controller (ExampleController); the ones I used are only examples.


First of all I want to point you to the AJAX Example module. This has some neat examples on how to use it.

For your task what you basically need is the following:

Replace normal submit handler by custom submit handler
Add an AJAX callback and wrapper to your submit button
Do your database queries in the submit handler, force rebuilding the form and define the message.
Replace the submit button of your form with a new one and show the message.

I cannot test the following code right now but it should basically give you the idea:

<?php

function MY_MODULE_form($form, &$form_state) {
  // some form elements

  $form['submit'] = array(
    '#type' => 'submit',
    '#submit' => array('MY_MODULE_form_custom_submit'), // define custom submit handler
    '#value' => t('Submit'),
    '#ajax' => array(
      'callback' => 'MY_MODULE_form_callback', // define ajax callback to show the message
      'wrapper' => 'my-submit-button', // define what div should be replaced
    ),
    '#prefix' => '
', // wrap this button in the div that is replaced
    '#suffix' => '
',
  );
}

function MY_MODULE_form_custom_submit($form, &$form_state) {
  // do your db query
  drupal_set_message(t('Something has been done!')); // your message

  $form_state['rebuild'] = true; // rebuild the form. not sure if this is required now.
}

function MY_MODULE_form_callback($form, &$form_state) {
  return $form['submit'];
}

?>

Hope this helps. If the code does not work as it should let me know and I will test it asap.

cheers,
j


View mode template for user-profile.tpl.php?

You already figured out how to create an additional view mode for the user entity:

/**
 * Implements hook entity info alter
 * Adds additional view mode for user entity
 */
function MYCUSTOMMODULE_entity_info_alter(&$entity_info) {
  $entity_info['user']['view modes']['teaser'] = array(
      'label' => t('Teaser'),
      'custom settings' => TRUE,
  );
}

Now you can define theme suggestions for that view mode using HOOK_preprocess_user_profile:

/**
* Implements HOOK_preprocess_user_profile()
* Adds theme suggestions for the user view mode teaser
*/
function MYCUSTOMMODULE_preprocess_user_profile(&$vars) {
  if ($vars['elements']['#view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'user_profile__teaser';
  }

After clearing the caches Drupal will search in the theme folder for a file called user-profile--teaser.tpl.php, which could look like this example*:

  <?php print render($user_profile['field_last_name'][0]); ?>

<?php print render($user_profile['field_user_picture'][0]); ?>

    <?php print render($user_profile['field_biography']); ?>
    <?php print render($user_profile['field_birthdate']); ?>
    <?php print render($user_profile['field_nationality']); ?>

(* actual code will depend on the fields you defined for the user profile)


Render simple php function in twig template

Would suggest doing a pre-process function and stuff in the variables everything the template needs to render. The point of Twig is to push the logic back to the PHP side so that your template does not look like "HTML-in-PHP" or "PHP-in-HTML" (whichever way you look at it) as with previous versions of Drupal.


How to redirect on node save to fill out extra fields attached to terms

I've found there's a new module called Entity Connect which adds a button to entity reference fields for creating new references on the fly.  The module sends the user to the entity creation page (add term, etc) allowing you to fill out all necessary fields, then redirects back to the original node form.

This works great.  Now the only thing necessary now for my use case is to figure out how to programmatically add taxonomy terms based on the value(s) of the entity reference field.


How to hide menu item from high level roles but show for low level

As per the discussion above,

Remove 'access callback' => 'learning_access', add drupal_access_denied() in page call back

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

  $items['learning'] = array(
    'page callback' => 'learning_output',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function learning_output() {
  global $user;

  $n = count($user->roles);
  if ($n === 1) {
    $data = array_values($user->roles);
    if ($data[0] === 'authenticated user') {
      drupal_access_denied();
    } else {
      //YOUR code Here
    }
  }
}

And Use Roles for Menu module to hide the learning menu.

  This module allows you to restrict access to menu items based on user
  roles. It is used when you don't want to copy your whole menu just
  because for one specific role you want to hide one menu item.

  The module will add a fieldset with options for restricting access or
  gaining access to menu link for a specific role/roles


Grouping nodes by common CCK values in views

Yes it is possible: On your view you have filters, you can filter results by A, then another view with all the results of B; then, if you want these both in a single page I'd suggest a Panels page.


use "php code" in page manager access rules to evaluate if current og_group has content of a specific type

Direct answer: To do this with the code you provided, you should use something like the following:

$node = $contexts['argument_entity_id:node_1']->data;
$args = array($node->nid);
return empty(views_get_view_result('rbv_view_group_content','panel_pane_3',$args));

Alternative answer: I have an alternative suggestion, and unless you absolutely want to use the Page Manager, it should allow you to solve your problem without any coding.

So, if you read so far... :-), I would suggest using Views and setting up a path that will 'link' your view to your group node's URL. You are probably already using a view to list your Events. You can set up a page for that view that has a path like the following:

node/%nid/events

You should further configure your page to be rendered as a "Menu Tab", titled "Events".

This Views Page will now be linked to your Group page, and you will be able to handle its behaviour in the case of no results (Events) for that og_group node; for your case to simply hide it.

To get this all working, you would also need to set up your contextual filters to use the og_group nid.

This is a bit theoretical, but I am not entirely sure of your setup.
I hope it helps you though!


How to create a separate web page menu to be used only on one of my web pages?

Add a new menu to the site.

Go to Structure > Menus > Add Menu

Once you have added a menu, and the links, this menu will now be available as a block.

Go to Structure > Blocks and assign the new menu to a region.

under that block settings, you can define which URL you would like the block to display on. Set that to the URL of your page, and you're good to go.


Having some conceptual trouble creating a View to list users that have nodes containing entity references

Got around my mental block.

Created a 'Users' view.
Added an 'Entity Reference: Referenced Entity' relationship.
Turned on aggregation for my view
Added the field I wanted to count and selected COUNT (distinct)

Working well now.

Danny.


Reinstalling Drush for Windows fix this problem.


Edit your cart view and under Advanced, Theming: Information, click on Information and you will see this:

For template file name you want to use the last suggested name, (which I underlined for you) that way it only affects this specific view and not others.

Now that you have a name, click on the blue link and copy all the code in there and paste it into your template file and modify as you wish.

Remember to flush the cache to see changes or you could click the Rescan template files button


Drupal Hooks are a call back mechanism, you name your function modulename_Hook like mymodule_form_alter(). Based on the name of the function, it is called in the proper phase of the Drupal execution. This is an entry point from Drupal into your module.

Using Drupal Hooks doesn't change that much from version to version, the hooks that are available do change from version to version. The old tutorials are still good. The best way to learn how to use hooks is to examine existing contributed modules, or that's what worked for me. Hooks you really need to learn, or that you should start with are the FORM API hooks hook_form_alter, hook_form, hook_form_validate (https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_form_submit/7), ..., hook_menu is generally needed if you're adding a page to the website.

If you can get a copy of "Pro Drupal Development" or "Pro Drupal 7 Development" (http://www.drupalbook.com/ or http://www.amazon.com/Drupal-Development-Experts-Voice-Source/dp/1430228385) it might help as well. Go with the pdf downloads. There are also 2 or 3 day classes you can take, or you can get training at your local Drupal Camp or Drupal convention.


How to:Pass arguments to views and use that as contextual filter-in code

Contextual filters are passed not like $_GET parameters but like part of an url (by $_GET parameters exposed filters are sent).
if you want send several values for one contextual filter - you need to separate them with comma or plus.

For example you have view with url '/product' and 2 contextual filters - 1st filter is product ids, and second one is country id.
The url of a view can look like this 'product/12,45/55'
In this example view will take 12 and 45 as product id and 55 as country id.


It seems like I have to provide a custom Element class in the module\Element folder to define the custom input elements for the form rendering.

See \Drupal\Core\Render\Element\Textfield.


How to remove a help text from the registration form?

I figured it out:

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

  if (!($form_id == 'user_register_form')) {
        return;
  }

  $form['account']['name']['#description'] = 'Username has to be between 5-20 characters long and can only contain letters and numbers.';
}


You can't do that. You can see node and file template. Unless, in your theme you set

base theme: stable

or when you don't define a base theme.


Rules action components do not have conditions, but you can also add a component that is a rule itself, not an action set, and then schedule that.  Then you can just add the condition node: has type and then do set a data value however you like.


Create role for changing user accounts and not admins

This module might be what your looking for. http://drupal.org/project/administerusersbyrole

With it you will get permissions for any role to change any other role. Here is a screen shot of it in action on the permissions page.


What is the name of the table where view modes are stored?

View modes are stored in the configuration entity entity_view_mode which you can load like any other entity:

$view_mode = \Drupal::entityTypeManager()
  ->getStorage('entity_view_mode')
  ->load('node.teaser');

To load all view modes for the entity type node:

$view_modes = \Drupal::entityTypeManager()
  ->getStorage('entity_view_mode')
  ->loadByProperties(['targetEntityType' => 'node']);

View modes don't store much data other than a label for the view mode name.

How a view mode is displayed for a specific content type is stored in a different entity:

$display = \Drupal::entityTypeManager()
  ->getStorage('entity_view_display')
  ->load('node.article.teaser');

The usage depends on how you define what being used means. If you mean with not used that it is not configured in a content type, which you can query in the config entities mentioned before, this doesn't mean necessarily, that the view mode is not used anywhere. If you configure an entity to be displayed in a view mode, for example in a View or a entity reference field, and this view mode is not configured in the content type, then it fallbacks to the default view mode.


Module Rules-> PHP Code, trying to use a Form Handler from Pardot, but Pardot is not receiving the info

It seems the reason why was, that the Iframe was loading and then the page would redirect to wherever the onSuccess page would be set as. So this worked instead.

1- Created a module that hooked the user_login(&$edit,$account) function.

Within the function I defined my variables needed for the form handler, (this example will be email, first name and last name). In my case the First name and Last name were found in the Profile page so I had to get the Profile Id to find them.

$uid = $account->uid;
$mail = $account->mail;
$Fname;
$Lname;
$pid = db_query('SELECT pid FROM {profile} WHERE uid = :uid', array(':uid' => $uid))->fetchField();
$Fname= db_query('SELECT field_profile_first_name_value FROM {field_data_field_profile_first_name} WHERE entity_type = \'profile2\' and entity_id = :pid', array(':pid'=> $pid))->fetchField();
$Lname= db_query('SELECT field_profile_last_name_value FROM {field_data_field_profile_last_name} WHERE entity_type = \'profile2\' and entity_id = :pid', array(':pid'=> $pid))->fetchField();

2- After I used the user_cookie_save(array()) function so I can send the info to the IFRAME after the page loads. (this is still in the user_login function)

user_cookie_save(
      array(
        'pardotParams' => '?Email='.$mail.'&FName='.$Fname.'&LName='.$Lname.'&RequestUpgrade='.$RequestUpgrade.'&Serial='.$Serial.'&Industry='
        .$Industry.'&Country='.$Country.'&USFedOrg='.$USFedOrg.'&State='.$State.'&Company='.$Company.'&Phone='.$Phone ,
        'pardotUrl' => $url
      )
    );

3- Lastly, I added this bit of code in the page.tpl.php file found in my template. This will create the iframe off screen but still give it time to load.

<?php

  // Comparing the login time to the current timestamp to see if the user just logged in
  if (property_exists($GLOBALS['user'], 'login')
      && (time() - $GLOBALS['user']->login) < 5 ) {
    // Show the ParDot hidden iFrame. Added some css positioning to move the iframe off the screen
    // as it was throwing off the page alignment regardless of where it was shown in the template.
    echo('<iframe src="http://go.pardot.com/l/38912/2014-03-31/cz7' .
     $_COOKIE['Drupal_visitor_pardotParams'] .
     '" width="1" height="1" style="position: absolute; top: -999px; left: -999px;"></iframe>');
  }
?>


I would look at your .htaccess rewrite rules. I've hit instances in the past where batch requests wouldn't fire during updates. Turns out I had custom .htaccess rewrite rules interfering with those requests.

Based on your example URL, it looks like you're running Drupal in a subdir on the domain. Have you set up the RewriteBase directive for that subdir? Do you have any other custom redirects in .htaccess?


Please follow the below steps :

Go to  Structure > Display Suite
Under Displays please click on settings tab and enable the checkbox named Enable Field Templates
Cheerss..now you can select desired templates.


If you set $term->tid for a taxonomy term you save with taxonomy_term_save(), the function will take you are updating an existing taxonomy term, with the consequence that the taxonomy term is not saved.

You could change the taxonomy term ID for the taxonomy term you right saved, but there is the risk of conflict with an existing taxonomy term you didn't import. You should change more that one database  table, and you should let other modules handling data related to taxonomy terms know they need to update their data, which means you probably should make those modules think a taxonomy term is deleted, and a new taxonomy term is created.
See also the code for taxonomy_term_delete() to understand what Drupal does when a taxonomy term is deleted.

If you really need to export taxonomy terms from a site, and import them in a different Drupal site, you should be interested to the Universally Unique Identifier module. In that way, the taxonomy term exported from site A, and imported in site B will have the same UUID.
In Drupal 8, any entity defined from Drupal has a UUID. The schema definition used for taxonomy terms in Drupal 8, for example, is the following one.

  $schema['taxonomy_term_data'] = array(
    'description' => 'Stores term information.',
    'fields' => array(
      'tid' => array(
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key: Unique term ID.',
      ),
      'uuid' => array(
        'description' => 'Unique Key: Universally unique identifier for this entity.',
        'type' => 'varchar',
        'length' => 128,
        'not null' => FALSE,
      ),
      'vid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {taxonomy_vocabulary}.vid of the vocabulary to which the term is assigned.',
      ),
      // …
    ),
    // …
  );


How can I bootstrap a multi-site instance?

I was able to get this working by setting the server variable  $_SERVER['SCRIPT_NAME'] to '/subsite/index.php' (where /subsite/ is the url path to the subsite).

$_SERVER['SCRIPT_NAME'] = '/subsite/index.php';

define('DRUPAL_DIR', '/usr/share/nginx/html');
use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';

// Specify relative path to the drupal root.
$autoloader = require_once DRUPAL_DIR . '/autoload.php';
$request = Request::createFromGlobals();

// Bootstrap drupal to different levels
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);
$em = $kernel->getContainer()->get('entity.manager');

$entity = $em->getStorage('node')->create(
array(
  'type' => "article",
  'title'=> "test entity",
  'body' => "body body body",
));

$entity->save();


How to create a User Feed using the modules Message and Flag?

If you'd add the Rules module (on top of the Message and Flag module you're already using), you can get this to work by using the "Replacement tokens" as part of your "Message type" configuration.

If you're not familiar with these Replacement tokens, you can learn about it the answer to What's the purpose of "Replacement tokens" of a Message type? This answer also includes a sample rule which is similar to what you'll need: it makes the value of token flagging-user available to the Message type.

Some more details to resolve this specific question here:

Add a Replacement token in your Message type, and call it (say) @user_who_flagged (or %user_who_flagged if you prefer).
Use that @user_who_flagged (or %user_who_flagged) token anywhere you want in the message you're trying to produce.
Have Rules create your message (of the message type you're using), which you can do like so:

Rules Event "Article gets flagged".
Rules Action "Create an entity" (corresponding to your Message type, and use a variable like (say) entity_created for that).

Add an appropriate Rules Action to pass the value of the "Replacement token" (which is used in the Message type as detailed above):

which looks like entity-created:arguments:user-who-flagged, and
in which you pass the value flagging-user (that's the clue to make it work ...).

Should you want to include additional info in your message about the actual Article (like nid, content type, title, author, whatever), then just create an additional Replacement token for each of them, and a similar Rules Action for each of them also.

With the above approach you'll have your messages created with the custom content you want. Those messages are Drupal entities, so creating an appropriate view from it is straight forward.

For anybody not familiar with the (great) Message module yet (which is poorly dcumented ...), here is your chance to get a first impression about it ... Below is an export of "a" message type that you could use to get started (by simply importing it in your own site). It actually works together with the example rule in the related question. This message type has machine name user_following, and uses a replacement token like @following_user (adapt both to fit your needs, eg change @following_user to @user_who_flagged to use what I suggested above):

{
  "name" : "user_following",
  "description" : "User following",
  "argument_keys" : [ "@following_user" ],
  "argument" : [],
  "category" : "message_type",
  "data" : {
    "token options" : { "clear" : 0 },
    "purge" : { "override" : 0, "enabled" : 0, "quota" : "", "days" : "" }
  },
  "language" : "",
  "arguments" : null,
  "message_text" : { "und" : [
      {
        "value" : "@following_user started following [message:user:name]",
        "format" : "plain_text",
        "safe_value" : "\u003Cp\u003E@following_user started following [message:user:name]\u003C\/p\u003E\n"
      }
    ]
  },
  "rdf_mapping" : []
}

Notes:

(to avoid confusion) [message:user:name] in the message type sample above is the user to which the message is targeted, not the flagging user!
(if you still don't get the clue of all this) using Rules it's possible to make data originating from any module (such as the Flag module) available as tokens to the Message module.


Views and empty parameter in Path to link

almost there,

add a link to the original content as a field, exclude it from display
add a path to the original content as a field, exclude it from display

rewrite the term reference to the full url you want to have using replacements [path]?something=[someid]

add a no results behavior and output the link from 1) [view_node]


how to create a view that shows blogs count for a user?

I'm going to take a stab at answering this. Create a view where:

Under Fields you select the User name, email and User:Uid. Then add a custom field.
Under the custom field write a query in Value:

<?php $result = db_result(db_query("SELECT COUNT(nid) FROM node where uid='%s' and type='blog'",$data->users_uid));
echo $result;
?>

This query find the number of posts written by each user.

Under filters choose Node:type = 'content type used to store profiles'
(as you want to count the number of blogs of every user who has a profile).


Drupal 7 How to find Nodes, tagged with Broken Taxonomies?

Just as an FYI, even if the terms had been deleted properly, the references still would have been broken (see Database records not deleted for Term Reference Fields after Term is Deleted).

Either way, to answer your question, you could use use super useful Taxonomy Orphanage module.

  This module provides interfaces (drush, cron, admin form) for removing
  orphaned taxonomy term references from entities.


If I want to display in autocomplete all this field I will use hook_form_alter
I will change the value of autocomplete with another function
so this is what i will do

function hook_form_alter() {
  $form['field_selectedarticles']['und'][0]['nid']['#autocomplete_path'] = 'autocomplete/filteration';
}

function autocomplete_filteration($string) {
  //select * fields I want
  print drupal_json_output($items);
}


Exclude viewing of a field in a view for a content type without excluding content

You can achieve that using Views Conditional.

I have added some random image from the web, just for reference purposes.

If this field... Content type

Is... Not equal to

This value Article

Then output this... [type]

Otherwise, output this... (leave empty/blank)


$items['gps/location/%/%'] = array(
  'title' => '',
  'page callback' => 'gps_lcoation_store',
  'page arguments' => array(2,3),
  'access callback' => 'custom_is_allowed_location',
  'access arguments' => array(2, 3),
);

function custom_is_allowed_location($arg1, $arg2) {
   //IF LOCATION IS XXXXX THEN ALLOWED
   if($arg1 == xxxx && $arg2 == xxxx) {
       return TRUE;
   }
   return FALSE;
}


How can I display the value of a variable inside a condition?

Try cloning the rule, and adjust the clone, remove your condition & add a system message action that shows the two variable values you are trying to debug.

BTW, Eventually you may want to install a debugging environment like xdebug. This is likely a longer process than you'd want to tackle for a quick fix. However, if you are planning to keep working in the field, it's incredibly helpful.

You'll find a good start here:
https://stackoverflow.com/questions/7303912/setting-up-xdebug-for-drupal-site


Cron function set to run once per month not completing

I always struggled to get cron jobs running at the right time until I found Elysia Cron. Inside the configuration screen of Elysia Cron you can specify which cron hooks run when, so the standard hooks can be set to run each hour, others each day, each week, each month, etc. and you don't need to worry about coding the date as you've done.

EDIT: I just ran the following code:

$day_of_month_to_run = 01;
$date_string = date('Y-m-'.$day_of_month_to_run);
dpm($date_string);
dpm(date('Y-m-d'));

The results were 2015-04-1 & 2015-04-15 your 01 is being collapsed to 1, you need to change it to '01'


Keep the destination argument in when user switch from user login to register?

I found for Drupal 7 there is no need to override the theme function, just adding a preprocess hook is enough.

/**
 * Add destination param to user tabs if set.
 * Implements HOOK_preprocess_menu_local_task()
 */
function THEME_preprocess_menu_local_task(&$variables) {
    $link = &$variables['element']['#link'];
    // check for $_GET['destination'] because drupal_get_destination() always contains at least the current page
    if ($link['tab_root'] === 'user' && !empty($_GET['destination'])) {
      $link['localized_options']['query'] = drupal_get_destination();
    }
}

Replace THEME with the name of your theme or module.


Get current user password before it is overwritten in user form?

Yes you can. The password only gets hashed when the user entity is saved as part of PasswordItem::preSave().

So you can add a submit handler to the user form, fetch both the old password and the new password (as users are required to enter both usually*) and do what you want with it.

There are discussions about that being insecure, so it is possible that this will change in the future.

There are exceptions to this, for example after using a one time login link, users are allowed to change their password without providing the current one.


How to properly check in entity form validation if field is empty?

I think I found what I was looking for, ContentEntityForm does it like this:

/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $this->buildEntity($form, $form_state);
$violations = $entity->validate();

All I have to do is building the entity, after that I have to just check the right field, which has already the ability to tell per fields if they are empty or not. (since each field is knowing it's type and also how to check if there is a value or not)


How to assign a dynamically updating date to a user based on a related field on their profile

You should be able to do those things without coding.

You can use the entity reference module to add a field to the user's profile that references the relevant delivery route node.

Then you can use the rules module, along with the rules conditional module to do the rest.

Have a rule that on user registration, uses the "Fetch entity by property" action to load the node that has the matching post code.

Then use the "Set a data value" action to set the value of the entity reference field for that user, based on the fetched entity.

Have another rule for when a user profile is viewed that uses the "Fetch entity by ID" action to load the delivery route node for that user.

Then add an if conditional that checks the entity type and content type, or use "Entity has field" and check that the date field is present. This step is required for you to be able to use all the fields on the fetched node in later actions.

Then you can use the "Show a message on the site" action to show a message to the user, in which you can use tokens to show the value of the date field attached to that delivery route node.


Adjust topic title length on topic listing page (Advanced Forum)

Not sure if this is exactly what you're looking for, but Advanced Forum integrates itself with Views.

So (assuming you have the Views module), you can trim the length of the title field in the advanced_forum_topic_list view. This c done by clicking the Content: Title (Topic / Topic starter) field, going to 'Rewrite results' and checking 'Trim this field to a maximum length'.

Because the field contains HTML to insert a span tag, you'll have to add 32 to the trim count (e.g. if you want to trim to 20 chars, enter 52), and ensure 'Field can contain HTML' is checked.


How to launch a Rule when X nodes were created in X days time?

I don't think rules by itself has the capability to do that - unless you get very deeply embedded into components, and by then it's almost the same as programming.

You probably need to write a custom module with a cron hook that checks how many nodes were created in the last 10 days. Do you want to know how many nodes were created at all, or just by a particular user? Either way that seems the best way to do it.


Install the SMTP module

Step 1: Download the SMTP module for Drupal: https://drupal.org/project/smtp

Step 2: Extract to /sites/all/modules

Step 3: Enable the module on Admin - Modules

Step 4 (for Drupal 6 only): you have to install the PHPMailer package from Codeworx Tech., version supported is below 2.2.1. Place it in a directory named "phpmailer" in /sites/all/modules/smtp

For Drupal 7, this is no longer required. The SMTP module for Drupal 7 is shipped with the PHP Mailer. It works out-of-the-box

Configure with Gmail account

Step 1: Pls go to Admin - Configuration - SMTP Authentication Support

Step 2: On Install Options, please choose On

Step 3: On SMTP server setting, please enter

SMTP server: smtp.gmail.com
SMTP backup server:
SMTP port: 465
Use encrypted protocol: Use SSL
Step 4: On SMTP Authentication: Enter user name and password of your Gmail account.

Step 5: On Email options: Enter your email from address (could be noreply@yourwebsite.com) and email from name (could be your site name).

Step 6: On Send test email: enter a email to test whether the module is working. Click on Save and go to your inbox to check. If there is an testing email then it is fine.

If it does not work, you may need to tick on the option "Enable debugging" and send a test email. The responses will be printed so you know more about the problem.

I attach the screenshot of a SMTP configuration.


Set a page to be only viewed by users who are logged in

It sounds like you're looking for a node access module. There are many of these modules available which approach this problem in different ways. But in the end, they all allow you to specify more fine grained access rights to nodes (and other types of content). There's a good overview of the various node access modules on drupal.org. This page explains what you should consider when choosing a node access module and describes quite a few of the popular ones. If none of these quite meet your needs and you're up for creating your own custom module check out the documentation for Node Access Rights (here's the Drupal 6 version just in case).

Edit:

In response to the comment from OP, in general you can't set access (view) permissions per content type (though you can set create/edit/delete permissions per content type). So either people can't see any content until they sign in, or they can see all content all the time. So if you have a specific content type that should only ever be visible by logged in users you'll likely need a node access module.


Installing / updating modules in multi-site environment

You have described the options for multisite pretty well:

Lots of shared code by putting modules in /modules
Lots of copies of module code by moving to /sites/[sitename]/modules but only one copy of core to update.
Use multiple instances instead of multisite (lots of copies of the same code but the ability to update one without risk to others).

Multisite is most useful when there is low variation in the configuration between the sites and therefore you can safely use the same copies of core and the modules on most (if not all) sites.  The more variation you have between copies the more likely it makes sense to ditch multisite and move to multiple instances.

While there are some very large instances of multisite in use, there are also people in the community who feel pretty strongly that multisite brings more headaches than it is worth.


Checkout the Views Group By module, this will do it. Here is a quote about it (from the module's project page):

... enriches Views2 functionality with SQL Grouping and Aggregation capabilities.
A new field group: SQL Aggregation is added, in Views, once you install the module. The field group has one available field: SQL Aggregation: Group By Fields. The field allows to configure many aspects of "group by" SQL clause and "count()" fields.


Knowing if the currently logged-in user has seen the list of nodes shown in a view

I think that the best option for you is to write a mini module with  a simple DB table. If you need designing it i will help you.

Also try the checklist module

Maybe it could help you


Duplication of files when using Acquia Dev Desktop

C:\Users\Sam\Sites\devdesktop\columbiablooms-dev contains data for your Acquia site (e.g. hooks has scripts that can trigger upon deployment, private contains files that setup as private in Drupal's file system, etc.)

The C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot dir is the webroot of your site; this is the dir that is the base of your domain that is uploaded to Acquia (e.g. C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot\index.php -> http://www.example.com/index.php). See this post for an explanation of all the subdirectories.

C:\Users\Sam\Sites\devdesktop\openoutreach-7.x-1.19 is a copy of OpenOutreach 1.19 you downloaded. It contains the OpenOutreach installation profile, its needed modules/themes, and the version of Drupal it's bundled with.


Import an Image Folder into one Image Field

It will most likely involve implementing the Drupal File API in combination with the Field API in your custom module. I can't write a full implementation for you here because honestly it would take at least an hour to do it correctly, and still my example could miss your use case. But if you have a good handle of PHP and Drupal, you should be able to do it with the two APIs I mentioned above.


This worked well for us: Webform Import

  Allows delimited data files to be imported as submission (results) into webforms.

  This is useful for importing submissions from other systems in to Webform. Can also be used to Edit submissions via Export / Import as long as the CSV has the SID column filled.


Help needed for adding and edit & delete link in a column in a view table

Could you just add a field with the node ID and rewrite it to reconstruct the url, inserting the node id where applicable (different structures for different entity types)?


7 - Views 3 - Displaying taxonomy description in a block

The URL is /taxonomy/term/% and I am using pathauto aliases.

If you're using aliases I assume that your URL is something like some/path/your-term-name.

In that case I had exactly the same issue a while ago. You should try setting Filter Value Type to "Term name converted to term ID and check "Transform dashes in URL to spaces in term name filter values".

Also make sure that proper value is provided to the filter.

In the WHEN THE FILTER VALUE IS NOT AVAILABLE section select Provide default value
and then select Raw value from URL and specify url component to provide as a default value. Unfortunatel "Term ID from URL" option doesn't work as you might expect in case of aliases so you need either provide default value from URL using Raw value option or even using PHP Code option. If you choose this option, you might find the following piece of code useful:

$get = explode('/', $_GET['q']);
return $get[2]; //the "2" constant assumes that your term name is a third path component


How to display the field in a joined table with hook_views_data()

You'll need to add a relationship to that table, then add the field from that table to your view.


How to use Views Photos Grid module with custom minimal theme

Issue was missing JS includes.
The working set is:

  <script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"screenshots","currentPathIsAdmin":false,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","google_analytics":{"trackOutbound":true,"trackMailto":true,"trackDownload":true,"trackDownloadExtensions":"7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip"},"viewsPhotoGrid":{"gridPadding":"1"},"user":{"uid":0,"permissionsHash":"797a0805952a191ed3acd8cc0feee5a8b53895cab4446ce069563dbdd87139da"}}</script>

  <script src="/core/assets/vendor/domready/ready.min.js?v=1.0.8"></script>
  <script src="//code.jquery.com/jquery-3.3.1.min.js?v=3.2.1"></script>
  <script src="/core/misc/drupalSettingsLoader.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.js?v=8.6.3"></script>
  <script src="/core/misc/drupal.init.js?v=8.6.3"></script>
  <script src="/modules/views_photo_grid/js/views-photo-grid.js"></script>

It doesn't work without the first messy line with data-drupal-selector. I wish I knew was is this good for...


User edit form on custom page is resetting roles when user belongs to the "Administrator role"

The form values still persist in the form state, and as they're not printed, the will be submitted as empty and saved accordingly.
Do not hide form element by not outputting them in twig, render the full form there and use [#access] = FALSE; on the form elements you don't want to show. Do so in the controller, to only have that on your custom page. If you do that in hook_form_alter it will apply to the form always (so here also for the profile page aka /user/X/edit).

You're mixing two concepts: Showing a form (where you have full
control and can add stuff before and after with entries in the render
array and use a form-mode for the form, so you can configure the
fields via UI and not code) and altering a form (where you do not
control where it is shown, and want to change it everywhere). I guess
you want to show a form, so I would remove the theme stuff and
concentrate only on the output form your controller.

Or even use a different approach .. and create a new form from scratch, populating with the user's value, and save them back to the user entity on submit (If you only need one "field" and even the password fields can be replicated in the custom form).
And replace the controller with a form callback in routing.yml.


How to automatically generate multiple aliases for one node?

In canse you didnt found it, you need to use the module Rules and follow these steps:

**Delete Node Aliases Ruleset**
- Delete all aliases that point to system path
- Delete all aliases that point to system path
- ... (and so forth)

**Create Node Aliases Ruleset**
- Create alias #1 to point to path A
- Create alias #2 to point to path B
- ... (and so forth)

**Triggered Rules**
- IF new node created (and any other conditions) THEN call Create Node Aliases ruleset.
- IF node deleted (...) THEN call Delete Node Aliases ruleset.
- IF node updated (...) THEN call Delete Node Aliases and then call Create Node Aliases


How to iterate over all field collection items in an eMail body using Rules?

Part 1: Processing field collections in a rule

Consider a configuration with a field collection like so:

The machine name of the field collection is field_treatment_details, and the number of values for it is unlimited.
This field collection has 2 fields:

a text field labeled "Doelpubliek" (Dutch for "Target audience") with machine name field_doelpubliek.
a boolean field labeled "Betalend" (Dutch for "Payable") with machine name field_betalend.

Assume a node with "some number of" field collection items, with values that look like so (with some number = 2 in this case, but that could be any number as per the "unlimited" above):

Doelpubliek=Baby with Betalend=Nee
Doelpubliek=Moeder with Betalend=Ja

Let's assume you want to display these data via a Rule, using Rules Action "Set message", and using Rules Event "Content is viewed", so that such message looks like so:

This is a demo of a node containing a field collection ...

About this demo:

The machine name of the field collection is field_treatment_details, and the number of values for it is unlimited.
This field collection has 2 fields:

- a text field labeled Doelpubliek with machine name field_doelpubliek.
- a boolean field labeled Betalend with machine name field_betalend.

Part 1: The field collection with machine name 'field_treatment_details' looks like so:

Doelpubliek: Baby
Betalend:    Nee

Doelpubliek: Moeder
Betalend:    Ja

Part 2: The result of a Rules loop that iterates for each of the field collection items (using its unique ID) ...

The unique ID of the field collection item: 2
The host entity of this field collection item: 43
Field "field_doelpubliek": Baby
Field "field_betalend": Nee

The unique ID of the field collection item: 3
The host entity of this field collection item: 43
Field "field_doelpubliek": Moeder
Field "field_betalend": Ja

Here is the Rule (in Rules export format) that produced the above "message":

{ "rules_field_collection_demo" : {
    "LABEL" : "Field Collection Demo",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_treatment_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_treatment_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has 2 fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EDoelpubliek\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_doelpubliek\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EBetalend\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_betalend\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The field collection with machine name \u003Cstrong\u003E\u0027field_treatment_details\u0027\u003C\/strong\u003E looks like so:\r\n\u003Chr \/\u003E\r\n[node:field_treatment_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-treatment-details" ] },
          "ITEM" : { "treatment_details_item" : "Treatment details item" },
          "DO" : [
            { "drupal_message" : { "message" : "The unique ID of the field collection item: [treatment-details-item:item-id]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [treatment-details-item:host]\u003Cbr \/\u003E\r\nField \u0022field_doelpubliek\u0022: [treatment-details-item:field-doelpubliek]\u003Cbr \/\u003E\r\nField \u0022field_betalend\u0022: [treatment-details-item:field-betalend]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      }
    ]
  }
}

Admitted, this is a slightly simplified field collection configuration (no "nesting" involved). But apart from that it is similar to what you will need to specify in your Rules logic. Here are some more details to explain the above rule:

You need (repeat: need) a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field.
The 1st Rules Action (which produces the data below "Part 1" in the message) just displays the entire field collection, simply by referring to token [node:field_treatment_details].
The 2nd Rules Action (which produces the data below "Part 2" in the message) is simply a Rules "loop", which iterates over each of the field collection items (it uses a variable that I named treatment_details_item to actually display a message for each item). You will then be able to use any of the typical tokens (in the replacement patterns) related to that variable, such as how I used them to create my message I wanted to display, i.e.:

The unique ID of the field collection item: [treatment-details-item:item-id]

The host entity of this field collection item: [treatment-details-item:host]

Field "field_doelpubliek": [treatment-details-item:field-doelpubliek]

Field "field_betalend": [treatment-details-item:field-betalend]

Notice how, in the message I wanted my rule to display, I was able to refer to my "Doelpubliek" and "Betalend" fields (part of my field collection).

Part 2: Performing a loop within

After posting Part 1 of my answer, this "Update" got added to the end of the question (after it was first posted as a comment below this answer):

  While I understand the example shown in the existing answer, I can't seem to conceptualize how I would be able to write a Rules "loop" to display the field collections in an email. The email body of the rules module does not seem to have the ability to "loop" over content.

I think you're right about 'The email body of the rules module does not seem to have the ability to "loop" over content', or at least I've never discovered anything to do so. However, if what you're looking for is not available, then just make it available ... The trick to do so is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

Populate some new Rules variable before the Rules Action to send an eMail, say you name the variable field_collection_var_for_email_body. And the value of this variable should consist of a concatenation of the appropriate values of your nested field collection.
Within the Rules Action to send an eMail, you'll be able to select the token for field_collection_var_for_email_body to include anywhere in your eMail body.

Attention: even though it should technically possible to do all this in a single rule, such rule would possibly get pretty complicated to understand/maintain. That's why if it was up to me, I'd probably implement the Rules logic (as explained in this Part 2) in a separated Rules Component, which provides ... (cfr Rules Component terminology) field_collection_var_for_email_body!!!

Voilà ...

Happying Rules-ing! ... Also with (unlimitted) field collections ... even inside the body of an eMail created with a Rules action to Send an eMail.

PS: No need to write some PHP code to make this happen ...

PPS: For the newbies out there, it should look something like this:

Note that the fields are different here, and not the same as the example/scenario provided above.

Important: Make sure you select True for the uniqueness option in Add an item to a list, other wise this will trigger a bug that causes your fields to become empty or get readed multiple times. Once you get this bug, the only fix is to restore to a DB backup as you are not able to remove these fields even after turning off the Rule. Some more details about the bug (to avoid):

The bug causes the edit form field collection fields to disappear, while the fields do show up when viewing the node.
In another case, the bug causes the field collection field to be added over and over again. Also, when you click remove, the field doesn't get removed.


Overcoming 255 character URI limit for files_managed

You can alter the database defined from another module, but this is generally a bad idea. As said from Letharion, it is probable you are going to cause issues with other modules that take assumptions.

If you really need to do it, then you should implement code that (at least):

Alters the database table defined from the other module
Implements hook_schema_alter() to make other functions know the new schema used for the database table

The latter step is necessary because there are functions, such as drupal_write_record(), that use drupal_get_schema(), which invokes hook_schema(), and hook_schema_alter() to know the schema used for a table.

Your code should be at least the following one.

mymodule.install

function mymodule_install() {
  if (db_table_exists('file_managed') && db_field_exists('file_managed', 'uri')) {
    $schema = drupal_get_schema_unprocessed('system');
    $schema['file_managed']['uri']['type'] = 'varchar';
    $schema['file_managed']['uri']['length'] = 12288;
    db_drop_unique_key('file_managed', 'uri');
    db_change_field('file_managed', 'uri', 'uri', $schema['file_managed']['uri']);
    db_add_unique_key('file_managed', 'uri', array('uri'));
  }
}

function mymodule_schema_alter(&$schema) {
  if (isset($schema['file_managed']['uri'])) {
    $schema['file_managed']['uri']['type'] = 'varchar';
    $schema['file_managed']['uri']['length'] = 12288;
  }
}

What is missing in the code I shown is the code to unistall the module. It should change the database table as it was before the module was installed, but what happens if another module installed after yours alters the same field in that table?

Notice that, generally, managed files have a URI that is similar to public://field/image/100_0140.JPG. If the problem is the path being too long, then you should use less directories, or a shorter filename.


How can I attach an image from an existing image field to another multi-value image field?

The first line doesn't get you an image, it's a field item list:
$items = $node->get('field_old_image_field');

Then you can get the first item
$item = $items[0];

and append the item properties to the new field:
$node->get('field_new_image_field')->appendItem([
  'target_id' => $item->target_id,
  'alt' => $item->alt,
  'title' => $item->title,
]);


how to? if is_front = div class "front-content" else "content"

Instead of adding a new class (and a div) you can simply target and override the layout for the front page in your style sheet with:

.front .content {
  width: 70%;
}

It's possibly you need to be more specific though, so you don't target all .content on the page. I don't know how you theme code looks, but it should be something like .front #main .content.

This assumes that your theme uses the default body classes in html.tpl.php for Drupal 7

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

Or page.tpl.php for Drupal 6.

<body class="<?php print $body_classes; ?>">

Cheers,


What is causing Drupal to return a 404 HTTP header, but correctly return the page?

Are you using clean urls?

It is possible that Drupal is called through the 404 error handler which results in the 404 header.

Make sure your .htaccess configuration is correct and that mod_rewrite is enabled and you're allowed to override the relevant settings.


If you deleted and returned a module to its original place, then all it takes for the website to start working normally again is to get cache refreshed, which will bootstrap it.

You can do it by:

Running the update.php file. Make sure to set $settings['update_free_access'] = TRUE; on the settings.php file.
Using drush. Installing drush is not as complicated as it might sound. Just follow instructions on http://docs.drush.org/en/master/install.
By clearing cache tables directly in the database. Just use some kind of user interface for the database like, for example, phpMyAdmin, open the website's database and truncate all the tables starting with cache.
If none of the above methods works, then try to uninstall and re-install the module or manually remove all database references to the fields which were created by the module.


Calculate time between start and end time

There is a way to accomplish this without writing any code. You can use the Rules module to calculate the difference between dates and to update a field in any entity or node.

There isn't a Rules action that will calculate the difference between dates, but there is still a way to do it in Rules. It involves four simple steps:

Use the "Convert data type" action to convert both date objects to Integer types. This will create variables that use a Unix int timestamp (number of seconds since 1/1/1970)
Calculate the difference between the two integers and store in a variable
Divide the result by x number of seconds, depending on what you want to calculate. To calculate days, divide by 86400 (60 * 60 * 24)
Use "Convert data type" to round the subtraction to an integer (and store in a new variable)

Then you can simply use the Rules action "Set a data value" to store this value in a node (or entity) field

You can trigger this Rule whenever the user saves or edits content of specific type.


Approach to removing extra space at beginning of RSS file?

Someone left a space at the beginning of a module.

[space]<?php

You can either try to find that bit of code with some tool or command OR put this in includes/bootstrap.inc at line 1112:

echo $filename;

The line number could change subject to updates to Drupal 7 so make sure it is inside the drupal_load function:

if ($filename) {
    echo $filename;  //this is your included line
    include_once DRUPAL_ROOT . '/' . $filename;
    $files[$type][$name] = TRUE;

The result will be a long list of the modules being loaded in source code of the page.  The space will be right after the module with the problem.


Migrating a Content Types and its Nodes into another site

migrate_d2d provides a framework based on the Migrate API for migrating content from Drupal 5, Drupal 6, or Drupal 7 sites into the Drupal 7 site where it is installed

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

Using this module you can easly migrate your content types to other d7 instance.
Here You Just need to give database link form which you want to migrating content types.


How to override configuration from a file?

To override config on code is simple. Above is an exemple how you get, set and save any config (that you just installed via .yml and from core).

On .install or .module file

  //Getting editable configs
  $module_cfg = \Drupal::configFactory()->getEditable('your.module.file');
  $settings = \Drupal::configFactory()->getEditable('any_core.settings');
  //Getting values
  $a_value = $settings->get('key_from_core');
  //Setting and save configs
  $module_cfg->set('any.key', $a_value)->save();
  $settings->set('key', 'new_value')->save();

From hook_install docs:

  Implementations of this hook are by convention declared in the
  module's .install file.

For further information see ConfigFactory docs.

There is a module called Features that helps if you want keep on track of your configs. I'm currently using this module for code-driven development, maybe is this what you're looking for.

Edit 1 - Replace entire config

First of all, you need to provide which config you pretend to override.

On my.custom.config.yml file

# Make sure this config exists in your database
target: 'config.to.override'
... # all your data (CAUTION with 'dependencies')

On .install file

function module_install() {
  //Get your custom config
  $cfg = \Drupal::configFactory()->getEditable('my.custom.config');
  //Get config name to override
  $target = $cfg->get('target');
  //Get Config object
  $settings = \Drupal::configFactory()->getEditable($target);
  //Override all data that can be overridden
  $settings->setData($cfg->get())->save();
  //If you won't store any previous state, get rid of your custom config
  $cfg->delete();
}

This was tested in my development environment.


Is there a successor project to Omega 4?

I found what looks like an explanation from 2016. It looks like Omega 4 is not going anywhere.

  ...both new Omega versions (7.x-5.x, 8.x-5.x) probably have nothing in common with (7.x-4.x) and are not the successor of Omega 4.

  The successor to (7.x-4.x) is new project Khan so all the questions about that should be posted there. Truth to be told, there is not much activity there, since.

  So if you wish to make some sort of continuation of current 4.4 code base to D8, probably you will have to do it yourself. Personally, I do not think it will make much sense as the differences between D7 and D8 would not leave much in common.

The same user asked what the status of Khan is two months ago and hasn't received any reply. In another thread, the maintainer posted that Khan is postponed indefinitely:

  ...This is a serious project but since I am currently focusing on GraphQL for Drupal you can consider it postponed until I am done with the first release of that module.

So it seem fair to conclude that there is no Drupal 8 successor to Omega 4 at time of writing.

Life is too short for drama, so I personally am going to (reluctantly) drop Omega and switch over to Bootstrap.


Clive's answer is correct. I am just pointing out where exactly that happens.

theme_render_template() is the function called by theme(), and it contains the following code.

  extract($variables, EXTR_SKIP); // Extract the variables to a local namespace
  ob_start(); // Start output buffering
  include DRUPAL_ROOT . '/' . $template_file; // Include the template file
  return ob_get_clean(); // End buffering and return its contents

The code that calls theme_render_template() is the following one.

    // Default render function and extension.
    $render_function = 'theme_render_template';
    $extension = '.tpl.php';

    // The theme engine may use a different extension and a different renderer.
    global $theme_engine;
    if (isset($theme_engine)) {
      if ($info['type'] != 'module') {
        if (function_exists($theme_engine . '_render_template')) {
          $render_function = $theme_engine . '_render_template';
        }
        $extension_function = $theme_engine . '_extension';
        if (function_exists($extension_function)) {
          $extension = $extension_function();
        }
      }
    }

    // In some cases, a template implementation may not have had
    // template_preprocess() run (for example, if the default implementation is
    // a function, but a template overrides that default implementation). In
    // these cases, a template should still be able to expect to have access to
    // the variables provided by template_preprocess(), so we add them here if
    // they don't already exist. We don't want to run template_preprocess()
    // twice (it would be inefficient and mess up zebra striping), so we use the
    // 'directory' variable to determine if it has already run, which while not
    // completely intuitive, is reasonably safe, and allows us to save on the
    // overhead of adding some new variable to track that.
    if (!isset($variables['directory'])) {
      $default_template_variables = array();
      template_preprocess($default_template_variables, $hook);
      $variables += $default_template_variables;
    }

    // Render the output using the template file.
    $template_file = $info['template'] . $extension;
    if (isset($info['path'])) {
      $template_file = $info['path'] . '/' . $template_file;
    }
    $output = $render_function($template_file, $variables);
  }


You need each subcategory in a separate opt-group.

There is a thread about adding support for that here: Support optgroups for taxonomy selection list.

The thread includes a patch that can be applied to give this functionality.

There is also a module called Taxonomy container that looks like it also does what you want (image from module page):

I would also recommend the chosen module to further improve the select and allow additional styling changes (it converts the select to a UL).


content contains the render arrays based on the configured formatters.

If you want to access the actual values, you want to access them through the entity object. Usually, that is available already to your template, for example node. For your case, it is a bit special because the block_content is rendered in the block content without its own template, so you have to make it available yourself in a yourtheme_preprocess_block($variables) like this:

if (isset($variables['elements']['content']['#block_content'])) {
  $variables['block_content'] = $variables['elements']['content']['#block_content'];
}

Then, you can access a field value with block_content.field_name.property. So in your case, block_content.field_align.value. The property is value for most field types, for references, you can either use target_id for the ID or entity for the referenced entity object. Yes, you can directly access fields on that, but make sure to always check that a reference exists otherwise you can end up with fatal errors or exceptions. To access the label of a term reference for example, you can access it as block_content.field_tags.entity.name.value.

If you don't specify the field delta, it defaults to the first. If you want to access a different delta, you can use entity.field_name.1.valueand so on. You can also loop over them.

This all maps directly to PHP, you can also do $block_content->field_tags->entity->name->value in preprocess and other places where you have the block_content.


How to make correct View for tasks for each user?

You can solve above problem using Views Field View module..

Project page says

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

Create a new view which accepts term id as argument and lists nodes related to that term
Add Contextual Filter Author ID - Provide default value
In your view add term id and select Exclude option
In your view add above view as a field and read term id using token in settings.

See the result below


Is there a module that allows me to add files via ajax to a body field?

It is probably not exactly what you are looking for, but I'll mention them anyway, as it might give you further search directions:

plup module
Insert module
Image Resize Filter module

I like the plup module a lot, very easy to use, but based on image fields, not inline. Perhaps, in combination with the Insert module, you can get them inline. I don't like the resulting UI, as people won't understand why something so easy (putting an image inline, optionally with fixed dimensions) needs to be presented so complex.

The Media module is still thinking how to handle inline images; see the issue #1283844.


Use the Features module to export content types and permission. You can go to admin/structure/features/create and the select the features you want to export.


Domain access issue w.r.t viewing a content other than admin user

My answer is based on experience with D6 version of the module but I believe the core is still relevant. As the site administrator (user id 1) you can view all site content unless you disable that option in the domain settings page (Administer >> Site Building >> Domain >> Domain Settings >> Domain module behaviors fieldset >> Enforce rules on administrators:).

With relation to content viewing for other users, it is the default behavior to return HTTP 403 (Not authorized) when a content created specific to one domain without being shared to all affiliates is viewed from a different domain. The option to publish node to one or few of the sites is available in the node creation or edit form.

If you wish to change the default behavior of specific node types, the option to either allow specific node types to be published to all affiliates can be found in Node settings under Domain. When nodes are saved that way domain access table has an entry for such nodes with affiliated domains as domain_site.


Yes, there is another way to do this in configuration. You can change

  translatable: true

in core.base_field_override.node.[content-type].title.yml.

If you don't find this configuration file, then there are no changes made so far for the title field. You can do this for example by modifying "Title field label" in the content type, which is also stored in this configuration and if it doesn't exist it will be created, so that you'll find the yaml in the exported config.

After you've changed the field label, export the configuration, open for each content type the mentioned yaml file, change translatable to false and reimport the configuration again.

See https://www.drupal.org/docs/8/configuration-management/workflow-using-the-drupal-ui or if you have installed drush use these two commands:

drush config-export
drush config-import

see https://www.drupal.org/docs/8/configuration-management/workflow-using-drush.


How do I add default header and footer regions to my site?

You define a region in your theme's info file and then print it in your page.html.twig. Content to each region is added via blocks. You only add your own region templates when you need to make some changes to the markup.

OK, so you added the regions in your info file, and printed them in your page template, fine. First of all, delete your region--header.html.twig and region--footer.html.twig again. Then in the backend of your site go to Structure > Blocks. Your newly added regions should appear there. Now place some blocks in your newly added regions. Save, flush cache and visit your frontend again. Your regions should be populated now.

And regarding the region--YOURREGION.html.twig templates you should have deleted by now, these only will be picked up when these regions are populated – with blocks. Otherwise these regions simply won't get printed at all.


How do I change the price of a flat rate shipping fee depending on a type of Product?

figured it out .. but not sure if its the best way i think it is. for reference:

created a light & heavy shipping flat rate option.
added in new conditions matching if its a heavy or light via taxonomy terms.
added in an extra condition for LIGHT shipping to make it disappear by detecting if there is a heavy item in the cart by doing a negate on the same above condition.

To make this work you will need https://drupal.org/project/commerce_rules_extra

As you need the Total quantity of selected product comparison condition to loop through the entire cart and match what you need in accordance to the terms you select.


I can't answer that exact question, but to solve that problem we typically use the Linkit module.

This will add an additional button to the WYSIWYG for creating links.  When you click it, you get a popup which lets you choose a link (somewhat similar to the entity reference autocomplete widget), and also set link options.

It will then build a link in the markup using a token.  When the page is rendered, the token gets replaced with the path alias for what you selected.  So, if the path for a node changes, the token replacement will take care of fixing everything.


How can I process a node form from a custom submit handler?

Typically, I found the answer 10 minutes after posting!

For anyone else, in your custom submit handler get the form object from the form state.

$formObj = $formState->getFormObject();

You can then call submitForm() on the form object and pass the form and form state variables.

$formObj->submitForm($form, $formState);

Then finally just simply trigger the save() function on the object.

$formObj->save($form, $formState);


You can't uninstall the default theme, because there wouldn't be a theme left for the site. Similarly you can't uninstall the Seven theme when it's selected as the admin theme.

You need to change the default to another theme, then under normal circumstances the "Uninstall" link will appear where you'd expect it.

If it doesn't, consult the documentation or contact support for the theme seller, because they've done something non-standard, and it's not likely to be possible to guess what that might have been from afar (especially if it was done as part of the initial SQL import)


Suggestions for settings.php - Local dev, Development server, Live server

What I do is separating that file into a settings.php and a local.settings.php.

At the end of settings.php is the following code:

if (file_exists(dirname(__FILE__) . '/local.settings.php')) {
  include dirname(__FILE__) . '/local.settings.php';
}

The local file is then excluded from whatever VCS you are using. The advantage is that you can put settings which are common over all instances in settings.php and have that versioned/distributed automatically and keep the local stuff in local.settings.php.


I know you explicitly stated that you don't want to create a subtheme of Seven, however short of hacking the core Seven theme or messing with the theme registry (which I explain below against my better judgement) this is the simplest way to accomplish what you are trying to do.  The amount of overhead to do this is incredibly small and requires only three files.  Simply create a folder named something like "mytheme" and add an empty "mytheme.css" file in addition to a "mytheme.info" file with the following code:

name = My Theme
description = Custom subtheme of Seven.
core = 7.x
base theme = seven
stylesheets[all][] = mytheme.css

Then add a template.php file and override the theme hook similar to below:

function mytheme_node_preview($variables) {
  // Do custom stuff here.
}

All done. This is the "Drupal way" of doing theme hook overrides.

Again, it is against my better judgement to post the code below. If you absolutely have your mind set on not creating a subtheme, you can implement hook_theme_registry_alter().  Did I mention that this solution is hacky and the hook is pure evil? :-) In a custom module named "mymodule", do the following:

function mymodule_theme_registry_alter(&$registry) {
  $path = drupal_get_path('module', 'mymodule');
  $registry['node_preview']['file'] = 'mymodule.module';
  $registry['node_preview']['theme path'] = $path;
  $registry['node_preview']['function'] = 'mymodule_node_preview';
  $registry['node_preview']['includes'] = array(
    $path . '/mymodule.module'
  );
}

function mymodule_node_preview($variables) {
  // Do whatever you need to do here.
}

Use the snippet above at your own risk.


Loading js file for all browsers except IE

As you may be suspected, the original condition is wrong.  Here's a related post on how someone was able to find a better condition for checking the user agent for IE:

https://stackoverflow.com/questions/5302302/php-if-internet-explorer-6-7-8-or-9

summary: use this instead:

if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])){}


Gating/Redirecting anonymous user back to an origin page after logging in/registration

You can have destination parameter in url. Something like below.

drupal_goto('custom/user/login', array('query' => array('destination' => current_path())));


Prevent Drupal from Caching API Responses

I think you need to define #cache settings in your controller's response. You could define it in such a way that your response isn't cached at all, but you're probably better off defining cache tags in such a way that the cache is cleared when the entity is updated. See the Cache API documentation for more info.

Based on the information you've given, I think you'll probably want something like below added to your response array.

'#cache' => [
  'keys' => [
    'MY_MODULE_WHATEVER_KEY_YOU_LIKE',
  ],
  'tags' => [
    'user:' . $id,
  ],
  'max-age' => Cache::PERMANENT,
],

You'll need this use statement at the top of your file for Cache::PERMANENT

use Drupal\Cache\Cache\Cache.php;

The above will cache your response permanently, but break the cache when the user with $id is updated.


Drupal do not publish more current notes to other browsers than admin logs in

I looked at your site and all I see is "File not found.". If posts aren't showing up, check the view that is creating that list of content, it might be limited by a date range.


Issue with attaching an existing file while creating node using RESTWS

I tested the following code it works fine. Replace your field machine names and bundle name accordingly. Hope it helps

Here is the XML format to send data

<result>
<title>title_of_node</title>
<type>sampleimage</type>
<field_samplefile>
<und is_array="true">
<item>
<fid>18</fid>
<uid>1</uid>
<filename>Drupal.txt</filename>
<uri>public://Drupal.txt</uri>
<filemime>text/plain</filemime>
</item>
</und>
</field_samplefile>
</result>

Here is the JSON format

{
    "title": "title_of_node",
    "type": "bundle_name",
    "field_samplefile": {
        "und": [{
            "fid": "17",
            "filename": "changes.txt",
            "uri": "public://changes.txt",
            "filemime": "text/plain"
        }]
    }
}


How to quick start sub-theming in Adaptive Theme?

No, you should copy only the sub theme folder. I have just downloaded all versions of AT and both theme-settings.php and template.php files are there. You may consider deleting the existing adaptivetheme folder and downloading it again.


Storage API stream wrappers Traffic Usage

If you look into the Drupal core's routing config, you can find the controller responsible for delivering private files. It's abstracted through the BinaryFileResponse object, but you can see in its sendContent method how the data is prepared for delivery.

It uses PHP's stream_copy_to_stream function to copy from your input stream (your private path) to the php://output stream, the HTTP body delivered via PHP/web server.


Using Services, why is the resource name appended to the endpoint?

See mradcliffe's comment for a good explanation of the difference between an endpoint and a resource, understanding that will make it clear why the Services module does things the way it does.

Why is the endpoint for the user entity type specifically named user?

Conceptually speaking it's a safe bet that the module developer followed common REST patterns, and adopted the name of the entity as defined by the system the code is sitting in (i.e. the user entity type defined by Drupal core).

From a technical point of view, the resource is named user because the services module explicitly names it as such in _user_resource_definition():

$definition = array(
    'user' => array(
      'operations' => array(
        ...

Not a fan of this particular convention? Not a problem, Services has you covered.

Go to the "Edit Resources" tab for your endpoint, and look in the right hand column of the table; you'll see a text field that takes an "Alias". Set that to "users" for the User resource.

Set your endpoint to something sensible like 'api/v1.0', and you can now access the user resource through its alias at http://example.com/api/v1.0/users. It sounds like you might also want to add a "pages" alias for the "Node" resource, but I'm speculating a bit.


Why don't you use Editview module? You can create an editview with a block display and show it on your page to edit your nodes from there.


Most likely the issue is probably related to caching, you can argue that it's a bug in devel/kint module and that is should have an implementation to handle this.

I would argue that the use of kint in a template file is made for running the site in development mode and if you disable caches (which is a really idea on an actual production site) it should work just fine.


Unable to get variable facebook_publication_id, it is not defined

Ok the problem was I set value incorrectly in rules component. Instead of [node:url_www] it should had been [fb-article-post-rule:url_www] which was causing facebook authentication issue as there was no link to post to facebook what is defined in their facebook app.


Metatag is not showing on front page whereas the front page is set from custom content type

If your are using page--front.tpl.php add the below line and clear the cache.

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

Meta tag will be added to the front page.


how to call handler on every ajax request

Setting a form element to type button prevents submit handlers from being executed. You'll need to change the type to submit if you want your submit handlers to be called.


You must mention the node type while doing the POST.

node_type will the machine name of your content type

for example try creating page with this,

StringEntity se = new StringEntity("{ \"title\" : \"Sample post\" , \"page\" :


Views show content where field used in user and node entity matches

Option 1

Add a contextual filter of your entity reference field.

Then programatically get the logedin in user's entity reference field value. (I'll let you figure this part out)

Once you have this value, you can programmtically print the view like this:

print views_embed_view('view_name', 'view_machine_name', $value);

This is the machine_name

ex: print views_embed_view('hello_kitty', 'block_1', $value);

Option 2

For a non-programatic answer, View Fields View module.

1) Create a User view with a Contextual filter of User ID. Select logged in user's ID. Now add the entity reference field as field.

2) Create a Content view with a Contextual filter of Entity Reference.

3) Go back to your User View, hide the entity reference field and add View as field. Select the View in #2 and for contextual filter, use the replacement pattern of the entity reference field.


Exclude current node from entity reference view (for related news)

there is a patch fixing that issue and helping you to use [node:nid] as an arg here.

Otherwise, did you try Entity Reference View Widget ?

  The module has a way of hiding selected items from the View. Simply
  add a base field contextual argument (Product ID for products, Node ID
  for nodes, etc) and in the "More" fieldset enable "Allow multiple
  values" and "Exclude". Then edit the Entity Reference field, and in
  the widget settings enable "Pass selected entity ids to View ".


How to disable adsense for this error page

use the Adsense module, you can specify pages where to display it or not to display it using :

Show AdSense on specific pages:

Show on every page except the listed pages.
Show on only the listed pages.
Show if the following PHP code returns TRUE (PHP-mode, experts only).


From your Comment "contain user entered data" i understood you need webform submitted data in Table format, If so then download and install this module Webform Report

  This module allows users to create simple, dynamic reports based on
  data collected by the webform module. It adds a new node type that
  contains the report criteria, and the data displayed is updated
  automatically as webforms are submitted.

See the webform report in below image, hope it helps you!!


What is the mechanism used to control how Drupal pages are rendered?

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

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

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

The nuts and bolts of the page above outline:

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

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

  return $items;
}

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

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

  return $content;
}

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

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

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


How to count elements grouped by an specific field?

You can use Views Aggregator Plus for this.


override view Use administration toolbar

I found out that  i need to do a custom module then do theme hook suggestion.

function my_module_theme($existing, $type, $theme, $path) {
    return array(
    'views_view__comments'=> [
        'template' => 'views/views-view--comments',
    ]);
 }

And then template in yout admin theme , or in your custom module. In my case in module forlder templates/view.


How to display drupal 7 Ubercart product attribute options in views filter?

Add "add to cart form" field in view. we can see all attributes in view which are added for this product


How do I set permissions for a subdirectory that Drupal creates when uploading a file?

A standard Drupal would use Core's FileSystem class to create directories and set permissions according to the file_chmod_directory setting, which you can adjust within your site's settings.php files:

/**
 * Default mode for directories and files written by Drupal.
 *
 * Value should be in PHP Octal Notation, with leading zero.
 */
# $settings['file_chmod_directory'] = 0775;
# $settings['file_chmod_file'] = 0664;

It defaults to 0775 and is therefore commented out in a regular installation.

However, you mentioned using the Flysystem stream wrapper module. A short look into it's code reveals, that it is indeed using the FileSystem::CHMOD_DIRECTORY constant as default for local files. But the final directory permissions can vary depending on the Flysystem adapter plugin you are using. Something that is out of our control here at Drupal Answers. It's a contrib module anyway. So you will have to check yourself, of whether your adapter plugin supports the Core setting values/allows to configure it by other means. If not, you may wish to file an issue against the module that is providing the adapter you are using.


ajax form element sometimes triggers submit

There is a quirk in the AJAX form api which causes the last button on the form to be submitted under certain circumstances.  Without seeing all of your code, it would be difficult to isolate the problem.


If I understand your question correctly, you need the functionality of the Views Selective Filter module.

Although I haven't used this module myself, I've written a similar Views handler in a custom module. This filter handler removes all options from select lists that don't provide any results (due to other selected values). If the Views Selective Filter doesn't provide the desired functionality, I can create a sandbox project of my code.


How to add dependency to a custom module with drupal-composer?

Ok, seems to me that I almost got it.

This was due to my repository list in the Drupal root composer.json. I had this kind of thing there:

{
  "type": "package",
  "package" : {
    "name": "blaah",
    "version" : "xxx",
    "type":"drupal-module",
    "source": {
      "url": "gitblaag",
      "type": "git"
    }
}

That some how seems to override what ever is in the modules composer.json. I do not really know why but something along the lines that the entry defines the whole package and no more info will be read from the composer.json in the module.

So I adding "require" there does the magic. Also probably removing some of those lines and making it just a repository, not a package, would result into composer reading the individual modules composer.json.

But now everything seems to be right and module is installed and it will install my other files under vendor but PHP still goes to "class not found" in my service when I try to use my class from the other library.


trigger a form submission button using custom cron

This seems a little bit odd. Form submission are meant to be dealt with by humans in order to transfer information to a specific service.

So if you want to send any kind of request to a dedicated service, yes, that is possible using drupal_http_request.

  This is a flexible and powerful HTTP client implementation. Correctly handles GET, POST, PUT or any other HTTP requests. Handles redirects.

If you want to submit a Drupal form on cron, then you can use drupal_form_submit.

  This function allows you to supply values for form elements and submit a form for processing. Compare to drupal_get_form(), which also builds and processes a form, but does not allow you to supply values.

If you want to execute any custom logic (which might also be the result of a form submission by humans) then this is also possible using custom code.

For all that, you will need to implement hook_cron() in a custom module.

If anything else, please elaborate on what it is that you want to achieve.


No Schema type for mysql type datetime error while creating view to show webform submissions

You likely already resolved this, but I just ran into the same issue.  Here's how I resolved it:

I applied the patches to the Schema module listed here: http://drupal.org/node/1237974.

This got rid of the error, but because i had a db_prefix on my tables, I could not adopt them.  In order to get that working, I tried the patches here (http://drupal.org/node/894074#comment-6459584).  It didn't work for my view, so I logged in via PHPMYAdmin and removed the prefix dr_ from the webform view (instead of dr_webform_myviewname, it's now webform_myviewname).  This allowed me to adopt it.

I'm not saying it was pretty, but it is working now.

KMT


Configure the field in the form display, export this file

core.entity_form_display.poll.article.default.yml

and put it in the folder /config/install. Remove the uuid line from the yaml file.


How can I grey out/disable certain fields?

If you're using Webform 3.x, you're probably looking for the Webform Conditional module.  If you're using 4.x, conditionals support is built in.

Adding conditionals to your webform will allow you to show or hide webform fields based on answers to other fields.  Using the above module or built-in support in 4.x, you could completely hide a certain field if the answer to another field was "Yes."


I believe this is only possible by hacking the core pager functionality, so I wouldn't suggest it.

You could add this to your theme

function MYTHEME_pager_link($variables) {
  $text = $variables['text'];
  $page_new = $variables['page_new'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
  $attributes = $variables['attributes'];

  $page = isset($_GET['page']) ? $_GET['page'] : '';
  if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) {
    $parameters['page'] = $new_page;
  }

  $query = array();
  if (count($parameters)) {
    $query = drupal_get_query_parameters($parameters, array());
  }
  if ($query_pager = pager_get_query_parameters()) {
    $query = array_merge($query, $query_pager);
  }

  // Set each pager link title
  if (!isset($attributes['title'])) {
    static $titles = NULL;
    if (!isset($titles)) {
      $titles = array(
        t('« first') => t('Go to first page'),
        t('‹ previous') => t('Go to previous page'),
        t('next ›') => t('Go to next page'),
        t('last »') => t('Go to last page'),
      );
    }
    if (isset($titles[$text])) {
      $attributes['title'] = $titles[$text];
    }
    elseif (is_numeric($text)) {
      $attributes['title'] = t('Go to page @number', array('@number' => $text));
    }
  }

  // @todo l() cannot be used here, since it adds an 'active' class based on the
  //   path only (which is always the current path for pager links). Apparently,
  //   none of the pager links is active at any time - but it should still be
  //   possible to use l() here.
  // @see http://drupal.org/node/1410574
  $attributes['href'] = url($_GET['q'], array('query' => $query));
  return '<a' . drupal_attributes($attributes) . '>' . check_plain($text) . '</a>';
}

You'd need to change this line if ($new_page = implode(',', pager_load_array($page_new[$element], $element, explode(',', $page)))) { to use the separator you wanted.

But you'd also have to change a line in Drupal's core pager include (/includes/pager.inc)

In this function you'd change the character in the explode to what you want to use.

function pager_find_page($element = 0) {
  $page = isset($_GET['page']) ? $_GET['page'] : '';
  $page_array = explode(',', $page);
  if (!isset($page_array[$element])) {
    $page_array[$element] = 0;
  }
  return (int) $page_array[$element];
}

Edit: keep in mind, this will break pagers that are not using your theme which means your admin pagers probably won't work unless you do the same for your admin theme.


Find out which modules set session data by dumping these variables for anonymous requests:

var_dump(\Drupal::request()->getSession()->all());
var_dump($_SESSION);

You can ignore the symfony metadata starting with _symfony or _sf2.

Then search the code base for session set() commands setting this data. You can then either change this code or remove the session data in your own code with remove().

When all session data is removed the session will be destroyed automatically at the end of the request. The metadata doesn't count.

A special case is the symfony flash bag. Data stored here is normally only kept between two requests. Ideally the first one is a redirect so the second one happens immediately. Drupal uses the flash bag for system messages. The messages are displayed and removed by the status messages block, which is enabled by default. The messages block is uncacheable and re-built on each request, because of how the caching system handles requests containing a session.


Came across your post considering I had the exact same problem. I had several different attached views to my page that were grouped by different taxonomy terms.

The way I fixed it is a little janky, but it works... basically edit the Views Bootstrap module in sites/all/modules/views_bootstrap/templates/accordion/views-bootstrap-accordion-plugin-style.tpl.php and store a random integer in PHP as a variable with rand(); then append that variable to the $key on your accordion-toggle  tag as well as the "collapse" div.

It should work after that.


Have you tried Commerce Product Attributes?


Can Drupal 8 Form #states API be used to expand/collapse

Unfortunately, I'm going to answer my own question:  expanded and collapsed states do work for the <details> type.

My problem was operator error.  I was adding the #states array at the level of the '#type' => 'container' but the container has a widget inside of it that holds the '#type' => 'details'.   Fun times with Form API!

The working code is this:

<?php
// In mymodule.module
use \Drupal\Core\Form\FormStateInterface;

function mymodule_form_node_<type>_form_alter(&$form, FormStateInterface $form_state) {
  $form['field_address']['widget'][0]['#states'] = [
    // Expand location field when the Type is 'On-site'.
    'expanded' => [
      ':input[name="field_trigger"]' => [
        'value' => 'open'
      ],
    ],
    // Collapse location field when the Type is 'Online'.
    'collapsed' => [
      ':input[name="field_trigger"]' => [
        'value' => 'closed'
      ],
    ],
  ];

  // Load edit form with Location field either open or closed, based
  // on the value of the Trigger field.
  $form['field_address']['widget'][0]['#open'] = ($form['field_trigger']['widget']['#default_value'] == 'open') ? 1 : 0;
}


How can I cache the operations on the admin content overview per user?

This is not a cache tag issue. You need a cache context.

You can use a contextual filter for the user, then Views would add the cache context automatically.

Another option is to add the context to the render array of the View:

function mymodule_views_pre_render($view) {
  if ($view->id() == 'content') {
    $view->element['#cache']['contexts'][] = 'user';
  }
}

The cache context user.permissions is used by default in drupal caching. If this doesn't give you the variations you need in cache use the more general user context. Then for each user a new version of the View is cached, which will obviously use more database space.


You just need to reverse proxy all the asset directories like here (this proxies site preosasde via real site proreos):

ServerName preosasde

ProxyPass /themes/ http://proreos/themes/
ProxyPassReverse /themes/ http://proreos/themes/

ProxyPass /core/ http://proreos/core/
ProxyPassReverse /core/ http://proreos/core/

ProxyPass /vendor/ http://proreos/vendor/
ProxyPassReverse /vendor/ http://proreos/vendor/

ProxyPass /sites/ http://proreos/sites/
ProxyPassReverse /sites/ http://proreos/sites/

ProxyPass / http://proreos/asde/
ProxyPassReverse / http://proreos/asde/

Take care about the order of that entries and be aware that you will loose your users credentials (cause of the different domain).


$options['dump-dir'] = '/path/to/dumpdir';

found in example.drushrc.php :)


What modules do I need to add tokens in my content that references the current nodes field?

You'll need...

Entity API for its extended entity/field token support
Token filter which provides a simple filter that supports tokens

And probably nothing else :)


Automatically group the sub menu items in drupal 7

You could make links list attachment with views for each taxonomy term and then add them in theme_menu_link function if the link in variables matches. Note that requires customization in template.php