Using hook_node_submit() from a custom module

hook_node_submit() will only be invoked for the module implementing the associated content type. If module A defines the content type, module B cannot implement hook_node_submit() on module A's behalf, unless it specifically calls the function module_B_node_submit().

If you want to hook into the validation process of a node form you can use the standard hook_form_alter(), e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['#validate'][] = 'MYMODULE_node_form_validate';
  }
}

function MYMODULE_node_form_validate($form, &$form_state) {
  // Logic here...
}


Using paragraphs tag instead of div in fields?

The extra junk is added by the field.tpl.php file from core.
But hey you can customize it.

Create a new file in your theme's templates folder. (For available variables, see here)

File name: field--body.tpl.php  (See http://drupal.org/node/1089656 for template file suggestions)
Contents:

Now, when you use render() in your node.tpl.php files, you will see the p tag wrapped content instead of the extra junk.

Update: I have forgotten that the $item comes from $items array. Updated the code above. If the body field has multiple instances, each one will be shown in individual p tags.


How can I return the selected radio button text on a form

If the value you want is not in $form_state you can check in the $form parameter for the original form definition.

e.g:

$chosen = $form['name_options']['#options'][$form_state['values']['name_options']];


How do I hide one block and show another in a template

Each block can have various visibility settings. Among others, you can configure that a block should only show up on a number of pages or everywhere except on a number of pages.

So go to the blocks administration page, click on the configure link for that block then make sure "All pages except those listed" is selected and insert the path for which you want to hide it. You can also use wildcards for something like "forum/*", which would hide the block when viewing a forum page.


How do I create a view that displays the author information of the current node being viewed?

Create a view with selecting a type as user.
Add "User:Content authored" relationship.
IN Contextual filters add nid and select the option of "provide
default value" and select content Id from URL.

.

That's it :)


How to let a user switch between blocks that need to be shown?

For Drupal 8, there is the Block Tabs module:

  This module provides basic tabs function for Drupal. Deep integration with Drupal8's API, Plugin, Block, Entity and Config API. Provide simple tabs functions, you can control the CSS by your self. Based on jquery.ui.tabs...Tab type using Plugin system, it is very easy to extend.

For Drupal 7:

The Quicktabs module might work for you.

  The Quicktabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content.

You would create a Quicktabs instance (Admin > Structure > Quicktabs) with the blocks you want to display. You can select a default block, and load the blocks with or without AJAX. With certain render options, you can choose to maintain a history of the user's selection.

The Quicktabs Styles sub-module provides various tab styles (enable the Quicktabs Styles module to use them and visit Admin > Structure > Quicktabs > Styles to preview them). Or you can style the tabs with your own CSS. Examples of some of the included styles:

Once your Quicktabs instance is created, you would add the block to the sidebar region (Admin > Structure > Blocks). Example:

If you need the selection element to be a dropdown menu instead of tabs, you might be able to use a custom renderer plugin. From the Quicktabs README.txt:

  Another way to extend Quicktabs is to add a renderer plugin. Quicktabs comes with 3 renderer plugins: jQuery UI Tabs, jQuery UI Accordion, and classic Quicktabs. A renderer plugin is a class that extends the QuickRenderer class and implements the render() method, returning a render array that can be passed to renderer service (\Drupal::service('renderer')). See any of the existing renderer plugins for examples. Also see Quicktabs' implementation of hook_quicktabs_renderers().


How do I programmatically render a form, other than the default form?

A contact form?

your_form_id is the form, you don't have to load a setting for that. If you know what contact form you want to display, just replace $default_form with your form_id and it should work.


Link to small .php script on drupal page gives 404

Make sure that your file player.php is in the right location; it should be in your Drupal root -- the same folder that has index.php.  In my test, a php file at the document root was executed correctly if it was readable by the webserver -- it would run even without execute permissions.  chmod 0 player.php gave me an internal server error, not a 404.  You should check your permissions, but this seems to not be the issue.

Is this site using your own web server configuration file, or is it on a shared or managed ISP?  Check to see if there are any rewrite rules that might be getting in the way.

The workarounds from my previous answer, below, should be unnecessary, but I will leave them here in case they may be of interest or help.

A. Put your file in a different location in the file system, and point at it with an alias.

    alias /player /srv/www/player
    <Directory /srv/www/player>
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

Put that in your Apache Virtual hosts file. If you cannot edit this file (e.g. on a shared hosting account), then this will not be an option.  If you set up your vhost conf file like this, restart Apache and put your code at /srv/www/player/player.php. Access it from www.mywebsite.com/player/player.php.

B. Instead of using a standard php file, write a Drupal menu.

function mymodule_menu() {
  $items = array();
  $items['player'] = array(
    'title' => t('Player'),
    'access callback' => TRUE,
    'page callback' => '_mymodule_player',
  );
  return $items;
}

Accessing the URL www.mywebsite.com/player will then run the code in the function _mymodule_player.

See: http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7


Drupal 8.3.1 CSS and JS aggregated by default

If you want to disable aggregation, you need to set these variables to 'FALSE' instead of 'TRUE'.

If you are interested in disabling cache for development purposes, you can find more information in the following response: https://drupal.stackexchange.com/a/183397/27068


How to configure wysiwyg_tools_plus module?

There's two ways of running CKEditor in Drupal, as a straight module install, and as a component of the WYSIWYG Tools module. It's the latter that you need.

So, install the normal WYSIWYG Tools module and then follow the instructions to install an editor (CKEditor) within. I've found only < v4 seems to work for this unfortunately, but there is an update to v3 from 2013 which seems to work ok.

Once you've got that working you will get a WYSIWYG editor that has no buttons, it's not broken, it just doesn't tell you that you have to configure it for each view (full HTML / filtered HTML etc) and select the buttons you want to appear.

When choosing the buttons, near the bottom there's a few for accordion & tabs, so just make sure these are selected for the content types you want to use.

It's not exactly intuitive, but it's actually fairly easy when you know how!

Hope that helps.


Drush installed in local directory but command not found?

You are calling a global command. Which is not installed or symlinked into one of your Mac's autoloaded bin directories (or is not added to your global $PATH).

Simplest option you have now is to use the local command:

$ cd mydrupal
$ vendor/drush/drush/drush status

Alternatively you may want to install Drush Launcher on your Mac (to be used together with the Composer template for Drupal projects). Which when you are inside a project that has a local Drush installed automatically associates the global drush command to the project's local Drush.


Selection of Nodes Based on Taxonomy Terms Percentages

With so many different possibilities that might fit your project and its needs, I'll try to address the forks in the road with how you could do this in drupal.

You most likely wont find any appropriate functionality for this task built into drupal or a contrib module but it is simple enough to implement yourself.

Option 1 Keep it in the database, but still in drupal.

Build queries using the Database API (most likely the static method as it'll be quicker to get going, instead of the dynamic method), depending on your creativity you can loop through each taxonomy term and execute a number of possible queries to get count() results based on timeframes as well as other criteria. You could also have a specific set of queries that you run on the taxonomy terms as a whole to get a view of the whole database table, instead of looping through each term. Whichever appeals to you, this list of common mysql queries has aggregates, statistics, comparison, frequencies and just about every other basic math centric query to get you started.

Option 2 Maintain your numbers in close to realtime in a node, variable or database table

This option is really if you'd prefer to do most of your work not just on the PHP side of things but in just PHP. The example above puts the burden on your SQL server but all of your logic still actually resides in the PHP (instead of stored procedures).

This would be my second choice of the two. Instead of running a lot of heavy queries on a regular interval, simply write some code to keep track of the total numbers of each taxonomy term as they are added or removed (you can use  a hook from the node API such as hook_node_presave() - any number of hooks to quickly sniff what taxonomy terms are being applied if you don't know where to do your addition and subtraction of the taxonomy terms as they are added or removed).

If you really want to hand this to drupal from your stored procedures...

Get ready to do a little battling with drupal depending on how light or heavy your code is. Queue API and batch API can help you with large background processes, otherwise you'll want to ensure things stay trim and quick if that means incremental updates to your taxonomy statistics or putting time constraints on your processes.

Good Luck!


You can set grouping after any field in the view at the format settings. This should work for this.


Setting php E_NOTICE within my .module file

I've never tried this, but if you don't mind modifying core on your dev server you can change drupal_error_handler(): examine the results of debug_backtrace(), decide if the error came via your module and act appropriately.


PDOException: SQLSTATE[HY000] [2003] Can't connect to MySQL server

For anyone having the SAME error code, please check if you have SELinux enable by typing sestatus. If that's the case then your firewall is most likely blocking the connection to the db.

To allow it you can use the following command line :

setsebool httpd_can_network_connect_db=1


excluding non english field values from search_api index (or facet)

I will venture a guess that when choosing indexed fields for the Product CT, you selected 'Factories' field and created the facet against this. Since you are using node translation, it is quite sensible that all available nodes (in various languages) are displayed in the facet. I suggest you try the following:

Remove/disable field 'Factories' from the list of indexed fields and remove the respective facet
At the bottom of the fields configuration for the index, you will find an option labeled 'Add related fields'. Choose field 'Factories'. With this action, all fields of the referenced Factory CT will become available for indexing
Enable the field that is correlated with the translation source node. Label should be something like this 'Factories >> Translation source node'. Create a new facet against this field
Clear indexed data and re-index

Most probably, the new facet will only display the facet terms in the default translation language (English in your case)


More options for page--node--edit.html.twig for content type

What you are looking for is called theme suggestions you can implement your own or alter existing ones. In this case since the theme hook is provided by another module (core) you need to alter the provided suggestions and add your own.

Check this post with useful examples. Also core's always have excelent examples (Bartik theme example).

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 */
function bartik_theme_suggestions_form_alter(array &$suggestions, array $variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $suggestions[] = 'form__search_block_form';
  }
}


You need to alter the Theme registry and set the path of the hook suggestion "form" to your_module/template path as bellow:

/**
 * Implements hook_theme_registry_alter().
 */
function My_Module_theme_registry_alter(&$theme_registry) {
  // You can add some conditions here in case you want
  // to override the form template only for some reasons.
  $theme_registry['form']['path'] = drupal_get_path('module', 'My_Module') . '/templates';
}

And the structure of your module should be:

-- My_Module
  +-- templates
     +-- form--pom-mapping-setting-form.html.twig


Drupal - Run update.php after updating several modules?

You can copy all the files at once and run update.php just once.


Cannot format date for date field in a Views_Database_Connector view

Took me a while but I figured out what I needed to do - create a custom module with a plugin to override the Date.php plugin (which actually overrides the FieldPluginBase.php).  Using the LastTimestamp.php plugin (which overrides the Date.php) from drupal's core comment module as a reference, I was able to piece together what I needed to do.

First step is when reading in the data from the tables (via the Views_Database_Connector module), I gave the drupal date field a different id rather than the default 'date' (eg "date_to_display").  This is the id used to trigger the call to the custom plugin rather than the Date.php plugin.  While the VDC was the first step, actually giving the date field a different id was the final piece of the puzzle to make this work.

Next step was to create the custom module and then create the plugin to override Date.php and use the id in the annotation (this is important):  @ViewsField("date_to_display").  You can read about this in Drupal's doc Annotations-Based Plugins in Views.  In the custom plugin, override the render function.  In my particular case, I simply just checked to see if the date field value was numeric (which seems to be required for this to not throw an exception), and if not, convert it to timestamp (new value = strtotime(value)).  For me that did the trick. The top part of the created plugin looks like this:

<?php

namespace Drupal\my_module\Plugin\views\field;

use Drupal\views\Plugin\views\field\Date;
use Drupal\views\ResultRow;

/**
 * A handler to provide proper displays for dates.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("date_to_display")
 */
    class ViewsDateField extends Date {

  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {


Drupal core tries to update to current version

I found the solution, with the following command line.

drush pm-update drupal-7.25

I still do not understand why the regular update fails but this last command works fine.


Instead of seeing the footer as a single entity you can consider it as different blocks of which the links would be a part.

So you would have a region defined as footer and add blocks to that region. One block would be the menu and could have another for the static text and may be another one for the images. and arrange the same in the order you want.

In this way the links would be managed through the menu and the rest of the things through the respective blocks.

If you are sure that the content is going to be static through out the site then it would be better to put the same in the page.tpl file.


How to update old CAPTCHA to use reCAPTCHA V2

Just update module via update modules page:
Your_site/admin/reports/updates/update

Follow steps and update DB.

Go to modules page and check configuration for recaptcha, there you'll put your new keys (got from https://www.google.com/recaptcha)

Note: If you update module files using FTP, remember to run update.php script.


How to do a URL redirect to the latest content?

There seems to be a module for that.
Smart Node Links


Drupal 7: Help me to wrap my head around EVA/reverse node reference

OK, i did it. Here's how:

Node types:
I've set up 2 node types "article" and "theme week".
"theme week" has a node reference field where nodes of the type "article" can be choosen.

View:
 - I've set up one "EVA" view (requires EVA) Under "advanced", I've
   selected the relationship to my "article" node type.
 - I did NOT set "require relationship".
 - Unter "contextual filter" I've set "Content: Nid", "Provide default value -> Content ID from URL".
 - I've set all my fields and filter criteria to use that relationship

Display Suite/EVA: - I've attached my View as a field in my "theme week" node type (requires Display Suite/DS).

Now when a "theme week" node is viewed, it shows the "article" nodes which have been referenced by "theme week".

I hope this might be useful to someone!


Change label max length on all field types

You can create a module and include the hook_form_alter for the content types you want. This is an example of how to do that:

function [MODULE_NAME]_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'your_form_id'){
    $form['your_field_name']['label']['#maxlength'] = 255;
  }
}

Also you can try this module: http://drupal.org/project/remove_field_label_length_limit


Empty view is rendered even though there is no result

You should add a filter criteria for any one of the fields. For example if you have a field called company then you could add a filter criteria for this field and then choose "Is Not Empty (NOT NULL)" from the Drop down. This would make sure that the view is rendered only if the required field is present.

In normal case  when you are passing a Contextual filter the view is rendered even though the result is null. but if we provide a filter as I mentioned above it does not display at all.


How to create a contextual filter to be used as the first character for a field?

You can create a contextual filter for the node title and configure it in "glossary mode". Provide a fixed value "a" and check the glossary mode settings at the bottom of the settings page.


How to send an email after a specific node field gets updated by an admin?

Check notification email link
my point is enough to post in comment box so i am posted here


No welcome email sent when users register via profile2 registration path

This appears to be an issue with the profile2 module. I've created a patch for another issue and this, in turn, has fixed the no emails sent issue I was experiencing.

For a patch and proposed solution please see: https://www.drupal.org/project/profile2/issues/1993770#comment-12699962


How can you render fields from an entity reference in node templates? [Drupal 8]

#node there is actually the current node.

If you want to access fields and their values, start off with node, not content, which is a render array with the configured fields.

You can access the reference entity like this {{ node.field_blog_author.entity }}.

From there, you can continue again to the field of the referenced entity that you want to display. You could try calling the view method, with will view it with the default settings, you can also pass a view mode as a string to it or an array display settings (not sure about the exact syntax for that in twig).

Also, my standard reference, see http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for a great overview of content entities, how they're structured and how to access values. Most of that also applies to twig.

And last, when trying to figure out what's in a content entity, use node.toArray(), that gives you an array representation that's very close to how you can access it as an object. While the internal structure is quite different.


Two ways are avaliable:

Recreate from nightly or hourly backup. This is preferred way to solve issues like yours.
Disable module, uninstall it, and then enable it again. Will be as good as new. To keep configuration:

Export configuration search index to Features.
Disable modules search_api, search_api_db,...
Enable modules again => tables will be recreate.


User register forms are built by the User module, but the timezone widget is added by the Locale module through locale_form_alter() (an implementation of hook_form_alter()).

The Drupal community suggests leaving the core files alone (see Do not hack core). If you want to change the form, just write your own implementation of hook_form_alter(), and add/edit the available values using the form API and the "select" form field.

There is a nice tutorial at Brenda Boggs blog.


How to assign alt text to current inline images

You can use my module Image auto ALT Filter in this case
https://www.drupal.org/project/image_auto_alt_filter
Only enable this filter for your text format, and all images will be with ALT tags. ALT generates from text keywords (I'm going to add some features in next release)


How do I create custom regions in a theme?

You define regions in your theme .info file. See: Structure of the .info file

You then need to put the relevant template tags in your page.tpl.php file.

So for example if you defined the region sidebar in your themes .info file, you would then add: <?php print render($page['sidebar']); ?> to the relevant place in your page.tpl.php.


I'm assuming you are using some content type for the content needed on your module.  If so, then you can use Views with a module like Views Data Export.


The Date module has a submodule called Date Views that allows Views integration with Date fields.

Once enabled, you should be able to add an Exposed, Grouped filter on your date field. For each grouped filter, you can add your Label (e.g. "Past 7 days"), Operator (is between), & Value which you can set to Relative dates that match your label (e.g. From: "-7 day" / To: "now").


Yes, there is actually a few modules that will allow you to get tabs in your content easily. The one I use is Quicktabs, listed below along with some alternative modules.

Quicktabs (module) - https://drupal.org/project/quicktabs
Field Group (module) - https://drupal.org/project/field_group (has tabs support)
jQuery Tabs Field (module) - https://drupal.org/project/field_jquery_tabs


Is there a module that lists which tables are created, owned or modified by a particular module?

Since Drupal 7, tables should get created by modules using hook_schema(), because these tables will also get removed when uninstalling the module.

You can find these tables by executing the code below, or by using the Schema module (https://drupal.org/project/schema):

$schema = drupal_get_schema(Null,TRUE);// Get List Of all tables.
  ksort($schema);// Sort Ascending
  foreach($schema as $table => $value){
    print_r($table."<br>");
  }

All well written modules should create tables only using hook_schema, and should not alter tables in other modules.

If you suspect that other tables got changed, you can find this in the .install file for each module. Look for the database layer calls like db_add_field or even db_create_table.

For a list of all these, consult the Drupal documentation:
https://api.drupal.org/api/drupal/includes!database!database.inc/


If you look at drupal_prepare_form() it says

  since tokens are session-bound and forms displayed to anonymous users are very likely cached, we cannot assign a token for them.

If you do want to go ahead with this, the following works when quickly tested with the default search and comment forms.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (!isset($form['#token'])) {
    $form['#token'] = $form_id;
    $form['form_token'] = array(
      '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
      '#type' => 'token',
      '#default_value' => drupal_get_token($form['#token']),
    );
  }
}

Be careful about page caching however (and a reverse proxy if you use one) if you do go down this road.


You don't have a piece of content at that URL mysite/speech/3, only a block. Don't use a block in this situation, just use a regular page.
Blocks are fine if you can cache them. Does the data change often? If not, set a very long cache and there should very little performance impact.


Manually update core from 7.0 to 7.78 in one fell swoop

The latest update contains all of the updates before so going straight to the latest one should be okay and is what is usually recommended. Be sure to backup your site and test the backup on a dev copy.
You should update your contributed modules at the same time as some of them may rely on updated versions of Drupal (core).
Lastly and very importantly, there have been numerous security releases since the 1st release and some of them are quite bad so I would say you should probably assume your site is compromised. That's 78(!) releases you've missed out on, including the infamous Drupalgeddon.


How to set the public file path to migrate site files and images through Migrate Drupal UI

So it turns out though I had difficulty understanding them, the directions are "correct". The difficulty I had is partly because of my inexperience, but it's also partly because of a slightly confusing UX in Migrate Drupal UI. The label is asking for your "Public files directory", but what it really wants is your absolute docroot path. The directions state this: "To import from you current Drupal Site,enter a local file directory containing your site (e.g /var/www/docroot), or your site address (for example http://example.com)"

This means when the source files UI is asking for the "public files directory", the sites/default/files portion is already assumed by Drupal Migrate and is not needed, nor is it welcome. I used
 C:\Users\user\Documents\mywebsite and it worked the first try, where repeated attempts that included \sites\default\files path failed.

Also, the unique settings in settings.php from Acquia dev desktop for the public file path for the new Drupal 8 site were not a factor.  I left those settings as they were by default when I executed the migration.


How to send values to an external database with a custom module?

I'm a little fuzzy on the details of what you already have but the code below should help you get you in the right direction (I think). It will check for changes to the fields, make sure the node exists in the external database and then update the external database table.

Just remember to change the db_set_active statements to the name of your database and change the table names.

As a side note, as you said you are more of a site developer, if you install the Devel module you can use dpm() to print variables, arrays,  messages etc. to the Drupal message space. E.g. if you wanted to see what was in $new, after the foreach() where we add the updated fields to $new, adding a new line with just dpm($new) will display the array in a structured and pretty way.

Its an invaluable tool for module development!

/**
 * Implements hook_node_update().
 */
function external_update_node_update($node) {
  // Get a list of fields for the content type.
  $fields = field_info_instances("node", $node->type);

  // Set variables as arrays.
  $old = array();
  $new = array();

  // Get the values of the fields for both the original and updated states
  // and add them to the arrays.
  foreach ($fields as $key => $values) {
    $temp_field = field_get_items('node', $node->original, $key);
    if (isset($temp_field[0])) {
      $old[$key] = $temp_field[0]['value'];
    }
    else {
      $old[$key] = NULL;
    }
  }
  foreach ($fields as $key => $values) {
    $temp_field = field_get_items('node', $node, $key);
    // If the field is not empty...
    if (isset($temp_field[0])) {
      $new[$key] = $temp_field[0]['value'];
    }
    // Else add an empty value.
    else {
      $new[$key] = NULL;
    }
  }

  // Check if there are any differences between the new and original states.
  $diff = array_diff($new, $old);

  // If there are differences then an update can occur.
  if (!empty($diff)) {
    // Start the database transaction in case something goes wrong.
    $transaction = db_transaction();

    // Add a try/catch to be able to roll back the database if it errors out.
    try {
      /** Check all node fields exists in external database. **/

      // Get database fields.
      $sql = "SHOW COLUMNS FROM update_save";
      // Switch to external database.
      db_set_active('external');
      $query = db_query($sql);
      // Switch back to drupal db.
      db_set_active();

      // Add list of database fields to array for use later.
      $db_fields = array();
      foreach ($query as $row) {
        $db_fields[$row->Field] = $row->Field;
      }

      // Check if the node contains new fields that are not in the database.
      $field_diff = array_diff_key($fields, $db_fields);
      // If extra fields exits set a log message
      // and remove these fields from the update.
      if (!empty($field_diff)) {
        foreach ($field_diff as $missing_field) {
          watchdog('node_update', "The field $missing_field is missing from the external database.", WATCHDOG_ALERT);
          unset($new[$missing_field]);
        }
      }
    }
    // If something went wrong and it threw an error,
    // catch the exception, roll back any database changes and log the error.
    catch (Exception $e) {
      $transaction->rollback();
      watchdog('node_update', "
$e
");
    }

    try {
      // Check if node already exists in the external database.
      $sql = "SELECT nid FROM update_save WHERE nid = :nid";
      // Switch to external database.
      db_set_active('external');
      $query = db_query($sql, array(":nid" => $node->nid));
      db_set_active();
      $nid = "";
      foreach ($query as $row) {
        // If there are any results add it to the $nid variable.
        $nid = $row;
      }

      // If the query came back with results and therefore $nid is not empty,
      // then the update can continue.
      if (!empty($nid)) {
        // Switch to external database.
        db_set_active('external');
        db_update('update_save')
          ->fields($new)
          ->condition('nid', $node->nid)
          ->execute();
        db_set_active();
      }
      // Else add a watchdog log.
      else {
        watchdog('node_update', "The node currently doesn't exist in the external database.", WATCHDOG_ALERT);
      }
    }
    // If something went wrong and it threw an error,
    // catch the exception, roll back any database changes and log the error.
    catch (Exception $e) {
      $transaction->rollback();
      watchdog('node_update', "
$e
");
    }
  }
}


Is there any way to restore deleted core block in Drupal 8?

If you delete some code block in /admin/structure/block

You just need to go on Place block and add block again.

Also Page Title block you can delete and return like this.

In drupal 8 every think is block, menu even a page title.


7 - HTTP error 400 when calling system_retrieve_file()?

In my case, I needed to encode urls, but not how you may expect with PHP's urlencode or rawurlencode.
For example, I needed to convert http://DOMAIN.COM/C8B195/assets/images/01 Grapes 3.jpg to http://DOMAIN.COM/C8B195/assets/images/01%20Grapes%203.jpg. I'm not sure why system_retrieve_file or drupal_http_request had a problem with the spaces.

  $encodedPath = rawurlencode($path);
  $encodedPath = str_replace('%3A', ':', str_replace('%2F', '/', $encodedPath));


Token Value to insert URL of page into field

you can use form alter .get the values from url put the values using form alter to default fields .


Maybe think about alternatives? We use BOTCHA module everywhere these days to combat spam submissions. Works much better than any captcha and is far less intrusive for real people. Just a thought.


How to make fields of a cloned node available in Rules

The problem was that I had to fetch the entity by property [cloned-node:author:field-firstname] inside the conditional and set the data value [cloned-node:field-student-name:0] to [firstname-fetched:0:field-firstname]
I still don't understand the actual logic why [firstname-fetched:] has to be followed by [0:field-firstname] but that works. See screenshots.
Hope this helps someone else out too.

After @Pierre.Vriens helped out my component code is now:

    { "rules_update_the_cloned_course_with_values_for_the_student" : {
    "LABEL" : "Update the cloned Course with values for the Student",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "cloned node", "component", "course", "update" ],
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "USES VARIABLES" : {
      "node_to_update" : { "label" : "Node to be updated", "type" : "node" },
      "node_author" : { "label" : "Node author", "type" : "user" }
    },
    "ACTION SET" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_is_of_bundle" : {
                "entity" : [ "node-to-update" ],
                "type" : "node",
                "bundle" : { "value" : { "course" : "course" } }
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "node-to-update:field-student-name:0" ],
                  "value" : [ "node-author:field-firstname" ]
                }
              },
              { "drupal_message" : { "message" : "Machine name of this Component was: \u0022rules_update_the_cloned_course_with_values_for_the_student\u0022" } },
              { "data_set" : { "data" : [ "node-to-update:field-status" ], "value" : "359" } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : {
                  "message" : "The field \u0022Student name\u0022 could not be set with the value of the Student\u0027s first name.\u003Cbr \/\u003E\r\nMachine name of this Component was: \u0022rules_update_the_cloned_course_with_values_for_the_student\u0022",
                  "type" : "warning"
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


Code to add node add form to a custom block (not working)

For people still having trouble with the above code when using anything AJAX-related (e.g. 500 errors) or simply trying to open up the 'blocks' tab in Panels without some error (e.g. some Entity Translation functions) you might want to try the following module code instead in Drupal 7 (but some parameters may still need to be added for your purposes).

function custom_example_block_info() {

    $blocks['example_node_form'] = array(
       'info' => t('What an example'),
    );
    return $blocks;

}

function custom_example_block_view($delta = ''){

    $block = array();

    switch ($delta) {
        case 'example_node_form':
            global $user;
                        //Note: 'type' is your node content type and 'language' must be included
            $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => 'example', 'language' => LANGUAGE_NONE);

            $form_state['build_info']['args'] = array($node);

            form_load_include($form_state, 'inc', 'node', 'node.pages');
            $block['content'] = drupal_build_form('example_node_form', $form_state);

            break;
    }
return $block;

}

The important difference is that drupal_get_form cannot load the $form_state so we use function form_load_include(&$form_state, $type, $module, $name = NULL) to ensure the include file is loaded whenever the form is processed and function drupal_build_form($form_id, &$form_state) instead of drupal_get_form to pass $form_state. The lines above create the $form_state.


Testing an update hook that updates fields?

Yes, very quickly. You already have part of the code. Since you have already loaded the node via the entity_metadata_wrapper() you have all of the information at your finger tips.

An example is this in your hook_update_N()

foreach ($node_ids as $node_id) {
    try {
      $node_wrapper = entity_metadata_wrapper('node', $node_id);
      $node_wrapper->field_new_field->set($node_wrapper->field_old_field[0]->value());
      $node_wrapper->save();
      if ($node_wrapper->field_new_field->value() == $node_wrapper->field_old_field->value()){
        print_r('Success. Old field data is in new field data');
      }
    }
    catch (Exception $e) {
      watchdog('mymodule', 'Problem with node @node_id', array('@node_id' => $node_id), WATCHDOG_ERROR);
    }
    $sandbox['progress']++;
  }

I added a comparison of the old field data and the new field data. If it is the same, it will print 'Success. Old field data is in new field data' in the console of Travis-CI. You can do this for any entity. You can use print_r() to output data that you can see in Travis-CI's console. I do this for troubleshooting my test scripts when I may be using a new test method I have never used before and I want to see what Drupal is giving me. Most of the modules I maintain on D.O are tested with Travis-CI.


Like any other extender, the TableSort class implements the SelectQueryInterface interface.

Your code doesn't work because tablesort_get_query_parameters() is a Drupal function, not a method defined from SelectQueryInterface. To change the behavior of an extender, you need to re-define one of the methods listed in the documentation for SelectQueryInterface.

References

Extenders


My final solution, by guidance @CG Monroe:

$query = $this->connection->select('node_field_data', 'n');
$query->innerJoin('node__field_date_created', 'fdc', 'fdc.entity_id = n.nid');
$query->addExpression('count(n.nid)', 'nid_count');
$query->addExpression('substring(fdc.field_date_created_value, 1, 4)', 'yr');
$query->condition('n.type', 'my_type');
$query->condition('n.status', 1);
$query->groupBy('yr')->orderBy('yr', 'ASC');
$result = $query->execute()->fetchAll();


Redirect after comment submit according to value of query string in comment form URL?

After More deep debugging I found that action of comment from is set to

  comment/reply/nodeid

So with below URL's:

  http://www.example.com/comment/reply/208943?destination=newsroom#comment-form

  http://www.example.com/comment/reply/208943?destination=sections#comment-form

My query string variable destination  is lost or either at form submit it shows null because from moves to action URL where no query string was set.

To solve this I have added query string in action URL which works very well :

function my_module_form_alter(&$form, $form_state, $form_id) {
   if ($form_id == "comment_node_link_form") {
      $form['#action'] = $form['#action'] . '?destination=' . $_GET['destination'];
  }
}

ie: All I have to do is add required query string to $form['#action']

Hope this will help any one who is trying similar solution.


Views Content: Title as an autocomplete exposed filter?

You can use the Views autocomplete filter

It will work for node titles and other exposed text fields


Why some features are overriden after installation

Normally Features automatically detects ctools exportables and add the modules containing those exportables to the dependency list, unless a module requirement for an exportable was not detected, or dependent modules were installed since feature was enabled.

Based on your menu link machine name (menu-editor-...), it seems it relies on Menu Editor module and you've missing dependency to that module, therefore Features module didn't detect that component as a requirement, so it become overridden and unrevertable.

The solution is to add the missing module into dependencies list. Then either disable the feature module and reenable it, or manually enable any dependencies not enabled (see Feature Diff to expose them).

See: Troubleshooting: Reasons Features may be stuck as Overridden at Drupal.org


Adding users to entity reference field by custom field

You can use any field to lookup a user in a entity reference field. You just need 2 things: an entity reference View & a configured entity reference field.

Through the Views UI, you can add a User view with an Entity Reference Display. Add any fields to the View that you'll want to search on. Once your do, the Settings link next to Format:Entity Reference list will popup a modal that will let select your Search Fields.
After you've created your view, add your node's entity reference field. Set the Reference method to Views: Filter by an entity reference view. Where View used to select the entities is set to the view you created in step #1. Once the new field config is saved, you'll be able to search for any users based of the text values in the fields selected in Search Fields.


D8 Widget Column is missing on manage field page

I'm sorry for a stupid question. I figured it out. It was under "Manage form display" screen. What got me confused was while googling for answer, I stumbled upon a few screenshots from an early D8 build which still had Widget Type column on Manage Fields screen and it lead me into thinking that something was wrong with my installation.


What method are you using to Push? Configuring the rule, you can select it at the bottom of the edit page:

I just tried it with Analytics.js support and the checkout page appears to display the Analytics code:

<!--//--><![CDATA[//><!--
var ga = ga || [];
ga('require', 'ecommerce', 'ecommerce.js');
ga('ecommerce:addTransaction', {"id":"5","affiliation":"Commerce Kickstart","revenue":16,"currency":"USD","tax":0,"shipping":8,"city":"Austin","region":"Texas","country":"United States"});
ga('ecommerce:addItem', {"id":"5","sku":"MG2-YLW-OS","name":"Coffee Mug 2","category":"Product: drinks","price":8,"currency":"USD","quantity":1});
ga('ecommerce:addItem', {"id":"5","sku":"shipping","name":"Standard shipping: 3 - 5 business days","category":"Shipping","price":8,"currency":"USD","quantity":1});
ga('ecommerce:send');

//--><!]]>

This appears to be correct. One of the difficulties with testing GA for Commerce is that they do not show up in realtime.

So, I'd try it with Analytics.js if you aren't currently using that method and ensure that something like what you see above is being included on the page. If it isn't, then something isn't working on the site side. If it displayed, then check your JS console for errors to see if something else happened. You can also open up the Network tab and ensure that you're seeing the calls to "collect":


Sending message body to email with PrivateMsg module

If you navigate to admin/config/messaging/privatemsg, you will find the template of mail which  get send by system when somebody private message to message some user.

You can modify the template. If you navigate to tokens below, you will find several tokens, one is - [privatemsg_message:original:body]. You can insert it in above template to send it in mail according to your need.

I think you need Token module for all this & I hope you must have this installed in your instance.


Can't clean URL from custom query parameters

I think you can use Redirection Rules in your .htaccess file to achieve this task.

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_URI} ^(/branch)$
  RewriteCond %{QUERY_STRING} branchID=(.*)
  RewriteRule (.*) /branch/%1?  [R=301,L]
</IfModule>

Hope, this helps you.


Transition plan for PHP5 abomination to Drupal

We have done a few sites where we have connected outside systems to Drupal where the data had to be kept in the outside system.  This is what I spend most of my time working with.

When we do this, we typically create a content type to "stub out" the content in the other system.  The content type only contains the node title and a CCK field for the unique identifier in the other system.  Along with this are a lot of hook_nodeapi functions.  For example, the load hook will call out to the remote system and add the data to the node.  You also need to devise a method for getting the outside data into search results.  There are a few methods for this, but those are too lengthy to get into here.

While there are some downsides, we find this works well and allows normal Drupal stuff like comments, tags, etc.


can i add multiple value in field ? (please see an image)

For simmilar needs, i am using this module, for me it is very good! There are some other alternatives too, but for me this module is proven as stable:

http://drupal.org/project/double_field


These functions actually have not much in common. There is no question of using one or the other. You will in fact use both of them, although you will most likely not call drupal_get_path_alias() directly.

entity_uri() returns an array that contains the path and options to link to an entity. So for example for a node, you call it like this: entity_uri('node', $node) and it will return node/$node->nid. That's kinda trivial. It gets more interesting with other entity types, like private messages (where the path is messages/view/$message->thread_id#privatemsg-mid-$message->mid).

You use the returned array like this: url($uri['path'], $uri['options']) (or similarly with l()). Then, that function will call drupal_get_path_alias() internally to check if there is an alias for that internal path and will use that.

The idea is that you can generate the internal path for any entity, without any kind of special handling. A real life example is the Userpoints project. Userpoints transactions support to reference an entity by specifying type and id (Yes, Userpoints used the entity_type terminology since Drupal 5...). Previously, there was a large bunch of code with support for nodes, comments and users and a custom hook to be able to support more things. When I ported the module to Drupal 7, I was able to replace all that with a simple call to entity_uri() and it now supports all entities out of the box: userpoints_create_description().


Migration: the "csvrownum" should start from the second row

I think that's the expected behavior, you could use the prepareRow() method to increment csvrownum in whatever your header_rows is.


I'm pretty sure your question is about a "multilingual" site, and not really about "multi sites". Consider editing your question (title, tags, etc) accordingly.

Moreover, your question is a variation of these types of questions, and that your issue is actually caused by a language detection issue (something you have not yet configured correctly in your site. Consider updating your question as appropriate. After doing so, I can also update my answer here, to actually pinpoint what kind of admin changes you might have to apply to achieve the desired result.

Based on the info provided in your question for now, I wonder what the DEFAULT language is that you specified within /admin/config/regional/language of your site. Could it be that it is "es"? If so, and if you also have enabled the "en" language, then change that default to "en" and retry again. Eventually, change the default language back afterwards, to whatever it was before (whenever your Pinterest script no longer requires you to (temporary) change that default language).

You may also want to check your configuration at Configuration -> Languages -> detection and selection: the order should be 'URL, Default, User', and not something like 'Default, URL, User'.


Is there a hook to alter webform confirmation message?

Like the @zhilevan told you can use hook_form_alter for placeholder and for str_replace you can implement hook_template_preprocess.

Here is an example.

function my_module_preprocess_webform_confirmation(&$vars) {

    $confirmation = check_markup($vars['node']->webform['confirmation'], $vars['node']->webform['confirmation_format'], '', TRUE);
    module_load_include('inc', 'webform', 'includes/webform.submissions');
    $submission = webform_get_submission($vars['node']->nid, $vars['sid']);
    $confirmation = _webform_filter_values($confirmation, $vars['node'], $submission, NULL, FALSE, TRUE);

   // Strip out empty tags added by WYSIWYG editors if needed.
   $vars['confirmation_message'] = strlen(trim(strip_tags($confirmation))) ? $confirmation : '';

}

Source Webform Token support on confirmation message.

you can also take a look on tpl file option.
Here webform-confirmation.tpl.php


What do Contextual Filters filter against?

Generally speaking, a view is used to show data for a list of entities. View filters are used to select (or filter) which entities are handled by the view; contextual filters are used to select the entities basing on the values passed in the URL.
For example, the Files view that comes with Drupal 8 has two pages: one whose path is /admin/content/files and one whose path is /admin/content/files/usage/%.

The second page shows data (the entity label and the entity type for the entity containing a reference to the file; the module managing the file relationship; the number of times the file is used by the entity) for the file whose ID is passed in the view path.

When I visit /admin/content/files/usage/3 on the test site I created, the view shows the following data.

On /admin/content/files/usage/2, the view shows the following data.

Using as another example a default view that is already enabled on /admin/structure/views, the Taxonomy term view has a page shown on /taxonomy/term/% which uses the Content: Has taxonomy term ID contextual filter.

It shows all the nodes using the taxonomy term whose ID is passed in the URL. In the test site I am using, /taxonomy/term/1 shows all the nodes using the taxonomy term whose ID is 1 (the test taxonomy term), while /taxonomy/term/2 shows all the nodes using the taxonomy term whose ID is 2 (the view taxonomy term).

Contextual filters are still filters, as they select (or filter) the entities from which the data is taken. The difference is that their values are passed from the view URL, not from a form like the filters set in the Filter criteria section.
The number of entities from which the data is taken and what entities are handled by the contextual filter is hard-coded in the class implementing the contextual filter: Content: Has taxonomy term ID selects all the nodes using the taxonomy term whose ID is equal to the value passed in the URL, which could be zero or more than one node, while Content: ID selects only the node whose ID is passed in the URL; User: Created selects all the user accounts that have been created at the time passed in the URL.
The category of the contextual filter (another value set by the the class implementing the contextual filter), which is shown in the contextual filter name, helps to understand which entities a contextual filter selects: Content: Has taxonomy term ID and Content: ID select nodes, while User: Created selects users.


How to get a custom block form in another custom block?

The answer is to use the plugin.manager.block service
Example:
In the Block B BlockForm method.
public function blockForm($form, FormStateInterface $form_state) {
  $block_manager = \Drupal::service('plugin.manager.block');
  $block_a = $block_manager->createInstance('block_a');
  $form = block_a->blockForm($form, $form_state)
  return $form;
}


How to create multi-page node views in D7

Have you tried the Book module which comes with core? It will do some bits of what you need but you can build a module to further modify it.


Drop-down menu that shows the average of multiple rating criteria on Fivestar

This problem has been solved: I wrote the code to paste in the template, and added a module to sort by votes.

See Dropdown menu that shows average of multiple rating criteria.


Getting error on installing bootstrap subtheme?

I was getting the same error message and here's how I fixed it.  In your subtheme folder (docroot/themes/bootstrap_subtheme) there's a config folder with two subfolders: install and schema.  Each of these subfolders has a YML file with THEMENAME in the file name, I just changed THEMENAME to my subtheme name and then I was able to install my subtheme.


Does pager(10) in EntityFieldQuery automatically invoke the pager?

Yes; it even avoids the usual problem of multiple pagers on a single page conflicting, by getting a new delta from the PagerDefault class.

  Should it be displayed with print(theme('pager'))?

Yes (but obviously only if there is more than one page worth of results to display).

  Is this functionality included in Drupal core (7.15)?

Yes.

This works perfectly for me:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->pager(10);

$results = $query->execute();
$nodes = node_load_multiple(array_keys($results['node']));

$build = array(
  'nodes' => node_view_multiple($nodes),
  'pager' => array(
    '#theme' => 'pager',
  )
);

That's returned from a menu callback function, so will be passed through drupal_render(). When it does so, a list of node teasers is displayed with the expected pager right below.

If the same example doesn't work for you then there must be something wrong with your installation, or something in a custom/contributed module conflicting with the core pager system.


Is it possible to use a function which uses $node without the expense of node_load

In this case, I would just look at the source for taxonomy_node_get_terms_by_vocabulary:

function taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, $node->vid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

The only thing needed is $node->vid.  Note that vid in this particular referes to node revision and not vocabulary ID.  If you knew the vid, then you could just create your own function:

function mytaxonomy_node_get_terms_by_vocabulary($nodevid, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, nodevid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

The problem is that in most cases you don't know the $node->vid without doing a node_load.  Just querying using the nid may or may not be right if you use revisions or start using revisions in the futures.  The proper way to do it would be to JOIN the node table into the query so you can use $node->nid as an argument instead of $node->vid.


Create views field template override for table style

What you are trying works fine for me under drupal6, so, I'd look at your theme information again and be perfecting sure that it is looking at the right theme when you switch styles from table to unformatted and so forth.  I did that once and had my views template file sitting in one theme and couldn't figure out why views wasn't picking it up in another :)


Create a view of the pages with, for example, a list of tiles linked to the content. Then create a contextual filter using the entity reference field. In the Contextual Filter configuration for the entity reference, select 'Provide default value > Content ID from URL' under 'When the filter value is NOT available'.

Set the view to display as a block on the page, and it will display a list of the titles referencing that page.


How to handle separated stock for a product bundle?

I am the author and maintainer of the Commerce Product Kit module which is close to your requirement.

  It provides a "field formatter" for the "product reference" or an
  "entity reference" fields to add all the commerce products referenced that
  field to the cart at once.

It also has support to the commerce stock module. If a product kit has 3 products in it (A, B, and C), and say one of them is out of stock (B), it is not added to the cart.

Not allowing any product to be added to cart even if one of the product from kit is not in stock makes sense and can be considered a good addition to the cart.

I have created a feature request in the issue queue for the same :
 #2821442 : Disallow adding product kit to cart if one product is out of stock.

While I do not have the time to implement it myself now, I would be happy to review any patches and make this a part of the module.


When developing a module's theming functions, should you use "template_preprocess..." or "mymodulename_preprocess..."?

Why not look at drupal core for best practice which favors template_process_X.

Also for some processors both template_preprocess and module_preprocess hooks can get called, see template_preprocess_block and system_preprocess_block as an example.


After the new Twitter API upgrade, I would recommend using the Twitter Pull sandbox project. It works beautifully.


What is the difference between t() and @Translation()?

In short, @Translation() is a string used in annotations, meta data written in PHP comments and pertinent to a Drupal 8 class.

For example, this is the annotation for the PathItem entity field class.

/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = @Translation("Path field item"),
 *   description = @Translation("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */

When Drupal loads the class annotations from a file, and it finds @Translation("Content") in the annotation, it creates an instance of the Translation class whose constructor receives the "Content" string; the instance is then used to get the value of t("Content").

As for the differences, they are the following ones:

@Translation() is a string used in class annotations: plain text that follows a specific format and it is written in PHP comments before the class that is being annotated. You cannot use it in code similar to the following one, except in the case a module defines a Translation() function. In that case, the @ before it would be understood from PHP as the error control operator.

$form['salary'] = array(
  '#type' => 'textfield',
  '#title' => @Translation('Salary'),
  '#size' => 10,
  '#maxlength' => 10,
  '#description' => @Translation('Please enter a valid number'),
);

t() is a Drupal function. It cannot be used inside class annotations like the following one, since it doesn't follow the syntax annotations follow. If it were used in an annotation as in the following, it would not cause Drupal to call t() and use its return value.

/**
 * Defines the 'path_field' entity field item.
 *
 * @DataType(
 *   id = "path_field",
 *   label = t("Path field item"),
 *   description = t("An entity field containing a path alias and related data."),
 *   list_class = "\Drupal\Core\Entity\Field\Field"
 * )
 */


View showing a list of tagged nodes related to term reference field

I have accomplished something along the lines of what you describe with a combination of a hook_form_alter and some Javascript. The following should help you set up something that will interactively enable/disable possible company choices based on the selected activity. Take note that it really only works if those inputs are selects and not Drupal's default autocompletes.

In a hook_form_alter directed at the "Request" node and node edit forms, create a simple of array of arrays, where the key is the term IDs of the activity, and the subarrays are the node IDs of the companies. Here is some pseudo-code, since I don't the actual structures of your entities:

$nested_array = [];

$term_query = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->getQuery();
$term_ids = $term_query->condition('vid', 'activity')->execute();

foreach($term_ids as $term_id) {
    $node_query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
    $node_ids = $term_query
      ->condition('type', 'company')
      ->condition('field_ref_activity', $term_id, 'IN')
      ->execute();

    $nested_array[$term_id] = $node_ids;
 }

 $form['#attached']['drupalSettings']['company_activities'] = $nested_array;
 $form['#attached']['libraries'][] = 'my_module/my_module.library_name';

The above makes the nested arrays available to the front end for on-the-fly manipulation. Create a library for your module with this jQuery-based Javascript. Again, pseudocode which you'll have to modify to your form structure:

function limitCompanySelection(selected_activity) {
    let allowed_companies = drupalSettings.company_activities[selected_activity.val()];

    $('company-input-selector option').each(function(){
        if ($.InArray($(this).val(), allowed_companies)) {
            $(this).prop('disabled', false);
        }
        else {
            $(this).prop('disabled', true);
        }
    });
}

Set the above function to run on initial load and every time the selected activity is changed, finding the selected activity and passing it into the function.


I wrote a module to do just that, Mobile Detect:

  This is a lightweight mobile detection based on the Mobile_Detect.php
  library, which can be obtained from the GitHub repository.

  This module is intended to aid developers utilizing mobile-first and
  responsive design techniques who also have a need for slight changes
  for mobile and tablet users. An example would be showing (or hiding) a
  block or content pane to a particular device.

  This module is not intended (and never will be enhanced) to provide
  theme switching or redirection; other modules already provide this
  functionality.

There is also Context Mobile Detect:

  This is a Context module which integrates Context and PHP Mobile
  Detect library Mobile_Detect.

  Module preserve drupal page cache working.

And you can check out Mobile Switch:

  The Mobile Switch module provides a simple automatic theme switch
  functionality for mobile devices, detected by Browscap or Mobile
  Detect.

These all serve slightly different audiences.  Pick the one that best fits your needs.


Drupal 7: Modifying the view page and edit form of a content type programmatically

If I understand what you are trying to do, you want to customise the node add/edit page and the node view page for your 'abstract' content type.

It seems like you are trying to duplicate what drupal already does for you for no apparent reason. Your code doesn't seem to really be doing anything that drupal does not do for you already (from the code sample you provided).
(As a side note, what are you actually trying to achieve?)

If so, I wouldn't be creating fully custom pages. Drupal gives you hooks so you can modify what it gives you by default.

For example, the node add/edit page (node/add/abstract & node/[nid]/edit) can be modified by using hook_form_BASE_FORM_ID_alter() or hook_form_FORM_ID_alter().
While form altering these forms you can add your own custom validate and submit functions if you need to do additional submission.

For path aliases, use the pathauto module, which will allow you to set the path alias for your page to abstract/[nid] - although you would generally be better off doing something like abstract/[title] for the sake of SEO and more user-friendliness.

For the node add page you can add a path alias by going to admin/config/search/path. Then you can make it something like abstract/add instead of node/add/abstract.

Drupal fields should be able to handle pretty much any of the data you want to handle, especially with the help of modules like date, link, email, and many many more.

Now that I know you want to store some node data in an external database then this next part is of interest to you. These node hooks allow you to hook into the node CRUD system:

If you really really do need to have extra data (not so common, you can generally do what you need with fields), for example, data you custom store in a separate database table, you can use the hooks hook_node_view() for showing your custom data on the node view page, hook_node_load() to load your custom data into the node object each time it is loaded, hook_node_delete() to delete your custom data when a node is deleted, hook_node_insert() for inserting your custom data when a node is created, hook_node_update() for updating your custom data when a node is saved.

There are other hooks too, like revision related ones if you are using revisions and search index related ones, for adding data to search index & search results.
See them here - http://api.drupal.org/api/search/7/hook_node_

Also, if you are adding data to nodes from your external database that aren't in drupal fields, you might also be interested in the APIs that the Entity module provides. In particular, you can define your data as properties of the entity, so they can be easily handles by modules such as rules and search api (and other modules that utilise the entity api). See http://drupal.org/node/1021466

If you really must do it that way, your hook_menu() also has some issues:
The % characters in the menu paths should really be replaced with %node - which will then call node_load and properly validate the nid in the path. See http://drupal.org/node/224170 for more information on menu wildcard loaders.

abstract/% also should not be MENU_CALLBACK, it should be MENU_NORMAL_ITEM.

Basically, you are trying to replicate the node/% node/%/view node/%/edit pages so you should try copying what the node module has in node_menu() for those items, but just change the path. Then you can have your new paths doing what the node module would do at node/% node/%/view and node/%/edit.
However you will then have issues with other modules that add node/%/something paths (if you are using any such modules). In this case those extra tabs on the node page would not be present on your pages because their paths would not match.

So unless you really really have to have abstract/%/edit, I would leave the menu alone and just use path auto to have abstract/[nid] or abstract/[title] and leave the edit pages as node/[nid]/edit.

An alternative solution, depending on whether or not it suits your use case better, is to not use the node system at all and create your own custom entity type. So you would have an abstract entity type, like the user, node and taxonomy term ones.

If you aren't really using any of the features that the node system provides this might be a better solution. It is relatively straight forward to do but the downside is a lot of existing contrib modules work only with nodes, and not other entity types. So those additional functionalities you might require you would also have to code yourself.
So it depends on whether you have the time to do the additional custom work required or if you are better off utilising nodes, so you get compatibility out of the box.


Render fields in node template with different view mode

Let me give you an example. I have one date field into my content type. Now I want to render that field twice. For getting that that i will print the output as Birthdate : Feb 22, 2006 for first instance and for second I want to print Age : 7 yrs old. In manage display I have format
   to date as well as Time ago and I want to use both format.

The easiest way to do this would be to create a second variable in your theme_preprocess_node() function, pull out the value that you want to format a second time, format it differently, and then print the variable where you want to see it a second time in your template.  Dates are particularly easy to format using the format_date() function, so you don't need to use a different views mode to achieve this.

In your theme's template.php file add something like;

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node']; // Nice shorthand.
  $lang = $node->language; // Shorthand again.
  $variables['new_date'] = format_date($node->field_date[$lang][0], 'medium');
}

Then in your node--whatever.tpl.php file print it out like;

<?php print $new_date; ?>


I was able to find a solution by following this example. Here is the code in my case:

function alter_users_query_query_alter($query) {
    if (isset($query->alterMetaData)) {
        if (isset($query->alterMetaData['view'])) {
            if($query->alterMetaData['view']->name == 'all_users') {
                $fields =& $query->getGroupBy();

                unset($fields['field-you-want-to-remove']);
                $query->groupBy('users_name');
            }
        }
    }
}


Use the Drupal date module.

Users can set their timezone and date will automatically be converted to the timezone of current user (you are presented with options about this when creating the field).


Post becomes unpublished upon editing it and no additional date values or image uploads are possible

I was having a similar problem when editing a node with a field that allowed for unlimited field collection values. Each field collection had 8 input fields, and after adding in over 100 field collection items it stopped adding in more and it would unpublish on Save.

I could publish it from the content administration screen.

I modified max_input_vars in the server php.ini file from max_input_vars=1000 to max_input_vars=2500 and that allowed for the addition of more field collection items and to keep the node published when saved.


I have successfully battled this error into submission over the past six hours.
I pieced together what I believe were the contributing problems and found a way for things to work correctly in a remote hosted (Bluehost) Drupal installation.

You must be able to use composer commands.  If composer is not installed on your remote host, you will need to install ssh and then install composer.  SSH lets you use command line typing so you can interact/execute composer commands
login to composer (I opened up Windows powershell and used SSH from there).  You will be challenged to put in your password for ssh the first time you use it.  If you have it configured tightly, you will be asked everytime.
cd www/your-drupal-directory If you don't start off in the drupal directory, you will not get code dropped into modules/contrib which means nothing will show up in your administration 'install' link from your site. Specifically, you login into composer and then just type the command and hit enter.  You'll then see your composer line now has your drupal path showing.  My path was www/d8 because Bluehost serves pages from www and I installed drupal in the d8 subdirectory. I'm sure public_html would have worked as well.
Commerce requires more than one module to run properly.  When you visit the Commerce installation page, pay careful attention to the Ludwig installation information.  The list of seven dependent modules is there.  You will need to be sure each dependent module is installed (some may already be installed).
--update-no-dev is the key to success.  Adding this option on your composer command will stop the addition of development packages during your module install.  A composer command for the general commerce package would be composer require drupal/commerce --update-no-dev then hit enter
Your next problem will be inconsistent 'stability' releases.  I used the default settings when I installed composer.  You can get around that problem by explicitly referencing the module version you want to install.  For example, Commerce requires the Entity module.  I used composer require drupal/entity:1.0-beta4 --update-no-dev

The issue of coder not being found seems to come from a difference between what is found in the composer.json file and the composer.lock file.  The update-no-dev is telling composer not to require the drupal/coder (and other things)

I am no expert on composer or drupal development.  I'm sure others can provide a more technical explanation.  It is always a good idea to check for updates periodically for all installed modules and themes.  You should have a report in your administration link on your site that gives you an idea of available updates.


Inserting Block with Custom Input Filter Module via Shortcode Causing http 500 error

A 500 error can be caused by lots of things. Your best bet is probably to use the Watchdog and/or Apache logs to narrow down the specific cause(s).


Prefix of drupal: in front of certain dependencies and what does it mean?

The 2nd is the correct way as per: https://www.drupal.org/docs/8/creating-custom-modules/let-drupal-8-know-about-your-module-with-an-infoyml-file but I think drupal is assumed for the project if its not specified (The first part before the : )

So for Drupal core modules they'd prefix with drupal: and for custom modules its usually the module name e.g. webform:webform as they are projects of themselves


Is linking to autocomplete results possible?

Yes it is possible.
You can try Search Autocomplete moodule.

Module page says:

 This module allows you to add autocomplete functionality to virtually any fields of a Drupal site. During the input, the field will be expanded and offer a list of suggestions before you start the search.
    By default, the module integrates with search forms from the Drupal core Search and Search Block.

Uses either static data, external or internal URL callback or an embeded view style to easily create your suggestions set.

For more information go through the module documentation.


Commerce: Diffrent text to add to cart button in product list and in product page

You should be able to use $node->type if you add this first

$node = menu_get_object();

Remember to check if $node is NULL and $node->type is set.

Also if you're wanting to use the "add to cart" hook_FORM_ID_alter() then the function name needs to be something like

custom_form_commerce_cart_add_to_cart_form_alter()


How do I redirect a domain but keep the URL structure?

Your second variant is close to the goal. But it needs some edits. Firstly, you should escape all dots in RewriteCond, so it will be
RewriteCond %{HTTP_HOST} ^example\.co\.uk$ [NC]

Secondly you need to edit RewriteRule to change regular expression and append request uri:
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

It also matters where you place the code. Your second variant is right. It's best to place code just after RewriteEngine on
Final code will be:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.co\.uk$ [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]


Drupal7: Rules Module - change the FROM field

I finally figured it out.
You can edit the "Send mail" component of the Entityform rules at:
/admin/config/workflow/entity_rules/entityform_submission/manage/rules_entityform_notifications_email_send

Then specify the value of the FROM field from the replacement patterns.
Keep in mind, when you build the form, or any new future forms, make sure that you always use the same field for the email and make it required. An empty email will result of the FROM field being sent from the site-wide admin email and not from the user's email.
See image, hopefully it helps:


Bundle field validation with Feature in Drupal 8

It looks like the field validation module has it's own configuration entity type.  This means that in the feature editor there should be a section labeled something like Field Validation Rule Sets.

Select the appropriate configuration under this section to include it with your content type feature.

I assume that you know that to include the content definition you need a minimum of the content type, the individual fields (storage and field settings), the entity form display, and entity view display.

There may be other specialty items like language settings here.  Enter the machine name of the content type in the feature editor search field (after checking include conflicts) to find them.  NOTE: Red indicates they are part of another feature and you may not need to include them.


Views - Filtering nodes by current user profile field

You want to use the Views module to create the list – actually a list
of users (rather than nodes/content).
Then you want to use relationships settings to add in the interests.
Finally, Add a contextual filter on "user: uid" with a default value
fetched from the currently logged-in user.

If you haven't used Views before you in for a ride. If you have used Views but not relationships or arguments/contextual filters, then you're also in for a ride.

There's a pretty nice guide for learning Views in the links in my signature – I hope that can be of help. Look especially for the episode on relationships.


Getting IMCE to accept multiple file uploads at one time

I don't know what version of Drupal you are using, If you are working with Drupal 7 you should take a look at: IMCE plupload that helps you to use IMCE with Plupload .

But in Drupal 7 the best option is Media module.


You can try and add the following lines to your settings.php file :
$databases['default']['default']['init_commands'] = array(
  'isolation' => "SET SESSION tx_isolation='READ-COMMITTED'"
);

https://support.acquia.com/hc/en-us/articles/360005253954-Fixing-database-deadlocks


How do I handle a dynamic domain i.e. www.(dynamic|.*).(com|org|ca|etc ...)

I've seen this done three different ways. Here they are, from basic to advanced:

Use Drupal's built-in multisite support by setting up different sites in the sites/ folder. This is sort of the "standard" way, and you'll end up needing things like the Features module.
Use Domain Access and all of its modules. This allows you to do all kinds of sharing between multiple sites, and you can generally accomplish a lot with very little coding. Ken Rickard, the owner of that project, will bend over backwards to help you, and you can typically ping him in IRC #drupal-contribute.
A custom module that intercepts the request early in the process (hook_boot, hook_init, and other places in D7) can often give you a chance to initialize the theme layer (and sometimes other subsystems) in a request-specific way. This is how we do our mobile version of our site (in D6), which uses the same nodes and stuff, but has much different template logic.


I think this pretty well covers it: Views template files


How to include the comment page number in views "rewrite results"?

I used a "Global PHP" field and added this code:

<?php
$new = $row->comment_count - $row->nc_count;
$page = floor($new / 50);
$link =  'nid;
if ($page > 0){
  $link = $link . '?page=' . $page;
}
$link = $link . '#new>' . $row->nc_count . ' new' ;
print $link;
?>

I don't like to use PHP in a view since it prevents caching. This view won't be cached, so it's not a problem this time. The other issue is that it doesn't generate the "pathauto" urls and requires an additional 301 redirect. I tried to use a "node link" variable but they don't seem to get changed to a pathauto link before the PHP field runs.

Any idea how I can render the /node/123 link to a pathauto link?


If you are using the Unformatted list format used by default from the front page view, you would see the author of the node. This happens if you selected Display author and date information on the settings page for the content type (admin/structure/types/manage/[content type]).

Supposing that you change the format to, for example, Table (which allows you to add fields), when you add the new fields you will notice that Content: Author uid field has the following description:

  The user authoring the content. If you need more fields than the uid add the content: author relationship.

So, you just add a relationship.

Once you do that, you will find the author name between the fields you can add.

As for the Grid format, it doesn't uses fields; that is why you cannot select them.


How to attach/upload a file to node using restws?

Here is the URL to access a node with file already attached to it

{domain_name}/[end-point]/node/219.json

Here 219 is the nid of the node.

Here is the sample JSON format to attach a file to node (node create).

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


If you are viewing a node that has revisions enabled, there will be a tab which will show all revisions of the current node.  If you want to see a list of all revisions on the site you could use Views to create a view of node revisions.  Then you can even add filters on content types, creation date, etc to customize your list.


Update node multi value field programatically

I think I found a solution.  I used hook_node_presave to check if a value was set, ad if not to set it to -1 for the 28 fields I have.  Maybe not the most elegant (I would love to hear if there is a more drupally way to do this) but it works.

function mymodule_node_presave($node) {
if ($node->type == 'mynodetype') {
for ($i = 0; $i < 29; $i++) {
if (!isset($node->field_scores_a['und'][$i]['value'])) {
 $node->field_scores_a['und'][$i]['value'] = -1;
}
if (!isset($node->field_scores_b['und'][$i]['value'])) {
 $node->field_scores_b['und'][$i]['value'] = -1;
}
if (!isset($node->field_scores_c['und'][$i]['value'])) {
  $node->field_scores_c['und'][$i]['value'] = -1;
}
}
}
}


It's cache issue of admin menu, you should disable the caching on client side.

You can do it here: /admin/config/administration/admin_menu, under Performance tab.


Target single block with amended theme function?

you can use preprocess_block function as follows:

 function mytheme_preprocess_block(&$variables) {
      if ($variables['block_id']->bid === 'target_block_id') {
       $users = $variables['users'];
      $title = $variables['title'];
      $items = array();

      if (!empty($users)) {
        foreach ($users as $user) {

          // $items[] = theme('username', array('account' => $user));

          $picture = theme_get_setting('toggle_comment_user_picture') ? theme('user_picture', array('account' => $user)) : '';
          $username = theme('username', array('account' => $user));
          $items[] = $picture . $username;
        }

      }
      return theme('item_list', array('items' => $items, 'title' => $title));
      }
    }


Adding a product field to cart summary in views

If anyone is interested, I found the answer here: https://drupalcommerce.org/discussions/1128/product-image-cart-form

It is a permissions issue. The solution was to enable the permission "view any product of any type" for anonymous users.


Add multichoice question to quiz node programmatically

Finally, I got the solution. The below code is used to add the multichoice question node to quiz node.

  $multichoice_node = node_load($nid); //load multichoice question nid
  $multichoice_node->add_directly = array(
    'latest' => array(
      $quiz->nid. '-'. $quiz->vid => $quiz->nid. '-'. $quiz->vid
    )
  );
  node_save($multichoice_node);


Letting users login with facebook to an existing account

Configuring OpenID for each services is so painful. I have also gone through the same process when I had to enable FB, Gmail & Twitter login at my website, but anyhow it was giving me problem even if I configured with the supported modules oauth & connector.

At last I found another module named HYBRIDAUTH & it worked so fine. Configuration is easy & there is no need of any other addon module with this. Best part is, it's free, otherwise most of the module of this kind are from some paid service provider..

Try this & I hope you will find all the services which you require along with facebook.


How to pass argument into markup (renderable array)?

The docs for format_string() should clear up the confusion:

  @variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
  %variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
  !variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).

So in the specific case you've provided, %wildcard is used to ensure that the value is :

  Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.

The different placeholder types are simply used in different situations, depending on what you need to do with the value, and whether or not you trust its source.

The docs for t() are also worth a read for extra context.


How to create review site with Drupal 7.7, FiveStar 2.x-dev, Node Reference URL, and Unique field?

I think this is what you need, its simple and clear about the topic http://drupal.org/node/1308114 only the thing you need is to just spend couple of minutes on it, you'll surely get what you are trying to achieve.

Good luck!


OK to have multiple media queries for each content type's CSS?

First, I'll say that I'm not sure if I should even be answering this question.  I don't think this is a Drupal specific question.  You may get more/better answers from a forum dedicated to CSS.

Having said that:

There's no reason this shouldn't work.  The CSS is valid, and if it helps you stay organized, I say go ahead.

I guess there could technically be concerns regarding the performance,  but I highly doubt you'd ever be able to see/feel a difference.


Is it possible to individually update each module using update.php?

You can't update single module using "update.php".
You can update single module if you installed drush.

List all available modules (except core) with below command.

  drush pm-list --type=module --no-core --status=enabled

Update specified module only.

  drush up 'module-name'

or

  drush pm-update --no-core "module_name"


Region for the footer not working, but the header is working

Regions are only rendered by default if they contain blocks (of which at least one must have content).

You can check whether the Footer region has blocks assigned to it by visiting the Block Layout admin page at /admin/structure/block. If you see the No blocks in this region message under the Footer block, you know that's the problem.


Drupal Commerce - Persistent Data Storage within the Cart

I discovered that the wise thing to do was to attribute tokens per user and do either a custom module validation or rules before the product being approved for checkout. Due to the fact that quantities can change in the cart, the validation would also trigger on deletes, or quantity changes in the cart.


How to test a code where the config is involved as parameter?

On a unit test, you can use getConfigFactoryStub():

namespace Drupal\Tests\my_module\Unit;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;

class MyModuleTest extends UnitTestCase {
  public function setUp() {
    parent::setUp();

    $config_map = [
      'my_module.settings' => [
        'setting_1' => 'value_1',
      ],
    ];

    // Get a stub for the config.factory service.
    $this->my_config_factory = $this->getConfigFactoryStub($config_map);

    $container = new ContainerBuilder();
    // Set the config.factory in the container also.
    $container->set('config.factory', $this->my_config_factory);

    \Drupal::setContainer($container);
  }

  public function testSomething() {
    $obj = new Something($this->my_config_factory);
    // ... asserts, etc.
}
}


how to add a class to the widget pager of views slideshow

In fact, after looking at the HTML code generated by views slideshow, pager widget is contained in a div on the same level that the content of the slideshow. So even if I could add a class, it would not be useful because I already positioned text to the right of my image. So the div content of the slideshow is already 100% of the width (and the sub-content have already custom classes to position them in line) .

So I have to use position: absolute to position the pager widget, so I can just add my classes on the container of all global gadgets (positioned at the bottom) by overriding the template views-slideshow.tpl.php as below, and then use the default classes of the widget in my css.

views-slideshow--MY-BANNER.tpl.php

<div class="skin-<?php print $skin; ?>">
  <?php if (!empty($top_widget_rendered)): ?>

      <?php print $top_widget_rendered; ?>

  <?php endif; ?>

  <?php print $slideshow; ?>

  <?php if (!empty($bottom_widget_rendered)): ?>

      <?php print $bottom_widget_rendered; ?>

  <?php endif; ?>

But I'd like to know if this is possible and with wich function.


As far as I know, every YT-channel has it's own embed code. Try to embed this code to your block and make sure "Full HTML" is set as text-format.

Look here as well: Embed You-Tube channel


What is the best way to track unique and overall clicks at my newsletters

I would suggest checking out https://support.google.com/analytics/answer/1033867?hl=en as it will help you build a link you can put in your newsletter that when clicked takes the person to whatever page you direct them to, but has analytic code built into the link so that you can track how many and how often it is used. Total sessions and unique users will both be tracked.


Best practice is to implement hook_field_formatter_info() and hook_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display). The examples module shows how to do this in greater detail in the field_example submodule.


Pathauto: Custom punctuation replacement

You can use hook_pathauto_alias_alter().


Can I route individual websites to a multi-site Drupal installation?

I have never seen this done in cpanel. Maybe under your reseller account
you could  create a instance of multi-site and then create sub-domains then
your clients could domain could be redirected to the subdomain?

Have you tried talking to the guys who created cpanel that might
be another resource

http://forums.cpanel.net/forum.php


Nest one content type in another to be able to add single fields

That's quite a cool question...

I think If I were doing it, I would have the basic form available to all standard users of a standard permissions role...

Then when a customer has paid for the privilege to use more advanced fields, I set up a rule to promote their role to an advanced user role after checkout.

You can then use a module like Field Permissions to determine which fields your basic users can edit, and which fields your advanced users can edit.

And, you only need one content type.


Deployment strategy for servers on internal network

The correct way is to use Acquia BLT. It generates a deployment artifact, which can be deployed anywhere.

So that the composer will stay in local and the deployment artifact can be committed to a different branch for deployment, with all the dependencies.


Boost not working on pages with ?_utma Google Analytics cookie in url

Boost saves the page cache in a file named after the page + the query string, the limit on the length of a filename is 255 in Linux so for pages with very long name/query string combinations caching will fail.

This should show up as an error in the Drupal log and if it does the solution is edit the .htaccess: Find the comment "Caching for anonymous users", after this you'll find a line "RewriteRule .* - [S=4]", replace this line with the following code:

RewriteRule .* - [S=6]

# If the page/query string combination is not over 255 characters, skip the following 2 rewrites
RewriteCond %{QUERY_STRING} "utm_campaign"
RewriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{REQUEST_URI}_%{QUERY_STRING} ^(.*\/)([^\/\n]{0,255})$
RewriteRule .* - [S=2]

# Custom Campaign Query
# Create file if not already boosted
# One campaign item is lost for file creation.
ReWriteCond %{QUERY_STRING} "utm_campaign"
ReWriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{DOCUMENT_ROOT}/cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html !-s
ReWriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI}? [L,T=text/html]

# Boosted file for campaign (now with query string).
ReWriteCond %{QUERY_STRING} "utm_campaign"
ReWriteCond %{QUERY_STRING} "utm_medium"
RewriteCond %{DOCUMENT_ROOT}/cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html -s
RewriteRule .* cache/normal/%{HTTP_HOST}%{REQUEST_URI}_\.html [L,T=text/html]

This makes sure that if the page/analytics query string combination is too long it will cache the page without query string instead, the first request will be redirected to the page without the Analytics query string, the next request will be served from cache and the query string will stay intact.

Note that this code is aimed at long url's with Google Analytics tracking variables only but can be (and possibly should be) rewritten so it can be used universally.


Your implementation is right but you are missing the print subject, you only print the content of the block.

if you debug the $block variable you will find 'subject' as key with value or without value based on the block if it has a title or not.

So your code should be like this in order to print the title.

 $block = module_invoke('menu_block', 'block_view', '3');
 print render($block['subject']);
 print render($block['content']);


If I only get your goal correctly, I would suggest: for each node - get attached terms - for each term - get taxonomy_get_parents_all - reverse the array to have parent-to-child chain - form a list into a tree

Forming a tree could be yet another function with logic allowing to merge terms that share branches.


You should avoid executing insert many times. It is enough to call ->fields multiple times, like this:

$query = db_insert('reservation');
foreach ($array as $room_id => $item) {
  foreach ($item as $reservation) {
    $query->fields(
      array(
        'room_id' => $room_id,
        'id' => $reservation['id'],
        'start' => $reservation['start'],
        'end' => $reservation['end'],
        'status' => $reservation['status']
      )
    );
  }
}
$query->execute();

This will speed up things, allowing database to prepare space for new data in one step, but with 30 thousands of records it still may take time. Be sure to tune your database accordingly - but that's out of the scope of Drupal Answers.

If you can't optimize DB enough, consider using Batch API for the job. It will make things a bit slower than the code above, but by importing a hundred or two each step you will avoid HTTP connection timeouts, PHP timeouts etc. Just make sure you only execute once per step with hundred records - even with Batch API it is good approach to group rows in as few inserts as practical.


You should take a look at Display Suite.  It makes easy work of most template modifications without having to create .tpl.php files.  It has an easy to understand method of managing View Modes.

From the above link:

Use custom view mode

Enable DS UI module.
Go to Administration > Structure > Display Suite > View modes (admin/structure/ds/view_modes)
Click "Add a view mode"
Enter a label & define to which entities the mode will be made available
Click "Save"
Go to Administration > Structure > Display Suite (admin/structure/ds)
Click "Manage display" for the entity (e.g., "User") whose display you like to change
Choose the vertical tab "Custom display settings"
Enable the new view modes
Click "Save"
Flush all caches
Choose the custom view mode from the secondary tabs in the top of the page.


You can use this module to place different menu attributes to your menu links:
Menu Attributes

This simple module allows you to specify some additional attributes for menu items such as id, name, class, style, and rel.
You should use this module when

You want to "nofollow" certain menu items to sculpt the flow of PageRank through your site.

You want to give a menu item an ID so you can easily select it using jQuery.

You want to add additional classes or styles to a menu item.

You can also add the ID using theme_menu_link like you were using above, you would place that code in your template.php of your theme.
If you use the Devel module you can print out the $variables array and see the different parts of the array there. You would basically want to use the mlid and the attributes part of the link to build out the ID (see code snippet below).
$element['#attributes']['id'] = 'menu-' . $element['#original_link']['mlid'];

If you need any other information just let me know, thanks!


"Edit layout" form missing revision log message field

I've added my initial patch to the issue - https://www.drupal.org/project/drupal/issues/3033516#comment-13136184

Adding this chunk to the init method of the OverridesEntityForm seems to do the trick, at least for nodes. We'll see what core maintainers come back with, but hopefully this can help you in the meantime.

  /**
   * {@inheritdoc}
   */
  protected function init(FormStateInterface $form_state) {
    parent::init($form_state);

    $form_display = EntityFormDisplay::collectRenderDisplay($this->entity, $this->getOperation(), FALSE);
    $form_display->setComponent(OverridesSectionStorage::FIELD_NAME, [
      'type' => 'layout_builder_widget',
      'weight' => -10,
      'settings' => [],
    ]);

    $section_storage = $this->getSectionStorage();
    $entity = $section_storage->getContextValue('entity');
    $entity_type = $entity->getEntityType();
    if ($entity_type->isRevisionable()) {
      $revision_log_message_form_item = $entity_type->getRevisionMetadataKey('revision_log_message');
      $log_field_definition = $entity->getFieldDefinition($revision_log_message_form_item);
      $log_field_revision_message_form_data = $log_field_definition->getDisplayOptions('form');
      $form_display->setComponent($revision_log_message_form_item, $log_field_revision_message_form_data);
    }

    $this->setFormDisplay($form_display, $form_state);
  }


user/%/edit - remove it from tab and make it an actual menu item

You want to alter the original menu item that was defined in user.module's hook_menu(). You can do this in hook_menu_alter().

The item's array key is simply the path, so:

function hook_menu_alter(&$items) {
  $items['user/%/edit'] = array(
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'my_custom_page_callback',
    'page arguments' => array(1),
    'access callback' => TRUE,
  ),
}