Custom html.tpl.php from module for custom type

Modules can use hook_preprocess_html() to override theme templates. You need 3 things:

A hook_preprocess_html() implementation
A hook_theme() implementation
A html template in your module dir

Using a module called MYMODULE, with a new node type mynodetype, & a template in the module dir named templates/html--mynodetype.tpl.php, we can add the following hooks to MYMODULE.

/**
 * Implements hook_preprocess_html().
 */
function MYMODULE_preprocess_html(&$vars) {
  $node = menu_get_object();

  // Add a new theme suggestion when viewing node's of mynodetype.
  if ($node && $node->nid && $node->type == 'mynodetype') {
    $vars['theme_hook_suggestions'][] = 'html__mynodetype';
  }
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $theme = array();

  //Add our templates/html--mynodetype.tpl.php to the theme registry
  $theme['html__mynodetype'] = array(
    'template' => 'html--mynodetype',
    'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
  );
  return $theme;
}


Check if your server supports Clean URLs. It is most likely the culprit.

You can consult the following threads on how to enable Clean URLs on Nginx.

Clean URLs on Nginx
Enabling Clean URLs on Nginx(Stackexchange)


Add the "center-block" class to the img tag.


How to set validation error for specific subfield of the paragraph type?

In the docs page for setErrorByName() we can read:

  string $name: The name of the form element. If the #parents property of your form element is array('foo', 'bar', 'baz') then you may set an error on foo or foo][bar][baz. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

We should also note the following code how it's parsed:

public function setErrorByName($name, $message = '') {
  // ...
      foreach ($limit_validation_errors as $section) {
        // Exploding by '][' reconstructs the element's #parents. If the
        // reconstructed #parents begin with the same keys as the specified
        // section, then the element's values are within the part of
        // $form_state->getValues() that the clicked button requires to be
        // valid, so errors for this element must be recorded. As the exploded
        // array will all be strings, we need to cast every value of the
        // section array to string.
        if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {

So the mentioned element should have the following syntax:

$form_state->setErrorByName("field_sor_rule][0][subform][field_sor_rule][0",
  t('Please enter a valid value!'));


How to list profile fields in a tableselect?

It sounds like you want field_info_instances():

$fields = field_info_instances('user', 'user');
$rows = array();

foreach ($fields as $field_name => $field) {
  $rows[] = array(
    $field_name,              // eg. 'field_my_field'
    $field['label'],          // eg. 'My Field'
    $field['description'],    // eg. 'A Description of my Field'
    $field['default_value']   // eg. 'default value'
  );
}


If you are running a script, you'll likely benefit from using Drush.  With the Drush php-eval and php-script commands, you can easily call a snippet of php code (such as the examples shown in other answers to this question) after bootstrapping Drupal.  Without Drush, you would have to set up a web service and use wget or curl to run your code, or try to call the Drupal bootstrap code yourself.  Better yet, Drush even comes with a built-in command to clear the cache, so you don't need to worry about writing any php code at all, if that's all you want to do from your script.  Just use:

cd /path/to/drupal/sites/default && drush cache-clear all

You may also wish to learn about site aliases; if you define an alias called @site, then you can instead use:

drush @site cache-clear all


Drupal 7 views - distinct not working with ordering by multiple (date) field

Apply a filter on the date field
Select the operator: 'Is equal to', and type '0'

  When you have a multiple value field, the field has a list or array of values. delta=0 is the first value

https://www.drupal.org/node/1872262#comment-6869736


You can use theme_site_map_box in your template.php!

I've done something similar before where I've changed the H2's to H3's:

Try something like the following in your template.php

function MYTHEME_site_map_box($variables) {
  $title = $variables['title'];
  $content = $variables['content'];
  $attributes = $variables['attributes'];

  $output = '';
  if (!empty($title) || !empty($content)) {
    $output .= '
';
    if (!empty($title)) {
      $output .= '
' . $title . '
';
    }
    if (!empty($content)) {
      $output .= '

' . $content . '

';
    }
    $output .= '
';
  }

  return $output;
}

I can't remember off the top of my head the structure of $content, but the above code should put an extra div around each section of the site map with the class of MYCLASS.

API Docs: theme_site_map_box()


How do i create node directly from my own module with data of my tables

From the information you provided I would handle this the following way:

Create a custom content type via the GUI with all the fields that you need.
Create a custom module and register a path via hook_menu(). I would set 'page callback' => 'drupal_get_form', 'page arguments' => array('mymodule_create_content_form') and 'access callback' => 'mymodule_admin_restriction'. mymodule_admin_restriction would be a function to allow access to user 1 only. mymodule_create_content_form would be a custom form builder function with just a submit button.
In the form submit handler I would then write code to extract data from the database and create new nodes from it. The easiest way to get data out of your database would probably be with db_query().
For programmatically creating nodes you could use either node_save() or drupal_execute(). The first one is a quicker option while the second one more closely mimics normal node creation by invoking additional hooks. You should be able to find a solid amount of information about them on the web (for example here, here and here).

This approach should be fairly good to get started with. Once you get the whole thing working without errors (in your development environment) you could move the code to your module's install file's hook_install() and maybe even programmatically create the new content type there if needed.


There's no way to do it with the default content admin page, short of writing code to alter the form. Vocabularies aren't linked exclusively to nodes in Drupal 7, they can be linked to any type of entity using the field system, so having this functionality wouldn't make sense by default any more.

Creating a View is definitely the right way to go; personally I'd install the Administration Views module which replaces (amongst others) the default content admin page with a View.

The module page says it provides support for filtering by vocabulary out of the box, but even if it doesn't provide sorting you could easily just tweak the View to your own requirements.


How do I set a custom path for feeds feed items in views?

The solution is to

Create a simple rule to delete and create url aliases after the content was saved, for the feed content type.
Used a pattern episodes/[node:title] which will give you the result.

Refer:

https://www.drupal.org/node/1161202
https://www.drupal.org/node/1210128


How to remove "Main Menu" title from Stark Theme

Go to admin/structure/blocks, find out the Main menu, click configure, and set title to <none>. This should resolve it.


For starters, looking at your code, $xml_data is instantiated but never used in your call to drupal_http_request(), you use the $data variable instead. Intentional or the culprit?

Second, your call to drupal_http_request follows the Drupal 6 (and earlier) syntax, what system are you using?

For Drupal 7, it should look like this:

$response = drupal_http_request($url,
  array(
    'headers' => $headers,
    'method' => 'PUT',
    'data' => $xml_data,
  )
);

// this should reveal what was actually sent out
dsm($response->request);

Hope this helps some!


How to verify only the email address on user registration?

I would NOT block the user at first. That will for sure also not cause that error message you try to get rid of. And instead use the Flag module (in combination with the Rules module) to implement your logic like so:

Use that same event When the user account is validated to flag that user with a flag labeled (say) "Validated".
Any time you want to check if an authenticated user has been validated, you just have to verify if that "Validated" flag has been set for that user (which you can typically do with the Rules module also.

As a remedy to the fact that a user who registers can login to the site without email verification (as in your comment below), you can add some Rules logic like so:

Rules Condition: if this user is not flagged (with that 'Validated' flag)
Rules Action: perform redirect to user/logout

Possibly with an extra message you could set (in the same Rules Action) like "sorry, your account has not been validated yet, please do so and so first".


How to grant referenced user access to Profile page

Here is ready to use code. For this to work you need to enable the Entity reference module, add entity reference field on admin/config/people/accounts/fields page targeting user entity and setting to unlimited, and finally giving access to View user profiles to all authenticated user role members.

Create my_module.info file and paste:

name = My Module
description = Does awesome things. Makes tea. Washes up. Favours of a personal nature.
dependencies[] = entityreference
core = 7.x

Create my_module.module file and paste:

/**
 * Implements hook_user_view_alter().
 */
function my_module_user_view_alter(&$build) {
  global $user;
  if ($build['#account']->uid == $user->uid || in_array('administrator', array_values($user->roles))) {
    // Return early if user is administrator or is at their own profile.
    return;
  } elseif (isset($build['field_users'])) {
    foreach ($build['field_users']['#object']->field_users[LANGUAGE_NONE] as $key => $referenced) {
      if ($user->uid == $referenced['target_id']) {
        return;
      }
    }
  }
  drupal_access_denied();
}

Go to a user profile, add some user references and try to view that user's profile as the referenced user to gain access and then as non-referenced user to get denied access.


Can we give serial numbers in views to each columns or row in a sequential manner?

When format is content

You can override views-view-unformatted.html.twig and perhaps create a twig file for just this particular view.

If your view name is test you can copy from core/modules/views/templates/views-view-unformatted.html.twig to your THEMENAME/templates folder and rename to views-view-unformatted--test.html.twig.  In this twig file you can use {{loop.index}} inside the for loop to give you the row index/count sort of like this:

{% if title %}

{{ title }}

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    row count: {{loop.index}}
    {{ row.content }}

{% endfor %}

When format is fields

Yes you can add view results counter when the format is fields


Views block template print individual field from content

I finally found the answer to this issue. Here it is in case some one is having the same issue.

The solution is insanely simple use the views fields template.

In my case I created a new template:

views-view-fields--VIEW-NAME.html.twig

And now you can access your fields values like this:

{{ fields.field_NAME.content }}

More details here

Enjoy.


how to remove duplicate from views' result page

What actually worked is the following

function mymodule_query_alter($query) {

  if (isset($query->alterMetaData)) {
    if (isset($query->alterMetaData['view'])) {
      if($query->alterMetaData['view']->name == 'node_search') {
        $fields =& $query->getGroupBy();
        // Tried various fields to check which was the field creating the problem.
        unset($fields['score']);
        $query->groupBy('nid');
      }
    }
  }
}

Answer found at http://www.brenthartmann.com/blog/how-use-hookqueryalter-drupal-7

PS: In order to check the sql query that produces your view, you need to go to admin/structure/views/settings and enable "Show the SQL query".


Checking if a machine_name exists or not

The exists key wants a callback that it can test for boolean true/false. The machine name to test will be passed as the first (and only) argument to that callback.

Since your entity class (not the list builder class) already has a load method, inherited from Entity::load(), which accepts an ID and returns either an entity object or a null/false value, you can (and probably should) use that.

So, assuming your entity is defined as \Drupal\mymodule\Entity\MyEntity, you would use the following:

'#machine_name' => array(
  'exists' => '\Drupal\mymodule\Entity\MyEntity::load',

Exactly the same method is used in the CommentTypeForm, and probably others:

$form['id'] = array(
  '#type' => 'machine_name',
  '#default_value' => $comment_type->id(),
  '#machine_name' => array(
    'exists' => '\Drupal\comment\Entity\CommentType::load',
  ),
  '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
  '#disabled' => !$comment_type->isNew(),
);


How can I direct the user to a different page on a multisite installation based on which subdomain they go to?

This is one of the things that you can do with the Domain Access module.  Essentially, it allows you to have different behaviors for a site with subdomains, but running from the same database.  This is different from multisite, which uses a different database for each site.


Applying Updates to Multiple Drupal Sites

Please remember that testing is a very important part of every site upgrade.  It would not be difficult to write a script to copy code & db from live to stage for all sites, and then run drush -y pm-update on each site in turn; however, you should include a manual testing phase after the pm-update, and then push each tested site back to the live site as they are found to be working.

For the deploy step, you will want to copy the code from stage to live, and then run updatedb on the live site.  The live site should be offline during this operation.  See also drush_deploy for scripting stage-to-live deployment.


Different "Asc" and "Desc" labels for different Views exposed sort fields

There's a feature for this in using the Better Exposed Filters module through certain combinations of BEF settings:

Set "Display exposed sort options as" to anything except Toggle links, which seems to give strange results
Under "Advanced sort options", tick "Combine sort order with sort by"
Save, and see what strings it outputs by default for the labels. For example:

  Price Highest
  Price Lowest
  Date listed Highest
  Date listed Lowest

Copy these into the "Rewrite the text displayed" field, then for each one put a | then the intended label, for example:

.

Price Highest|Price - Highest
Price Lowest|Price - Lowest
Date listed Highest|Date - Newest
Date listed Lowest|Date - Oldest

It then outputs as intended

  Price - Highest
  Price - Lowest
  Date - Newest
  Date - Oldest


How to update only one field using Views?

You might try the module Editable fields It is an old module that hasn't been updated in a long time, but I did get it working recently on a new project.

Another option is to build your own with rules, and rules links

With rules links you can set a path that sets a rule to activate. You can have that rule update the content with whatever setting you wish.


Can't seem to load CSS in a custom theme

Ensure you have a call to your library in your .info.yml

libraries:
 - pixelcircus/global


Twig template suggestions for paths such as page--node--page-url

You can add suggestions for the page template in a hook:

mytheme.theme:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function mytheme_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
}

This is an example how to add a suggestion with the path for any page. You can narrow it down to the pages you are interested in and if necessary check for paths that are too long.


Edit the classess applied to a field from outside the field template

Check out Semantic Panels. It lets you choose HTML element and classes for wrapper, the field and the label. The module provides the same options that are available to customize the field output in Views.

Here's a screenshot from the user interface when you customize the field.


A radios form field uses a process function (form_process_radios()) which is the function that expand the form element, and add its child elements (the single radio elements a radios element is made of).
When you call theme(), that process function is not called, and those child elements are not added.

theme_radios($variables) executes the following code.

  $element = $variables['element'];
  $attributes = array();
  if (isset($element['#id'])) {
    $attributes['id'] = $element['#id'];
  }
  $attributes['class'] = 'form-radios';
  if (!empty($element['#attributes']['class'])) {
    $attributes['class'] .= ' ' . implode(' ', $element['#attributes']['class']);
  }
  if (isset($element['#attributes']['title'])) {
    $attributes['title'] = $element['#attributes']['title'];
  }
  return '<div' . drupal_attributes($attributes) . '>' . (!empty($element['#children']) ? $element['#children'] : '') . '</div>';

As $element['#children'] is not set, what you get from theme('radios') is an empty <div> element with some CSS classes, and attributes.

Differently, when drupal_render() is called:

Any #pre_render, #process, #theme_wrappers, and #post_render function is called
Any child element is rendered


The best explanation of how to do a custom grid in Omega I have found is in the Omega documentation wiki: Creating and Setting up a Custom Grid for Omega 3.x. As the Omega documentation matures, I hope this will move into the main documentation.

The basic idea is below (but see the link above for more details):

Copy the appropriate grids entries from alpha.info into mytheme.info. There will be no grids entries initially in your mytheme.info if you have created a subtheme in the normal way. You will be copying various grids[alpha_default] entries. Then edit those entries to be grids[mytheme_default].
Generate a new CSS grid file at http://grids.heroku.com/ or http://www.spry-soft.com/grids/. Just use this as a model for the next step, as it does not correspond exactly to the way Omega CSS grid files are written.  The class naming conventions are a little different ("_" vs "-", for instance.
Copy the css and png files you need from sites/all/themes/omega/alpha/css/grid/alpha_default/{normal,wide,narrow,..}/alpha-default-*-*.{css,png}. to sites/all/themes/mythemes/css/grid/mytheme_default/{normal,wide,narrow,..}/mytheme-default-*-*.{css,png}. You will not need all the files unless you are planning to provide a complete set of narrow, normal, and wide 12 and 16-column grids. Just put in the ones you need.
If you are changing the default number of columns from 12, don't forget to edit the number-of-column defaults for all the different regions given further down in mytheme.info. Otherwise your pages will look wrong because they are using the original default settings.
Note you must also rename the mytheme/css/mytheme-alpha-default.css and mytheme/css/mytheme-alpha-default-{narrow,normal,wide}.css files to mytheme/css/mytheme-mytheme-default*.css. This is because you have changed the alpha-default grids name to mytheme-default.

I did all this recently for a design I was given that was 960px wide with no left and right margins. I set up a 60px by 16-column 960px grid.

The Omega Tools module has an incomplete wizard for setting up your own custom grid. Unfortunately, it does very little of the above as of this writing.


Form not receiving a CSS class, it's block wrapper does instead

Obviously the block plugin thinks the #attributes key in the returned array is meant for the block wrapper. So I would try to put the form in a subkey, this should prevent that the block plugin can access the attributes of the form:

  return ['form' => $this->formBuilder->getForm(...)];

By the way the core search block is also returning the form array directly like you did in the question and indeed, the resulting form tag in the search block has no classes too. I'm not sure, but this seems to be the same issue.


U want a block for image picker, I have checked it and found that it creates iframe for the same. so what we can do, is create a block either programmatically or manually and alter its content, by using hook_block_view_alter, and load image picker in it, and hide rest of element in drupal 7.


Is there a way to add a button to my form that does not submit the form but performs a mini validation and adds more inputs to the form

You can use #limit_validation_errors to limit the fields validated when a form is submitted with the button you add.
If you set $form_state['rebuild'] in the validation handler you add for the button the form will be rendered again instead of being submitted.
Then all you have to do it add some logic to the form that will display the extra fields. This can be done with the data in the $form_state.


Trying to display/printing latitude and longitude from Geolocation Field to node template

I did this by printing, {{ node.field_geolocation.lat }} and {{ node.field_geolocation.lng }}.

That should print the values.


How do I pass arguments from URL into panel page block?

I have not used Panels with D8, but...

With D7 Panels I remember there was a way to set/pass a contextual filter value, but one thing I noticed was if I did not set it in Panels and instead set it directly in the View's settings, it also worked.

So all you have to do is edit your View block, under Advanced, for contextual filters add Has taxonomy term ID

In the settings for that, select Provide default value and for type use Taxonomy term ID from URL

Alternatively, you could do


hook_commerce_checkout_complete is never called

Is the hook still being used in Commerce 2.x?

No.

  If not, what should I look at instead to achieve a similar effect?

Commerce 8.x-2.x depends on the state_machine module which has events that are triggered when an order is placed (=checkout complete) as well as other state changes.

See Assigning (adding) an entity reference when an Order process is completed


Unchecking a boolean field on form render

You can use hook_ENTITY_TYPE_prepare_form() to change entity values before the entity form is built:

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for Nodes.
 */
function mymodule_node_prepare_form(\Drupal\node\NodeInterface $node, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($node->getType() != 'my_content_type') {
    return;
  }
  if ($operation == 'edit') {
    $node->field_my_boolean_field->value = 0;
  }
}

This changes the value of the field for this node, but only temporary as long as the user doesn't submit the form.


Only the word "array" gets printed when I try to render custom block in template

You haven’t rendered the render array:

$output .= "
".render($block['content'])."
\n";


Does drupal_http_request ever cache results?

No, drupal_http_request() is not doing any kind of caching. If the results are cached then it's either the server or some intermediary system, e.g. a proxy.


Adding META tag to nodes with a specific topic

I think you definitely could use hook_page_build() (it would work), but since that hook is really intended for use with page.tpl.php, and meta tags are outputted in html.tpl.php, I think it might not be the 'Drupal' way.

Another option might be to use hook_html_head_alter(), which allows you to alter the <head> tags before they're rendered:

function MYMODULE_html_head_alter(&$head_elements) {
  if ($node = menu_get_object()) {
    $tid = function_to_get_term_id();
    $related_tids = field_get_items('node', $node, 'field_FIELD_NAME');

    if (!empty($related_tids) && $related_tids[0]['tid'] == $tid) {
      $head_elements['MYMODULE_meta_robots'] = array(
        '#tag' => 'meta',
        '#type' => 'html_tag',
        '#attributes' => array(
          'name' => 'robots',
          'content' => 'noindex'
        )
      );
    }
  }
}

You might also want to look at adding rel="nofollow" attributes on the links to those node in teaser displays, it might help speed up the process a bit.


I can not post an comment?

Anyway, there is not much information given about the hardware, settings etc. so from that point off its hard to say.

You might wanna retrace your steps if you are sure the uploadtime increased with 500 percent. Then you know if Memcache caused any problems, what ever the result is please update the question with more specific information.


If you are adding classes which will be styled by your theme then it is best to add them with the theme in template.php. Each theme might handle this differently.

For example, if your theme is based on Fusion then you can add new classes by implementing hook_core_preprocess_html()

<?php
function mytheme_core_preprocess_html(&$vars) {
    $vars['classes_array'][] = mytheme_hour_based_class();
}

function mytheme_hour_based_class() {
    // Return a CSS class based on the current 24 hour time
    return 'hour-of-day-'. date('H');
}
?>

If there isn't an existing context module which serves your purpose then you would have to create your own module which implements the context API. You can learn about the context API here.

http://drupalcontrib.org/api/drupal/contributions!context!context.api.php/7

Telling you how to do that would essentially require writing the module for you, which seems outside the scope of an answer.


Is it possible to display a field value as part of Views title?

Changing a View's title is a theming issue. Have a look at Views: how to programmatically change Views title?. The accepted answer is almost what you need. Add the function to your theme's template.php file (or your custom module if you don't have a custom theme yet).

The rest is simply coding. Store the field that you need as a variable $my_field and adapt the code from the referenced answer as follows:

function MY_THEME_views_pre_render(&$view) {
  if ($view->name == 'YOUR_VIEW_NAME') {
    \\ Store your field: $my_field = ...
    $view->build_info['title'] = "YOUR TITLE" . $my_field;
  }
}

You can use the Devel module to inspect $view in order to easily find the correct code for $my_field.


Using drush when database and web server are separate

The user name is taken from root's .my.cnf file (normally located in /root/.my.cnf. Either remove the user line from that file, or run Drush as another user than root (which might not have a .my.cnf file.)

Added: The relevant part of the MySQL documentation:

  If multiple instances of a given option are found, the last instance
  takes precedence, with one exception: For mysqld, the first instance
  of the --user option is used as a security precaution, to prevent a
  user specified in an option file from being overridden on the command
  line.


How to convert year to date with Migrate

Just found out that to_format value is the problem. Setting it to 'Y-m-d' works fine and imports the year value as date putting month and day to values of today. So actually to get specific day and month added to year value, this code works fine:

process:
    field_fecha:
      plugin: format_date
      from_format: 'Y'
      to_format: 'Y-01-01'
      source: year

Probably that's because I defined the date field as "date only". For "date and time" fields 'Y-m-d\TH:i:s' should work fine.


Link checker modules fails to detect a test broken link

Found Link checker works after  'run cron'

-- Found in video: https://www.youtube.com/watch?v=Hcl9iwIFZ2k
That a cron job has to be run after the configuring.
--  I had already set for automatic running of cron job.  For some reason it didn't work.
--  It worked after running cron job manually.
site-url/cron.php for D5 and D6

-- OR For Drupal 6.x, see in your site: Administer > Reports > Status report > Cron maintenance tasks > Run cron manually.

Steps for checking links:

Make sure link checker configuration is what you want
http://site-url/cron.php  in browser to run cron job (it yields blank page after the run)
See report for broken links and follow up specific links.

Here is another link for some relevant info on link checker module:
http://www.lullabot.com/blog/article/module-monday-link-checker


How do I get rid of the node title on a specific view mode?

Since already using Display Suite you can enable Extras module in orde to hide page title

DS config
admin/structure/ds/extras

Tab "Other"
Check "Page title options"

Node Manage Display
admin/structure/types/manage/article/display/full

Tab "Layout for article full"
select Hide "Page title"


First you need to set up an ID for the paragraphs. You can do this in oko_preprocess_paragraph():

/**
 * Implements template_preprocess_paragraph().
 */
function THEME_preprocess_paragraph(&$variables) {
  $variables['paragraph_id'] = $variables['paragraph']->id();
}

Now, you can output the ID of the paragraph using {{ paragraph_id }} in any paragraph templates you have. So you can copy paragraph.html.twig to your theme, and change this:

<div{{ attributes.addClass(classes) }}>

To this:

<div{{ attributes.addClass(classes) }} id="paragraph-{{ paragraph_id }}">


Responsive Grid in Drupal 7 Views with 5 columns

I think i figured it out.

If I set columns to 1 then I can use any responsive number of bootstrap columns according to the width.


Different number of decimals for prices and totals

If you can set the number of decimal places site wide... I would set it to most precision I am likely to need and shorten it through the theme/js in the places where I need it shorter.  It may not be as graceful as variable precision, but if no other answers come up, it will get the job done...


The name entry in variable table is supposed to be maintenance_mode following updates in D7 after which site_offline and site_offline_message were replaced with maintenance_mode and maintenance_mode_message. Refer the inline comments in  update_fix_d7_requirements in update.inc

  // Rename 'site_offline_message' variable to 'maintenance_mode_message'
  // and 'site_offline' variable to 'maintenance_mode'.
  // Old variable is removed in update for system.module, see
  // system_update_7072().

Assuming you have access to the database or drush try updating the variable which is likely set as 1 to 0.

drush vset maintenance_mode 0

or

UPDATE variable SET value = 's:1:"0";' WHERE name= 'maintenance_mode';

You might also want to ensure that this value is not set as 1 with a $conf variable in your site's settings.php.
Many users with similar issue also suggest even clearing the cache table entries named variables for this to work after changing the variable value. If things go well this should bring your site back online.


In a drupal commerce, how to use the same picture for every size attribute

If you're using commerce feeds, just use the same url to the same image on your server; or manually upload the same image for each!


How to set required to TRUE or FALSE based on the GIVEN #states?

States are used to set properties/values by javascript. The #required property is for the server-side validation, it can't be controlled using states.

You could either implement an AJAX callback on the text field change to update the required status and rebuild the form, or implement a validation handler which checks the status of the text field and throws an error if it contains text but no payment method has been selected.


How do I create a tax calculation rule that runs by default before the customers address has been set?

It looks like your problem might be caused by the incorrect usage of the "OR" (within your Rules Conditions). The logic you have in your "conditions" is like so:

Order address component comparison.
AND one of the next conditions in the OR group must be true:

Data value is empty.

Here is an attempt to translate your current Rules Conditions:

  "Order address component comparison must be TRUE" AND "Data value is empty".

I doubt that is what you wanted to implement as Rules Conditions, but that is how Rules actually interprets them ...

I'm not sure which (at least 2!) set of Rules Conditions you wanted to combine with the "OR"-operator, but what is shown in your question for sure cannot be right. Maybe you want to try to see what happens if you adapt your Rules Conditions like so:

OR one of the next conditions in the OR group must be true:

Order address component comparison.
Data value is empty.

That is: move the "Order address"-condition below the OR, and also indent it (same indent as for "Data value is empty).

So if either (or both) of those 2 Rules Conditions are satisfied, then the Rules Actions will be performed. That should be pretty close to "*If the country component of the order address is AU OR (repeat: OR !!!) if it is not set, then calculate GST*" (as in your question).

For an interesting video tutorial about this, refer to "Combining conditions". Somewhere around '9:00' (near the end), it has a similar OR condition. Here is a summary of that tutorial:

How to be confused over the positioning of the AND and OR statements
How to combine conditions with AND requirements
How to combine conditions with OR requirements
How to combine AND and OR groups to create complex conditions
Some advice about the order of conditions
How to delete reaction rules
Why you shouldn't use the "send e-mail to all users in a role" action
Why it might be useful to have messages printed out when configuring complex rules


How to get Block Plugin Id? when block created using block type entity?

You use the custom block uuid:

'plugin' => 'block_content:' . $custom_block->uuid(),


After enabling repeat date on node, calendar won't show repeated dates

After deleting and recreating the date field on your content type (as in the Original post), re-add it to the list of fields in the Views context filter (Date: date(node)).


In Views, what is the difference between "Show Fields" and "Show Content" under Format?

Show: content will render the content as it is normally displayed if you access it at its URL.  For example, selecting Show: content for a view displaying users will display each user's full profile.  Selecting it for a view displaying nodes will render each node in its entirety.

Show: fields, by contrast, allows you to select (limit) which fields to display.


Conditionally hide the node comments via preprocess function

$variables['content']['comment']['#access'] = FALSE;

That should work, assuming you use the default comment field named "comment", otherwise whatever you named it. Comments are just a field, nothing special about them.

You can also check it directly in twig and not print it there.


How to stop autosuggest in node author field and write our own?

You could write a small module that implements hook_form_alter in which you remove the autocomplete functionality for this field.  This should convert it to a textfield.  However, this will certainly break if an author name that is not also the username of a user is inserted, since this field is used to populate $node->uid, which must have a valid username.

A more viable solution would be to create a vocabulary of your author names, and a taxonomy term field on your content type (pointing at that vocabulary).  And then display this field as you desire.


Views aren't respecting the ?destination=xxx in the URL

It's not views, is the Drupal core. When creating/saving a node, you are automatically redirected to that node. You could create a module that hooks into node saving form and redirect you to the url destination path.

you should also check the rules modules. It seems that could do the job for you.


Get the current range values from a QueryAlterableInterface

Luckily (or thankfully) the Reference module adds some rather useful information as meta data to the query in question. Making it easy to spot in terms of its id (although you have to watch out that the id is prefixed with a whitespace character). This is the same id for all similarly made queries. It also records the $options array, which means we have a reference to the ['limit'] value without going through the $query object.

I've set the following to work for any field, but have left reference to the $field in use just in case it is useful for others. For my purposes 300 rows is a suitable default to have, rather than just accepting an infinite number or records.

Whilst this doesn't access the limit/range value from the query itself, it does solve the problem in quite a general way.

/**
 * Implements hook_query_alter().
 */
function HOOK_query_alter(QueryAlterableInterface $query) {
  /// trim due to typo in references module (took me a while to spot this)
  $id = trim((string) $query->getMetaData('id'));
  if ( $id === '_node_reference_potential_references_standard' ) {
    $field = $query->getMetaData('field');
    $options = $query->getMetaData('options');
    if ( !empty($options) && (empty($options['limit']) || !$options['limit']) ) {
      drupal_set_message('Modifying Node References query to ' .
        'protect against too many values (limited to 300 values)');
      $query->range(0, 300);
    }
  }
}


I hope I understood your question correctly, that you want to apply theme on form submit.

theme_hook_suggestions is used when a template is being rendered. I think you don't need to save it on form submit. You just need to provide logic of selecting a template file in preprocess function of template.php file. Drupal looks for the suggested template file to apply to particular page/node etc

As a pseudo code, it would be

if(template_type is default)
   apply default type
else if(template_type is blank)
   apply blank type

For help, visit this link  https://www.drupal.org/node/1089656

Moreover, the example of preprocess function is as follows

function THEME_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type)) {
    // If the content type's machine name is "my_machine_name" the file
    // name will be "page--my-machine-name.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}


Translating interface - same word duplication

You need to translate each of these strings individually. It is not enough to do it only once.


Your problem is that you are using routeMatch() to get the node id, which won't be returned when using VBO.
You said you're using hook_entity_update():
function hook_ENTITY_TYPE_update(Drupal\Core\Entity\EntityInterface $entity)

This code assumes that the entity you are running hook_entity_update() for is the node entity.
Since the hook provides the $entity object, you can get the node id like this:
$nid = $entity->id()


How to avoid Drupal redirecting my multilingual Views pages?

i18n_path submodule

I assume you're also using the i18n module. So make sure you also enabled the i18n_path submodule (= Path translation). More details about it, from the community documentation (bold markup added here):

  ... allows you to map together existing pages that are translations of each other. This will allow users to use the language switcher to navigate between the associated pages.

  The module is meant to be used as a last resort to translate paths that can't otherwise be mapped together as translations. For example, paths to translated nodes can already be linked with the Content translation module and paths to translated taxonomy terms can be linked with the Taxonomy translation module. Path translations should be used to link generic paths, such as those provided by Views or Panels.

  To set up translations of a particular path, you need to create a path translation set by going to Configuration > Regional and language > Translation sets > Paths and clicking Add path translation.

i18n page views

You may also want to check if you can get it to work using the i18n page views module. Some details from its project page:

  ... provides a new display of views, where you can select different paths for each language enabled on your site, so a view has a localized route for each language.

Note 1: "if you cannot find any option in the view to translate the path" (as in your comment below), then you may want to have a look at what's mentioned in Comment #1 of issue 2389535, which states:

  ... May be you have chosen a page display rather than a i18n page display when you created your view. Please be sure that you selected the correct views display. I attach some screenshots for helping:

Screenprint 1:

Screenprint 2:

Note 2: To answer the question about "Will I have to create the whole view page again to make it as an i18n_page?" (as in one of your (now deleted) comments below this answer), I would give it a try using either of the approaches described in the answers to the question at
How to duplicate a Views display (which is not the master) as a different display type? ... If that doesn't work / apply, then recreation of the whole view page seems like the only option left.


Is using Drupal for a frontend and a non-Drupal API for a backend possible?

Drupal 7/8 can make use of Remote Entities which could be provided in a JSON format. But, what your describing seems needlessly complex. If you have a JSON based backend I would do something more simple like create the frontend using Javascript to talk to your backend, or maybe using a more generic php framework.

Attempting to use Drupal as a frontend and ignoring its data creation CRUD, Content Types and storage mechanisms -- sounds like big headache.


You can run your custom cron methods as an authenticated user as follows:

use Drupal\user\Entity\User;

/**
 * Implements hook_cron().
 */
function my_module_cron() {
  // Login as user 1
  $user = User::load(1);
  user_login_finalize($user);

  // Your custom cron functions

  // Login as user 0 (anonymous)
  $user = User::load(0);
  user_login_finalize($user);
}


Does ajax used in views call preprocessing hooks?

In template "views-view-fields.html.twig" there is a three variables returned : "view", "fields", "row" you can see this here
.

So to add your custom variables you need to put it into these three variables like below

 function dt8_preprocess_views_view_field(&$vars)
  {
    $vars['row']->my_var = 'Hey';
  }

and in our template "views-view-fields.html.twig" we print int like this

{{ row.my_var }}


Access one Field from another field via field.tpl.php

You can access to the entity (node) to which the field is attached using $element['#object'] variable from the field template (or preprocess function).

For example, add this code in field--field-cta-button.tpl.php:

<?php
$field_cta_text = $element['#object']->field_cta_text;
echo $field_cta_text[LANGUAGE_NONE][0]['value'];
?>

If you installed devel module you can use dpm($element['#object']) function to inspect the entity variable.


I think you need to look at URL aliases under configuration/Search and metadata or look it up in the url_alias table in the database.

Worst case scenario, try to search "&mch57a" in the entire database, to see which module is generating it.


maintenance mode after error occurs while running update

Most housekeeping tasks like these can be done using Drush, a Drupal command line managing tool. For example, you can reinstall the module using

drush pm-disable modulename
drush pm-uninstall modulename
drush pm-enable modulename

the database can be updated by issuing

drush updatedb

And code is easily updated with

drush pm-update

To use drush you need a shell access to a server your site runs on. No authorization as Drupal user is needed.


How to add html to the "My user points" page (user points module)

You can find the menu path defined for " My User Points " page in userpoints.module file in hook_menu implementation..

  $items['myuserpoints'] = array(
    'title' => 'My !points',
    'title arguments' => userpoints_translation(),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('userpoints_list_transactions'),
    'access callback' => 'userpoints_access_my_points',
    'file' => 'userpoints.pages.inc',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'user-menu',
  );

As you see above..

Page callback drupal_get_from with arguments "userpoints_list_transactions" is defined in "userpoints.pages.inc" file...

/**
 * Displays a detailed transaction report for an individual user.
 *
 * @param $account
 *   For which account to display. Defaults to the current user.
 */
function userpoints_list_transactions($form, &$form_state, $account = NULL, $tid = NULL) {

  // If this is an AJAX request, update $_GET['q'] so that table sorting and
  // similar links are using the correct base path.
  if ($_GET['q'] == 'system/ajax') {
    $q = 'myuserpoints';
    if (!empty($account)) {
      $q = 'user/' . $account->uid . '/points';
    }
    $_GET['q'] = $q;
  }

  if (empty($account)) {
    global $user;
    $account = $user;
  }

  $settings = array(
    'show_user' => FALSE,
  );
  $header = userpoints_get_transaction_header($settings);

  $query = db_select('userpoints_txn', 'p')->extend('PagerDefault')->extend('TableSort')
    ->fields('p')
    ->condition('p.uid', $account->uid)
    ->orderByHeader($header)
    // Enforce consistent sort order.
    ->orderBy('p.txn_id', 'DESC')
    ->limit(variable_get(USERPOINTS_REPORT_LIMIT, 10));

  if (module_exists('taxonomy')) {
    $query->leftJoin('taxonomy_term_data', 't', 'p.tid = t.tid');
  }

  $unapproved_query = db_select('userpoints_txn', 'p')
    ->condition('uid', $account->uid)
    ->condition('status', USERPOINTS_TXN_STATUS_PENDING);
  $unapproved_query->addExpression('SUM(points)');

  $values = userpoints_filter_parse_input($form_state, $tid);
  $active_category = userpoints_filter_query($query, $values);
  userpoints_filter_query($unapproved_query, $values);

  if (isset($active_category)) {
    drupal_set_title(t('!Points for @username (%category category)', userpoints_translation() + array('%category' => $active_category, '@username' => format_username($account))), PASS_THROUGH);
    $total_title = t('Total !points (%category category)', userpoints_translation() + array('%category' => $active_category));
  }
  else {
    drupal_set_title(t('!Points for @username', userpoints_translation() + array('@username' => format_username($account))));
    $total_title = t('Total !points', userpoints_translation());
  }

  $rows = array();
  foreach ($query->execute() as $transaction) {
    $rows[] = userpoints_get_transaction_row($transaction, $settings);
  }

  // Store context in the output array so that modules have access to it.
  $output = array(
    '#account' => $account,
    '#attached' => array(
      'css' => array(
        drupal_get_path('module', 'userpoints') . '/userpoints.css',
      ),
    ),
  );

  $output['form'] = userpoints_filter_form($account, $values);

  $output['list'] = array(
    '#type' => 'container',
    '#id' => 'userpoints_list_wrapper',
  );
  $output['list']['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('No !Points earned', userpoints_translation()),
    '#weight' => -5,
    '#attributes' => array('class' => array('userpoints-myuserpoints-list')),
  );
  $output['list']['pager'] = array(
    '#markup' => theme('pager'),
    '#weight' => 0,
  );

  // Fetch pending (not yet approved) points according to the category filter.
  $pending = (int)$unapproved_query
    ->execute()
    ->fetchField();

  // Display both pending and approved points in a simple table.
  $output['list']['summary_table'] = array(
    '#theme' => 'table',
    '#header' => array(
      array(
        'data' => $total_title,
        'colspan' => 2,
      ),
    ),
    '#rows' => array(
      array(
        'data' => array(t('Approved !points', userpoints_translation()), userpoints_get_current_points($account->uid, isset($values['tid']) ? $values['tid'] : 'all')),
        'class' => array('userpoints-myuserpoints-total-approved'),
      ),
      array(
        'data' => array(t('Pending !points', userpoints_translation()), $pending),
        'class' => array('userpoints-myuserpoints-total-pending'),
      ),
    ),
    '#weight' => 10,
    '#attributes' => array('class' => array('userpoints-myuserpoints-total')),
  );

  // For simplicity, the generated output is passed to a custom alter function.
  // This would also be possible through hook_page_alter(), but that hook is
  // hard to use.
  drupal_alter('userpoints_list_transactions', $output);

  return $output;
}

In the end you can see generated output is passed to a custom alter function

  drupal_alter('userpoints_list_transactions', $output);

By implementing hook_TYPE_alter()  in your custom module you can able to change the output..
i.e YOURMODULENAME_userpoints_list_transactions_alter function you need to implement..

/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
}

$output is a form variable.. You can add a new element to $output ..

/**
 * Implements hook_userpoints_list_transactions().
 */
function MODULENAME_userpoints_list_transactions_alter(&$output) {
  // you can now change $output directly here
  $output['custom_text']['my_link'] = array(
    '#markup' => l("LINK", "Your Link"),
  );
  $output['custom_text']['my_text'] = array(
    '#markup' => 'Blah Blah',
  );
}


Something very simple like this, using user_load_by_name(), would be an option:

$original_username = $username = 'something';
$count = 1;
while (user_load_by_name($username)) {
  $username = $original_username . $count++;
}

$fields = array(
  'name' => $username,
  ...

That will keep on trying 'something', 'something1', 'something2', 'something3', etc. until it finds a unique name.


How to show drupal error messages in batch scripts?

You should really be using Drush.  It handles bootstrapping and reporting error messages, etc.  In particular, the command drush php-script will be useful to you.

$ cd /path/to/drupal/sites/mysite
$ drush php-script /path/myscript.php

Write your script as usual.  Drush will bootstrap for you, so you may simply start calling Drupal APIs.  Any error messages generated will be printed to stderr.  See the readme file, http://drush.org, and  drush topic for all sorts of advice on getting started.


How can I have custom content as last page?

Probably the easiest way to do this would be to add a footer to your view. If you are on the admin screen for your view, you should see options for Page Settings, Header, and Footer in the middle column.

If you "Add" content to the Footer area it will always output below your view content. There are several options including to display a rendered node.


You didn't mention which version of Drupal you are using, I'm assuming 7:

This is exactly what the image module in core does, it allows you to upload one image that it then can scale, crop and more. What it doesn't do is provide the links to download. I'd package this up into a small module (I couldn't find anything similar with a quick Google search) that defines the image styles using hook_image_default_styles(). You could then possibly create a field formatter that shows a thumbnail and then the links to different image sizes (you'd get the URL for each image style with image_style_url().

Probably one of many ways of doing this but if you are comfortable writing code this could be a good way to go!


Even if you don't use pathauto,  Drupal7 can not differentiate case sensitive urls. This 'issue' is not code related,  but it has to be with the database collation. non-binary string comparison are case-insensitive by default.

A solution could be to set the 'alias' columns (menu_router.path, url_alias.alias) to binary (case-sensitive).

Be aware that changing the structure of those two columns in existing sites could result in broken links because paths/alias would have to match base on case.


Related nodes displaying same related data

The duplicate node with different locations is in question. I would do it using the Location module which can add multiple locations to a single node.

  Location Add Another: Allows you to quickly add new locations to a
  node.

In your case, you can even add many locations to a restaurant node without creating duplicates. The menus nodes can be entity reference to each restaurant node.


As said in other answers you can do that by theming. If you want to go for modules. Then these are for you.
Background Images

Background images is a collection of modules that allows users to add background images to html elements on pages of the site

Background Images Formatter

This module provides an image formatter who allows you to set an image
in background of a div. The images are from a field of an entity and
not from a configuration page or sth else, so it's very easy to setup
and manage.
Use cases

You want to display a image on the back of a div when viewing a
particular node.
You want to display a random image on the back of a div on the
frontpage only. This can be done using Views. Create a block, select
the "Background Image" formatter for your image field, save, place
the block, boom, you're done.


Creating a view block inside a fieldset using templates

Put the template file in your themes directory not views theme directory. It will detect it there. I like to have a views directory inside the themes template directory to organize view template files. I mimic views naming convention for a directory structure so views-view-fields--brands--default.tpl.php and views-view-grid--brands--default.tpl.php would go in:

views/brands/default

It's a nice way to keep the files organized.


In the template.php, add an "onclick" attribute with theme_preprocess_block:

function mytheme_preprocess_block(&$variables, $hook) {
  if ($variables['block']->delta == "my-viewblock-name") {
    $variables['attributes_array']['onclick']='my_click-routine()';
  }
}

Then, in a .js file you add

function my_click-routine(){
  // Do whatever you want here, e.g. show the "page view" when clicking on the block view;
  document.location="page-view-url";
}

This makes the entire block clickable. You can also do more than just navigate to another page.


How to make a Feature available only to certain Spaces?

The features for each space are configured via the spaces_features_form() function. You could implement hook_form_alter() to selectively and conditionally remove features from specific groups.

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'spaces_features_form') {
    $space = spaces_get_space();
    // Populate the array with hard-coded NIDs, or whatever logic
    // needed to determine if these features should be allowed.
    if ($space->type == 'og' && !in_array($space->group->nid, array(...))) {
      // Hide features foo and bar.
      foreach (array('feature_foo', 'feature_bar') as $feature) {
        $form['spaces_features'][$feature]['#access'] = FALSE;
      }
    }
  }
}


hook_field_formatter_info() hook lets Drupal know about the new display denfinition and field settings, you will see your display type under Manage display settings of your content type. However the actual format of the field is returned with help of hook_field_formatter_view.

Example Code


Need webform with list of items, price, and total

You can try Webform Calculator, I know it has checkbox support. You can set values for fields, then calculate the total amount at the end of webform for the submission.

  Provides a formula webform component for computed values, where you
  can enter a mathematical calculation based on the other fields. E.g.,
  create a formula field with value formkey1 * 0.1 * formkey2.


Drupal Views module provides this functionality. You don't need to write the code for that.
See the image below
Here you can set item to display as want. It has many more options


Reduce the amount of information returned from standard service actions

For user objects specifically there's hook_services_account_object_alter(), e.g.

function MYMODULE_services_account_object_alter($account) {
  unset($account->mail);
}

For other entity/resource types there's hook_services_request_postprocess_alter(), e.g.

function MYMODULE_services_request_postprocess_alter($controller, $args, &$result) {
  // Manipulate $result till your heart's content.
}


Bootstrap Views Grid Unable to specify Medium and Small device classes

I had a similar issue some months ago. It seems Bootstrap Views allows this possibility, but only in the dev release, not in the latest stable release.

In order to do what I wanted in the stable release of the module, I ended up with the following solution:

/**
 * Implements preprocess_views_view__VIEW().
 */
function scicnet_preprocess_views_view__MY_VIEW(&$vars) {
  $display_id = $vars['display_id'];
  switch ($display_id) {
    case 'MY_DISPLAY':
      $vars['rows'] = str_replace('col-lg-4', 'col-lg-4 col-md-4 col-sm-12', $vars['rows']);
      break;
  }
}

Not the most elegant solution, I admit, but it does the job...


How to make 'Views' consider contextual filter value to be 'all' automatically?

I don't know if it clashes with your configuration, but usually you use the option Display all results for the specified field under When the filter value is NOT available.

There is also the option under When the filter value IS available or a default is provided > Specify validation criteria:

Action to take if filter value does not validate

where you can choose to Display all results for the specified field. Maybe you can combine it with some Validation conditions to achieve what you want.


Rendering renderable arrays in an item_list

According to https://api.drupal.org/api/drupal/includes!theme.inc/function/theme_item_list/7 theme_item_list is looking for data key so your list item should look like this:

// Construct a renderable array wrapper for the template invocation.
$tmp = array(
  '#type' => 'container',
  '#attributes' => array('class' => array('provider')),
  'providername' => array(
    '#prefix' => '',
    '#type' => 'markup',
    '#markup' => $name_link,
    '#suffix' => '',
  ),
  'providervalue' => array(
    '#prefix' => '',
    '#type' => 'markup',
    '#markup' => $value,
    '#suffix' => '',
  ),
  'metricname' => array(
    '#prefix' => '',
    '#type' => 'markup',
    '#markup' => $class_link,
    '#suffix' => '',
  ),
);
$items[$metric]['data'] = drupal_render($tmp);

That should give you single element:

test1test1test1


You can add the map into a view in simple way.
Enable the "geofield map" module .Create a view . you can add a field(geofield) and in the settings you can give the "Formatter" as geofield map. You can also add the other fields you needed from that node.

Step 1 :Enable the "geofield map" module in the  geofield module pack. Than create a view with the geofield (latitude and longitude) fields with a contextual filter node id. In the view you can set the "Format" as geofield map(see attachment). . You can also do with the help of "location" module. Now you have a view of map.

Step 2: Enable the views_field_view module. Create another view for the restaurant details. For viewing the map, you can select "Global :view" in the field. There you can select which view you should have to embed in that field and you can give the arguments there(here 'nid') in the field settings(see attachment).

See also the Views Field View module, which may help you.
You can first create a view for the map with a argument as node->nid. Then create another view for your restaurant. In the second view you can embed the first view (for map) as a field.


If you add the JavaScript in hook_init, then it will be there the next time the page is served from the cache.

And if the page is served from the cache, then calling drupal_add_js in hook_boot will not add JavaScript to the page, because the page is not assembled from calling the page callback, but is served from the cache.

Use hook_init instead of hook_boot.


You should not be using theme_preprocess to perform any processing the results of which cannot be cached, only manipulation of variables to be passed to the final theme processing function or template.

Doing a redirection in a theme_preprocess will cause the result to be empty and this is what leads to the WSOD, I believe.

Instead the preferred method is to use an event subscriber, as described on this page: https://www.drupal.org/node/2013014

  Register your Event Subscriber in your mymodule.services.yml and tag it as such:

services:
  mymodule_event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    tags:
      - {name: event_subscriber}

  Your MymoduleSubscriber should be placed in folder structure of modules/src/EventSubscriber/MymoduleSubscriber.php and should implement the EventSubscriberInterface interface and in its getSubscribedEvents() point to the method that should be executed:

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  public function checkForRedirection(GetResponseEvent $event) {
    if ($event->getRequest()->query->get('redirect-me')) {
      $event->setResponse(new RedirectResponse('http://example.com/'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

}


Create an "About the Author" box for multilingual sites

Profile2 is based on Entity and you have 2 ways of translating entities in Drupal.

by creating an instance of the entity for each language : see https://www.drupal.org/node/1280934
by defining some fields that are translatable : see https://www.drupal.org/node/1280632


I think the estrange behaviour it's because the suffix is after and not inside the wrapper, thus not get replaced and since you're ajaxly returning $form['field_job_description']; which contains the wrapper; thus, you end up with two same ID wrappers and fails on the second run.
Move the link generation to a function.
Here is an alternative AJAX approach where we target the link wrapper rather than the form wrapper.
function my_dashboard_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'node_job_listing_owner_job_form_form'){
    $link = _my_dashboard_get_term_link($form, $form_state);
    $form['field_job_description']['#suffix'] = '
' . $link . '
'; // wrap link
    $form['field_job_description']['widget']['#ajax'] = [ // removed 'wrapper' =>
      'callback' => 'updateJobDescriptionPreviewLink',
      'event' => 'change',
    ];
  }
}

function updateJobDescriptionPreviewLink(&$form, \Drupal\Core\Form\FormStateInterface $form_state){
  $link = _my_dashboard_get_term_link($form, $form_state);
  $response = new \Drupal\Core\Ajax\AjaxResponse();
  $response->addCommand(new \Drupal\Core\Ajax\HtmlCommand(".term-link", $link));
  return $response;
}

function _my_dashboard_get_term_link(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $tid = $form_state->getValue('field_job_description')[0]['target_id'];
  if(empty($tid)){
    $tid = $form['field_job_description']['widget']['#default_value'][0];
  }
  $link = null;
  if(!empty($tid)){
    $link_url = \Drupal\Core\Url::fromRoute('entity.taxonomy_term.canonical', [
      'taxonomy_term' => $tid
    ], [
      'attributes' => [
        'class' => ['use-ajax'],
        'data-dialog-type' => 'dialog',
        'data-dialog-options' => \Drupal\Component\Serialization\Json::encode(['width' => 420]),
        'data-dialog-renderer' => 'off_canvas',
      ],
    ]);
    $link = \Drupal::l('Preview Job Description...'.$tid, $link_url);
    return $link;
  }
}


Parent and subordinary weights and relations like in menu and taxonomy system module

Couldn't you do this with the Relation module, views and Rules?


Main differences between registry and file_registry tables in Drupal SQL tables structure?

The file_registry stores entries for all uploaded files as attachments or file_entities to Drupal. Files marked for deletetion are removed at Cron and cleared from the table.

The registry table stores Drupal system information on all available code files available to the system from modules and themes. And more importantly includes all php classes used in the system and where they may be found. When you install or remove modules or themes from your Drupal installation php files are added/removed from the registry table.


Maybe you could use the Closed Question module.
You can find more information about the module here.

  Features

  Designed for practicing: students can take as many attempts as they like.
  Many feedback options, feedback can change with attempts.
  Many question types.
  Questions can be added anywhere in a site.
  Only Questions. Ordering questions in a quiz or case is done by a separate module.


D7: Get terms from node and display other nodes with same term in block?

Try this module - https://drupal.org/project/views_arguments_extras
This allows you to select a field from the current node as a contextual filter.
Enable this module.
Create a  new view, block display, and the chose the relevant field as the contextual filter.
Configure the view as per your requirement and show the block on your node page. It should work.


Using base_path and directory variables in twig template

You can expose the base_path variable to all you templates by implementing hook_preprocess() in your theme .theme file.

e.g.

/**
 * Implements hook_preprocess().
 */
function mytheme_preprocess(array &$variables, $hook) {
  $variables['base_path'] = base_path();
}

where mytheme is the machine name of your theme.

You can use {{ active_theme_path() }} to get the path to the active theme.


Reply for comment redirects to the next page

It seems the AJAX Comments module is what you're looking for.
I've installed it it's working good without Advanced Forum module.

Features:
Provides ajax comments to Drupal sites. Features:

Makes AJAX submits
Allows replies to comments on the actual thread page
AJAX comments deleting
Works with CAPTCHA
Cool jQuery sliding
views integration


use different "From" header for different actions when sending emails

use hook_mail_alter function in your custom module and change the from address based on your requirements.


How to target the "site name" within a css file

It depends on the theme that you're using.

As Patrick Ryan said " You should look into using firebug in firefox or inspect in chrome or developer tools in IE. These will all easily show you what css class you need to target to make these and any other changes."

I personally use Chrome so in order to do that, just right click on the site name. Here's a preview in chrome.

you can use #site-name or #name-and-slogan in this theme. But this will change per theme. The same process can be done if you want to align the text or make it wider.

The great thing about using these development tools is that they allow you to add CSS right on the browser. you'll see that on the right side. Just double click.

If you're using a subtheme of Zen, for example, check the templates in the zen folder to see the page.tpl.php file for the template of the page.

I touch on using templates in Zen subthemes in my slides here (slide 44 onwards): http://www.slideshare.net/japodomingo/theming-with-zen

If you know how to use templates, you can manipulate the display any way you want. :) Here's a brief overview of the templates. https://drupal.org/node/190815

I hope this helps.


You should not edit core code, ever.

For variables (set with variable_set) can try using something like strongarm module, or you can override using $conf in settings.php:

 /**
 * Variable overrides:
 *
 * To override specific entries in the 'variable' table for this site,
 * set them here. You usually don't need to use this feature. This is
 * useful in a configuration file for a vhost or directory, rather than
 * the default settings.php. Any configuration setting from the 'variable'
 * table can be given a new value. Note that any values you provide in
 * these variable overrides will not be modifiable from the Drupal
 * administration interface.
 *
 * The following overrides are examples:
 * - site_name: Defines the site's name.
 * - theme_default: Defines the default theme for this site.
 * - anonymous: Defines the human-readable name of anonymous users.
 * Remove the leading hash signs to enable.
 */
 $conf['site_name'] = 'My Drupal site';
 $conf['theme_default'] = 'garland';
 $conf['anonymous'] = 'Visitor';

This documentation is from default.settings.php.


Entity Reference Autocomplete module: hook_entity_info definition?

I'm the module maintainer. Thanks for using the module, hope you're finding it useful. You need to add a 'label' key to your entity definition, like:

'entity keys' => array(
  'id' => 'grid',
  'label' => 'table-column-that-contains-the-human-name-of-entity',
),

With that, and after flushing caches, etc, your form should work fine. The reason is that entityreference_autocomplete assumes that (as a best practice), every entity would have, apart of the ID, which will be normally just a number, some friendly way to identify it through a label. Therefore, you need that on your custom entity.

However, I get that not everyone might want / need that 'label' key or a column for the label in their schema, for whatever reason, and I've added support to the module to work without that. That bit is on the dev version on the module, and will be rolled out in the next stable version. So it's up to you, to define a column for the 'label' key in your schema, or download the dev version, or wait a  couple days for the stable release that supports entities without the 'label' key.

Cheers!


Migrate a filefield to another filefield?

The best way to do this without writing a module or messing with your database is to use views bulk operations with rules.

Here is an example of moving a file from one file field to another.  You'll have to change the field names before you import this rule.

Basically add a rules component- then add your conditions and action

Variables

Datatype Node

Usage Parameter

Conditions

Entity has field - field_a

Entity has field - field_b

Actions

Create a loop to loop over multiple values in field_a.

Inside loop add item to list

Inside same loop remove item from list

Outside of loop Save your node.

{ "rules_fa_fb" : {
    "LABEL" : "Move resource files from one field to another.",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "TAGS" : [ "Dev" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "nodes" : { "label" : "nodes", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "nodes" ], "field" : "field_field_a" } },
      { "entity_has_field" : { "entity" : [ "nodes" ], "field" : "field_field_b" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "nodes:field-field-b" ] },
          "ITEM" : { "file" : "files" },
          "DO" : [
            { "list_add" : {
                "list" : [ "nodes:field-field-a" ],
                "item" : [ "file" ],
                "unique" : 1
              }
            },
            { "entity_save" : { "data" : [ "resource" ], "immediate" : "1" } },
            { "list_remove" : { "list" : [ "nodes:field-field-a" ], "item" : [ "file" ] } }
          ]
        }
      },
      { "entity_save" : { "data" : [ "nodes" ], "immediate" : 1 } }
    ]
  }
}

Then create the view with a bulk operations field, you'll need to change some values to import into your system.

$view = new view();
$view->name = 'move_files_from_on_field_to_another';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Move files from on field to another';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Move files from on field to another';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_operations'] = array(
  'action::node_assign_owner_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_item' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_delete_revision' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_script_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::flag_node_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_sticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_make_unsticky_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_modify_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'show_all_tokens' => 1,
      'display_values' => array(
        '_all_' => '_all_',
      ),
    ),
  ),
  'rules_component::rules_fa_fb' => array(
    'selected' => 1,
    'postpone_processing' => 0,
    'skip_confirmation' => 1,
    'override_label' => 0,
    'label' => '',
  ),
  'action::views_bulk_operations_argument_selector_action' => array(
    'selected' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
    'settings' => array(
      'url' => '',
    ),
  ),
  'action::node_promote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_publish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpromote_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_save_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::system_send_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::redhen_fields_email_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::node_unpublish_by_keyword_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::auto_entitylabel_entity_update_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
  'action::pathauto_node_update_action' => array(
    'selected' => 0,
    'postpone_processing' => 0,
    'skip_confirmation' => 0,
    'override_label' => 0,
    'label' => '',
  ),
);
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Files - for digital */
$handler->display->display_options['fields']['field_resource_file']['id'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['table'] = 'field_data_field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['field'] = 'field_resource_file';
$handler->display->display_options['fields']['field_resource_file']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_resource_file']['delta_offset'] = '0';
/* Field: Content: Files - for print */
$handler->display->display_options['fields']['field_files_for_print']['id'] = 'field_files_for_print';
$handler->display->display_options['fields']['field_files_for_print']['table'] = 'field_data_field_files_for_print';
$handler->display->display_options['fields']['field_files_for_print']['field'] = 'field_files_for_print';
$handler->display->display_options['fields']['field_files_for_print']['click_sort_column'] = 'fid';
$handler->display->display_options['fields']['field_files_for_print']['delta_offset'] = '0';
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'resource' => 'resource',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'admin/move-files-from-on-field-to-another';


What is the skeleton structure for a Drupal 7 module?

Minimum files needed:

Normally, the minimum files needed for a module is the following:

sites/all/modules/{name of your module}

{your module}.info
{your module}.module

Or use the examples module:

The examples module on drupal.org provides you skeleton modules to develop custom/contrib modules. Just use that to copy and create your modules off of.

Check out the project page:

  This project aims to provide high-quality, well-documented API
  examples for a broad range of Drupal core functionality.

  (Interested in other, non-core examples?)

  Developers can learn how to use a particular API quickly by
  experimenting with the examples, and adapt them for their own use.

Link to the git repository: http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x

Code from the examples module:

I've also just pasted in the code you could get from the examples module.

example.info file:

name = Examples For Developers
description = A variety of example code for you to learn from and hack upon.
package = Example modules
core = 7.x

example.module file:

<?php

/**
 * @file
 * This file serves as a stub file for the many Examples modules in the
 * @link http://drupal.org/project/examples Examples for Developers Project @endlink
 * which you can download and experiment with.
 *
 * One might say that examples.module is an example of documentation. However,
 * note that the example submodules define many doxygen groups, which may or
 * may not be a good strategy for other modules.
 */

/**
 * @defgroup examples Examples
 * @{
 * Well-documented API examples for a broad range of Drupal 7 core functionality.
 *
 * Developers can learn how to use a particular API quickly by experimenting
 * with the examples, and adapt them for their own use.
 *
 * Download the Examples for Developers Project (and participate with
 * submissions, bug reports, patches, and documentation) at
 * http://drupal.org/project/examples
 */

/**
 * Implements hook_help().
 */
function examples_help($path, $arg) {
  // re: http://drupal.org/node/767204
  // 5. We need a master group (Examples) that will be in a main
  // examples.module.
  // The examples.module should be mostly doxy comments that point to the other
  // examples.  It will also have a hook_help() explaining its purpose and how
  // to access the other examples.
}

/**
 * @} End of 'defgroup examples'.
 */


Why are my radio buttons not displaying?

Form builder functions must return a form array, not a string, otherwise they won't work with drupal_get_form(). If you need to add markup before and after the form you you should use the #prefix and #suffix properties, or do it outside of the form function altogether.

Also the function signature for Drupal 6 should not contain the $form variable as an argument, but the $form_state variable instead. And you're currently setting the value (text) of the submit button to the HTML representation of a an <input> field which will never do what you want.

Try using code like this instead:

function ismiv3point1_search_block_form($form_state) {
  $form['search_block_form']['#title'] = '';
  $form['search_block_form']['#value'] = 'Search mysite.org';

  $form['submit']['#type'] = 'markup';
  $form['submit']['#value'] = 'Search the Site';
  $form['submit']['#weight'] = 2;

  // this is the new field I'm trying to add
  $form['image_switch'] = array(
      '#type' => 'radios',
      '#title' => t('Image Switch Radios'),
      '#prefix' => '
',
      '#suffix'   => '',
      '#weight' => '3',
      '#options' => array(
          1 => t('Images'),
          2 => t('All'),
      ),
      '#default_value' => 1
  );

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

Sort by newest first

Sort by newest first

Sort by relevance

';

  return $form;
}

EDIT

Just a bit of extra info on how to do this with a form alter hook:

function ismiv3point1_form_search_form_alter(&$form, &$form_state, $form_id) {
  $form['image_switch'] = array(
    '#type' => 'radios',
    '#title' => t('Image Switch Radios'),
    '#prefix' => '
',
    '#suffix'   => '',
    '#weight' => '3',
    '#options' => array(
        1 => t('Images'),
        2 => t('All'),
    ),
    '#default_value' => 1
  );
}


I'm assuming you're using the VAT module. Ubercart's prices aren't flexible enough to adjust the display price based on the VAT. You should probably enter the prices for each product including the VAT and adjust your uc_vat so the sell price is inclusive.


How can I allow users to add a reason for a flag?

There is a really good discussion about something like this at http://drupal.org/node/871064.  It will take some patching and such but there seems to be a semi-working version available.

Other than that, it doesn't look like there is anything else readily available for Drupal 7 at the moment.


CSS. Your fieldset should be wrapped in one big div, with each field-item wrapped in it's own div. I see no reason you couldn't do this with CSS alone.

Unless there's a specific reason you need each line to be exactly three images. In that case you would have to override the field template: https://drupal.org/node/1089656

Then you would have to write some basic PHP logic that counts the number of field items and print those out in a 1X3 display.


How do I move a https site to localhost?

As Kevin suggested in the comments, I did not have a local certificate installed. Using MAMP, I ended up following the instructions here to solve the issue.


Why can't I override my views theme template files?

Be sure you use the Rescan button in the Theme: Information dialog. Also, be aware that pasting names not carefully enough can put white space in front of the file name. You wont see the spaces in FileZilla or TC, but it can leave your file unrecognized. So watch out when pasting.


You can use the method view() of the field.

Example, to get the render array of the body field as configured in the viewmode full:

$renderarray = $node->body->view('full');


Create View to display users with same select list value to each individual user

You can do it creating using Views with a contextual filter.

Profile2 has integration with views, and if you create a view's page display with a path like yoursite.com/user/[username/id]/users-with-same-college url. You get it!

Hope it helps.

Regards.


Monitoring field changes in custom content type

Step 1 - Detecting changes

You can make this work using the Rules module:

Rules Event: Before saving content.
Rules Condition (1st): "Entity has field", whereas you should specify these values:

"node" (saved content) for the "data selector" of entity.
the machine name of your price field.

Rules Condition (2nd): Compare the value of the specific field, for both the original value (before editing the field) and the (new) updated value, to verify if they are different. For this you add an additional Rules Condition which is a Data comparison. And the actual data to be compared are:

original value of the field, which you should be able to find/select by first using as data selector the node-unchanged:...(unchanged content), followed by selecting the field name of your field from the additional list that is shown after you selected that node-unchanged:...(unchanged content).
updated value of the field, which you should be able to find/select by first using as data selector the node:...(saved content), followed by selecting the field name of your field from the additional list that is shown after you selected that node:...(saved content).

Step 2 - Logging changes

By using the Message module, you can create your custom logging of changes detected by the Rules module. For way more details on this, refer to the answer to "What is a good flexible way to send auto system emails to users?".


Figured it out:

function comply_advantage_uc_cart_alter(&$items)
{
    $item->price->setValue($item->price->value * 0.95);
}

Hope it helps someone!

** IMPORTANT **

It looks like if you use

$item->price->setValue($item->price->value * 0.95);

Yo might end up altering the price several times. So I had to actual recalculate the price completely, without using $item->price->value, or it would deduct 5% multiple times.


Yes, that's possible. You can try to adjust the used base URL by setting the $base_url value in your settings.php .


I can't login to Drupal as my session cookie was deleted?

Pound passes along the client IP appropriately, but it needs to be forcibly set for non-https (http) requests to Varnish.

if (req.http.X-Forwarded-Proto !~ "https") {
  remove req.http.X-Forwarded-For;
  set req.http.X-Forwarded-For = client.ip;
}


Subscribe to the UserLogin event like below:

in yourmodule/src/Event/UserLoginEvent:

<?php

namespace Drupal\yourmodule\Event;

use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\Event;

/**
 * Event that is fired when a user logs in.
 */
class UserLoginEvent extends Event {

  const EVENT_NAME = 'yourmodule_user_login';

  /**
   * The user account.
   *
   * @var \Drupal\user\UserInterface
   */
  public $account;

  /**
   * Constructs the object.
   *
   * @param \Drupal\user\UserInterface $account
   *   The account of the user logged in.
   */
  public function __construct(UserInterface $account) {
    $this->account = $account;
  }

}

in yourmodule/src/UserLoginSubscriber.php:

<?php

namespace Drupal\yourmodule\EventSubscriber;

use Drupal\yourmodule\Event\UserLoginEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Class UserLoginSubscriber.
 *
 * @package Drupal\yourmodule\EventSubscriber
 */
class UserLoginSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      // Static class constant => method on this class.
      UserLoginEvent::EVENT_NAME => 'onUserLogin',
    ];
  }

  /**
   * React to the user login event dispatched.
   *
   * @param \Drupal\yourmodule\Event\UserLoginEvent $event
   *   Dat event object yo.
   */
  public function onUserLogin(UserLoginEvent $event) {
    $response = new RedirectResponse("yourpath");
    $response->send();
    return;
  }

}


Migrate Private Files: FILE_EXISTS_REUSE still duplicate files

This solved it for me.  The documentation at this link has been updated to show that you need to use the class prefix:

$this->addFieldMapping('preserve_files')
  ->defaultValue(1);

$this->addFieldMapping('file_replace')
  ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);


Drupal Commons: Active sub theme of Commons Origins is intermittently not working (base theme is showing)

Turns out the theme_registry... entries in the cache table were not getting cleared for some reason.  I ran the following in mysql prompt:

delete from cache where cid like 'theme_%';

It's been working fine for hours now


URL in link field adds duplicate parameters in query string when using an internal relative path

Seems like a bug in Core at the moment. Follow the issue queue: https://www.drupal.org/project/drupal/issues/2885351

Seems like a workaround currently is to use full paths instead of relative ones or use the patch in the issue above to patch core.

There seems to be a module someone made too since patching core isn't ideal:
https://www.drupal.org/project/link_formatter_query_fix


Controlling blocks displayed in domain access for each sub-domain

You've a module that gonna help you. Domain Blocks. And here you've many other that add some features to Domain Access module.


Image style effect for removing empty space around image

I don't think you can with a module. The only solution is use Photoshop or else.
ImageCache Actions is the best module for custom style image, but I don't believe is going to...


Is registering a controller as a service still frowned upon in D8

From a Symfony docs discussion

fabpot commented

  @lsmith77 is right. I strongly believe that this is NOT a best practice. I don't recommend it at all. That's why it's not in the book and explained in a cookbook entry.

mahono commented

  It would be nice to understand why what is (not) best practice. @fabpot: could you give some more info why you think so (or is there more information about that somewhere else?) To me most important is to learn best practices how to make my bundles customizable.

fabpot commented

  The DIC mostly helps manage "global" objects. Controllers are not global objects. Moreover, a controller should be as thin as possible. It's mainly the glue between your Model and the View/Templates. So, if you need to be able to customize then, it probably means that you need to refactor them and extract the business logic from them.

With that said, here's a blogpost arguing for controllers as services: http://pooteeweet.org/blog/1947


User field imported with Feeds but not showing in user edit page?

I can't delete foo and recreate it for it contains several data

Here is how I would try to fix this:

Backup your entire Drupal Database.
With phpmyadmin or some other database manager/viewer, find the field_foo table and extract the table as a CSV file.
In Drupal, go to user manage fields and Delete field foo
Flush the cache (not necessary, but eh, just in case)
Add a new field, foo
Edit user 1 and put something for field foo. (This is just so we get the table structure on step 7)
Find field_foo in DB and extract.
Open Original field foo .csv in excel and highlight all data and copy.
Open new field foo .csv and paste data and save
Import new field foo .csv to DB.
Flush/Clear the Cache
Try importing with feeds again and see what happens.


How to include multiple taxes to a product's price?

This is not supported unfortunately; it would require custom code for both the price field widget and the tax module's saving routine. If that's beyond your capabilities, you'll simply have to reverse calculate the price and enter it, accepting that the rounding may not always work out to nice round product prices like you want.


One possibility is to create a custom search page using Views and Search API. With Search API you can select precisely what you want to get indexed.


Decoupling Drupal 7 from Ubuntu/Debian package management

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

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

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

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


Generate breadcrumb based on a given Path

It really depends on what module/configuration you are using to generate the breadcrumb, sometimes some basic configuration is set in the base theme you are using as well, you might wanna check that out in your page.tpl.php file. basically your question is so vague it's hard to answer.

but mostly in most of themes the breadcrumb is being generated like this:

Home > Node title

Home > Taxonomy Term > Node title


Bartik theme: How to extend text/content below blocks in sidebar 1 and 2

Edit your page.tpl.php
Cut and paste both the sidebar sections into the content section.
Content section starts with:

I mean these parts:

<?php if ($page['sidebar_first']): ?>

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

  <?php endif; ?>

<?php if ($page['sidebar_second']): ?>

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

<?php endif; ?>

I think you will need some extra CSS to make it look nice.


It appears that:

function THEME_preprocess_html(&$variables) {
    drupal_add_library('system', 'ui.slider');
}

is needed for query_ui to be available for anonymous users on every page.


Assuming you built this form programmatically (custom module):

Wrap your radios field inside a class using #prefix and #suffix

   $form['email']['required'] = array(
        '#type' => 'radios',
        '#default_value' => 0,
        '#options' => array(0 => $this->t('Required'), 1 => $this->t('Not Required')),
        '#prefix' => '
',
        '#suffix' => '
',
    );

Use CSS to alter the look.

Create a CSS file.

my_module/css/myform.css

  a bit indented

.indent {
  margin-left: 10px;
}

  make the radio buttons inline?

.indent .js-form-type-radio {
  display: inline-block;
}

Create a library

my_module/my_module.libraries.yml

form-stuff:
  version: 1.x
  css:
    theme:
      css/myform.css: {}

Attach library to your form so it loads your CSS

$form['#attached']['library'][] = 'my_module/form-stuff';


How to restrict editing some node properties (like title / URL) for some users (roles)?

If you want finer control over any field then you can implement hook_field_access($op, $field, $entity_type, $entity, $account) and provide/deny access.

Determine whether the user has access to a given field.
This hook is invoked from field_access() to let modules block access to operations on fields. If no module returns FALSE, the operation is allowed.