How to debug / log comments when developing a custom module to fire when cron is run

The function watchdog is also available in Drupal 7

Here is an exemple of how you can use it in your case :

watchdog('MyModule', 'My message, this is my node title : %node_title', array('%node_title' => $node->title), WATCHDOG_INFO, NULL);

If you want to use a translated string you can do something like this :

watchdog('MyModule', t('My message, this is my node title : @node_title', array('@node_title' => $node->title)), array(), WATCHDOG_INFO, NULL);

If you need to print an array, you can try something like this :

watchdog('MyModule', '<pre>'. print_r($node, TRUE) .'</pre>', array(), WATCHDOG_INFO, NULL);

You can watch the log in Reports -> Recent log messages (admin/reports/dblog) if the core module "Database logging" is activated.

Once your module is stable, you can remove the watchdog line.


You can use attachment for this. In Views UI push add and choose attachment. Add the fields as you want them to be displayed. Also look under Attachment settings in the attachment display, choose which view to attach to, before / after etc.


This is taken directly from Form API Reference. Familiarize yourself with it.

$form['selected'] = array(
       '#type' => 'select',
       '#title' => t('Selected'),
       '#options' => array(
         0 => t('No'),
         1 => t('Yes'),
       ),
       '#default_value' => $category['selected'],
       '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
   );

EDIT

To print the result from the selection, you could consider a few things:

Do not use a form at all. Just use theme_item_list wherein you create hyperlinks to pages with nodes or users.
Use the form, but persist the user's selection (node or user) to the database or SEESION. Then when the form is created you reload the persisted value from the database or SESSION (if not present use default) as the default value so it always reflects the user's last choice, and you create a markup element wherein you show either the nodes or users that were the result of the selection or the default. In the submit you only persist the value to the database or SESSION. In the form creation you look at the persisted or SESSION value (if present, else use default), and display it in the markup element.
Use the form, do not persist anything in the database, and in the submit you inspect the select list value, and depending on the value you redirect (using $form_state) to a page that will show either nodes or users.
Create a jump list: for example ARCHIVE: Example: How to Create a 'Jump Menu' from a List View


For any POST, PATCH or DELETE request, you always need to pass along the X-CSRF-Token.

After logging in via REST, the new X-CSRF-Token should be provided in that data result, then you can just set that aside (in a global variable, in local storage, etc) and then pass it along with each request.

I personally use (and created) this module to make things easier: https://www.drupal.org/project/angular_drupal


Pre-process drupal_goto or use hook_exit to stop redirect

This is most often caused by UTF-8 with BOM. Check your editor and change the file format if it is.

The only way to redirect in hook_exit() is another drupal_goto(). Be careful that you don't create redirection loops.


How to set the default values of "Included Export Components" for a Drupal Webform

I remember having to do that once, and though I looked at how the values were initially set, I still ended up using hook_form_alter to change them.
I don't remember why exactly, but presumably due to fact I couldn't reach them as easily.

Just use a hook_form_alter in a custom module to get to the form, and unset the defaults you don't want.

This should pretty much do it in a hook_form_alter or hook_form_ID_alter ( example is for hook_form_alter ) :

if ($form_id == 'webform_results_download_form') {
  /**
  * default ( and named ) components are :
  * - serial: Submission nr
  * - sid: Submission ID
  * - time: Time
  * - draft: Draft
  * - ip_address: IP Address
  * - uid: User ID
  * - username: User Name
  */
  $excludes = array('serial', 'sid');

  foreach ($form['components']['#default_value'] as $cid => $component) {
    if (in_array($component, $excludes)) {
      unset($form['components']['#default_value'][$cid]);
    }
  }
}

This will uncheck both the Submission Nr & Submission ID checkbox. Adjust the $excludes array accordingly to your needs


How can I create a very simple entity definition for Webform submissions?

Got it working. In a custom module (mymodule), I implemented hook_entity_info() like so:

function mymodule_entity_info() {
  $info = array();
  $info['mm_submission'] = array(
    'label' => t('Simple Webform Submission Entity'),
    'base table' => 'webform_submissions',
    'fieldable' => FALSE,
    'entity keys' => array(
      'id' => 'sid',
      'label' => 'sid',
    ),
  );
  return $info;
}

This very simple entity definition was sufficient for VBO to treat my submissions as entities and pass their IDs to my custom URL.

Though I didn't need to, it should be possible to override the entity class controller and its entity functions (load, save, delete, etc) should you need to. This tutorial by Ronald Ashri was useful to me and talks more about that.

After installing my custom module, I was pleasantly surprised to see a "Bulk operations: Webform submissions" field magically appear in the list of available Views fields.

I didn't make any other connection between Webform submissions and my custom entity type, nor otherwise tell VBO to treat the Views results as mm_submission entities--somebody (Views/VBO/Webform?) just automatically made it happen; which is awesome.

I presume VBO knew to process the submissions as mm_submission entities because of the entity type base table attribute? Not sure without looking more closely; perhaps someone else can shed more light on that.


Internal Server Error and Machine Readable Names

Just try this :
on .htaccess, replace Options +FollowSymLinks by Options +SymLinksIfOwnerMatch

Example from : http://www.drupal8.ovh/en/tutoriels/9/install-drupal-8-virtualmin-error-500


Panels- How can I show the related terms pane only if the term being displayed has only the root as parent?

I wrote something quick together over in Different variant for other Taxonomy hierarchy within vocabulary, that gives a selection rule for the term level.

It sounds like that would help you.


How to show more terms in the "Parent terms" select list when adding taxonomy term?

OK Nick, you need to add the 'hook' into a custom module..
so for drupal 8 if you do not have a custom module follow the documentation here
https://www.drupal8.ovh/.../create-a-simple-module-for...
https://www.drupal8.ovh/.../create-a-simple-module-to-use...

In 'modules' folder create a custom folder 'custom' to hold your custom modules.
path should be ...modules/custom
inside this create a folder folder to hold your custom module my_custom_module ( orwhatever you want to call it )
path should be ...modules/custom/my_custom_module

inside this folder (my_custom_module) add a 'my_custom_module.info.yml' file in this file add

name: My custom module
description: My custom module description
package: Custom

type: module
core: 8.x

run drush en my_custom_module -y
or in admin/modules enable the module

once enabled add a .module file to the my_custom_module folder, called my_custom_module.module (or whatever you have called it)

in this file you can add the hooks you want to use for your one it will be

<?php
function my_custom_module_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'taxonomy_term_vocabulary_name_form') {
$form['relations']['parent']['#size'] = '15';
}
}

change the my_custom_module to whatever you have called your module
change the section of the form id == vocabulary name to the name of the vocab you have created, you may need to inspect this and find it the form id! mine matched the vocab

clear the cache, go to your vocabulary and add a new term ! fingers crossed the size of the selct box has changed

think this covers it all, good luck


How do I enable a features module in the setup of a simpletest testcase

As of Drupal 7 you don't have to explicitly specify module dependencies, they are resolved automatically.  The order doesn't matter either for that same reason.

As far as actually enabling the feature, it should be fine... I was going to suggest calling drupal_static_reset('system_list') before module_list() but it already does that itself when you pass TRUE as the first param like you did.

I've had some issues when testing features modules and, in certain situations, I've found that it's actually better (and much slower) to force SimpleTest to use the live database.

Granted, that's very specific to certain types of client projects, but still, might help! :)


Custom Field Type only shows -hidden- Widget

If you are absolutely sure your field type is compatible with some existing widgets and formatters you can reuse them by implementing hook_field_widget_info_alter and hook_field_formatter_info_alter.

/**
 * Implements hook_field_widget_info_alter().
 */
function gettweet_field_widget_info_alter(array &$info) {
  $info['text_textfield']['field_types'][] = 'get_tweet_field_type';
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function gettweet_field_formatter_info_alter(array &$info) {
  $info['text_default']['field_types'][] = 'get_tweet_field_type';
}


How do you transfer ownership of a Drupal contrib module to someone else?

You can either:

Open an issue on the Drupal.org project ownership queue, asking to make the new project owner a user on drupal.org that you know be willing to become the new project owner
Open an issue on the same queue, asking to make the new project owner the maintainer who did more commits or who was more active in following and answering the project issues
Open an issue in the same queue, stating you are seeking for a new project owner, using Needs maintainers as Component value

Once you open the issue queue, the procedure will be handled by Drupal.org site moderators.
As alternative, you could simply set the Maintenance status field of the project to Seeking new maintainer and (eventually) the Development status to No further development. Users who need the project, and who are able to develop code for a project, seeing you set that status, could ask to be the new project owner or maintainer, if they are interested.
Finally, if you think you won't maintain anymore a project hosted on drupal.org and you won't use Drupal, you could delete your account on drupal.org. Authenticated user are now able to delete their account on drupal.org, for any reason they could have.


Look in settings.php; I expect someone set $conf['site_name'] = 'Test name'.  Anything hard-coded there cannot be overridden.


When does system generate global variable $user?

Drupal initializes the global $user during bootstrap. Unfortunately, it doesn't invoke any hook, as modules are not yet loaded. (Loading the enabled modules is the last step of Drupal bootstrap.)

The following code is used in the Drupal session handler _drupal_session_read().

  // Handle the case of first time visitors and clients that don't store
  // cookies (eg. web crawlers).
  $insecure_session_name = substr(session_name(), 1);
  if (!isset($_COOKIE[session_name()]) && !isset($_COOKIE[$insecure_session_name])) {
    $user = drupal_anonymous_user();
    return '';
  }

  // Otherwise, if the session is still active, we have a record of the
  // client's session in the database. If it's HTTPS then we are either have
  // a HTTPS session or we are about to log in so we check the sessions table
  // for an anonymous session with the non-HTTPS-only cookie.
  if ($is_https) {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
    if (!$user) {
      if (isset($_COOKIE[$insecure_session_name])) {
        $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
          ':sid' => $_COOKIE[$insecure_session_name],
        ))
        ->fetchObject();
      }
    }
  }
  else {
    $user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
  }

To extend the global $user, you can implement hook_boot(), which is invoked when Drupal is still bootstrapping, or hook_init(), which is not invoked for cached pages. hook_user_load() is invoked when user_load() is called, but user_load() is not used for the global $user.

As side note, the global $user is not a complete user object. It contains the data saved in the "users" table, and not (for example) the value of any field (fields implemented from the field API) associated to the user entity.
$user->data can be used to store extra data for the user object. Its content can be altered through hook_user_presave() in the same way done by overlay_user_presave().

function overlay_user_presave(&$edit, $account, $category) {
  if (isset($edit['overlay'])) {
    $edit['data']['overlay'] = $edit['overlay'];
  }
}


You're probably logged in to the site.

The user login and registration pages are not available for authenticated users, as it doesn't really make sense for a logged in user to login again or register.


Google Analytics Events Tracking Module not working out of the box

No JS additions are needed; that's taken care of for you. The GA Events Tracking module doesn't work by itself however, it requires 2 things:

The GA module.
A module implementing hook_google_analytics_et_api().

The module includes an example module which you can either alter directly (not recommended) or just create a renamed copy of it (renaming files & functions from google_analytics_et_example to mymodule). More information can be found on the project page on what you need to do. It does require you to know a little something about:

jQuery: To set the appropriate event (e.g. mousedown) & selector (e.g. #main-menu li a).
Google Analytics Event Tracking: (to set the right data for the event).


You will need to join in the comment table and check the comment count.

...
LEFT JOIN {comment} c ON (c.nid = n.nid)
...
HAVING COUNT(c.cid) > 0

The whole query would probably become something like this:

$row = db_query('
  SELECT nid \'id\',title \'name\', field_category_tid
  FROM {node} n
  LEFT JOIN {field_data_field_category} fdft ON (fdft.entity_id = n.nid AND bundle = :article AND entity_type = :node)
  LEFT JOIN {comment} c ON (c.nid = n.nid)
  WHERE type = :article AND status = :status AND fdft.field_category_tid = :cat
  HAVING COUNT(c.cid) > 0
  ORDER BY title asc
  '.$limit, array(':cat' => $cat, ':article' => 'article', ':status' => NODE_PUBLISHED, ':node' => 'node'))->fetchAll(PDO::FETCH_OBJ);

Final note, what you want can be easily achieved with the Views module without having to write a query.

UPDATE:

Count should be checked in HAVING.


I think Opengraph Filter is a better solution than Facebook-Style Micropublisher since FBSMP relies on Statuses module and both modules are not very stable yet and also they serve for a more specific purpose. Opengraph Filter does only that what you need.


I believe there's a quiet simple solution using rules.
More specific based on the existing commerce_stock by default enabled rules :
- Stock: validate add to cart
- Stock: validate checkout
These rules have both an action "Set the state of the checkout process (called once per item)", preventing add to cart or checkout when the stock conditions are not met.

In order to check line item quantity with on product level defined minimum order quantities,  you can clone these rules and alter the rule conditions.
There's a way to implement a custom rule condition using hook_rules_condition_info().

Example implementation could be :

/**
* Implements hook_rules_condition_info().
**/
function my_custommodule_rules_condition_info() {
  return array(
    'minimum_product_qty_applied' => array(
      'group' => t('Commerce Line item'),
      'label' => t('Min. product qty selected'),
      'parameter' => array(
        'commerce_line_item' => array(
          'type' => 'commerce_line_item',
          'label' => t('Commerce line item'),
        )
      ),
    ),
  );
}

function minimum_product_qty_applied($line_item) {
    return _check_minimum_product_qty($line_item); //returns TRUE or FALSE
}


How attach a Custom Field do it by code to a Custom Type Page

You just have to create or change the file attaching the field to instead be attached to the page content type:

First we'll have to rename it: field.field.node.page.field_brand_information.yml

Secondly, we should be fine just changing all the references from car_brand to the page bundle instead:

# field.field.node.page.field_brand_information.yml
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_brand_information
    - node.type.page
  module:
    - text
id: node.page.field_brand_information
field_name: field_brand_information
entity_type: node
bundle: page
label: 'Brand Information'
description: 'More specific information about the car brand'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  display_summary: false
field_type: text_with_summary

Generally this approach is quite tedious and I agree as also pointed out in the article that you rather do it through the UI and then export the files appropriately.


Using RNG with a seminar with multiple optional sessions

What you have so far sounds good, and you're on the right path by setting each seminar to be an RNG event. Unfortunately there is no "conference track" support built in, so you will have to write some code to prevent new registrations based on predefined constraints.

What I would do is add a date field on each session, then another field indicating which track each session is on.

RNG uses the entity reference plugin system to determine if a user is eligible for each event. What you can do is create a hook_query_alter implementation in a custom module. In that hook, you can determine which event the query is for. Then with partial assistance from the RNG API, determine if there are any events the user is registered with the same constraints as the queried event. If you want to allow the user then you do no modifications to the query. If you want to prevent the user from registering, you can add on a condition hack which never evaluates such as $query->condition('uid', NULL, 'IS NULL');

I understand this solution may be complex, especially if you are not a coder or familiar with Drupal 8 API's. Check out UserRNGSelection.php for some inspiration.

Side note: I am maintainer of RNG.


Show a Display Suite view mode depending on a field value in the profile of the viewing user

Are you looking for code or just the approach? One approach would would be to use HOOK_entity_view_mode_alter(&$view_mode, $context) in a custom module:

Check that the user is logged in
Check that the user is viewing the right kind of node
Load the user and get the profile field value
Based on the field value, set the view mode ($view_mode = 'custom')


You can use SystemController::systemAdminMenuBlockPage as controller in the route of parent menu of module. Some like this:

mymodule.overview:
  path: '/admin/mymodule'
  defaults:
    _controller: '\Drupal\system\Controller\SystemController::systemAdminMenuBlockPage'
    _title: 'My module overview'


Privatemsg module shows admin and myself in autocomplete

Put this code in your template.php file

function yourtheme-name_query_privatemsg_autocomplete_alter($query) {
  global $user;
  $query-> condition('u.uid' , $user->uid, '<>');
}


Make user logged in after created by rule

Have a look at the Logintoboggan module. This offers you to login new users immediately.

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

1.Allow users to login using either their username OR their e-mail address.

2.Allow users to login immediately.

3.Provide a login form on Access Denied pages for non-logged-in (anonymous) users.

4.The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a
separate page, but returns the user to their original page upon login.

5.Customize the registration form with two e-mail fields to ensure accuracy.

6.Optionally redirect the user to a specific page when using the 'immediate login' feature.

7.Optionally redirect the user to a specific page upon validation of their e-mail address.

8.Optionally display a user message indicating a successful login.

9.Optionally combine both the login and registration form on one page.

10.Optionally have unvalidated users purged from the system at a pre-defined interval
(please read the CAVEATS section of INSTALL.txt for important information on 12.configuring this feature!).

11.Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)


Adding a new taxonomy term from a custom content type field

Check out taxonomy_save_term(). Here's an example from the comments:

$term = array(
'vid' => 5, // Voacabulary ID
'name' => 'Drupal', // Term Name
'synonyms' => 'Druplet', // (Optional) Synonym of this term
'parent' => 11, // (Optional) Term ID of a parent term
'relations' => array(15), // (Optional) Related Term IDs
);

taxonomy_save_term($term);

You could use this inside hook_nodeapi() on the operations insert or presave (and update). See the comments at the first link for more info.

EDIT: For drupal 7 you have to check out the node api instead of of hook_nodeapi().


Should drush configuration export automatically update core.extension.yml?

I think that the problem comes from where you have the config files, to be sure that they are really in the config/sync folder go to check if you have this following line in the settings.php file:

$config_directories = array(CONFIG_SYNC_DIRECTORY => 'config/sync');

Keep in mind that this line will have the location of the site configuration files.

Each time you use the drush cex or drush cex sync command the core.extension.yml file will be updated (if needed) with the actual modules (and others) configuration.


The most important advantage of using fields, rather than custom data in a custom table, is that your data has immediate integration with the rest of the system; including (but in no way limited to):

Automatic integration with Views
Potential to use EntityFieldQuerys
Fields can be managed using the standard system UI, even if built in code
Automatic integration with Features
There are many contributed widgets that can enhance the UI of a field (e.g. the Term Reference Tree widget
No need to load your custom data onto the node/entity in a load hook, the core field system does that for you
No need to define CRUD operations for your data

I'm sure there are many, many more.

Basically, if you want fine-grained control over the operation/performance of your extra data then use a custom table. If you want the system to handle all of that for you, use a field. For what it's worth I pretty much always use a field to store any entity data these days.


Change content in page.tpl.php depending on the page

As you're already using a View to create your slideshow, could you not simply use an argument to change the View output based on URL? I would need to dig into the specifics of your site to help further, but that seems like the easiest thing to do - no custom functions necessary.


Multiple Price for same product in commerce kickstart?

Might as well jump all in using Commerce Customizable Products and use this screencast to walk yourself through adding a line item type and a field to set the price.


how do i link a field to another field in views

In theory, you should be able to use the link module to create a link field within your content, and use a default value pointing to the newly created content - this may require some customization of the code - it accepts tokens, but I don't know if the node id has been assigned at that point or not.

Assuming it works, one way or another, you would then simply include that field in the view, which should display as a link - if it is used, it would link to the external link, otherwise to the content (as default value).

If that isn't reasonable, you could try to use the same field (without modifications or default value) in the view, and create a NO RESULTS BEHAVIOUR that rewrites it to the content - meaning if there is no value in the field, it would link to the content, or use the value of the field (external link) if present.


To alter the order of specific meta tags, a hook_html_head_alter() implementation in your theme's template.php file would be your best bet:

function MYTHEME_html_head_alter(&$head_elements) {
  // Combined with the devel module this line will tell you what elements you have to work with
  dpm($head_elements);

  // Any you can just alter the weight like this
  $head_elements['module:key']['#weight'] = -1000;
  $head_elements['another_module:another_key']['#weight'] = -999;
}


Scheduling unpublish too complex for existing modules

Drupal Scheduler will provide the proper infrastructure. Then in a hook_form_FORM_ID_alter(), you can set the date as follows:

global $user;
$roles = $user->roles;

$plusThreeMonths = date("Y-m-d H:i:s", strtotime("+3 months"));
$form['scheduler_settings']['unpublish_on']['#default_value'] = $plusThreeMonths;
// Disable setting of unpublished date unless admin or user 1
if ($user->uid != 1 && !in_array('administrator', $roles)) {
  $form['scheduler_settings']['unpublish_on']['#disabled'] = TRUE;
  $form['field_package_winning_bid']['#disabled'] = TRUE;
}

Then if you need to update the unpublish date, you can use a function similar to the following:

function _republish_node($nid, $time) {
  $node = node_load($nid);
  // Add time to the publish date
  $unpub = date("Y-m-d H:i:s", strtotime($time));  // pass in a string like "+2 weeks"
  $node->unpublish_on = strtotime($unpub);
  // Set published to true
  $node->status = 1;
  node_save($node);   // Re-save node with updated status
  scheduler_node_update($node); // update publisher fields
  // Add watchdog or other method to alert admins (or use rules)
}


What is the difference between hide() function and unset()?

hide() and unset() are not same.
hide() is a Drupal function and unset() is a raw php function.

unset() simply destroys a variable.
For an example,

<?php
$name = 'Drupal';
unset($name);
print $name; // this will result an error as $name is no longer set. `isset()` will return FALSE.

hide() does NOT destroy the variable. It's useful to mark some render-able array is already rendered so it will not be rendered again.

it simply adds/replaces the given argument's #printed to TRUE so drupal_render or render() won't execute the theme functions again - instead, it will use cached version if available.

A sample use case of hide() would be to hide comment form in a node template and show it somewhere else in the template. You will also find it useful when altering pages or blocks. Do NOT unset() a render array if you want to use it somewhere else.

If you want to hide some specific form element from the user but still want to keep the form structure, set #access of the element to FALSE.

hide()

drupal_render()

unset()


url() uses the current language by default, you only need to pass the language to it if you want another language, e.g. when sending mails to a user with a different language.

If you're on en/something and the global language is not en, then something else might be problem, for example incorrectly configured language recognication.


If you're going to use jQuery anyway, why not just use the .first and .last selectors?

$('.item').first().addClass('first');
$('.item').last().addClass('last');


Where is the node created timestamp stored in the database?

The created date is stored in the node_field_data table as a UNIX timestamp in a cloumn called created.

Here's the code you would use to fetch the nodes that has been created X days ago, using a direct select query.

$day = 86400; // One day in seconds.
$days = 3; // The amount of days ago to fetch from.

$nids = \Drupal::database()->select('node_field_data', 'n')
  ->addField('n', 'nid')
  ->condition('n.created', \Drupal::time()->getCurrentTime() - $days * $day, '>')
  ->execute()
  ->fetchField();

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

Make sure to inject the database and the entity_type.manager services (if possible) when implementing the code yourself.


When you type in safefields.org/user your site immediately redirects to the login page safefields.org/user/login which I believe indicates that your Drupal site is running but gives you a WSOD (white screen of death).
Usually that is because of a memory_limit constraint.
Things to investigate:

Try to use Drush to set the maintenance mode back to 0: drush vset maintenance_mode 0 this should get your site visible again
Check your settings.php and see if you have a memory_limit set there, increase to 512M or higher clear cache (either via Drush or empty cache tables directly in the database)
Check your php.ini file either in the root of your site's folder or in your public_html folder and increase it in size.
Google "Drupal 7 WSOD" as they say: add error reporting to your settings.php file to see what the errors are so you can search more effectively for what's causing your problem. https://www.drupal.org/node/158043

error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);


Exclude certain webform field to be saved in Database

This feature is currently not supported by the Webform module for Drupal 8. You would have to write custom code using hook_webform_submission_presave() to remove unwanted element data.


How to set up a text format that replaces the tokens?

Token Filter is a very simple module to make token values available as an input filter.

This doesn't mean that all tokens will work in every location. For example, if you use a [node:field_foo] token in the text of a block, the token system will not know which node you are referring to and will not replace the token.
It is up to you when you are implementing this module to be aware of the context for token usage and use them appropriately

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


How to render a menu_block in a specific language (i18n)

ok - this is extremely ugly, but seems to work

global $language,$language_content;
$org_language = $language;
$language = $language_content;
$block = module_invoke('menu_block', 'block_view', IAF_BOOKLETS_MBID);
$language = $org_language;

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

Feel free to boo me on this one :-D


If you see Content-Type: text/html when running Drush commands, it means that you are running Drush with php-cgi instead of php-cli.

If you already have php-cli on your system, set the environment variable DRUSH_PHP to point to the full path of php-cli.  If you do not have it installed yet, try installing it and see if that clears up your trouble (sudo apt-get install php5-cli on Ubuntu).


How to use Views to make a Block that displays a field from the author's profile?

I assumed that you have create a block view. (In case if you want to know how to create, check the revisions of this answer)

Add Author Relationship

Add Fitter Criteria : User: Current with author relationship

select Is the logged in User - yes. Click on Apply.

It pulls a field from a node (the author of the current node) and display it in a block


Get rendered content of one block created as derivative block

It sems this will do the trick:

  $blockManager = \Drupal::service('plugin.manager.block');
  //see all available block plugins (even not instantiated)
  $contextRepository = \Drupal::service('context.repository');
  $definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());

Here is how I used this info:

function TEMPLATE_preprocess_node(&$vars) {
  $blockManager = \Drupal::service('plugin.manager.block');
  $vars['content']['derivative_block'] = $blockManager->createInstance('module_name:block_derivative_id')->build();
}

If you enable the commented lines $definitions will get you all available blocks

Credit goes out to enzo for this solution.

More info about programmatic block placement.


I did it implementing a middleware:

mymodule/mymodule.services.yml:

mymodule.http_middleware:
  class: Drupal\mymodule\StackMiddleware\BeforePageCache
  arguments:
    - '@cache_tags.invalidator'
  tags:
    - { name: http_middleware, priority: 280, responder: true }

mymodule/src/StackMiddleware/BeforePageCache.php

...
/**
 * {@inheritdoc}
 */
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {
  if ($request->cookies->has('myValue')) {
    $this->cacheTagsInvalidator->invalidateTags(['my_tag']);
  }

  return $this->httpKernel->handle($request, $type, $catch);
}
...


Customize Order Items table on admin order screen

I mentioned this above in a comment, but the reason this takes more work than editing a View is because there's no simple way for a field widget to use Views to build part of a form. You can easily use Views to render content, and you can even use Views to construct a complete form, but using it to embed part of a form inside another form is not likely to happen.

There is a more straightforward way to customize the table if you're interested, based on the fact that the Inline Entity Form module gives you two ways to override the fields shown in the table of its "complex" widget.

If you anticipate making more holistic changes to the behavior of the inline form, you might consider setting a custom inline_form handler for order items via hook_entity_type_alter():

use Drupal\custom\Form\CustomOrderItemInlineForm;

/**
 * Implements hook_entity_type_alter().
 */
function custom_entity_type_alter(&$entity_types) {
  $entity_types['commerce_order_item']->setHandlerClass('inline_form', CustomOrderItemInlineForm::class);
}

Your handler class would inherit the default OrderItemInlineForm class and override its getTableFields() method to return a different fields array that adds your SKU field in the right place:

namespace Drupal\custom\Form;

use Drupal\commerce_order\Form\OrderItemInlineForm;

/**
 * Defines the inline form for order items.
 */
class CustomOrderItemInlineForm extends OrderItemInlineForm {

  /**
   * {@inheritdoc}
   */
  public function getTableFields($bundles) {
    $fields = parent::getTableFields($bundles);

    $fields['sku'] = [
      'type' => 'callback',
      'callback' => 'custom_order_item_sku',
      'label' => t('SKU'),
      'weight' => 2,
    ];

    $fields['unit_price']['weight'] = 3;
    $fields['quantity']['weight'] = 4;

    return $fields;
  }
}

Alternately, you can just implement hook_inline_entity_form_table_fields_alter() to do the same thing:

/**
 * Implements hook_inline_entity_form_table_fields_alter().
 */
function custom_inline_entity_form_table_fields_alter(&$fields, $context) {
  // Note: you'd want to check the context here to only alter the desired table.
  $fields['sku'] = [
    'type' => 'callback',
    'callback' => 'custom_order_item_sku',
    'label' => t('SKU'),
    'weight' => 2,
  ];

  $fields['unit_price']['weight'] = 3;
  $fields['quantity']['weight'] = 4;
}

Note that when you define the field for the Inline Entity Form table to include, since the SKU doesn't come from the order item itself (which is what is rendered in that table), you can't just use the 'field' type - you have to define a custom callback. Your callback is a simple function that can load the purchased entity from the order item, confirm it has a SKU, and then return it for display:

/**
 * Returns the SKU for the product referenced by an order item.
 */
function custom_order_item_sku($entity, $variables) {
  // Extract the purchased entity from the order item.
  $purchased_entity = $entity->getPurchasedEntity();

  // If the purchased entity couldn't be loaded or doesn't have a SKU...
  if (!$purchased_entity || !$purchased_entity->hasField('sku')) {
    // Return a placeholder string.
    return '-';
  }
  else {
    // Otherwise, return the SKU itself.
    return $purchased_entity->getSku();
  }
}

I tested this myself locally and it worked like a charm. : )


#states not detecting a change to form via ajax_command_invoke

For those who might come across this post, I think the problem is related to these issues :

Display Bug when using #states (Forms API) with Ajax Request
FAPI #states: dependent element added via AJAX initializes incorrectly if dependee has been initialized earlier

I found the solution to my problem (close to this one) by reading them.

Actually states may be no longer valid after an AJAX modification because some elements are still flagged as already initialized by the states system. This case produces when just the dependee element or the dependent element is altered by the AJAX request, not both. Only a side of the relation is updated, the other side keeping its old information. Dependee and dependent are therefore no longer linked and the state has no more effect.


Convert a node from one content type to another, using a rule set

Node Convert might help you with the node conversion from one type to another. http://drupal.org/project/node_convert

I'm not sure if you can use this module to do it programmatically, but it might help to look at this structure and run something similar on a cron job.


What's the right way to have Drush make automatically add version numbers to my info files?

I have this in my makefile:

api = 2
core = 7.x

projects[drupal][version] = "7.26"

;===============================================================================
; Ctools
;===============================================================================

projects[ctools][type] = module
projects[ctools][subdir] = "contrib"
projects[ctools][download][type] = git
projects[ctools][download][revision] = e720f61
projects[ctools][download][branch] = 7.x-1.x
projects[ctools][download][full_version] = 7.x-1.x-dev

I run it like so:
drush make --working-copy --no-cache --no-core my_make_file.make

For a good overview of the drush make flags:
http://www.drushcommands.com/drush-6x/make/make

In my case version info wasn't written because I had --no-gitinfofile in my script for some reason. I hope this helps!


Do you mean of "apply a patch" on a drupal module?
You should use composer-patches, the github page cleary explain of setup it and use for a patch modules\core.
In your case it should be somethings like:
{
  "require": {
    "cweagans/composer-patches": "~1.0",
    "drupal/core-recommended": "^8.8",
  },
  "config": {
    "preferred-install": "source"
  },
  "extra": {
    "patches": {
      "drupal/pathauto": {
        "issue name": "https://www.drupal.org/files/issues/2020-04-27/3131286-3.patch"
      }
    }
  }
}

However, this issue is already "fixed", so it is already in the dev version of the module. Applying on the stable one could fail, so you'd just have to switch to the dev version of the module, aka
composer require 'drupal/pathauto:1.x-dev@dev'

Please note that is best to avoid on production dev version unless strictly necessary. In other words, if you switch to dev, you should update to the next release of pathauto asap it's released


Views, Contextual Filters, and Path Alias

Ok, under Fields, click on the Title, then tick "Link this field to the original piece of content", then under "Rewrite results" tick "Output this field as a link", then in Link Path below it try "widgets/[nid]" then save obviously!


Updated search index display, but old index is still being used

When you save the settings for the search index display, nodes are not marked as needing to be reindexed.  You can either reindex the full site, or add in your own submit handler to mark them as dirty:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_field_ui_display_overview_form_alter(&$form, $form_state) {
  if ($form['#view_mode'] == 'search_index' && module_exists('search')) {
    $form["#submit"][] = 'MYMODULE_mark_search_index_dirty';
  }
}

function MYMODULE_mark_search_index_dirty($form, &$form_state) {
  $entity_type = $form["#entity_type"];

  $query = new EntityFieldQuery();

  $query->entityCondition('entity_type', $entity_type, '=');

  if (!empty($form["#bundle"])) {
    $query->entityCondition('bundle', $form["#bundle"]);
  }

  $entities = $query->execute();

  $sids = array_keys($entities[$entity_type]);

  $num = db_update('search_dataset')
    ->fields(array('reindex' => REQUEST_TIME))
    ->condition('type', $entity_type)
    ->condition('sid', $sids, 'IN')
    ->execute();

  if ($num > 0) {
    drupal_set_message(format_plural($num,
      '1 item needs to be indexed.',
      '@count items needs to be indexed.'));
  }
}

This will alter the form used to edit the display settings.  It checks to see if you are on the tab for changing the display of the search index view mode, and also have the Search module enabled.  If so, it adds on a new submit handler.

The submit hanlder does an EntityFieldQuery to get all of the entity IDs for the type/bundle pair specified by the $form.  It used EFQ instead of db_query() to be entity-type agnostic.

Then, based off of the code for search_touch_node() (which is called from node-related insert and update update hooks), it updates the search index to mark those entities as needing to be reindexed.  This will leave the old indexed data in place, and subsequent cron runs will reindex.

If you want to remove those from the index until reindexing, then you can replace the query with a loop like:

foreach ($sids as $sid) {
  search_reindex($sid, $entity_type);
}

$num = count($sids);


How to force Panels to render a node field even when field is empty

The reason i wanted to render an empty field in a panel was because the views hybrid formatter shows a view when the field is empty.  Instead,  i ended up showing the view via a views pane and making that pane conditional on the value of the field being empty.


I've got it, just using :

$check = db_query("SELECT DISTINCT A.something FROM {table_A} as A
    where something not in (
    SELECT  B.something FROM {table_B} as B)
    ")->fetchField();


field_view_value returns null for boolean field

Set

$display['type'] = 'list_key';

in your theme function to get not null key of field. Or create own formatter, for ex.

function mymodule_field_formatter_info() {
  return array(
      'my_formatter' => array(
          'label' => t('My formatter'),
          'field types' => array('list_boolean'),
      ),
  );
}

function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  switch ($display['type']) {
    case 'my_formatter':
      foreach($items as $delta => $item) {
        $value = $item['value'] == 1 ? 'ON TEXT' : 'OFF TEXT';
        $element[$delta] = array(
            '#markup' => $value,
        );
      }
      break;
  }

  return $element;
}

and after that set

$display['type'] = 'my_formatter';

in Your theme function


You should wrap your functionality in a Drupal Behavior. This will make it work even if elements on the page change via ajax and whatnot.

So the following:

(function($) {
  Drupal.behaviors.myCustomModule = {
    attach: function() {
      //var msg = $().jquery;
      //console.log(msg);
      $('div.quicklink-row').hover(function() {
        $(this).addClass('blue-link');
      }, function() {
        $(this).removeClass('blue-link');
      });
    }
  };
})(jQuery);

But aside from that.... why are you using Javascript for something that can be done so simply with CSS?

div.quicklink-row:hover {
  background: #00F;
}


resolved - I had restricted the main menu block to specific content types. Removing the restriction restored main menu block across all content types.


In my one of my setups I have a main server and a backup server.
They are separate small virtual machines on different physical boxes.
The entire Drupal install including file uploads is copied over from the main server to the backup server using rsync.

Rsync is an excellent command line *nix tool for copying, syncing files both locally and remotely. There are many configurations you can use. You can then configure a cron job to run it every so often. Here is one of the hundreds of threads

https://unix.stackexchange.com/questions/67539/how-to-rsync-only-new-files

In your case you could just rsync over the /sites/default/files folder.
Just one solution to your problem, but there are many.

Other Drupal module soltions using 3rd party services (like you suggested) are Media mover, CDN and Storage API, all take a bit of configuring but worth it.


Assuming this is an entity (it looks like it probably is), you might want to look into using entity metadata wrappers. It'll make your theming life much easier.

Otherwise, to immediately display your field, this would work (assuming a node):

echo $node->[field_serial_571][LANGUAGE_NONE][0]['value'];

LANGUAGE_NONE is a constant for an undefined language, in your example the 'und' part of the array. It's best practice to use that constant rather than using 'und'.

Read even more about entity metadata wrappers here: http://www.pixelite.co.nz/article/how-use-entity-metadata-wrappers-drupal-7/


Created flag for "add friend", set a View, works but there's a problem

It sounds like your view is already set up with the proper Flagged: Node relationship and "User ID from URL" contextual filter.  If you edit the view and then edit the Flagged: Node relationship, you can try checking the box for "Only display if flagged by the currently logged-in user" and see if that helps you.

Keep in mind, this method will still display people that were flagged by both Person 1 and Person 2 (common friends, in other words).  Another solution would be to have a private profile page and a public profile page, with different views on each; you might want to look into the Profile2 module.


You have to override the theme you are using in Drupal.

There is a good overview of this here.


Rewrite content of view field based on value

you can rewrite the output of a field using "Rewrite the output" option in views.

In your case, you might also need php code:
ex:

   $selectedValue=5; // this you can get from the replacement tokens easily

   // this array can be populated using some db query too.
   $selectedText=array('1'=>'satisfactory','5'=>'Very helpful');

   $selectedDisplayTitle=$selectedText[$selectedValue];
   return $selectedDisplayTitle;

Hope this helps.
Let us know if you come across a better solution.


You need to create a custom module and use hook_form_alter to modify the form.

That particular form id is views_form_commerce_cart_form_default, so in your custom module, you could have something like this:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  //cart form
  if (strpos($form_id, 'views_form_commerce_cart_form_default') === 0) {
    //change the value
    $form['actions']['submit']['#value'] = "New Update cart value";
    $form['actions']['checkout']['#value'] = "New Check-out Value";

    //add additional callback functions on the checkout button
    $form['actions']['checkout']['#submit'][] = 'mymodule_callback';

    //replace callback functions on the checkout button
    $form['actions']['checkout']['#submit'] = array('mymodule_callback');
  }
}

Refer to the Form API Reference to see what else you can do.


Only ONE CSS File for Visitors (and more for Admins)

You can achieve this by extending a hook_css_alter in your template.php for module file.

function hook_css_alter(&$css) {
  global $user;  //  Use this object to check current user roles

  //  The $css variable is an array of all of the css files that will be loaded
}


Have you checked the field collection feeds module? It does exactly what you are looking for.

  Provides feeds integration for field collection module.
  Require Feeds alpha7 or later version.


Take over display of a content type node route

You'll need to alter the entity.node.canonical route to do this. You can do this via a RouteSubscriber::alterRoutes() in a custom module to have the route driven by your custom logic. In src/Routing/RouteSubscriber.php:
namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Alter the canonical node route to our custom route
    if ($route = $collection->get('entity.node.canonical')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\NodeRedirectController::view');
    }
  }
}

Then build the logic in your custom controller to redirect based on your node type, in src/Controller/NodeRedirectController.php:
namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\Controller\NodeViewController;

/**
 * Custom node redirect controller
 */
class NodeRedirectController extends NodeViewController {

  public function view(EntityInterface $node, $view_mode = 'full', $langcode = NULL) {
    // Redirect to the edit path on the discussion type
    if ($node->bundle() === 'discussion') {
      return new RedirectResponse('/node/' . $node->id() . '/edit');
    }
    // Otherwise, fall back to the parent route controller.
    else {
      return parent::view($node, $view_mode, $langcode);
    }
  }
}

Lastly, register your routeSubscriber service in mymodules.services.yml:
services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Documentation is on drupal.org: Altering existing routes and adding new routes based on dynamic ones.


How can I send an email using the Rules module to a user specified via Entity Reference in a Content Type?

After some trial and error, I found how to reference the field.

Within the Conditions section of the rule, I needed to:

Add "entity has field"
Enter "node" within the Data Selector box
Select the entity reference field within the Value dropdown

I was then able to refer to the field required, with the mail parameter appended, directly from a standard Send Mail action (i.e. [node:MY-REFERENCED-FIELD:mail]).


How to create db table while installing a module?

You should implements hook_schema() in your modulename.install file. In druapl 7, you do not need to use hook_install to create database table.

  A Drupal schema definition is an array structure representing one or
  more tables and their related keys and indexes. A schema is defined by
  hook_schema() which must live in your module's .install file.

Code Snippets:

/**
 * Implements hook_schema()
 */

function custom_travel_api_schema() {

  $schema['custom_booking'] = array(
    'description' => 'To store the booking flight.',
    'fields' => array(
      'bid' => array(
       'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'The booking id.',
      ),
      'source' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'The source city for the booking.',
      ),
      'destination' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'The destination city for the booking.',
      ),
      'bdate' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The date of the booking',
      ),
      'amount' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The amount of the booking',
      ),
      'status' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The status of the booking(0 -> In process, 1 -> completed)',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The user id of the booking',
      ),
    ),
    'primary key' => array('bid'),
  );

  return $schema;

}

You can check this for more reference.


Why is my subtheme screenshot not appearing?

Sub theme by default inherit the screenshot from base theme.You can override the screen shot by simply adding screenshot of your sub theme in your sub theme directory

  The optional screenshot key tells Drupal where to find the theme's
  thumbnail image, used on the theme selection page
  (admin/build/themes). If this key is omitted from the .info file,
  Drupal uses the "screenshot.png" file in the theme's directory.

  Use this key only if your thumbnail file is not called
  "screenshot.png" or if you want to place it in a directory outside of
  your theme's base directory (e.g. screenshot = images/screenshot.png).

screenshot = screenshot.png

Reference: https://drupal.org/node/171205#screenshot

Other things which may help.

As Jhilke comment try clearing your caches.
Check the screenshot file permission it should readable by web-server.


Stop rendering custom entity label in view mode

The below function stops a custom entity label from being rendered based on the view mode.

function HOOK_entity_view_alter(&$build, $type) {
  if($type == 'YOUR_ENTITY_TYPE' && $build['#entity_view_mode']['view_mode'] == 'YOUR_VIEW_MODE'){
    $build['#page'] = TRUE;
  }
}


Commerce - how to allow users to buy 2 free products

By using the Goals module (disclosure: I'm its maintainer) you can have the Rules module take care of "monitoring users about buying their first 2 products" (as in your question). The advantage of using the Goals module, is that you can keep track of all sorts of events that are happening asynchronously (which you cannot do by only using Rules and its events).

So with that it seems that your question (challenge) is reduced to finding a way to configure the appropriate set of Goals and related Tasks. For a basic introduction about Goals, have a look at:

How to implement gamification in a Drupal site and award incentives?
Its video tutorial.

Here is what it would take to implement something like a frequent buyers program:

Goal = "New customer", with only 1 Task = "Buy 1 product" (say with machine name = buy_product).
Goal = "Existing customer", with Task = "Buy 2 products".

The interesting part of this is that you'd only have to write 1 rule (related to that machine name = buy_product) to keep track of the progress of any user to become either a "new" or "existing" customer (check the video for a similar sample).

Homework: how should a rule look like to indicate that a user bought a product (either the very first one, or yet another one)?


The biblio_get_contributor() function is located in the includes/biblio.contributes.inc file. The file isn't automatically included by the module unless it needs it, which is probably why you're getting that error.

You can include it into a page build explicitly with the following:

module_load_include('inc', 'biblio', 'includes/biblio.contributors');


How do I filter a views page with contextual filters?

you can add exposed filters to show past and future events. When you use the filters you'll see the URLs it generates. Those are your links and you can add them to the header of the view with a "global text area".
You can now hide the exposed filter forms by setting "Exposed form in block:" to yes. That will remove them from the view.


How do I add the "onload" attribute to a script tag?

If you want to make sure you're javascript is loaded in the header:

For drupal 7

/sites/default/themes/yourtheme/template.php

function theme_preprocess_html(&$var) {
      $path = $GLOBALS['base_url'] . '/' . path_to_theme() . '/js/yourscript-min.js';
      $script = array(
        '#tag' => 'script',
        '#attributes' => array(
            'type' => 'text/javascript',
            'src' => $path
        ),
        '#value' => '',
       );
       drupal_add_html_head($script, 'script');
    }

or if you want it loaded in the page:

function theme_preprocess_html(&$var) {
      $script = array(
        '#tag' => 'script',
        '#attributes' => array('type' => 'text/javascript'),
        '#value' => 'Add your javascript here',
       );
       drupal_add_html_head($script, 'script');
    }

For drupal 8

In the yourtheme.libraries.yml you need to create a library like so:

yourtheme.libraries.yml

library-name:
  header: true
  js:
    js/yourSrctipForTheHeader.js: {}

Also in the theme.info.yml you need to add this library, then it will automatically comes in head tag and will be available before the page load, if you remove header:true the script will be loaded after the page load.

theme.info.yml

libraries:
  - yourtheme/library-name

Alternativly, you can make use of this module:
https://www.drupal.org/project/header_and_footer_scripts and put the scipts in manually in the position that you want. But to be honest, i think the first solution is the more elegant way.


How to link 1000 parked domains to nodes, each with node title corresponding to the domain name

I'm assuming you have a field on your nodes with the name field_domain.

On your website:

Create a new node. This will be a place holder.
Get the NID.
a) Go go /admin/content/
b) Click edit on this placeholder node
c) Check the url. It will be in the form:
       /node/<NID>/edit
      Get that NID.
Go to your theme.
On the templates folder, create a file with the name:
node--NID.tpl.php so something like: node--78.tpl.php
On this file, put the following content:

  &lt?php
    $query = new EntityFieldQuery();

    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1) // published
      ->fieldCondition('field_domain', 'value',  $_SERVER['SERVER_NAME'], '=');
    $result = $query->execute();

    $nid = array_keys($result['node'])[0];
    if($nid) {
      $nodeObj = node_load($nid);
      $nodeRndr = node_view($nodeObj);
      print(drupal_render($nodeRndr));
    }

    You need to update 2 things:

       article to the machine name of the content type you're using.
       field_domain to the machine name of the field you're using.

Now, go to admin/config/system/site-information
Change the front page to node/NID where NID is the value from #4.

Explanation:

What that code does is checks $_SERVER['SERVER_NAME']. This should be the domain that's being used. Using that, it looks to see if there's a node with the field field_domain that has a value that matches $_SERVER['SERVER_NAME'].

If there's a match, it will load the node and render it.

If not, it should still load the placeholder node you created. This could be your default home page.

Hope this helps.

Original comment:

Have you considered writing some custom code?

If the only thing different is the title. I would create a small module that:

On installation creates a table with a domain and a title column.
When a page loads, reads the table and matches the domain and selects the title.
With the title, on... hook_preprocess_page (probably) you can set the title

I think there's a bit more functionality you want. If you're acting like a broker or if it's only a single owner, you probably are sending an email. So you would need the domain that was visited in the form as a minimum.

You can do this by having a hidden field and setting the value on load as well.

Or when submitting the form, reading it and processing it.

If it's more like a marketplace and you're sending an email to the owner which would vary per domain.

I think that processing that after the fact and only having one form would probably be more efficient than having a form per domain.

It depends on the use case. Just offering another option.


There is no table named node_comment. You must do the inner join to the node table, in the same way as the Views query.

SELECT comment.uid AS comment_uid, comment.cid AS cid, comment.created AS comment_created, 'comment' AS field_data_comment_body_comment_entity_type
FROM
comment
INNER JOIN node node_comment ON comment.nid = node_comment.nid
WHERE (( (node_comment.nid = '1330' ) )AND(( (comment.status <> '0') AND (node_comment.status = '1') )))
ORDER BY comment_created DESC
LIMIT 10 OFFSET 0


Langauge is a visibility condition for blocks, so you could use multiple branding blocks and hard code the paths.

Setting it automatically is a little harder, language is not available in $variables in preprocess so you'd need to add it - you could add these to all preprocess functions and templates:

/**
 * Preprocess variables for all templates.
 * @param $variables
 */
function HOOK_preprocess(&$variables) {
  // Inject the current language into every template to ease theme development.
  $variables['current_language'] = \Drupal::languageManager()->getCurrentLanguage();

  // Inject a usable directory path.
  $variables['theme_path'] = base_path() . $variables['directory'];
}

You can use these in the branding block or page template to set a path to a language specific logo, e.g.:

<img src="{{ theme_path ~ '/logo-' ~ current_language.getID() ~ '.svg' }}" alt="{{ 'Home'|t }}" />

So you'd have logo-en.svg for english, logo-sv.svg for Swedish etc in your theme root, getID() just returns the two character language code.

You could go further and just build the whole thing in preprocess, just for the template you are using (either page or the branding block).


Is it always bad to pass a variable through t()?

The first argument of t() needs to be a literal string, which excludes:

variables, even the parameters of a function: t($description)
a concatenation of strings: t('If you want to add a link, click on' . 'this link.')
the value returned from a function:t(get_menu_description())
a constant: t(MYMODULE_MY_WIDGET_TITLE), t(MyClass::WIDGET_TITLE)

The reason is that, apart few specific hooks (e.g. hook_menu(), hook_perm(), hook_permission()), the string to translate are found from a script that scan the code of a module, looking for code such as t('This is an example.'); when it finds a value that depends from runtime, such as the value of a variable, the script is not able to understand which is the string that needs to be translated, as a variable could contain a different value each times the code gets executed.
In fact, http://localize.drupal.org reports a warning similar to the following one, in the case the argument for t() is not a literal string:

  The first parameter to t() should be a literal string. There should be no variables, concatenation, constants or other non-literal strings there. At t($filter['name']) in customfilter/customfilter.module on line 30.

If you are passing a dynamic value to t(), the script that extracts the strings to translate will not extract any value, in that case; the effect is the argument passed to t() will not be translated, which has the same effect of not using t() and using the dynamic output directly in the user interface. The only case for which the string will be translated is when the dynamic string is equal to the literal string a function passes to t(). Suppose, for example, that you have a library not thought for Drupal, which contains a function returning the name of the current month. With the following code, the value returned from that function would be translated.

function mymodule_calendar_page_title() {
  return t(Calendar::getCurrentMonth());
}

function mymodule_calendar_translations() {
  $translations = array(
    t('January'),
    t('February'),
    t('March'),
    t('April'),
    t('May'),
    t('June'),
    t('July'),
    t('August'),
    t('September'),
    t('October'),
    t('November'),
    t('December'),
  );
}

mymodule_calendar_translations() doesn't need to be called, nor to return any value. When the code of the module will be parsed, the call to t() will be found from the code that looks for literal strings passed to t().

Translating the description given for a database table and its fields is then not something that you should do, as none of the Drupal core modules do that; for example, node_schema() contains the following code:

function node_schema() {
  $schema['node'] = array(
    'description' => 'The base table for nodes.',
    'fields' => array(
      'nid' => array(
        'description' => 'The primary identifier for a node.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'vid' => array(
        'description' => 'The current {node_revision}.vid version identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      // …
    );
    // …
  );

  // …

  return $schema;
}

The report that caused the removal of the calls to t() from any Drupal core implementations of hook_schema() is Remove t() from all schema descriptions, which has been open by webchick (Drupal 7 co-maintainer).

  In Szeged, we had a big long discussion about t() around the schema descriptions and it was the consensus of everyone at the table (who included Dries) that t()s should be removed from these descriptions. They mess up things because t() isn't available that early, and people discussed that no one is going to take the time to translate technical descriptions of stuff, and it doesn't really make sense since we also don't translate code comments, for example.

The article about converting a Drupal 6 module to Drupal 7, has a dedicated paragraph: Schema descriptions are no longer translated.


Do we require a token module for token_replace() to work?

You don't need the Token module to use the functions you mentioned in your question. They are defined in Drupal core.

References:

token_replace()
hook_token_info()
hook_tokens


Disable taxonomy terms in certain contexts or split into different vocabularies?

Alternative 1
Create two different taxonomy vocabularies:

Events
Users

since the use cases for each are different.
To create another taxonomy vocabulary easy and fast, you could export your existing terms and then import them into a new vocabulary. This could be done with some taxonomy bulk import/export module, maybe with https://www.drupal.org/project/taxonomy_csv or with https://www.drupal.org/project/taxonomy_manager
Alternative 2
Added to this answer after OP's first comment.

Keep the Events and Users together in one vocabulary, EventsUsers.

Create another vocabulary, EventUserType. Add two terms:
Events and Users.

Add a Term reference field with Check boxes/radio buttons to the EventsUsers, save. In the next
configuration pages choose vocabulary EventUserType. Also change the Number of values
from 1 to Unlimited.

Now all the terms in the main vocabulary can be tagged as Event, User or both.

The filtering could be done using the Views module, but I guess that would be a separate question here on Drupal Answers.


How to get content with their taxonomy term name and id?

Make a dynamic query like this:

$query = \Drupal::database()->select('node_field_data', 'nfd');
$query->condition('nfd.type', 'product');
$query->leftJoin('node__field_category', 'ft', 'ft.entity_id = nfd.nid');
$query->leftJoin('taxonomy_term_field_data', 'fd', 'fd.tid = ft.field_category_target_id');
$query->fields('fd', ['tid', 'name']);
$query->fields('nfd', ['nid']);
$results = $query->execute()->fetchAll();

Suppose the reference field taxonomy machine name is "node__field_category".
The result of the query will be node id , term name and term id.


How to add a language dropdown switcher to top panel?

I believe Flags does not integrate with Language switcher dropdown (contrib module) it only integrates with the core language switcher block

Here is some alternatives

1. Language Switcher Dropdown + languageicons

Install both modules
Go to config > regional and language > language icons and choose

  Icon placement
    Before link
    After link
    Replace link

Go to Structure > block layout add Language dropdown switcher block to your desired region

2. Bootstrap Languages

Compatible with bootstrap based themes only

Install module
Go to Structure > block layout add Bootstrap Language switcher block to your desired region

3. dropdown_language

With this module icons have to be setup manually using css


How to programmatically update the allowed values of a list field?

Something along the lines of...

// Get the field info
$info = field_info_field('field_some_field');

// Get a reference to the values
$values = &$info['settings']['allowed_values'];

// Manipulate the values in some way, e.g.
$values['new_value'] = 'New Value';

// Save the field
field_update_field($info);


How to display image instead of a value in Drupal 7?

I can suggest an idea I used in Views output — this may help you find a solution for your case. I needed to display an icon near an article depending on its material type. I added a hidden PHP field with the following code (image names are not directly the same as the type name, that was the brief :)):

<?php
switch ($row->type) {
case 'article':
  print 'articles'; break;
case 'gallery':
  print 'gallery'; break;
case 'music':
  print 'music';
}
?>

And then a “type” field, which had the following override:

<img src="/sites/all/themes/my_theme/images/[php].png" alt="[type]" title="[type]" width="22" height="22" />

[php] is where Views output inserts the output of the PHP field I showed earlier. This same approach can be used to add a class to the HTML tag, and define a CSS image background for each class.

I hope this helps to find a solution for your problem.


Taxonomy menu with custom path for taxonomy terms

If you want to alter taxonomy term paths for taxonomy terms implemented by your module, then you can implement hook_term_path(), which is the hook that allows a module to alter the taxonomy term paths.

The function that returns the taxonomy term paths is the following:

    function taxonomy_term_path($term) {
      $vocabulary = taxonomy_vocabulary_load($term->vid);
      if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
        return $path;
      }
     return 'taxonomy/term/' . $term->did;
  }

Implementing that hook would also help to modify the path of any vocabularies, if the field $vocabulary->module is changed to the short name of the module you created.

Alternatively, you can write the custom_url_rewrite_outbound() and custom_url_rewrite_inbound() that allows to rewrite the URLs being shown to the "outside" world, and convert a URL into the one used by Drupal.
The example given in the documentation should make clear how to use this functions.

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  global $user;

  // Change all article/x requests to node/x
  if (preg_match('|^article(/.*)|', $path, $matches)) {
    $result = 'node' . $matches[1];
  }
  // Redirect a path called 'e' to the user's profile edit page.
  if ($path == 'e') {
    $result = 'user/' . $user->uid . '/edit';
  }
}

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  global $user;

  // Change all 'node' to 'article'.
  if (preg_match('|^node(/.*)|', $path, $matches)) {
    $path = 'article' . $matches[1];
  }
  // Create a path called 'e' which lands the user on her profile edit page.
  if ($path == 'user/' . $user->uid . '/edit') {
    $path = 'e';
  }
}

In other cases, you can use a module like Pathauto, or Views Term Path Override, which allows to override the taxonomy term paths in views.
Other modules that could be of help are Path redirect, and Taxonomy Redirect; The project page for Views Term Path Override suggests Taxonomy Views Integrator as alternative.


Change article Status based on Workflow module

First, install the Rules module.

I would highly recommend watching the Rules video series at NodeOne by the incredibly talented Johan Falk.

With the Workflow module and the Rules module installed and configured we can create a rule that automatically publishes (or unpublished) content based on it's current workflow state.

To ensure our content is not published by default, we will need to change a few things.  Visit example.com/admin/structure/types (if clean URL's are enabled) and click edit next to the content type you're working with. Scroll to the "publishing options" and uncheck "Published" so new content is not publicly visible by default.

Next, create a new rule.  Available at example.com/admin/config/workflow/rules/reaction/add once the Rules module is installed and enabled.

Configure your new rule to react on the event: "Workflow State Has Changed" and click save.

Next, add a new condition.

Choose the "Check workflow transition" condition.

Configure which transition you wish to react on.  For example, if you have created the workflow states "Pending Approval" and "Published" you would choose "Pending Approval" under "Old Workflow State" and "Published" under new workflow state.

Now we can automatically trigger actions once Rules detects a workflow transition from "Pending approval" to "Published".  For example, we can trigger an email to editors, publish a node or just about anything else.

Next we need to add an action.

There are dozens of built in actions, and you can even add your own.  One that you may specifically be looking for though is "Publish content."

Rules and Workflow work very well together in this sense and will likely be able to do everything you need.

I hope this helps. If I misunderstood your question or if I got too off topic I'll try again. :)


It's been a while since I've done this but this link should be a good start. File Load

Assuming $form_state['storage']['image'] is the image's fid, what you may want to do is.

$image = $form_state['storage']['image'];
$file = file_load($image);

// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Save.
file_save($file);

// add image back
$node->field_image['und'][0] = $image;

Depending on what your doing you may want to add the file to the usage table. Details here.
File Usage Add


It looks like you're indiscriminately popping values off of the array returned from field_get_items, without checking to see which index you actually need. I haven't tested this but I think you'll have better luck with code like this:

$items = field_get_items($entity_type, $entity, 'field_start_date');

// Use array_shift if you want the FIRST field item
$item = array_shift($items);
// OR
// Use array_pop if you want the LAST field item
$item = array_pop($items);

// Get the date value of the field
$start_date = $item['value'];

// Use start date
$entity_field[1]['value'] = $start_date;


Anyone manage to work entity metadata wrapper with profile2 entity?

The problem is that profile2_load_by_user() returns an array of all user profiles by default, whereas entity_metadata_wrapper() needs a single entity object.

Try loading a single profile:

$profile = profile2_load_by_user($account, 'profile_name');
$wrapper = entity_metadata_wrapper('profile2', $profile);
$wrapper->field_first_name->set(devel_generate_word(mt_rand(6, 12)));


Integration between js and php code in custom module

You would use drupal_add_js() to pass the data from PHP to JS:

$block_ids = array('blockid1', 'blockid2');
$settings = array('myModule' => array('blockIds' => $block_ids));
drupal_add_js($settings, 'setting');

Then in JS you can pick these up like so:

var blockIds = Drupal.settings.myModule.blockIds;


As described in EntityFieldQuery::propertyCondition(), you can use that method for every database field defined in the hook_schema() implementation for the base database table used from the entity.

  $column: A column defined in the hook_schema() of the base table of the entity.

The code that effectively handle that is in EntityFieldQuery::propertyQuery() which contains the following code.

  $entity_type = $this->entityConditions['entity_type']['value'];
  $entity_info = entity_get_info($entity_type);
  if (empty($entity_info['base table'])) {
    throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
  }
  $base_table = $entity_info['base table'];
  $base_table_schema = drupal_get_schema($base_table);
  $select_query = db_select($base_table);
  $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
  // Process the property conditions.
  foreach ($this->propertyConditions as $property_condition) {
    $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
  }

You could implement hook_entity_query_alter(), which is invoked before EntityFieldQuery::propertyQuery() is called, and which (by default) it's the EntityFieldQuery::executeCallback callback, the same callback hook_entity_query_alter() is suggested to change. Using your own callback, you could make a join with the tables the Workflow module is using.


Is there a Self-Imposed Bulk Operations Limit?

No. there is no such limit.

In Views, make sure you have enabled the option to select all items across all pages. With that configuration, all items will be selected regardless of the pager configuration.


Use the Search API module with Views to accomplish this functionality. Here is an example.


Unfortunately, this isn't possible yet. A request has been made here. Hopefully, the maintainers will provide this feature in the future.

If someone gives a working solution later on, I'll mark it as answer instead.


Using jQuery $.ajax() on my site won't work

In Drupal, JavaScript files are added via the drupal_add_js() function or in the
theme’s .info file.
A simple example of using jQuery in drupal is

    <?php
    drupal_add_js('jQuery(document).ready(function () {
   jQuery.ajax({
        url: '/code/test-ajax.php',
        data: {'a':'hello','b':'world'},
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus + errorThrown); //Better diagnostics
        }
    });
    });', 'inline');
    ?>

you have to use 'jQuery' instead of $.


Scripts are added to the last in the resulting HTML Page in Drupal 8, and External CSS is added in the head, but external CSS is loaded after internal CSS that is used in modules. This might be creating an unwanted delay in rendering your font awesome styles.

I suggest you minimize the delay of your font awesome script by hosting it on your own server and calling it from there.


You cannot use menu wildcards like that. You need to use the following code.

<?php echo l(t("Profile edit"), 'user/' . $GLOBALS['user']->uid . '/edit'); ?>

<?php echo l(t("My posts"), 'user/' . $GLOBALS['user']->uid . '/track'); ?>

<?php echo l(t("Exit"), "user/logout"); ?>

The global $user is the user object for the currently logged-in user. Be careful: It is not a fully-loaded user object. If you need that, you should use the value returned from user_uid_optional_load().


How do I prepopulate a field with calculated options, when user is editing node?

Use hook_form_alter or hook_form_FORM_ID_alter to pre-populate your dropdown list with results returned from a custom function.

For example, using a form of hook_form_alter():

$form['field_my_field']['und']['#options'] = _my_custom_function();

Then make sure your function _my_custom_function() return's a proper array.

function _my_custom_function() {
    $custom_values = array();
    $custom_values['key1'] = 'value1';
    $custom_values['key2'] = 'value2';
    $custom_values['key3'] = 'value3';
    return $custom_values;
}

Obviously you can include some 'logic' in the _my_custom_function() to return your calculated list.

Here are a few super-useful link's I wish I would have know about before.

The Devel module has two functions that make hook_form_alter simple as pie... check out dpm() and dd().
The FormAPI page is priceless for all things hook_form_alter().
The Example Modules for Developers makes for an awesome intro to the FormAPI


Programmatically using values from a loaded entity inside a message

As Clive also mentioned use double quotes instead of single quotes to allow the variables to get replaced inside the string

'body' => "Hello $nodeowner this is your body message"

if $values["selected_node_owner"] gives you the UID here is how to get the username

$account = \Drupal\user\Entity\User::load($values["selected_node_owner"]);
$nodeowner = $account->getUsername();


Commerce order confirmation message with shipping service

Assuming that you are using Commerce Message module for this.

One way to do this is by adding your own token. In your custom module (MYMODULE) add this code (I have too many comments just for educational reasons):

// Set arguments for our custom token !order-shipping
function MYMODULE_message_presave($message) {
  if (!empty($message->mid)) {
    return;
  }
  $message->arguments['!order-shipping'] = array(
    'callback' => 'commerce_message_order_shipping',
    'pass message' => TRUE,
  );
}

/**
 * Message callback; Show Order Shipping Service label (!order-shipping).
 *
 * @param $message
 *   The Message entity.
 */
function commerce_message_order_shipping(Message $message) {
  $wrapper = entity_metadata_wrapper('message', $message);
  // Get order id from current commerce message
  $order_id = $wrapper->message_commerce_order->getIdentifier();
  // Get order from order_id
  $order_wrapper = commerce_order_load($order_id);
  // Get the line items. Shipping service is a line item (like product, discount etc)
  $line_items = $order_wrapper->commerce_line_items['und'];

  // Loop through the line items so you find the shipping service
  foreach ($line_items as $delta => $line_item_wrapper) {
    $line_item_id = $line_item_wrapper['line_item_id'];
    $line_item = commerce_line_item_load($line_item_id);
    //dpm($line_item);
    if(isset($line_item->commerce_shipping_service)) {
      // This is want we need, the shipping service label
      $shipping_service = $line_item->line_item_label;
    }
  }

  return $shipping_service;
}

Then in your message body add you new token !order-shipping.

Notice that this method works for other line items too... Also, it works for other modules that send emails (such as commerce_email) but with some difference in the hook function - currently hook_message_presave($message) -.

Credits to this issue: http://drupalcommerce.org/node/10096


Migration with unique index across multiple fields

This is what I'm using in one of my imports:

source:
  ids:
    event_id:
      type: integer
    date_iso:
      type: string

I'm explicitly specifying the ID column type using type: integer or type: string.


Reason for adding .value to access node id?

Short answer: Because nid is a field and you want to get the field value.

Long answer: Node is like User or Taxonomy Term an entity and provides the method id(). So instead of accessing the id fields by their individual field name (nid, uid, tid), it's easier and better OOP practice to use the method EntityInterface::id:

{{ node.id }}


How to rewrite the ouput html of the image field for a node page?

This looks like output coming from theme('field') theme function in field.module. You can override the output by putting the following function in your template.php:

/**
 * Implements template_preprocess_field
 */
function mythemename_preprocess_field(&$vars) {

}

More info on the preprocessor (with examples of how to add additional classes) is here: template_preprocess_field

EDIT:
Actually looking at the theme function, it seems that in your case I think you need to implement both a preprocessor and a template file for your field. So in the preprocessor you create a variable for the class:

/**
 * Implements template_preprocess_field
 */
function mythemename_preprocess_field(&$vars) {
  $element = $vars['element'];
  if ($element['#field_name'] == 'field_myfieldname') {
    $number = 123; // This variable should get the value you wish to attach to the class
    $vars['field_myfieldname_custom_class'] = 'field-item-' . $number;
  }
}

And then create a field template file field--field_myfieldname.tpl.php and put <?php print $field_myfieldname_custom_class; ?> where the class should appear.


Can I ask why you are not using views for this task?

Views 3 for drupal 7 is a powerful interactive SQL builder. And trivial tasks like this are can be easily sold without even knowing SQL or which tables to join on etc.


Two different versions of the same base theme in the same site

Themes, like modules, are identified by their names. The version number is never really used (except for updates obviously).

Anyway, i found myself facing a similar problem sometimes, and running a find&replace on the theme directory to change every occurrence of the name with another inside the files never lead to unexpected behaviors.

well, i also had to manually rename the .info file, so it's not a completely automatic procedure, but still nothing that caused problems of any sort.


Patch for module applies with patch command but not composer

It turns out this is an issue with Drupal patches for composer when using an older version of Git.  The problem is with composer-patches 1.6.3.

Three possible solutions for now until the bug gets fixed.

Force 1.6.2

In composer.json, specify 1.6.2:

"require": {
"composer/installers": "^1.0.20",
"cweagans/composer-patches": "1.6.2",

Force git clone with 1.6.3

In composer.json, instead of "dist", use "source":

"config": {
    "preferred-install": "source"
  },

Update git to the latest version


Event registration for events with multiple dates/places

I would suggest that you create two different content types. Event Display and Event Entity

Event Display : Will be just used as a placeholder or display item. It will contain all jazzy text fields and images. It will also contain Node References to the Actual Event Eneities.
Event Entity : This will just contain Location, Date and Capacity.

Now Enable Entity Registration for the content type Event Entity.

Suggestion : Use Inline Entity Form so that you can edit the Event Entities directly from the Event Display Content.


Using views to find list of users nearby using location in arguments

I think you are telling about the proximity search and you want to display the user/nodes with in a particular distance based on the location of a single user/node.

You can select the "location" in the filter and there you can see the distance/proximity option


How to pass content type filter to taxonomy

I think you need to edit the location links to include a second "parameter" so it could look like:

yoursite.com/yourview?location=yourLocation&articletype=yourArticle

For this you would need to implement some hooks. Maybe you can start with hook_preprocess_node.

What I would do is to:

Use the said hook
Get the location terms available for the current viewed node
Construct the URL based on the term data and content type the way I want it to look.

Then in your view, you need to add just two contextual filters that would be those fields. The location term reference field and the content type.

EDITED

Node view and term link update

Created a new content type name Article 2 (Machine name: article_2) to follow your structure of content types having Vehicle, Clothing and etc. So mine is just Article and Article 2. My content types have the Term reference field of the Tags vocabulary w/c in your setup is the Location.
Added terms into the Tags vocabulary: Term 1 and Term 2.
Created a simple custom module using hook_preprocess_node() w/c looks like:

function yourmodulename_preprocess_node(&$vars) {
  // Check if your term field is being rendered in the node view
  if (isset($vars['content']['field_tags']['#items'])) {
    // Loop through all terms present in the node
    foreach ($vars['content']['field_tags']['#items'] as $index => $info) {
      $node_type = '/' . $vars['type'];
      // We append the node type to the URL of a term so that
      // it can be used as a contextual filter in the term view.
      $vars['content']['field_tags'][$index]['#href'] .= $node_type;
    }
  }
}

Remember to do a Flush Cache since were adding a new hook function into the system. Now when you view a node, check the term link(s) listed and you will see that the URL structure is not like http://yoursite.com/taxonomy/term/2/article

Term View

Clone the Taxonomy Term view (So that we wont be changing the original)
Add a second wild card argument in the Path w/c looked like taxonomy/term/% to taxonomy/term/%/%. The second argument would be for the content type.
Under contextual filter add the Content: Type field following the settings in the image.

And then place the Content: Type contextual filter at the second row to match the URL structure w/c would look like:

And that's it. A simple sample result based on this URL http://localhost/drupal/taxonomy/term/2/article would look like:

So it's filtering the right node that has Term 2 as its Tag(my setup)/Location(your setup) and only the Article content type.

My test data are:

Article content type: Article 1, Term 1
Article content type: Article 2, Term 2 (This is the result in the latest screenshot)
Article 2 content type: Article 3, Term 1
Article 2 content type: Article 4, Term 2

Issue

So far I haven't figured out how to use this style with Pathauto so the URL would look better for example, www.mysite.com/illinois/chicago/article.


ubercart 2 with smtp - sending unformatted emails

I tried phpmailer module https://www.drupal.org/project/phpmailer and all messages (even created by ubercart) are displayed as formatted to end users.


Table count is not an indicator of optimization. It is actually opposite of what someone might think. Good database design breaks data up into multiple related tables that are kept small in field count. Drupal core has a very efficient relational database design compared to WordPress. I have experience with both platforms and your statement highlights what you must realize about Drupal. Drupal really is a content management framework, WordPress is a content management system. They are vastly different in their capabilities.

So to answer your question plainly, no optimization is required. It already is optimized for a relational database.

As always, choose the right tool for the project. Even though I am a Drupal developer I have recommended Wordpress to several clients. Because their needs and requirements could be satisfied with a simple Wordpress site.


How to alter form password and add current password in user_profile_form

Take a look on Password Separate Form module.

The Password Separate Form module provides the separate password change form.

By default it comes with user account page that little bit confusing for end
users. This module would help to make this form as a separate form to help end users, there is no need to change these fields every time if you are editing some other fields on user account page.


Taxonomy Terms node count of different content type along with zero count in a hierarchy

Check what you have set for the "no results" behaviour on that field. You will not want it set to "hide".

Also check if it displays in the views preview. If it displays there but not on your page then it may be that your template is checking if a field is blank and before deciding whether to show it - you could solve this by setting a default/no results value of "0"


How to make breadcumbs grab taxonomy terms and use tokens

First of all if you have not tried Taxonomy Breadcrumb module yet, give it a try.

If you already have tried that module and had no success , you can write your own code.

the simplest solution can be achieved by implementing hook_preprocess_page, then you should check if there is a node and node is of a certain type used to store school type and then you can change $variables['breadcrumb'] to modify breadcrumb as you wish.

in drupal 7 you also can use drupal_set_breadcrumb to change breadcrumb in a code and in drupal 8 you can implement hook_system_breadcrumb_alter to make it done.


How to add Login menu to the first sidebar (secondary menu)

Try turning off the secondary menu (admin/structure/menu/settings).

Then, on the blocks admin screen (admin/structure/block), place the User menu in the first sidebar.


Or simple use

drush ev 'var_dump(module_implements("cron"))'

For list the cron job that exists.


How to show difference between views page and views block

Using This page override  option in view field configuration instead of All display


Is there a way to use Translation Overview with Entity Translation?

Maybe you should consider switching from the Translation Overview module to the Translation Management Tool module, which allows all Drupal text elements to be used as source for translation. I.e. Nodes, Entities, I18n Strings (Menu, Terms etc.).

That's also what seems to comply with what is written on the Translation Overview project page, i.e.:

  ... The superseding Translation management (TMGMT) module was initiated with Drupal 7 and is already well ported to Drupal 8. We highly recommend it - already with Drupal 7.


Modify/hook into admin page of rate module

I found the solution for my problem. I used hook_form_FORM_ID_alter

function hook_form_rate_widget_form_alter(&$form, &$form_state, $form_id){
enter code here...
}


How to mix charts views and table views on the same page?

A possible answer to this question for anybody using the charts module is contained in Steps to create charts using the views UI, located within its community documentation.

Here is part of the Bonus Tip included in it:

  You may find it easier to start with a "Table" display and convert it
  to a chart display after setting up the data. It can be easier to
  visualize what the result of the chart will be if it's been laid out
  in a table first.

Refer to "Example 2" in my answer to "How to create a chart from simple data without using the Views aggregation feature?" for an illustration of this approach (which also includes a view in export format to start from).

Another approach is to use module Panels to show charts created with module Charts.

Here are some other (related) documentation pages for the charts module, which may help to get you going with the charts module:

Getting Started.
Create Charts using views.
Charts Howtos.


How to change the value of a commerce token?

token_find_with_prefix() doesn't return, in your case, the [commerce-order:payment-method] token, but tokens like [commerce-order:payment-method:date] or [commerce-order:payment-method:client], if they exist.

The correct code you should use is the following one.

function mymodule_tokens_alter(array &$replacements, array $context) {
  if ($context['type'] == 'commerce-order') {
    if (!empty($replacements['payment-method']) && $replacements['payment-method'] == 'card_payment') {
      $replacements['payment-method'] = 'This order is paid';
    }
  }
}

As side note, altering the value returned for the [commerce-order:payment-method] token doesn't alter the value returned for similar tokens like [commerce-order:payment-method-title]. If you need to alter the value returned for [commerce-order:payment-method-title], the code needs to be similar to the following one.

function mymodule_tokens_alter(array &$replacements, array $context) {
  if ($context['type'] == 'commerce-order') {
    if (!empty($replacements['payment-method-title']) && $replacements['payment-method-title'] == 'the payment title you want to change') {
      $replacements['payment-method-title'] = 'This order is paid';
    }
  }
}

Remember to change 'the payment title you want to change' with the effective payment title you need to alter, which probably isn't 'card_payment' (but that is something you need to verify).


How can I encrypt the login process without using SSL?

So far, the only way that I've found to encrypt user login without SSL is the Encrypt Submissions Module (https://www.drupal.org/project/encrypt_submissions)

It uses the jCryption library (http://www.jcryption.org/) to encrypt the username and password that drupal offers up in clear text otherwise. Fairly straightforward to set up. The only server requirement is bcmath php module which most servers have anyway.

I use Encrypt Submissions whenever I can't use SSL, not as a replacement. You may want to consider switching hosts if they don't allow SSL certs, they sound pretty backwards.


Dynamically change views entity reference filter based on current form value

Here's my solution:

I used Entity Reference Prepopulate for my "venue" for my case (linked from my question), so whenever I choose a venue it will pass a parameter to the url.

Then I used Views Contextual Filter Query to get the value of the parameter from the URL and automatically filter the view without saving the form.

BTW, Entity Reference Prepopulate doesn't work on edit form, so you need to create a node_load function on your custom module. Check this for code reference

Then I created a code for edit link that has the param of venue and it's target id.

<?php
    $nid = arg(1);
     $node=menu_get_object();

    $l = l( t('EDIT'), 'node/'.$nid.'/edit',   array('query' => array('field_product_venue' => $node->field_product_venue['und'][0]['target_id'] )  ));
    echo $l;

?>

I hope this will of help to somebody!

Thanks!


Problem setting user specific cache tags on custom block with user context

To sum up the comments: As a general rule, if you render the current user, then always add the correct cache metadata to the render element:

 public function build() {
    return [
      '#markup' => 'Current User ID: ' . \Drupal::currentUser()->id() . '',
      '#cache' => [
        'contexts' => ['user'],
        'tags' => ['user:' . \Drupal::currentUser()->id()],
      ],
    ];
  }

If you have a block, which doesn't return a cacheable render result in all cases, you can add additional cache metadata in the block plugins cacheable dependencies methods. It doesn't harm when you declare a cache tag or context twice.


Assuming you have Drush installed and working properly, just type drush status in your command prompt. It will give you drush version as well as Drupal version info. If you have aliases set up for remote (or local) sites, you can run drush @alias status and it will give you the status info for that remote system.