Add microdata to breadcrumbs - Some trouble with hooks

Your implementation of hook_page_alter() doesn't work because the parameter passed to the hook ($page) doesn't contain $page['breadcrumb'].

I used the following code to verify the content of the parameter passed as argument.

$path = 'node/14';

if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    if ($router_item['include_file']) {
      require_once DRUPAL_ROOT . '/' . $router_item['include_file'];
    }
    $page_callback_result = call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
  }
}

$main_content_display = &drupal_static('system_main_content_added', FALSE);

if (is_string($page_callback_result) || (is_array($page_callback_result) && (!isset($page_callback_result['#type']) || ($page_callback_result['#type'] != 'page')))) {
  drupal_set_page_content($page_callback_result);
  $page_callback_result = element_info('page');
}

foreach (module_implements('page_build') as $module) {
  $function = $module . '_page_build';
  $function($page_callback_result);
}

drupal_alter('page', $page_callback_result);

if (!$main_content_display) {
  $page_callback_result['content']['system_main'] = drupal_set_page_content();
}

dsm($page_callback_result);

"node/14" is the path for an "Article" node I have on my test site.
The code has been created looking at the code of different Drupal functions: drupal_deliver_html_page(), drupal_deliver_page(), and menu_execute_active_handler(). It requires the Devel module, as it uses one of its functions.

This is the output given by dsm().

You can override the theme function used for the breadcrumb, implementing hook_theme_registry_alter().

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['breadcrumb'])) {
    $theme_registry['breadcrumb']['function'] = 'theme_mymodule_breadcrumb';
  }
}

theme_mymodule_breadcrumb() is the function that replaces theme_breadcrumb(), and it gets the same parameters.

  $variables: An associative array containing:

  breadcrumb: An array containing the breadcrumb links.

The theme function should be overridden if you want to alter its output. If you want to alter the value of the variables passed to theme_breadcrumb(), with Drupal 7 you can implement a preprocess function.

function mymodule_preprocess_breadcrumb(&$variables) {
  // Your code.
}


How is domain_taxonomy_access module configured?

I have found the solution by myself.

I use domain access with simplenews, i need the Domain Simplenews to,

What you have to do, is go to:

structure / taxonomy / [yourtaxonomynewsletter]

Then edit some term of the taxonomy and at the end of the configuration called Term source domain there is an option to set the domain to the taxonomy.


How to implement something to differentiate nodes?

You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


dependent dropdowns via #ajax for unlimited option

Use drupal_html_id() to generate unique ids. That is:

$html_id_first = drupal_html_id('dropdown-first-replace');
$form['field_mycollection']['und'][$key]['field_field1']['und']['#ajax'] = array(
  'callback' => 'custom_dependent_dropdown_callback_year',
  'wrapper' => $html_id_first,
);
...
$form['field_mycollection']['und'][$key]['field_make']['und']['#prefix'] = '
';
$form['field_mycollection']['und'][$key]['field_make']['und']['#suffix'] = '
';


How can I save an Advanced Action on Drupal 7 installation when there's no save button?

The Module "Token 7.x-1.2" is the culprit.  By disabling this module, the Save button again appears on the page.  Of course, to disable the Token module, I must also disable two other modules first.  Hence it's not a fix at all but a work-around because I have to re-enable this module for PathAuto.  I will attempt to submit an issue with the Token module.


Is there a module to include translatable variables in content?

Can't you wrap them in t() when fetching them?

Note: The author wants to be able to translate values from the variables table. I suggest a way to translate values from the variables table. No point in using contrib modules if core can do it just fine. That is, unless there are restrictions not mentioned in the original post that would make using the t() function impossible.


Why no alias record could be found when I'm trying to sql-sync the database?

Seems that this feature is buggy in Drush and will be removed. Check this out: drupal.org/node/1316378


Are you filtering your block to only display on certain pages? It could be that the block is not displaying because of your filtering constraints.

Another thing to check is to make sure the region you have placed the block in exists on that particular page.


I think that you can do it with jQuery.

Add this code in your template: <iframe id="frame-id" src="" frameborder="0"></iframe>
Add this jQuery:

$("#SUBMIT-ID").click(function(e) {
  e.preventDefault();//This prevents the site from being redirected.
  var a_href = $('.A-THAT-HAS-REDIRECT-CLASS').attr('href');
  $("#frame-id").attr("src", a_href);
});


It's not a D7 bug - all core code uses drupal_html_class(), which removes any dodgy characters (including ampersands) by running the incoming string through drupal_clean_css_identifier().

Presumably your theme (or a custom/contrib module) is adding a class without sanitising it. Look for something like:

function MYTHEME_preprocess_html(&$vars) {
  if ($node = menu_get_object()) {
    $vars['classes_array'][] = str_replace(' ', '-', $node->title);
  }
}

and change it to use

$vars['classes_array'][] = drupal_html_class($node->title);


Why source is empty object for hook_feeds_after_parse in dpm()?

Ooops ok,
dpm($source) does not show protected class properties if you don't specify which protected variable you want to display.
You have to point the property you want to display.

After some research in FeedsConfigurable.inc and DB
dpm($source->id) is the unique id (string!) I search for.

/n


How to set up content writers to produce articles in their own languages

I manage multilanguage sites with lingotek module, but it can be with other modules,to prevent a user to upload a node in a wrong language, with rules module add a rule, event: Drupal is initializing, condition: compare user language with current language, action: page redirect, change language or whatever to prevent it to be in wrong language. once uploaded you can translat it. with lingotek configure your contentype to be auto-translated when uploaded.


Access Denied on Drupal 8 image styles despite correct permissions

I have had issues in the past where derivatives weren't generating correctly intermittently and it was due to disc space running out.  When logs were purged the image derivatives would generate, but otherwise, the server was running out of space.  So that's one idea.


You can make the code work in 2 situations.

$term = menu_get_object('taxonomy_term', 2);
if (empty($term)) {
  if ($node = menu_get_object('node', 1) ) {
    $wrapper = entity_metadata_wrapper('node', $node);
    $term = $wrapper->field_organisation->value();
  }
}

if ($term) {
  $title = $term->name;
  $title = str_replace(' ', '', $title);
}

entity_metadata_wrapper() is the function provided by module Entity


Disable user registration for certain pattern of: IP address, name, mail

Drupal 6 had the possibility of avoid specific usernames, email addresses, matching an SQL pattern match could be used from users, and avoid those users matching those conditions could log in. There was also a setting for avoiding users could be log in from specific IPs, which is the only part kept in Drupal 7.

The other part has been moved to a third-party module I maintain. Being the maintainer, I can tell you that I didn't recently commit code for User restrictions, which at the moment is not usable because the code needs to be fixed. I count to start committing the code I have developed in the previous months starting from tomorrow, if there is not something else that take me busy.
I actually need it in my website, which is running Drupal 7. I count to make the module as much generic as possible, and allow other modules to integrate with it through hooks; for example, the code I developed allows other modules to add rules that would be used to temporary block users.

For avoiding users would use specific usernames, there is also Ban List.

  Banlist allows the administrator to disallow users from using a username from a list of usernames. The list consist of usernames such as: admin, administrator, root, demo, test, superuser, etc.

  Although core can handle this, the primary purpose of the module is for people in the community to contribute to the list and make it very easy for everyone else to take advantage.


Try this:

find -name   "123.JPG" -exec rm {} \;


Using Entity API, if given an entity in a function scope, how do you get the entity type?

There are various (convoluted) methods for getting the entity type and bundle, but none that I'd consider "acceptable" on a large-scale. What I've done is implemented hook_entity_load() and added the entity_id and entity_type properties on all entities at load-time.

The following code does this, and is part of the Devtools module I maintain:

function hook_entity_load($entities, $type) {
  // add the entity type & id to all entity objects for easy data access
  // from other hooks & modules
  foreach ($entities as $entity) {
    // we don't want to add these entity fields when the entity is being exported into
    // a feature, otherwise the feature will always show as overridden and will not
    // revert
    if (  preg_match('#admin/structure/features#', $_GET['q'])  // features page
            ||
          (                                                     // drush fu command
            isset($_SERVER['SCRIPT_FILENAME']) &&
            preg_match('/drush\.php$/', $_SERVER['SCRIPT_FILENAME']) &&
            isset($_SERVER['argv'][2]) &&
            $_SERVER['argv'][2] == 'fu'
          )
       ) {
      continue;
    }

    // set entity_type
      $entity_type_field = (!isset($entity->entity_type)) ? 'entity_type' : 'devtools_entity_type';
      $entity->{$entity_type_field} = $type;

    // set entity_id
      $entity_id_field = (!isset($entity->entity_id)) ? 'entity_id' : 'devtools_entity_id';
      list($entity->{$entity_id_field}, $vid, $bundle) = entity_extract_ids($type, $entity);
  }
}


You are basically right regarding views. Views is a way to see data aggregated together in some fashion. Think visual SQL.

The original request seems a bit confusing to me. I think you are asking for 2 things. Theming the content based on type as well as theming the views output.

For content type, take a look at theming nodes by content type . Drupal 6 and 7 are different in the way they go about this but for drupal 6 you are more or less looking to use the template node-[NODETYPE].tpl.php. This will adjust your node's output on a full view.

For theming your view, take a look at your view in the edit mode. Under basic setting you will see Theme: Information. Click on that and you will get a listing of possible templates that you could use to theme your view. Generally the same way you would edit your node type template you would edit your views template file. Check Theming Views for more info.


How to collect the node ID on a webform?

Re-write the reservation link field to include the ID in the URL.


It is hard to tell what your exact problem is, but the default .htaccess does more than just redirect requests to index.php.  It

Protects certain directories and files from being accessed
Set up safe PHP defaults for those with old configurations
Sets up some baseline cache rules
Redirects directory/file not found to index.php

In addition, the catch-all rules that you are using is not the correct one for Drupal 7.

Unless you really know what you are doing, you should keep the .htaccess in each Drupal site's DOCROOT, and then configure your server to support multiple sites using the normal methods.  You really shouldn't have to do any configuration specifically for Drupal, other than potentially needing AllowOverride All.  Personally, I use virtual hosts on all of my servers.  The Apache config for each site essentially looks like:

<VirtualHost *:80>
  ServerName www.example.com
  ServerAlias example.com *.example.com

  DocumentRoot /var/www/example/docroot

  <IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteRule ^(.*)$ http://www.example.com$1 [L,R=301]
  </IfModule>

  <Directory /var/www/example/docroot>
    AllowOverride All
  </Directory>
</VirtualHost>

That could run just about any site on the planet, Drupal, PHP, or otherwise.

On high volume sites, it sometimes makes sense to avoid .hatccess files (they are scanned every request), and place everything in your apache config (where it will be parsed/stored upon startup).


How to create relationships between Taxonomy vocabularies?

This can all be done with Drupal's built in taxonomy module and the User Terms module.

Create a node type for Items.
Any Item a user creates is automatically tied to them by them being the author.
Create a taxonomy for Locations and assign it to Items and Users.
Create a taxonomy for Categories, assign it to Items, make it multi selectable.

You can then use Views to create all the different listings pages and blocks.


How to write inner subquery in db_select() method?

You can assign your sub query to a new variable say subquery and pass it to the db_select using

$query->condition('WN.sid', $subquery, 'IN');

You can know more about this by visiting this page.


How to remove delete link from admin manage fields ui

this function will do one of two things - remove the link from the screen, or limit it's effect to doing nothing, depending on what you want to accomplish.

This will work on the Body of an Article - you will need to adjust names appropriately for the content type and field names.

Keep in mind however this will not prevent them from accessing the delete functionality using the url: example.com/admin/structure/types/manage/article/fields/body/delete - you would need to either override the menu, use an access restriction module or something like Rules to prevent users from manually deleting the field.

function MODULE_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'field_ui_field_overview_form' && $form['#bundle'] == 'article')
  {
    unset($form['fields']['body']['delete']);  // remove the link

    $form['fields']['body']['delete']['#href'] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . '#';  // make the link have no effect
  }
}


How can I retrieve the profile2 fields selected in a custom module?

Finally this is giving me the results I am after:

$profile = profile2_load_by_user($user->uid);
$customer = field_get_items('profile2', $profile['customer'], 'field_cid');
$key = array();
foreach($customer as $item=>$value){
  $output = field_view_value('profile2', $profile['customer'], 'field_cid', $customer[$item]);
  $key[] = strip_tags(render($output));
}
foreach($key as $word) {
  echo $word . "</br>";
}


Site gives 500 error or malformed page in place of WSOD and useful error reporting

Fixing such errors is a panic, as in comments you have tried php debugging.

Below tries may help:

1- Try to install new drupal site locally to ensure that your machine and required programs for drupal "If you don't have any working drupal site" works fine, If you faced problems in the installation fix them till you have successful installation.

2- Try to flush cache and running cron from the admin interface if it works or using drush by drush you can see latest log messages using commands "wd-list, ws".

3- Implement hook_init in any custom module and print any message after that call drupal exit to see tha messages in the browser.

4-disable "without uninstall in order not to loose configurations" last enabled custom or contributed modules, If you have drush installed try

  drush dis Module_name -y

Or from phpmyadmin

  Delete from system where name='Module_name';

I used these steps before to solve similar situation and I remember it was from one the contrib modules.

If you still have the problem these guides may help.

Fixing white screens step by step

Blank pages or "white screen of death" (WSOD)


What you can do is first create nodes using the API data and create a table view. so that the views fields can be referenced to nodes and they can be updated.
By this way you wont be needing any additional event handlers.
To Create Nodes you can use the following snippet:
use \Drupal\node\Entity\Node;

$node = Node::create([

       'type' => 'new_content_type',

       'title' => 'Creating a new node',

       'body' => 'Body of the node',

       'field_mail'=>'email@gmail.com',

       'field_link'=>'http://www.example.com',

       'field_date'=>[ '2017-07-22', ],

]);
$node->enforceIsNew();
$node->save();


Should views search specific caching skip preprocess?

I was misusing theme_preprocess_views_view_unformatted.

I'm running views caching, search specific (I think this may also apply to time specific) in order to cache the results of the view.

This caches the HTML of the view and means that the entire view creation, render and theming steps are skipped. When the view calls the search the correct HTML is returned.

However they do have to be run originally to build the cache. (For some reason it kicks in after a random number of refreshes? Perhaps there's simply a delay on creating the cache.)

I was using watchdog to log when the code runs and so obviously this only runs until the cache is created. This won't be an issue if everything you're doing in
theme_preprocess_views_view_unformatted alters the HTML because that will be cached the first time it happens. However I was using it to add text to header based on the results of the view, which obviously didn't work.

This was possibly muddled by the fact that I run Varnish & Authcache on my live environment so I think this would cache the initial version (before the search cache is built) and thus stop me from re-creating the bug on my live version.

Make sure you're aware of all your caches and how they run!


Submit AJAX form and update database then show all database results

Add a wrapper around the entire form, and return the entire form from your ajax callback. Then just build the rows reguarly in your form definition - The newly added rows will be shown since all the data is pulled from the database when the from is generated.

function clay_mod_blacklist_form($form, &$form_state) {
  $form['#prefix'] = '
;
  $form['#suffix'] = '
';

  // Add the rest of your form definition here

  $form['submit_button'] = array(
    '#type' => 'button',
    '#submit' => array('clay_mod_blacklist_form_submit'),
    '#ajax' => array(
      'callback' => 'clay_mod_blacklist_form_ajax',
      'wrapper' => 'clay_mod_blacklist_form_wrapper',
      'method' => 'after'
    ),
    '#value' => t('Add To Blacklist'),
  );

  $rows = db_select('blacklist', 't')
    ->fields('t')
    ->execute()
    ->fetchAll();
  foreach($rows as $k => $v) {
    $form['results'][$k]['#markup'] = "
x{$v->name}y
";
}

function clay_mod_blacklist_form_ajax(&$form, &$form_state)
{
  return $form;
}


How to change background color in my Tao subtheme

It depends on the structure of the theme. If your can´t see any change after apply this, there are two possible reasons:

body {
  color:#fff;
  background:#333;
  }

There are other elements, like divs, upon your body elemnts.
The change that you made is not reflected on your site. Check if you are working in the correct css file. If it is a .sass file, maybe it needs to compile. Other reason for that, is for the cache, try to delete by going to admin/config/development/performance

Good luck!.


You can simply add <?php print file_get_contents('my_file.html'); ?> in your module's template file, or even do that inside your module's callback function, and return it as output.

It's a little bit messy, but including off-site files or scripts is always a little messy.


How do you set the alt attribute with the Media module widget?

After one whole day of searching and patching without success I finally found out I only simply had to download and enable Token module to make Media correctly set images alt and title attributes when inserting images in CKEditor wysiwyg. I wonder since this is nowhere stated as an requirement. That's the bundle of modules it finally worked with:

media-7.x-2.0-alpha3
wysiwyg-7.x-2.2+46-dev + CKEditor profile (CKEditor 4.4.2.1567b48)
token-7.x-1.5

Now I even can use the default view mode to display the alt or title attribute below the image to use it as an image caption.


How to add wrapping elements & classes to a table in a view?

You can add css class to the whole view (go to your view edit page -> Advanced -> Other -> Css Class). It will print something like this:

       ...

In views UI there is no option to add class to
 element, but you can create/copy a template file (e.g. views-view-table.tpl.php, you can copy it from views module, look in "Theme information" in your view for more specific details) in your theme, clear caches and edit it as you wish.


How to change Solution Name display on authorize.net under Transaction Source useing Drupal commerce

It's unfortunate that Authorize.Net identifies it as "Commerce Guys". It should be identifying the request as coming from "Drupal Commerce", which allows them to monitor adoption by users of the module overall (and justifies their continued investment in our community). I'll follow-up with them immediately to change this so it's actually identifying the solution and not the creator of the solution instead (i.e. Commerce Guys). Changing what appears there is only possible from their end, but I have a contact who should be able to get it done.


Template suggestion for 'content' in custom page

You need to copy the file

entity.tpl.php

from the theme directory of the module : entity.

Paste it into your theme's template directory, and rename it to

registration.tpl.php

Other theme suggestions are:

registration__TYPE
registration__TYPE__VIEWMODE
registration__ID

If you want to have access to the preprocess function then add this function to your theme's template.php file :

function MYTHEME_preprocess_entity(&$vars) {
  //dpm($vars);
}


How to tell if a field has renderable content before printing HTML around it?

The answers so far are only valid for non reference fields. A reference field is different, because the referenced entities can have different access results than the parent entity. The rendered field can be empty although the field in the node object is not. As explained in How do I hide an empty field if my custom field formatter removes all items? there are two unambiguous empty conditions for the output of the field formatter in {{ content.field_name }}:

Check the first field delta, which always starts with 0:

{% set display_related = content.field_name.0 is defined %}

or check whether the field formatter could find any renderable children and has added the field wrapper:

{% set display_related = content.field_name['#theme'] is defined %}

For a reference field it is important to render content.field_name even if the result is negative, because it contains the cacheable metadata of the access checks. When for example a referenced node is published, the parent node needs to be invalidated and rerendered.

So checking content.field_name|render|striptags|trim is not so bad at all, because this check renders the field content and if the result is negative you don't have to render the field again, because the metadata bubbled up already.

Field Groups

For halve a dozen fields you could use Field Groups. Place all reference fields in a group "Related" and display the header in the field group template. If the field group template doesn't hide automatically you can check with striptags as before. You get the entire rendered result of all fields in the variable children.

Although I would prefer to check the specific content you expect to be inside of the field group and so ignore labels or other things that may be added later. The already rendered field group content is in a markup object and you need to render it again in twig, so you can check it casted as a string. For example whether it contains a linked node:

field-group-html-element.html.twig:

{% set display_related = '<a href' in children|render %}


A view with an exposed filter is what you are looking for.

Create a view with the fields that you want to show, and select the state code field as an exposed filter. Then the view will display only the content related to the state code selected by the user. The view may contain only one field, or many. If the relevant fields are in different entity/content types, you will need to define a Relationship in the view to connect them using an entity or node reference field.

Using Views you can get almost everything that you want if all the data involved is related. If you give us more concrete details about what you want to achieve, I could give you precise details of how to configure the View that will solve your problem.


How do I populate an email field from a single user “Name” reference?

Maybe I don't understand the need, but once you reference an entity what is the point of adding the values from the referenced entity into the referencing entity?

Is this a UI thing when creating a node? Or a display issue when displaying a node?

If it's a display issue, wouldn't you just create a new display for the reference user for when it is being referenced only showing the fields that you want shown?

To do what I am saying, you would need either https://www.drupal.org/project/ds Display Suite, or embed a view, or call the referenced user fields in a template or module.


Best way of having Pathauto based off node title, but not tied to it?

The contributed module Pathauto will provide you a setting to set your own alias urls in the add content page.

Suppose you are adding a content of type basic page (using node/add/page), at the bottom there will be an url path settings tab where you can uncheck the 'Generate automatic URL alias' option and set your own path alias for the page.


Can you try:

$item['#attributes'] = array('class' => 'photo');


Empty field collection in hook_node_presave with entity_metadata_wrapper

By this way as per this post:

/**
 * Implementation of hook_node_presave.
 */
function mymodule_node_presave($node) {
  if ($node -> type == 'my_type') {
    $field_field_collection = field_get_items('node', $node, 'field_field_collection');
    foreach ($field_field_collection as $key => $value) {
      $fc_wrapper = entity_metadata_wrapper('field_collection_item', $value['entity']);
      $fc_name = $fc_wrapper -> field_field_collection_name -> value();
      dsm($fc_name);
    }
  }
}

See: Understanding Field Collection Values and Entity metadata wrappers pages.


How to alter $form_state before render a form?

An edit form for what exactly?

getForm() accepts arguments. All additional arguments are passed to the buildForm() method of your form. So you pass whatever you are editing in, and when building the form, you get the current value and set it as #default_value of the form elements.

If you are editing entities, then you should consider using an entity form. I'm maintaining the _entityform_block module, which has the following build() method in it's block, you could do something similar in a controller:

$values = array();
// Specify selected bundle if the entity has bundles.
if (\Drupal::entityTypeManager()->getDefinition($this->configuration['entity_type'])->hasKey('bundle')) {
  $bundle_key = \Drupal::entityTypeManager()->getDefinition($this->configuration['entity_type'])->getKey('bundle');
  $values = array($bundle_key => $this->configuration['bundle']);
}

$entity = \Drupal::entityTypeManager()
  ->getStorage($this->configuration['entity_type'])
  ->create($values);

if ($entity instanceof EntityOwnerInterface) {
  $entity->setOwnerId(\Drupal::currentUser()->id());
}

$form = \Drupal::entityTypeManager()
  ->getFormObject($this->configuration['entity_type'], 'default')
  ->setEntity($entity);
return \Drupal::formBuilder()->getForm($form);


Form in modal dialog: Template suggestions have weird random suffix

Create a .module in your module folder ex : library_assets/library_assets.module

in the .module file use this HOOK to create a new form suggestion that will be dynamically equal to form--{form-id}.html.twig

    <?php
/**
 1. Implement {module_name}_theme_suggestions_form_alter
 */
function library_assets_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  //Get the form id
  // ! - you must replace the '-' with '_' in the suggestion name otherwise it won't work.
  $form_id = str_replace('-', '_', $variables['element']['#id']);

  // adding a new suggestion to the form template
  $suggestions[] =  'form__'.$form_id;
}

now clear the cache and inspect the code again and you'll find a new theme suggestion = form--{form-id}.html.twig


How to get Form API #states selected value onchange?

Drupal #states is nothing more than the page containing JS data, and states.js reading them and adding necessary JS events to hide/show/etc fields. At the moment, there is no #states based method to get the selected value.

Note that it's perfectly OK to add #states to elements that are passed through Ajax. The beauty is that, whenever something containing #states is rendered, Drupal pipes these JS data along with the Ajax response. Since behaviours are run everytime after an Ajax response, states.js can update its visibility rules even for Ajax-changed elements.

I think your solution would be to use #ajax to do this. Your [#ajax]['callback'] will contain just-selected values in $form_state['input'], so you can use them.


Please help for the moment no way to include chemistry in Mathjax

You need to add the mhchem.js extension to another part of your configuration, namely the TeX part.
Here is a configuration that worked correctly for me (a modification of the 'default' custom configuration on a clean Drupal7/MathJax environment:

MathJax.Hub.Config({
  extensions: ['tex2jax.js'],
  jax: ['input/TeX','output/HTML-CSS'],
  TeX: {
    extensions: ['mhchem.js'],
  },
  tex2jax: {
    inlineMath: [ ['$','$'], ['\\(','\\)'] ],
    processEscapes: true,
    processClass: 'tex2jax',
    ignoreClass: 'html'
  },
  showProcessingMessages: false,
  messageStyle: 'none'
});

My content looked like this:

$2 + 2 = 4$

$\ce{H2O}$

and gave me this as an output:

Hope this helps!


Let images work properly online and offline (MAMP)

Part of your code did not go through; however I believe it's pretty clear that the issue is in image paths.

Check out Pathologic module, as it deals with exactly such issues:

  Pathologic is an input filter which can correct paths in links and images in your Drupal content in situations which would otherwise cause them to “break;” for example, if the URL of the site changes, or the content was moved to a different server. Pathologic can also solve the problem of missing images and broken links in your site’s RSS feeds. See more example use cases on the documentation page.


using drush for upgrade drupal 6 to 7 - create alias problem

Although the Drupal root is a valid place to store alias files, Drush will not be able to find the alias records described there until the Drupal root as been specified.  Therefore, drush @sub status has a chicken-and-egg problem; you want to use @sub to specify the Drupal root, but Drush won't load the alias file that defines @sub until the Drupal site it is defined in is bootstrapped.

To resolve this problem, move your aliases file to $HOME/.drush/aliases.drushrc.php.  Once you do that, then your status command will work.

You may define your 'onward' alias either in $HOME/.drush/aliases.drushrc.php, or in /var/www/vhosts/domain.com/httpdocs/aliases.drushrc.php, per your preference.


For these situations I prefer to use the Chosen jQuery plugin, which makes  elements way more user-friendly. For easy intergration of this plugin with Drupal, see the Chosen module.


How to import Custom Post Types of wordpress into Drupal?

This isn't currently available in wordpress_migrate however there is a feature request open here. https://drupal.org/node/1580412

Your best option would be to write a custom migration using Drupal's migrate module. You would need to write a custom source to load your data from WordPress and you'd be able to look at wordpress_migrate for help as needed.


On Centos systems Solr assumes your cores will be stored in /var/solr/data/[core-name].

So if your core is named my-core, Solr might already have created the folder /var/solr/data/my-core for you. Simply place the conf directory in that folder, overwriting anything that might already be in conf.
No need to touch any of the other files.


media_youtube plugin doesn't work with ckeditor 4.3.x

This just may be a temporary problem with the editor, or a preference setting that may be overlooked. I know the Media module and related modules have had some significant updates and changes, so if that preview feature was unreliable at some point then deactivating it would be the right solution until a better solution comes around.


link to create a user relationship type in views

Hope this will help  you,

In Drupal 7, after configuration User relationship

Create a php field using views php module and after enabling, add below code in OUTPUT CODE within PHP tags.

  global $user;
  $opt = '';
  $requestee_id = $row->uid;
  $requester_id = $user->uid;
  if (user_is_logged_in()) {
    if ($requestee_id != $requester_id) {
      //for friend request button
      $relationships = user_relationships_load(array('between' => array($requester_id, $requestee_id)));
      if (empty($relationships)) {
        $opt = l(t('Add Friend') , "relationship/$requestee_id/request/2", array('html' => TRUE, 'absolute' => TRUE, 'query' => array('destination' => 'user/' . $requestee_id), 'attributes' => array('class' => array('ur-link add-friend-btn user_relationships_popup_link'))));
      }
      else {
        foreach ($relationships as $relationship) {
          if ($relationship->approved == 1 && user_relationships_ui_check_access('view', NULL, $relationship)) {
            $opt = t('Friends');
          }
        }
      }
    }
  }
  print $opt;

Note

2 is the default USER relationship.
Requester ID - Who requested and Requestee ID - to whome the user is requested.

Make changes as per your requirement.


How to add extra field after caption and title on images

The file entity module will allow you to add fields to your files (including images) like you would with nodes.

You can then add whatever fieds you like and configure how those fields display use them in views etc.


After trying everything that I could figure out, I have uninstalled the module, deleting all the views and installing it again and it works. No idea about what was happening sorry, but it work.

Finally thanks for some help I could understand what was happening :D The Filter Criteria Fulltext search was a Required, if you remove the checkbox then you will get the full list of items by default.


`composer require` fails because "Source directory docroot/core has uncommitted changes"

Explanation: The problem is that cweagans/composer-patches is applying patches to Drupal Core after cloning it, leading Composer to believe you've modified the affected files and therefore to prompt you to overwrite them lest you unwittingly lose work in progress.

Solution: Configure Composer to discard-changes which "[sets] the default style of handling dirty updates when in non-interactive mode... [to] always discard changes in vendors", then modify your script to pass the --no-interaction (or -n) flag. E.g.:

$ composer config discard-changes true
$ composer require -n drupal/examples
Using version 1.x-dev for drupal/examples
./composer.json has been updated
Gathering patches for root package.
Removing package drupal/core so that it can be re-installed and re-patched.
  - Removing drupal/core (8.6.x-dev)
Deleting docroot/core - deleted
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
Gathering patches for root package.
No patches supplied.
Gathering patches for dependencies. This might take a minute.
  - Installing drupal/core (8.6.x-dev 8dbf42a): Cloning 8dbf42a90c from cache
  - Applying patches for drupal/core
    https://www.drupal.org/files/issues/2869592-remove-update-warning-7.patch (2869592 - Disabled update module shouldn't produce a status report warning)
    https://www.drupal.org/files/issues/2885441-2.patch (2885441 - EntityReferenceAutocompleteWidget should define its size setting as an integer)
    https://www.drupal.org/files/issues/2018-09-24/2815221-109.patch (2815221 - Add quickedit to the latest-revision route)
    https://www.drupal.org/files/issues/2018-10-12/1356276-531.patch (1356276 - Allow profiles to define a base/parent profile and load them in the correct order)
    https://www.drupal.org/files/issues/2018-07-09/2914389-8-do-not-test.patch (2914389 - Allow profiles to exclude dependencies of their parent)

Writing lock file
Generating autoload files


Why my Webform special token values not rendered correctly in D6?

In case anyone comes across this, I finally found a thread confirming that Webform tokens in D6 do not support arrays, and I had to apply a patch for the functionality to work.

This is NOT a problem in D7

http://drupal.org/node/824606

Patch - http://drupal.org/files/nested_tokens-824606-13.patch


Try to add cardinality and settings parameters:

  function _my_installed_fields() {
    $t = get_t();
    return array(
      'my_dropdown_list' => array(
        'field_name' => 'my_dropdown_list',
        'label' => $t('Select an item'),
        'type' => 'list_text',
        'cardinality' => 1,
        'settings' => array(
          'allowed_values' => array(
            1 => 'One',
            2 => 'Two',
            3 => 'Three',
          ),
        ),
      )
    );
  }


Views with two content type and different fields in one table

For things like this I use Views Conditional.
Work with the replacement variables and hide unused content.


Block cache depending on current node and its last modification time

See my answer to a similar question here: Passing current node ID to the block template

In short, use the plugin context system to get the current node injected. It will automatically ensure that the right cache tags and contexts are added, based on where node is coming from.

Depending on what information you need exactly, you could also consider using the default entity view blocks provided by ctools. That allows you to view the node in a given view mode.


Menu is not highlighted when viewing its corresponding page

I put a condition for that node and added the style for the menu in the page.tpl.I don't know is this is the right solution.But it worked for me.


If this is not working, then the reason for this is, that the block plugin is not the form class. This is BlockForm, which calls the methods in the plugin while building, validating and submitting the form. So if you want to add custom code to the submit in a block plugin override:

public function blockSubmit($form, FormStateInterface $form_state) {}

This code will then be included when the form class calls submitConfigurationForm().

If you have more than one submit button you can check the triggering element in $form_state.

Edit:

Another option is to use a static submit function instead of the class method.


Drupal 7 "Page not found. The requested page "/" could not be found" after enabling module

After extensive research I managed to solve this issue. The following info was helpful:
https://www.drupal.org/node/262892

What I did:

Disabled the problem module in the system table in SQL, by setting
the status field of the suspect module to 0 in the {system} table.
Rebuilded Database menu system to get access again, by running update.php. The update.php by default don't allow to access, so I need to edit settings.php (located in /sites/default/) and change
$update_free_access = FALSE; to TRUE. After rebuilding menu remember
to change this back to FALSE.


Is there any way to view dpm() data other than printing it on page?

I know you say you are logged in as admin but even so just check the permission "Access developer information" is checked for the admin role just in case that makes a difference.

I've also heard of dpm not working as a result of modules not being uninstalled before they are deleted. Maybe try this module to see if that helps.

Another option would be to see if kpr() works instead.


Pass variables to template using hook_block_view_alter()

I think a better option is to override PathProcessorFront::processOutbound():

 public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    // The special path '<front>' links to the default front page.
    if ($path === '/<front>') {
      $path = '/';
    }
    return $path;

Overriding in this case means using a similar outbound pathprocessor with a higher priority and replace '/<front>' or a lower priority and replace '/'.

Edit:

Register the path processor as a service with the tag path_processor_outbound in mymodule.services.yml. This is the core service definition from the example before:

path_processor_front:
    class: Drupal\Core\PathProcessor\PathProcessorFront
    tags:
      - { name: path_processor_inbound, priority: 200 }
      - { name: path_processor_outbound, priority: 200 }
    arguments: ['@config.factory']


Add variations to coupons commerce module of drupal

Sure, no problem. Just create a new rule that triggers on the event "Calculating the sell price of a product."

You want the condition: Entity has field, then choose the commerce_product. This is the product reference field that is inherent in line items.
Then, choose the condition: Entity has field again. Choose the brand entity reference field that you have built into your product type. Basically, you will be reaching through the line item, through the product the line item refers to, to hit the brand that product is tagged with.
Next, choose the condition: Data comparison. For Data to Compare, choose that brand reference field. For Data value, switch from data selection to direct input mode, then choose the brand you wish to target.

Finally, under actions, add one of the commerce line item actions based on the mathematical operation you wish to do with that brand price.

This should do it!


In general using hook_install or hook_enable or a hook_update function in a module is prefered over hardcoding the value in settings.php of your drupal site.

Another option is to use the Configuration module or Features to encapsulate your database configuration to code to be enabled on the drupal website.


This Problem happens when we put our file in different folder like as includes/form_test.inc.In this scenario batch function can't call.So to handle this we put 'file' => 'path_to_file_containing_myfunctions' in our submit function.I wish this code will help you in understanding.you are missing 'file' in your batch array.

$batch = array(
  'title' => t('Custom File uploader'),
  'operations' => array(
    array('test_feeds_import_form_batch', array($uri)),
  ),
  'progress_message' => t('Uploading Multiple Products...'),
  'error_message' => t('Error!'),
  'finished' => 'test_feeds_import_form_batch_finish',
  'file' => drupal_get_path('module', 'test') . '/includes/test_form.inc',
);

batch_set($batch);
batch_process('admin/import-data'); //Work like as drupal goto


This now works in Drupal 8.3-x-dev. This is an example to do it from Angular:

  /*
   * Register new User.
   */
  register: function (email, password) {

    var defer = $q.defer();

    $http({
      method: 'POST',
      url: config.endpoint + '/user/register',
      dataType: 'json',
      data: {
        'name': {
          'value': email,
        },
        'mail': {
          'value': email,
        },
        'pass': {
          'value': password,
        }
      },
    })
      .success(function (data, status, headers, config) {
        defer.resolve(data);
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  }

Make sure you enable the resource to enable user registration (I use the REST UI module).

The last step is enabling the permissions on this resource:

Now you are all set!


Auto import Facebook page photos as nodes for views display

JSON parser did the trick with a feeds importer properly mapped. Once I figured out how to get the data from Facebook, it was really just a matter of configuring the importer properly with the right expressions. I was pleasantly surprised to find that I could get the data without any token because the data comes from a public page, rather than a private profile. The url structure: http://graph.facebook.com/[album id]/photos.


How to change html of CAPTCHA module in another module?

I guess you could override theme_captcha. here is the code

function bartik_captcha($variables){
  $element = $variables['element'];
  $output='<h2>'.$element['#title'].'</h2>';
  $output.= drupal_render_children($element);
  return $output;
}


Is it possible to replace page arguments with new ones in a view exposed filter?

You can adjust the default Filter identifier for each Exposed Filter in its settings. The Description:

  Filter identifier
  _
  This will appear in the URL after the ? to identify this filter. Cannot be blank. Only letters, digits and the dot ("."), hyphen ("-"), underscore ("_"), and tilde ("~") characters are allowed.

In your case you can chage the first one to geo and the other to _. That way you get the output:

cities?geo=2&_=4

although you'd probably name the second one to something more meaningful, like region:

cities?geo=2&region=4

For full control use the module Query Parameters To URL (Drupal 8 version Needs work).


Commerce by default supports line item fields that can appear on the Add to Cart form. If you only sell this one type of product on the site and will always need that "additional pages" field, then you could just add the field to the default product line item type. If you have other needs, you'd use a custom line item type either defined in code or created via https://drupal.org/project/commerce_custom_product.

Once you have customers putting in their custom number of pages, it's up to you to adjust the price accordingly. Pricing rules receive the full line item object for price manipulation, including the values of any line item fields present on the Add to Cart form. You can construct a variety of rules that look at the referenced product to determine how much to charge for additional pages and work it out using the Rules actions to create data values.


How do I install with PostgreSQL using Docksal?

It should be noted that you need postgres 10+ when using Drupal 9.
The steps that you are following in are for Drupal 8 and they will install postgres 9.
Recently a services has been added to Docksal that installs a postgres database that matches your Drupal version (8 or 9).
See the Docksal documentation on adding a postgres service.
Add this service and outcomment the default db image in docksal.env:
#DB_IMAGE='docksal/mysql:5.7-1.4'

When this services is added check that it works correctly by checking the docksal status:
~/S/mysite ❯❯❯ fin status
   Name                  Command                 State                         Ports
-------------------------------------------------------------------------------------------------------
d9geo_cli_1   /opt/startup.sh supervisord     Up (healthy)   22/tcp, 3000/tcp, 9000/tcp
d9geo_db_1    docker-entrypoint.sh postgres   Up             0.0.0.0:49174->5432/tcp,:::49174->5432/tcp
d9geo_web_1   httpd-foreground                Up (healthy)   443/tcp, 80/tcp

Your Drupal settings should look as follows (note that the driver should be pgsql)
$databases['default']['default'] = [
    'database' => 'default',
    'username' => 'user',
    'password' => 'user',
    'host' => 'db',
    'driver' => 'pgsql',
];

User, password etc. can be changed using environment variables.
Now you should be able to install the website.


Upload file in system_settings_form in Drupal 6

I found the problem: https://www.drupal.org/node/64984

Drupal 6 won't upload a file if file field is required.

Such an enormous bug. No mention in documentation about that, you have to find it yourself.
Drupal can be really disappointing...


What you are looking for is hierarchical list and can be accomplished by using these well-maintained modules below. The difference is Simple Hierarchical Select module provides a simpler implementation for dependent taxonomies [might work for your situation better].

  - Hierarchical select --
  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy. Hierarchical Select has the ability to save the entire lineage of a selection or only the "deepest" selection. You can configure it to force the user to make a selection as deep as possible in the tree, or allow the user to select an item anywhere in the tree. Levels can be labeled, you can configure limit the number of items that can be selected, configure a title for the dropbox, choose a site-wide animation delay, and so on. You can even create new items and levels through Hierarchical Select!

  Simple hierarchical select Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
  The widget is available in node forms and as Views exposed filter.This module has been inspired by Hierarchical select but is much simpler (hence the name ;) ).Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. As an addition Simple hierachical select works as Views exposed filter.


Is there a replacement for comment driven?

I have found a replacement for my uses of comment driven. Its called Node Changes, and allows changes to nodes to be recorded as comments.

  This module stores the changes of a node into a field attached to comments allowing to display a kind-of activity stream on the node much like on drupal.org issues just with a lot less custom code.


When I added my custom fivestar, I saw a similar issue, you do not have your CSS listed  but check to see if in the css you copied, check to see if all instances of the .fivestar- class has your custom star name after the hyphen.  i.e. .fivestar-bone_stars
Also of note, I answered this on another person's post here is a really nice tutorial on adding custom stars using file_scan_directory so that all you have to do is add a new folder and update the css and the hook will automatically pick it up.

Custom fivestar widget does not display custom icons


Check Form API documentation on this. It looks like someone hid field priority from output so users can't see or change it from form, but value of this field still can be used on form handlers.


Custom node add/edit form - How to leave value of undisplayed field as set?

After some research I found out, that it is very important to have the full node form be added to the panel to get all fields (like publishing option, date created...), so the submit routine gets data for all node fields.

You can show/hide fields for certain roles using the Field Level Permission Module for the standard Drupal roles. But I like to use the OG roles to define the permissions. There is already an OG function for this under admin/config/group/permissions.

I did it this way:

Activate the node/%/edit page under pages
Create a variant for editing node of a certain type
Add all required fields, which should be shown to the normal user to the form and layout it
Add the submit buttons to the form
Add General Form to the panel, so that all fields, which are not build before are added to the form (like publishing status, author, date created...)
Goto admin/config/group/permissions and set the edit rights for the fields, the normal user should not see. The fields then are not on the node form anymore, but the values remain in the database.

I hope that helps someone else.


I cannot get fields to render in a view fields template

The problem is because those fields are hidden in the view and {{field.<field-name>.content}} will be empty.


How to get the uid of a newly created user?

Where are you creating the user? Could you use entityTypeManager and EntityStorage instead of User::create()? I have the following in a method in a custom entity:

$storage = $this->entityTypeManager()->getStorage('user');
$owner =  $storage->create(['mail' => $email, 'name' => $this->getName()]);
$owner->save();
$uid = $owner->id();

If you don't have access to entityTypeManager() in your class, you could alternatively use:

$storage = \Drupal::service('entity_type.manager')->getStorage('user');


Add product - price and sku field missing

A variations tab, which is skus and prices. A product is paired to 1 or more variations.

Answer provided by smccabe from commerce slack.


How can I check if the author of the current node is the current logged in user?

I have managed to work it out! Below is the code for checking whether the current user is viewing content they are an author of:

global $user;
if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);
}

if($node->uid == $user->uid){
return TRUE;
} else {
return FALSE;
}

Hope this is helpful to someone.


Have users answer a question before viewing content

I'm not aware of a module that does this out of the box. But depending on your details there are a few ways to try to solve this problem.

One solution would be to create your form using Webform or Entity form (assuming your on Drupal 7 a contact form could be used in Drupal 8), place that form in a hidden block on the pages in question. On page load use JavaScript to put the form into a lightbox and set some kind of CSS effect over the rest of the page. When the user completes the form set a cookie so that on the next page load they aren't bothered by the popup. This is a common solution used by News papers trying to enable paywalls but it often means users can bypass the effect by disabling JS.


Performances with many fields per content type

MySQL limits you to 61 table joins but Drupal doesn't care about this limit. Each field gets loaded individually, so every field will slow down Drupal a little bit but there is no practical limit. The impact depends on how long a round trip to the database takes. If you have Apache & MySQL on the same box and you're using sockets for communication then the impact will be minimal (read slides 60-68 from my presentation for more info). If Apache & MySQL are on different servers then the number of fields will have more of an effect. All of this can be mitigated by using something like the https://www.drupal.org/project/entitycache module.


Form API: Hiding form option on node forces node to be unpublished

When you hide the form['options'] array you essentially set it to 0.  Which means the published field will always be 0 (unpublished).  Try hiding the fields with CSS or JS if you need it to be conditional.


How do Image Optimize pipelines coexist with core's Image toolkit optimization?

With the Image Optimize pipelines, I'm not sure if core's JPEG quality
settings are still used: does the image get core's optimization plus
the Image Optimize pipeline?

Yes

does the Image Optimize pipeline override core's optimization?

No
According to the module's creator you should set your core's image toolkit to 100%; otherwise, you will endup with double compression and lower image quality.


Why do I get Template "@bartik/block" is not defined?

I didn't know of Twig namespacing just until now. But what always worked for
extends and includes is to point to the template you want to extend/include directly, with the path starting from Drupal web root. So in your case it needs to say:

{% extends "core/themes/bartik/templates/block.html.twig" %}

You could also try the following which seems to follow theme inheritance but only up to the final base theme (which would be Classy).

{% extends "@block/block.html.twig" %}


take a look to Disable Messages module http://drupal.org/project/disable_messages I think that could be useful for your needs.

  Features

* Filter out messages that match a full text string exactly.
* Filter out messages that match a regular expression.
* Permissions to specifically hide all messages of a given type from any role.
* Disable all filtering for specific users.
* Disable all filtering for specific paths.
* Apply filtering only for specific paths.
* Debug system to get messages in the HTML without showing it to the end users.


How to hide "Delete Site" link for a user rather than Admin?

$global $user
    //Get admin_id from database and add condition
    if ($admin_id == $user->uid){
         add your code here
         }

Hope this idea of code is helpful for you


When using Rules, does a page refresh happen immediately if the event is set to 'Drupal is initializing'

You have not specified the exact condition you are using. If you are using 'When content is viewed by an authenticated user' condition, then yes, views are being loaded in node load hooks, and they are already there by that time. The good news is that if these are cached, it will lighten things up, and the amount of admins is always limited, so a non-issue performance-wise.

But, if you really wanted to make one view show to one user and another to another, this is what you can do:

Create a separate block for each view display.
Put these blocks on the page.
Apply conditions for blocks that will show them for specific roles. Advanced to admins, and usual for non-admins, or all else.

And voila - you will have a solution without redirects and overhead.


How to change node field label for some specific conditions?

This doesn't work for two reasons. First, you shouldn't change objects unless you want to save the changes  because they are shared across the entire Drupal application. Second, preprocess is for preparing variables printed in templates. Changing other variables has no effect.
So in hook_preprocess_node you can change only $variables['content'].
For most fields the label is stored in #title unless the field is built in a special way by callbacks:
$variables['content']['field_bar']['#title'] = 'Foo';

More straightforward, though, would be changing the label directly in hook_preprocess_field:
$variables['label'] = 'Foo';

which is then printed in the template as {{ label }}.

By the way, if you want to rewrite your code for field preprocess you find the node in this variable:
$node = $variables['element']['#object'];


Automatically downloading libraries for a module

You can use drush make to do this, but that will only work if the person downloading the module is using drush make.

In your modulename.make file:

libraries[foolib][download][type] = "get"
libraries[foolib][download][url] = "http://path.to/file/or/tarball.gz

This is only advisable if you are grabbing libraries. Adding dependent modules here currently can cause version conflicts (although many modules supply this info via a modulename.make.example file).


What modules do I need to implement web services?

I've used the soapclient module in D6 for my cause with a SOAP server. It works by making SOAP calls and keeps things really simple. One method to instantiate the SOAP object and another to make the call. It has a good test page where you could enter the webservice end point, the mode like XML RPC etc. and other options such as the service method and service parameters and test the response which is quite good as you can test the service without any actual code. If you plan on implementing webservice with SOAP it is a nice module.


Can you use views instead?
The Views Natural Sort module may help you

Otherwise, in drupal 7 you can go with

$query->orderby( 'CAST(n.title AS SIGNED)', 'ASC');

Check also  CAST Mysql documentation


How to execute a query taken from views in custom module

Goto admin/structure/views/settings and enable the setting

  Show other queries run during render during live preview

As the help text for the setting reads, probably during the view rendering time there are some changes that could be happening. Enabling this setting will give you an insight into what is happening.


How to create additional drupal sites with a drush script

Drush has very limited support for table prefixes; site-install is just one of the ways that Drush can fail.  sql-sync has similar problems.  It would take a lot of work to fully support table prefixes everywhere; it is best and safest to just use multiple databases when using Drush.


Are Wysiwyg and CKEditor modules incompatible now?

Yes you use one or the other of the CKEditor & WYSIWYG modules.

They both provide the same sort of functionality.

As to which is better is up to your preference. You can try them both and see which one you prefer.


Trigger a rule when a module update is available

I know that you specifically asked about Rules, but you might also consider using Drush for this.  For example, if you want an email to be sent to you every time an error appears on your status page, you could just drop this one line into your crontab:

0   */1   *   *   *   /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin /bin/drush --root=/path/to/drupalroot --uri=mysite.com status-report --severity=2

(n.b. your path may vary.)  If there is output from the status-report command, cron will send it out in an email; if there is no output, nothing happens.

Hope you don't find this answer to be too off-topic.  Rules is great for responding to user actions, but for scripting site maintenance tasks, Drush is often more convenient.


The only way I have found to fix this problem is to change the default php used by the server. In other words, /usr/bin/php was originally a symlink to /usr/bin/php7.1, and changing it to a symlink to /usr/bin/php5.6 solved the problem.

But it appears that drush will always use the default php even if you install it with an alternative.


Getting the apartment cleaning and dish washing to work properly with Omega Theme?

check settings for filth and grime under settings.php, these settings override any other setting in omega be sure they are both are set to active. Run update.php.

It's possible that your filth and grime settings are set too low so you may need to adjust these in your ini.php file. (i have mine set to "CDC alert")

Any use of hand-sanitizer or disinfecting sprays can cause the omega settings to malfunction, this is a known issue.


Let assume the page is a node whose ID is 4. You can use the following code, in a template file.

About us"


How to add class to individual radio item inside "radios"?

No there's nothing built-in for this (take a look at form_process_radios(), nothing in there that would let you specify individual classes).

No need to hack core though like in the solution you linked to. Simply implement hook_element_info_alter(), and replace the process function with your own, which will be based on the original form_process_radios(), but that can handle individual classes for options.

function MYMODULE_element_info_alter(&$info) {
  // You might want more advanced logic here, to replace instead of override altogether,
  // in case other modules have already altered the core info.
  $info['radios']['#process'] = array('MYMODULE_process_radios');
}

function MYMODULE_process_radios($element) {
  // ...
  return $element;
}


What you want, as I understand you, is to have a fixed interface language for a certain role.

You can adjust the user interface text language in admin/config/regional/language/configure. Unfortunately there's no method based on role. You can only use the user method, so users see the interface in their prefered langauge. This setting is for all users, not just for a role.

You may code a new language detection method based on role, but I don't know where you have to start (except checking the i18n module code).


When you edit your view, you should see "Sort Criteria" at the bottom of the left column. I think it defaults to "Updated date". If anything is in this section, you'll probably want to delete it and then click on "Add" to pick the id as your real sort criterion.


Problem on the comment form #validation and #submit

You're missing $form_id, the third parameter of the function.

See hook_form_alter() reference on drupal.org. The problem you're experiencing might be a (weird) way of PHP reacting to that.

In situations like this you may want to check for errors on the logs (Drupal, PHP, MySQL). Some times there are useful hints there to figure what's wrong.


Multiple page versions and caching for anonymous users

$_SERVER['REQUEST_URI'] is the simplest way. The other option is to modify the key used in the cache. There is a 6.x memcache patch that I've been using http://drupal.org/node/942914

The latest version of http://drupal.org/project/authcache might be able to do it.


Redirect to PayPal site without payments pane in checkout

Commerce Paypal WS already redirects automatically by using the "offsite_autoredirect" flag in hook_commerce_payment_method_info:

  $payment_methods['paypal_wps'] = array(
    'base' => 'commerce_paypal_wps',
    'title' => t('PayPal WPS'),
    'short_title' => t('PayPal'),
    'display_title' => $display_title,
    'description' => t('PayPal Website Payments Standard'),
    'terminal' => FALSE,
    'offsite' => TRUE,
    'offsite_autoredirect' => TRUE,
  );

The behaviour of this flag is to redirect automatically:

if (!empty($payment_method['offsite_autoredirect'])) {
  $form['#attached']['js'][] = drupal_get_path('module', 'commerce_payment') . '/commerce_payment.js';

And the js is the simplest it can be:

  Drupal.behaviors.commercePayment = {
    attach: function (context, settings) {
      $('div.payment-redirect-form form', context).submit();
    }
  }

So if you're experiencing a 10s delay on this operation, you need to debug what's happening in your payment page to cause this slowness. Check things like other panes you've put there (there should be just the payment one), cache, js compression and so on.


Based on your edit including html.tpl.php, I agree with Chapa that's it very, umm, "Un-Drupaly".  This is the default system rendering of html.tpl.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

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

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

You see where it says:

<?php print $styles; ?>
<?php print $scripts; ?>

That's where Drupal dumps your JavaScript and CSS files.  If you're not making those calls chances are you're not going to get any included files.  I guess to verify this you'd also have to edit in your header.php and footer.php files so we can see what they contain.  This is where you want to start looking.

I recommend backing up your existing html.tpl.php file to somewhere, and then overwriting it with the system version of it, which can be found at modules/system/html.tpl.php relative to the root directory of your site on your system.


How do I save data into a custom table on form submit?

As per the change record, drupal_write_record has been removed, with the new advice being:

  Developers should use \Drupal::database()->merge(), the Entity API or one of the provided services, like key value.

As you're using a custom table, you'll need the first method. An example from that change record:

\Drupal::database()->merge('example_deleted_entity_statistics')
  ->key(array('type' => $type, 'id' => $id))
  ->fields(array('count' => $count))
  ->execute();

As always, inject the database service if possible, rather than requesting it from \Drupal.


Best practice to change 403 page depending which page 403?

This: How can a module detect when the "access denied" page is output? along with arg() is probably how I would do it. D7 doesn't have the correct hooks for this so you have to use an API in a way that it wasn't originally intended.


Where can I find good, reliable Drupal freelancers?

A lot of generic freelancer site members may have used Drupal but usually work with anything, wordpress, joomla etc. Drupal has a fairly high learning curve and to get the best out of it you would be best with a Drupal Expert. Maybe try something closer to the Drupal community.

Using a Drupal resource for Drupal freelancers might provide more Drupal expertise...

http://drupal.org/paid-services
http://drupal.org/marketplace-preview


You must declare the field for the DS be able to handle it. In your case:

/**
 * Implements hook_field_extra_fields().
 */
function mymodule_field_extra_fields() {

  $extra['node']['article']['display']['field_video_embed_code'] = array(
    'label' => t('Custom field embed video.'),
    'description' => t('Adds a custom field.'),
    'weight' => 0,
  );
  return $extra;
}


Is it possible to organize template files?

Is it possible to organize template files into different directories within the primary templates directory?

Yes, absolutely. Drupal will recursively search the root and every subfolder in your theme for .tpl.php files.

Stick them in whatever structure suits you, Drupal will find them.


"Redirect Loop" when creating a multisite

Assuming you have ServerName and ServerAlias properly defined in Apache, I suspect you have the default canonical URL redirects enabled in your .htaccess.  Make sure this stuff is all commented out:

  # If your site can be accessed both with and without the 'www.' prefix, you
  # can use one of the following settings to redirect users to your preferred
  # URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
  #
  # To redirect all users to access the site WITH the 'www.' prefix,
  # (http://example.com/... will be redirected to http://www.example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} !^www\. [NC]
  # RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  #
  # To redirect all users to access the site WITHOUT the 'www.' prefix,
  # (http://www.example.com/... will be redirected to http://example.com/...)
  # uncomment the following:
  # RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  # RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

Also make sure you don't have any other Apache rules that are doing something similar, and that you don't have any modules (eg, Domain Access or Mobile Tools) or custom code that would do a redirect.


Map subset of taxonomy terms to a content type

Achieved this using Taxonomy Publisher Filter which is part of Taxonomy Tools module


Cannot create users as administrator. Users can register by themselves but I can't add users (site exported directly from Drupal Gardens)

I had the same problem. However, once I disabled three Drupal Gardens custom modules, I was able to add users. The modules are:

Gardens Features
Gardens Feedback
Gardens Required Features


The right way is using template_preprocess_node().

Place the following code in template.php of your front end theme:

function YOUR_THEME_preprocess_node(&$vars) {
  // I suppose you don't want to do this for every content type on the site.
  switch ($vars['node']->type) {
    case 'YOUR_CONTENT_TYPE':
      $vars['count'] = flag_get_counts('node', $vars['node']->nid);
      break;
  }
}

This will make the $count variable available in .tpl.php files that are used for displaying nodes of your content type.


Restrict administrator users from seeing blocks

If you don't want the block displayed on admin PAGES, eg, www.yourhost.com/admin/HERE, you can go into the block admin pages and restrict the block to be displayed on all pages EXCEPT admin/*.

However, if you don't want your "root" or "superuser" to see the blocks on any page, you can do what @BetaRide has suggested above in the PHP area of the admin page.

In the same vein, if you don't want anyone with an admin role to see the block, you can do something like this:

global $user;
if ($user->uid==1 || in_array('admin users', array_values($user->roles))) {
  return FALSE;
} else {
  return TRUE;
}

Of course, here you have to make sure you have a role called admin users so that might be different on your system.

If you don't want to add a role, you could use permissions and do it like this:

if (user_access('access administration pages')) {
  return FALSE;
} else {
  return TRUE;
}

which would display the block only to those users who could NOT access the admin pages.


How to force caching to work for View with filter by date offset?

In Drupal caching system, there's an option to cache pages/blocks for anonymous users only, maybe it's the same thing for Views. Check if it works with a not logged in user.


Change value on validate form when I create or edit a block

Please insert the validate method inside the #element_validate function and then change the element value.

/**
 * Implements hook_form_FORM_alter().
 */
function MY_MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'block_content_MY_BLOCK_form' ||  $form_id =='block_content_MY_BLOCK_edit_form') {
       $form['field_test']['widget'][0]['#element_validate'][] = '_custom_validate';
      }
    }

function _custom_validate(&$element, FormStateInterface $form_state, &$complete_form) {
  $form_state->setValueForElement($element,['value' => 'See the change']);
}


If Feeds creating empty values on Auto create, you need to verify your mapping. Make sure your Context Value in XML Xpath parser is fetching the right data by enabling Debug option, so you can see exact value being imported. If it's not, please validate your XPath on your sample data (e.g. on-line on XPath Tester).

If your XPath is correct, then use hook_feeds_after_parse() to debug your feed items, e.g.

/**
 * Implements hook_feeds_after_parse().
 * Invoked after a feed source has been parsed, before it will be processed.
 */
function MYMODULE_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
    foreach ($result->items as &$item) {
      drupal_set_message(print_r($item, TRUE));
      // or: drush_print(var_export($item, TRUE)); exit;
      // or: var_dump($item, TRUE); exit;
      // or: dd($item); exit;
    }
}


How do I postpone an already postponed deletion

First an educated (wild) guess ... Since Drupal, out-of-the-box, does not come with some "postpone" facility, I'm going to assume that you implemented that by using the Rules Scheduler to schedule the execution of a Rules Component, which does nothing but delete some content (node).

Have a look at my answer to the question "How can I set a reminder for a specific user to be triggered on a specific date?". Obviously, that is not the same question as yours here. But the "specific date" there appears to correspond to your "postponed date".

With that, you could just trigger a rule each time that the content is edited, and then verify the relevant data of your content to decide if you need to do either of these:

no more need to postpone the deletion of content "later on", so just DELETE the scheduled execution of the Rule to delete content.
(re-)schedule the execution of the Rule to delete content.

PS: from revision 1 of your question, I understand it is about D7 ...


I want to modify the drop down menus for Marinelli (a Drupal theme)

The marinelli_menu.js on the marinelli theme folder is controlling the JavaScript.

The primary-links.css file is handling the theming.

Armed with this knowledge you can use Firebug to easily tweak the CSS and find out how it looks without having to save the file. And with Firebug's command line and debugging you can explore how those JavaScript functions behave and what's the best way to modify them if necessary.

If you don't know JavaScript or CSS then you have bigger issues.


Resolved it.

The trick was to create a new variable in the rule.

Store > Configuration > Checkout Settings > Checkout Rules.
Edit the rule : Send an order notification email.
Create a loop over each commerce-order:commerce-line-items.
Add a variable to the loop.

This was the trick.

The data selector is: list-item:commerce-file-line-item-files:0:file

Don't worry about the the 0 - the loop is sending 1 email per document. The result could be cumbersome, but means that if people order 20 documents and they are large, they should still get through.

I called the variable: added_commerce_file_licence_items.

6) Create a Send HTML e-mail rule. Put it in the loop.

The attachments field contains:

[added-commerce-file-licence-items:path]

7) Make sure that the permission "Send arbitrary files" is set.

I could also send by hook_mail_alter(&$message), which allowed me to try a few different things such as permutations of the URL and get a working version without too much experimentation.

function commerceemaildoc_mail_alter(&$message) {
  if (array_key_exists('attachments', $message['params'])) {
    foreach ($message['params']['attachments'] as $attachment) {
        $file_content = file_get_contents($attachment['filepath']);
        $mime_type = file_get_mimetype($attachment['filepath']);
        $attachment = array(
            'filecontent' => $file_content,
            'filename' => basename($attachment['filepath']),
            'filemime' => $mime_type,
        );
        $message['params']['attachments'][] = $attachment;
    }
  }
}


node_overview_types no hook? how to customize

Since there's no specific theme function used the easiest way I can think of is to implement hook_page_alter() and alter the table directly. The following code works for me:

function MYMODULE_page_alter(&$page) {
  if (request_path() == 'admin/structure/types') {
    // Get the types, they will automatically be in the same order as the rows
    // in the existing table
    $types = array_keys(node_type_get_types());
    $limit = count($types);

    for ($i = 0; $i < $limit; $i++) {
      // Get the existing row
      $row = $page['content']['system_main']['node_table']['#rows'][$i];

      // Get the type related to this row
      $type = $types[$i];

      // Make a link to add to the table
      $link = l('Link Text', 'my/path/to/' . $type);

      // Make up the new cell. I know there's an easier way to do this but
      // I can't for the life of me remember it right now
      $new_row = array($row[0], $row[1], $row[2], $link, $row[3], $row[4]);

      // Overwrite the existing row with the new one
      $page['content']['system_main']['node_table']['#rows'][$i] = $new_row;
    }

    // Increase the colspan of the header to take into account the new column
    $page['content']['system_main']['node_table']['#header'][1]['colspan'] = 5;
  }
}


jQuery hasn't been deprecated. Some unused jQuery UI components have been deprecated in 8.8 and will be removed in Drupal 9.0. core/jquery.ui.dialog is not among them.

[8.8 issue] Deprecate unused jQuery UI components in favour of a suite of contrib modules
[8.8 change record] Deprecated unused jQuery UI asset libraries
[9.0 issue] Remove deprecated jQuery UI components and fork remaining source code into core
[9.0 change record] jQuery UI source added to Drupal core and deprecated code removed

Nonetheless there's the new Dialog API. For that you have to require the core/drupal.dialog library or the core/drupal.dialog.ajax library for more advanced stuff. Some examples can be found in the docs on Ajax Dialog Boxes. The following sample requires the core/drupal.dialog.ajax library.

  This link opens /node/1 in a modal dialog box:

<a class="use-ajax"
    data-dialog-options="{&quot;width&quot;:400}"
    data-dialog-type="modal"
    href="/node/1">
    First node displayed in modal dialog.
</a>

What you currently do in your code sample hasn't much to do with Drupal at all. To do it the Drupal way check the docs on adding JS/CSS to your module or theme first. You could attach the library simply to your theme or directly to all nodes of a given type for example.

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme


To theme/design the complete row, you need to use Style output template file.

Click on Theme: Information in your view, in pop-up see the last file in Style output section. Copy the name and create file with same name and save this file at sites/all/themes/YOURTHEME/templates.

Then click on Style output, copy the code and paste into the newly created file. In this file, you can add your own HTML display the result.

Hope this helps.

Thanks


No emails being sent when using User Registration Password set up

This all works perfectly now, i needed to use an email address that belongs to my domain i.e. anything@mydomain.co.uk otherwise it gets blocked, therefore use this email in Configuration/Site Information and also in the Trigger rule I created to alert me when a new user is created. Thank you for guiding me towards using the Dev version.


I haven't found a module which does this yet.  You can do these steps:

Create a text field named ip_address
Manage display: make the field hidden
Use Display Suite or a custom hook (or even CSS) to hide the field when filling out the form
Create a Rule on event "Before saving content"
Set a condition of content type: your content type
Set a condition of Data comparison: [node:is-new], Data value: True (check the checkbox)
Set an action of Set a data value, and set the field to be:

PHP Code

<?php
  print ip_address();
?>

That should do it.

You could also accomplish this by creating a module and using some hooks


Multisite logic (picking what site is what) works in Drupal itself, rather than the Apache level.

I do not think that putting a .htaccess in the sites folder would work, mainly because nothing is really fetched from there from Apache's perspective, except for files.  Normal URLs would never see that file.  There would also be some weirdness with the RewriteBase, and other complications because of the way .htaccess gets processed up the directory hierarchy.

My suggestion would be to use the Redirect module.  This module essentially presents a UI for making and managing redirects for your Drupal site.  You can enable this per site in your multisite setup.  Therefore each domain could redirect its own URLs.  I have found this module very useful for new site launches that use a new URL scheme.

Your other option would be to RewriteCond, eg

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule some/old/url.html the/new/url [L,R=301]

I would do this as an include from the main Apache configuration, rather than .htaccess, unless you a really careful about backing this up when you update core.

Of the two options, I would use the Redirect module.  I would also think very carefully about committing to a multisite solution.  They tend to create more problems than they solve.


Drupal core expects only internal URL (node/123) in the page.front setting. See \Drupal\Core\Path\PathMatcher::isFrontPage.

To be able to set page alias in the front page settings, I have created
a workaround. I made a replacement of the path.matcher using an alias fallback:

mymodule/src/MymoduleServiceProvider.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the path matcher service.
 */
class MymoduleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Override the path matcher for the alias fallback.
    $definition = $container->getDefinition('path.matcher');
    $definition->setClass('Drupal\mymodule\AliasFallbackPathMatcher')
      ->addArgument(new Reference('path.alias_manager'));
  }
}

mymodule/src/AliasFallbackPathMatcher.php:

<?php

namespace Drupal\mymodule;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Path\AliasManagerInterface;
use Drupal\Core\Path\PathMatcher;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * The path matcher with alias fallback implementation.
 */
class AliasFallbackPathMatcher extends PathMatcher {

  /**
   * The alias manager.
   *
   * @var \Drupal\Core\Path\AliasManagerInterface
   */
  protected $aliasManager;

  /**
   * Creates a new PathMatcher.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The current route match.
   * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
   *   The alias manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, RouteMatchInterface $route_match, AliasManagerInterface $alias_manager) {
    parent::__construct($config_factory, $route_match);
    $this->aliasManager = $alias_manager;
  }

  /**
   * {@inheritdoc}
   *
   * Support path alias for the front page path.
   */
  protected function getFrontPagePath() {
    if (!isset($this->frontPage)) {
      $path = parent::getFrontPagePath();
      $this->frontPage = $this->aliasManager->getPathByAlias($path);
    }
    return $this->frontPage;
  }

}


In the case that your insertion script is not capable of handling UTF-8 encoding (it sounds like this is the case), you can get around this by inserting this character as 7-bit HTML entities (i.e. &#174; or &reg;) provided the field where it appears is going to be rendered as HTML (and not as plain text).  Just do a search and replace and replace all occurences of ® with &#174; in the source text file.

If this workaround doesn't work (because the field is supposed to be plain text, or for some other reason), you must do two things:

Make sure your file containing these characters is UTF-8 (not ISO-8859-1 or some other encoding incompatible with UTF-8).
Make sure your insertion script is capable of handling UTF-8 (db_insert is, but I don't know what other components you use).


Crumbs not adding home link to beginning

How to find out why not seeing the home link in bredcrums Drupal 8.

Check your theme (admin/appearance/settings/THEMENAME)

Some themes like bootstrap can set to show or not.
Check modules for any 'hook_system_breadcrumb_alter'

These can alter how bredcrums work.
Check modules for any services tagged with - "{ name: breadcrumb_builder" (same as above)
Check theme templates for any templates overriding core bredcrums or .theme overrides
Check if the block is enabled (admin/structure/block)
Cry


Using views to generate a summary view of nodes

There are a million different ways to do things in Drupal, but:

Create a View
Filter on node published and type
Sort by whatever criteria you desire and select how many items you want displayed
In Fields, select:

a. Node Title - link to node

b. Body or Field that contains the description you want displayed (select Trimmed if you want it shorter than all of it) and remove the label

c. Node Link - enter Read More as the text to display and remove the label

and you should be on your way...


How to Replace Value of CKEditor Field via Custom Module

I have had some success.

MYMODULE.module:

use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  if ($entity->hasField('field_name')) {
    $entity->get('field_name')->value = $newValue;
  }
}


Drupal commerce: Purpose of utilizing different product types?

Different set of fields should be the main reason for different product types. In my opinion, it is the same reason which puts us in the position of creating new content types.

Different set of fields might seem trivial, but if you are using rules/triggers to do different things to a unique set of fields, then that's altogether a different feature.

Hope this explains the difference.


How to bypass HTML mail for specific Webform

There are two parts to this answer 1) Mailsystem configuration and 2) Mailsystem template suggestions.

1) Mailsystem configuration

This solved the issue for me and I was perhaps being silly:
Go to /admin/config/system/mailsystem and set Mime Mailer as your default config, well I want that as default.

Then below I had webform config for all webforms, but this was overkill as the settings above already made webforms use Mime Mailer, what I needed to do was add an override for this one email handler:

The specific email handler machine name was email so you can see its key is "email_email".

2) Mailsystem template suggestions

Something I learnt while investigating this is that there are template suggestions added by mimemail.module of the following pattern:

$suggestions[] = "mimemail_messages__" . $variables['key'];

So the above webform email, if using mimemail would use a template named mimemail-messages--email-email.html.twig


Submit handler: Prevent other handlers from running in certain circumstances only

By the time your submit handler is running you cannot change the other submit handlers that are running.

What you could do is make sure your form alter runs last (change the weight of your drupal module in your install file to a highier number to make it run later).
That way you can be a bit more sure that no one else is adding submit handlers after your form alter.

Then in your form alter do something like this:

// Add the original submit handlers to the form state for us to use later.
$form_state['original_submit_handlers'] = $form['#submit'];
// Replace the original submit handlers with out own.
$form['#submit'] = array('honeytrap_submit_handler');

Then in your submit handler:

if (honey_trap_fails) {
  // Do whatever, but don't call the original submit handlers.
}
else {
  // Do whatever, and then:
  // Call the original submit handler because it was a successful submission.
  // Replacing yours as it has already been called.
  $form['#submit'] = $form_state['original_submit_handlers'];
  form_execute_handlers('submit', $form, $form_state);
}

There is something important to take into account here:
If there are submit handlers on the button that was clicked then they will take precedence over submit functions attached to the form.
See form_execute_handlers() for a bit of further insight on how to handle button submit handlers.


What is stopping my theme from using a file that uses a suggested file name?

Your can either use hook_preprocess_page or if you don't want to code use something like context module. You can add a new context to select theme template based on your requirement.


Views Load More for products listing page in ajax

You can use views load more module. It provides a button. Clicking that button lists more contents only. The pager should be defined in your views settings.


D7: $node->created property not available in mytheme_preprocess_block(&$variables) function?

The important difference between the two code examples you're giving, is $node = $vars['node'];. You can only use the variables that are available inside the function you're writing. If you declare a function cybele_preprocess_block(&$variables), then the only variable you start with is $variables. In other words: inside that function, $node doesn't exist yet!

Sometimes, the current node is stored in the $variables array, so if it's in there, we can take it out again. That's what the line $node = $vars['node']; does: it creates a new variable $node and populates it with the value of $variables['node']. You do not have to put the node in a separate variable; you can also do this:

function mytheme_preprocess_node(&$variables) {
  $variables['day'] = format_date($variables['node']->created, 'custom', 'd' );
}

If the node is not available inside $variables (which I think is the case in _preprocess_block) you will have to load the current node. Fortunately that's rather easy in Drupal 7, because you can use menu_get_object. This will only work when viewing a node page.

function mytheme_preprocess_block(&$variables) {
  $node = menu_get_object();
  $variables['day'] = format_date($node->created, 'custom', 'd' );
}


There is a login block that you need to disable.
structure > blocks disable the login block.


Restrict node for anonymous user programmatically

hook_init:

<?php
// Get the current active node object if present.
$node = menu_get_object();
// Redirect to login page if NID == 42 and user is anonymous.
// User will then go back to node page due to destination being set.
if (   user_is_anonymous()
    && !empty($node)
    && !empty($node->nid)
    && $node->nid == 42
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);
}
?>

hook_boot:

<?php
$args = arg();
if (   user_is_anonymous()
    && isset($args[0]) && $args[0] == 'node'
    && isset($args[1]) && is_numeric($args[1])
    ) {
  drupal_goto('user/login', array('query' => array('destination' => 'node/' . $node->nid)), 307);
}
?>


Nodes being imported from the Feed module not being published

I know this might sound way too easy but have you been into the content type you are importing to and made sure that it is set to default published? Unless you tell the imported nodes otherwise, they will use the default for the content type. If you are using the published status from the xml as the published status for the imported nodes, then thats another matter.


If you are sure that settings.php and ftp files are all set right, my guess is you miss some package in php or in appache. Please compare php and appache settings between old host and new host. For example, rewrite_module in apache


Can I "drush rsync" with "chown @ destination"?

If you do not tell rsync to preserve the uid, then it will create all transferred files under the ownership of the user that you connected as.  The key, then, is to make sure that you put 'remote-user' => 'bob' in the site alias for your destination site.

The rsync flags I use to achieve this are -rlptz.  So, in my drushrc.php, I have:

$command_specific['rsync'] = array('mode' => 'rlptz');

See also:

http://drupal.org/node/1169776#comment-4612944

http://drupal.org/node/1343892

Supporting rsync modules in Drush would be awkward. If you want to use modules, it's probably best to call rsync directly.  e.g.:

rsync -av --rsh=ssh drush dd @siteA root@siteB.loc::SiteB

You would need to configure your SiteB module to point to the Site B Drupal root anyway, so it seems like there is little value to tying this to a site alias.


If it is an option you want to consider, you could use a convention for your select list values like so:

01-Apple.
02-Orange.
03-Raspberry.
00-TBD.

The sorted version of this list would look like so:

00-TBD.
01-Apple.
02-Orange.
03-Raspberry.

It's what I often do for any software where I somehow want to overrule the whatever sorting (eg to ensure my most often used folder names are always at the top) ... And it works in pretty much every OS I ever used (including mainframes ...)


How to know if i click any link in drupal and set a variable?

As I understand it, you need to pass a value via the URL, and fix a forms element based on this.

You have to output a link ith your variable in it, in the form yoursite.com?variable=value, preferably via the l() function.

On your second page, the value will be accessible in several ways, for example in the $_GET variable.

More powerfull and Drupalish, you could also implement a hook_menu to be able to use clean URLs like yoursite.com/some_menu_entry/yourvalue and the corresponding function.


Render field collection multiple times on node.tpl.php

You should read manual for field_view_field function.

Do not use inside node (or any other entity) templates; use render($content[FIELD_NAME]) instead.
Do not use to display all fields in an entity; use field_attach_prepare_view() and field_attach_view() instead.
The field_view_value() function can be used to output a single formatted field value, without label or wrapping field markup.


User Login: login failed: 400 Bad Request

try

const headers= new Headers({
  'Content-Type': 'application/json',
  'X-CSRF-Token': 'Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM',
  'Authorization': 'Basic Qfnczb1SUnvOAsEy0A_xuGp_rkompgO2oTkCBOSEItM'
})

let options = new RequestOptions({ headers: headers });

login (user: User): Observable<User> {
  const url = `${this.mainUrl}/user/login?_format=json`;
  return this.http.post(url, user, options ).map((res)=>{console.log(res)});
}


How can i prove that the activation link sent to subscriber (anonymous user) has actually been activated?

You can check the Status of your subscribers by going to People > Newsletter subscriptions (/admin/people/simplenews).

There are 4 places within Drupal admin navigation that Simplenews entries are interspersed into:

Configuration » Web services » Newsletters (/admin/config/services/simplenews) for creating different Newsletters (you want at least one)
Structure » Content types » Simplenews newsletter (/admin/structure/types/manage/simplenews) to choose and edit a Content type to use for the newsletter content
People » Newsletter subscriptions (/admin/people/simplenews) to list and filter all your Subscribers
Content » Newsletters (/admin/content/simplenews) to see all the created Newsletter issues and their status


There was a patch for this for 6.x but it has not been updated for D7.  If you want this feature now, you'll have to build it yourself.