How do I override recurring text/strings with icons/images?

Drupal allows you to override almost anything and what you are referring to here is the theme()ing of various pieces.  In your specific example, 'View' and 'Edit' are tabs/local tasks on a node page, and they are themed something like this in Drupal 6:

/**
 * Generate the HTML output for a single local task link.
 *
 * @ingroup themeable
 */
function theme_menu_local_task($link, $active = FALSE) {
  return '
'. $link ."
\n";
}

and this in Drupal 7:

/**
 * Returns HTML for a single local task link.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: A render element containing:
 *     - #link: A menu link array with 'title', 'href', and 'localized_options'
 *       keys.
 *     - #active: A boolean indicating whether the local task is active.
 *
 * @ingroup themeable
 */
function theme_menu_local_task($variables) {
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '' . t('(active tab)') . '';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '
' . l($link_text, $link['href'], $link['localized_options']) . "
\n";
}

So, to change this from text to a graphic, you would create a theme function of your own in your theme's template.php file:

function YOURTHEME_menu_local_task(....

that looked at either $link or $variables['#link'] and output an image instead of the text.

And if php isn't your forte, but jQuery is, you could also do it in the browser with something like:

$('.tabs a[href$="edit"]').html('');

which would replace the text of your edit link with an image.  If you went this route you would put this in a suitable drupal behavior wrapper in your theme or custom module as well.


Entity forms, also know as Reusable forms, because they are not created directly in the process but in the entity that contains their information, that is, in the Context entity.

Now you please take a look at "Reuse of field collection entity type on more than one collection field?", a drupal community question explains something about it(google for it).
I hope this would help though.

Thank you.


What argument to use in Views that excludes the node currently being displayed?

This can be done with a regular argument.

Create an argument for Node -> ID, choose Node as the validator and Node ID as the argument type. Then just tick the Exclude the argument check box. You can also choose specific node types here if you want.

Used with a block, this will list all nodes that aren't the one currently being viewed. You can then filter it further to suit your needs.


"Your site was unable to contact the Apache Solr server"

There a  lot of apache solr variables set. Can you uninstall the solr module, remove the variables if left over and re-install. Sometimes, when you do a wrong config and it can't connect, it presists this in variable. Un-installing and re-installing should help.


How is it possible that neither if nor else branch gets executed here?

It was a character encoding problem in the source file. I changed the encoding in my favorite  text editor, and the code started working.


Webforms - Is it safe to allow users to upload attachments?

Here is a security advisory from drupal.org that explains some of the dangers of letting anonymous users upload files: https://www.drupal.org/psa-2016-003

tl;dr

Configure upload fields that non-trusted visitors, including
anonymous visitors, can upload files with, to utilize use the private
file system.
Consider forcing users to create accounts before
submitting content.
Audit your public file space to make sure that
files that are uploaded there are valid.


However if I remove it on the basic page 'Edit' page, it will also
  still keep a record in the database.

Correct, however after editing, the status of the file should be set to 0. (Unless the same file is in use elsewhere.) Drupal has a built in system that should automatically clean up these stale files both from the filesystem and the database, which you can configure on example.com/admin/config/media/file-system. The default time is set to 6 hours (depending on when cron runs this could take up to the next cron run).

Be aware though that there are known issues with this automated deletion. See the File usage tracking causes unexpected file deletion section in the release notes.


How to sync a taxonomy between Drupal and a 3rd-party system?

You can import taxonomies, and even nested taxonomies, with CSV data generated from your source data. I have been done before and it works quite well with module Feeds.

As for your taxonomy system, you must generate dynamical CSV files (in fact, a PHP or a Drupal node with some custom code), which feeds the Imports you generate in Drupal and which are associated to a vocabulary. In that way you can generate taxonomies with children.


Notice: Undefined property: stdClass::$field imce drupal

The global $user object is not guaranteed to have all the fields loaded onto it.

Try specifically loading the user like this:

global $user;
// Load the full user object.
$account = user_load($user->uid);
// Get the user code.
$code = '';
if ($items = field_get_items('user', $account, 'field_code')) {
  $code = $items[0]['value'];
}
return $code;


You could do this by creating a content type with fields, or using Webform module. A lot depends on who will be filling out the form (anonymous visitors, content editors) and what you need to do with the results.


Why does the "Registration List" tab not appear for my events for users with adequate privileges?

Figured it out - I had installed and was using the Field Permissions module which takes over any and all other permissions set in any of those other places. Once I edited each field on the event content type with custom permissions everything works great.

This still doesn't solve or explain the missing Registration list tab for admin users per How do I limit permissions to manage an event? though.


The template should idealy not be used to do database queries or other code that belongs in the Model or Controller of the MVC pattern.
The problem is that it is impossible to have a perfect implementation of the MVC pattern in Drupal.

What I mostly use as a rule of thumb is this:

Is this functionality that belongs to a module? Then put it in a module.
Would I have to copy this to a new theme if I made a second one? Then put it in a module (or parent theme if it should be in a subset of themes).
Does this function get/compute data or results which should be provided by a module? (like fetching user-data or a list of items) Then put it in a module.

In general the theme should only contain HTML, JS, CSS and a minimum of PHP used for simple loops, printing and simple conditional statements.

So the answer to your question would be; Probably not, it should probably be in a preprocess function or a getter function (like book_get_books()) in the module.

Edit: As Clive points out in the comments, Drupal does not strive to be fully MVC. The MVC pattern is only used to make it clear what belongs in the template, the controller and view don't really exist in drupal. Even the view is not as clear cut as it is in something like Symfony or Zend framework.


Getting rid of strongarm in features export

the short answer is yes you can delete it since you don't have any strongarm stored in this feature.

usually features add 3 pieces of code to any exported type:

the configuration it self in a file feature_name.features.config_group.inc or feature_name.config_group.inc
the include part in features feature_name.features.inc
what are the content of the export in feature_name.info

you can delete those manually and the feature will act as if they where never there, though removing a complete set of config group (e.g: remove all strongarm config) form the features UI will usually leave you with config file .config_group.inc (1), and rarely with include settings in .features.inc, which you can delete them manually.


Calendar module: Where is the pager markup? How can I translate it?

The pager markup is not directly related to calendar. It is part of date views, a submodule to the date module. Assuming your date module is installed in sites/all/modules, you can override the markup by copying the templates in sites/all/modules/date/date_views/themes to your themes template directory. You can also see the template preprocess functions in sites/all/modules/date/date_views/themes/theme.inc


Feeds remove item with certainly conditions

To alter the source items for the D7 version of Feeds, implement the hook hook_feeds_after_parse().

/**
 * Implements hook_feeds_after_parse().
 *
 * Removes duplicate phone numbers for importer 'myimporter'.
 */
function mymodule_feeds_after_parse($source, $result) {
  if ($source->importer->id == 'myimporter') {
    foreach ($result->items as &$item) {
      if (isset($item['phone 1']) && isset($item['phone 2']) && $item['phone 1'] == $item['phone 2']) {
        // If phone 1 and phone 2 are the same, do not import phone 2.
        unset($item['phone 2']);
      }
    }
  }
}


Views strips/merges unlimited values/fields of same field into one

If you are displaying fields, you need to configure the settings for multiple values.

From the edit screen for the view, select the properties of the field set to unlimited.  Then scroll down and find the part that says Multiple field settings:


Joomla to Drupal: how to use migrate module

Use Joomla to Drupal Module

  This module enables the import of the following content from a Joomla
  website into Drupal.

  Users
  Sections & Categories into Taxonomy Vocabularies and Terms
  Content items to nodes

If you want to use Migrate module, Here is the link Getting started with Migrate


How to change the output of a multiple image field for a node?

You can overwrite the field output template, e.g. field--field-name.tpl.php, or a module template, if that's the case. See http://drupal.org/node/1089656.
You can overwrite the node template for this content type (node--type.tpl.php). Type in
<?php print_r($node); ?>
 to find the element you want. For template information, see http://drupal.org/node/1089656.
You can create a page in Views.


Does pre-populated body for content types in Drupal 7 affect performance too?

tl;dr: No.

What happened in D6 when you shared a field, was that it got moved to it's own table.
This became irrelevant with D7, as all fields are now stored in separate tables, which was a very controversial decision, due to the performance effects this has.

If you want to increase performance, you can read some more here: How do you improve drupal performance.


Node not being saved when using Rules redirect

You may be redirecting before the pending node_save is called.

Try explicitly adding the action "Save Entity" under the Entities heading just before your redirect rule is evaluated. Make sure the redirect is the last action called.


Your hook_theme implementation is not being done in the usual way.
It should only have default values for the variables, like this:

/**
 * Implements hook_theme()
 * @return
 *  An array with the name of template file and variables
 */
function simple_faq_theme($existing, $type, $theme, $path) {
  return array(
    'faq_template' => array(
      'template' => 'simple_faq',
      'variables' => array('records' => array(), 'description' => ''),
    )
  );
}

Then when you call the theme function is where you send the actual values in, like this:

/**
 * FAQ Page content
 *
 * @return
 *  HTML created by template file
 */
 function simple_faq_page() {
   // Get faq content.
   // Categories, questions, answers.
   $records = get_faq_content();
   // faq description.
   $description = get_faq_info('intro');
   return theme('faq_template', array('records' => $records, 'description' => $description));
 }

As far as I know you can't give 2 values for the template file, however what you want to do should already be possible.
All you have to do is tell it where the original template file is in your module, then drupal will automatically find ones that are in any themes (the defining module doesn't have to set up anything for the theme).


install views module and create a new view with comments as base, block as output, and the actual node as context.
set it to use ajax, et voilà.

then - add this block to the content section and limit its visibilty to the corresponding content type.

to make sure the JS of views is added you have to add them manually. so in you template.php - add
function YOURTHEME_preprocess_page(&$vars, $hook) {
//Reload the javascript into the scripts. $vars['scripts'] = drupal_get_js(); } - may be even better to check the $vars if you're on the desired content type


You might simply be editing the wrong "display". Happened to me :)

If you have the Display Suite Drupal module installed, node types can each have several option sets (called "displays") how to display their fields, and a template or view then selects one of them to show the node. With the Taxonomy display Drupal module, the same is possible for taxonomies.

In these cases, you might simply be trying to adapt the image style setting in the wrong display. Check if you have a second line of tab-like options (starting with "Standard") for either nodes or taxonomies. In that case you have multiple displays for this node type / taxonomy, and you have to configure the image type for the right one.

You'll have to visit one of these admin menu items to check for displays:

"Structure → Content Types → [your content type] → Manage Display"
"Structure → Taxonomy → [your taxonomy] → Manage Display"


Hook not getting called (image_title module)

Figured it out.  There was this crazy code in image_title_nodeapi():

function image_title_nodeapi(&$node, $op, $teaser, $page) {
  if ( !user_access('create image titles') ||
       (variable_get('image_title_'. $node->type, 1) == 0) ) {
     return; // do nothing ...
   }

Which meant people could only see the images if they could also create images.  Not real bloody useful!  Fixed here:  https://github.com/kenahoo/drupal-image_title/commit/a4458676e7a6d1e00839a3d0e02a9d6c4f01fe2c

Update: on Paul's advice I created a fork in the Drupal Sandbox area: http://drupal.org/sandbox/kenahoo/1411716 .  I'm probably going to delete the github.com project now.


How to share saved data from 2 different input fields

You can use this code to compute age from date field:

    //compute age
    $bdayunix = strtotime($data->node_data_field_role_field_birthdate_value);
    $nowunix = time();
    $unixage = $nowunix - $bdayunix;
    $age = floor($unixage/ (365 * 24 * 60 * 60));

    print $age;

I hope these links will also help you solving your problem:

https://www.drupal.org/node/149237
http://www.kadimi.com/en/age-from-date-of-birth-in-drupal-7


Single page Drupal apps with custom theme

you could do it using the single page module. Each menu item can be a single page which can be mapped to a node.


Views: Get nodes of last added Node Reference

Order by the date DESC and restrict the displayed items to 1 through your pager options.


Example 1 is node 5 (http://erlinevanhijfte.be/node/5). go to it and delete it.
Example 2 is node 102 (http://erlinevanhijfte.be/node/102). go to it and delete it.

To find the node I just looked at the page source which has a shortlink meta tag which shows the node id and also the body tag has a class which shows the node id


VDD of  8 version doesn't support the feature of changing PHP version. You may try other Vagrant box for Drupal. For example this one, it has very good documentation.


Theme developer module crashes the whole site when enabled, how to fix?

I did manage to get it to work properly … eventually. This is how, on D7 7.5.

Download and install Theme Developer 7x. Do not enable yet.
Download and install SimpleHTMLDom  7.x-1.12. Do not enable yet.
Download SimpleHTMLDom library from
http://sourceforge.net/projects/simplehtmldom]1 and install to
sites/all/libraries, so that your library path is
sites/all/libraries/simplehtmldom/simple_html_dom.php.
Now you can run drush en -y devel_themer and it will automatically
enable the simplehtmldom.

I did notice that my /tmp folder was not giving correct permissions to the /tmp/devel_themer folder, so doing a chmod -R on that fixed the problem.


One path alias for differents / multiple internal path?

You cannot have one alias for two items. That's not how router works. On the other side, you can create a page only guests will have permission to see, and place it under the same name in the same menu. Then both guests and logged in users will see identical menu, but they will actually get different set of menu items.

If that's not enough, you can use Menu per Role to get more control of who sees what in your menus.


How to force a JavaScript library to load in the  of a Drupal 8 page

header: true needs to go under your js declaration, not within each file.

See: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

  By default, all JS assets are now loaded in the footer. Being loaded
  in the header is now an opt-in choice, that is only necessary for
  critical UI elements that cannot be shown unless their corresponding
  JS has already run.

js-header:
  header: true
  js:
    header.js: {}

js-footer:
  js:
    footer.js: {}

  You have to set the new header property on asset library definitions
  to true, to indicate that the JavaScript assets in that asset library
  are in the critical path, and should therefore be loaded from the
  header. Note that any dependencies — direct and indirect — of asset
  libraries marked as being in the critical path are also automatically
  loaded from the header, so you don't need to worry about dependencies
  being unavailable.


The project used to be on www.drupy.net (not .com), but that is an advertisement now as well.

The project was unfortunately discontinued (I like Drupal, but it is hard to move away from if you have to, and sometimes that is the better solution). The remainder can be downloaded from GitHub.


Changing workflow status programmatically in Drupal 7?

workflow_transition() is a function implemented from the Workflow module, and it still is implemented in the version of the module for Drupal 7.


is there a module for instagram like YouTube Field?

Firstly user will have to authenticate to their Instagram account. Then the user can access his personal photos via the end-point /users/self/media/recent. You will have to write some code to achieve this. The authentication part can be achieved using the HybridAuth module. Then you'll have to implement your own interface to search content.

This is if you want the user to first see a list of photos and then choose from it. If you just want to embed from url, you can use this module  along with the media module.

Its also important to note that Instagram API no longer permits public scope, and you can only search your own images.

With respect to youtube, Media module along with Media: Youtubemodule allows you to add youtube video from a link. You can then set the video player or thumbnail settings from the display settings. However, by default, there is not out of the box solution to search for youtube video graphically and then add it to Drupal.

However, adding this on top of Media Youtube field won't be very hard. Quick js around this form could solve the issue. See to quick js based youtube search below:

https://codepen.io/timivey/pen/jEXxZY
https://www.w3tweaks.com/youtube/search-youtube-videos-using-youtube-v3-api-using-jquery-ajax-call.html (Click on Demo)

You can use the Drupal Form Alter and Form attached options to add the necessary JS and CSS to the form.


How to start migration with migrate module

Is the Migrate UI module active? If yes, please try to clear the menu cache.


Try the folling setup:

In settings.php:

if (PHP_SAPI !== 'cli' && !empty($_SERVER['REVERSE_PROXY_ADDRESSES'])) {

  $settings['reverse_proxy'] = TRUE;
  $settings['reverse_proxy_addresses'] = array($_SERVER['REVERSE_PROXY_ADDRESSES']);

  $settings['reverse_proxy_header'] = 'X-Forwarded-For';
  $settings['reverse_proxy_proto_header'] = 'X_Forwarded-Proto';
  $settings['reverse_proxy_port_header'] = 'X-Forwarded-Port';

  // HTTPS behind reverse-proxy
  if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
    $_SERVER['HTTPS'] = 'on';
    // This is hardcoded because there is no header specifying the original port.
    $_SERVER['SERVER_PORT'] = 443;
  }
}

In your .htaccess:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
#RewriteCond %{HTTP_HOST} !^(.*\.)*localhost(.*)$ [NC]
RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]

(change $_SERVER['REVERSE_PROXY_ADDRESSES'] to $_SERVER['PROXY_ADDRESS'] for your setup)

This worked fine for me.


Drupal 8 always editing a translation, never the original

If you want to use English as default without URL prefix you have to disable

Session
Browser

in the language detection list, so that only URL and Selected Language (which can't be removed) is enabled.

Then configure in

Selected Language

the site's default language (English).


Arrange fields in a drupal form by multiple columns/rows

I did use the https://drupal.org/project/webform_layout Module which does create a div container around one or more fields.

You may choose between Horizontal, Equal Width and Vertical Orientation.
Further you can nest divs of Layout Boxes.

It is simple and does the job.


How can you compute grand totals in an aggregate view

You have to use Views Calc module.
The project page says:

This module adds simple calculations to a views table. Requires the
Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
in theme makes the view look more spreadsheet-like (right justifies
numeric fields, shades calculated columns and rows, and underlines
calculated rows).

For more information go through the module documentation.


Remove user entities on module uninstall

You can load all user uid's and call user_delete


How do I create a collaborative webform using Webforms?

I have been able to share a single submission with a role.

First, enable the 'save draft' option in webform Advanced Settings The 'Save Draft' option is here: webform/configure -> Advanced Settings -> Show "Save draft" button

Then, create a role with

'Access all webform results'
'Edit all webform submissions'

permissions. Any user assigned to this role can edit a submission started by another user.

The edit submission link (node/%/submission/%/edit) will be shared with the appropriate team members.


Are there any custom block type template naming conventions?

Here's one way to do it, in a module or theme:

function MYMODULEORTHEME_theme_suggestions_block_alter(&$suggestions, $variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof \Drupal\block_content\BlockContentInterface) {
    $suggestions[] = 'block__' . $content['#block_content']->bundle();
  }
}

Results in template suggestions like:

block--custom-block-type.html.twig

The instanceof might be overcautious, take it or leave it.


Easy content management for a Views powered site

For that particular use case, I'd suggest using the Nodequeue module. You could set up the nodequeue to contain 3 items and then users with the correct privileges would have the ability to add new items to the queue by clicking on a link on the node they want to add. In addition, users with permission to the administrative side of the Nodequeue module can also control the sorting of the items in the queue.


Using AJAX in Drupal 7 to change a form action

For more examples, here is the link to Lullabot's jQuery and JavaScript in Drupal video tutorial source files. I would pay attention to the Drupal 7 quickview.module example.

Here they use a page callback that passes either 'nojs' or 'ajax' as the second argument. The Drupal ajax framework will change the links on the page from 'node/[id]/nojs' to 'node/[id]/ajax' if the client has ajax enabled. The page callback function tests for the presence of ajax. If not, it will use drupal_goto() to gracefully degrade and reload the page. Or, if the ajax framework changed the link to ajax it will construct the HTML can send it back to the page with json headers and all using the new command() to manipulate markup, javascript Drupal setting, or CSS on the page.

I image with a tweaking this same technique can be used for Form API.


The user_block_view() function has this line in it for the login delta:

if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {

If you're logged in, the function will return an empty array, which is probably what's happening in your case.

If that's not the reason (and even if it is) you can get around it by calling the form function directly:

$form = drupal_get_form('user_login_block');

There doesn't appear to be any extra access checks done in the form function so it should be rendered regardless of whether you're logged in or not.


There is Ignore User, but for D7 there is only a dev version that hasn't seen any progress in over 2 years. Might be worth a look though, maybe you can start with that and even contribute back any improvements.

Everything else would require a considerable amount of configuration concerning the flags themselves, any views listings and node displays. Probably you will even need to do some custom coding.


Problem with Drupal 6 built in "normal" caching - users getting data several days old on front page

A couple of things to look at:

Adjust the Minimum cache lifetime set at on admin/settings/performance to something better suited to your users.
Make sure you have cron tasks in place to rebuild that cache on a regular interval. You can do it using Poormanscron in D6 (Built in core in D7).
Disable any server-side performace/caching mechanisms, such as APC, memcache, varnish etc...
Disable any extra Drupal caching mechanism, such as Boost.


Variable passed into a preprocess function has incorrect data or or an unexpected format

It happens because template_preprocess_forums(), which is executed before any hook_preprocess_forums() implementation, overrides $variables['topics'] with the render array for its table.

It would have been better to put the render array in a different array value. As you notice from the function code, starting from Drupal 8.6.x, the original value of $variables['topics'] is available in $variables['topics_original'].

  $variables['topics_original'] = $variables['topics'];
  $variables['topics'] = $table;
  $variables['topics_pager'] = [
    '#type' => 'pager',
  ];


How can I have the URL path (node slug) be different from the Title?

If you want control over the generated URL, then you need to enable the Path or Pathauto modules. Once these are enabled, Edit the piece of content for which you want to set a specific URL path, and go to "URL Path Settings" to do this.


restrict user to libarary tab in media file selector in media module

To prevent user(s) from uploading files, remove the following permission from their role (admin/people/permissions)

  edit media

For the role to still be able to access the library of media that has already been uploaded, ensure that they still have the permission

  Import media files from the local filesystem


add role to existing user on hook_entity_presave

Code should look like this, as an example:

use Drupal\Core\Entity\EntityInterface;
use Drupal\user\Entity\User;

function mymodule_entity_presave(EntityInterface $entity) {
  if ($entity instanceof AccountInterface && $entity->isTranslatable()) {
    $user = User::load($entity->id());
    $user->addRole('foobar');
  }
}

Or better yet, hook_ENTITY_TYPE_presave():

use Drupal\Core\Entity\EntityInterface;
use Drupal\user\Entity\User;

function mymodule_user_presave(EntityInterface $entity) {
  $user = User::load($entity->id());
  $user->addRole('foobar');
}

Simply using hook_entity_presave will fire for any entity about to be saved. So you either need to check the incoming entity, or use the second hook to isolate it.


Views Contextual Filter - Full Month display

function your_module_name_date_select_process_alter(&$element, &$form_state, $context) {
  $element['month']['#options'] = array
  (
    '' => t('Month'),
    1  => t('January'),
    2  => t('February'),
    3  => t('March'),
    4  => t('April'),
    5  => t('May'),
    6  => t('June'),
    7  => t('July'),
    8  => t('August'),
    9  => t('September'),
    10 => t('October'),
    11 => t('November'),
    12 => t('December')
  );
}


Attach the module "Insert" to ALL "Body" fields?

You may add this code snippet in the install file in your custom module and run update.php. It works fine, I've tested this code on my local site

<?php
/**
 * Add an image field to a node.
 */
function my_module_update_7001() {
  $field_name = 'field_insert_image';

  // Make sure the field doesn't already exist.
  if (!field_info_field($field_name)) {
    // Create the field.
    $field = array(
      'field_name' => $field_name,
      'type' => 'image',
    );
    field_create_field($field);
  }

  $content_types = node_type_get_types();
  $exclude = array('example');
  foreach ($content_types as $content_type) {
  if (!in_array($content_type->type, $exclude)) {
    $instance = field_info_instance('node', $field_name, $content_type->type);
    if (!$instance) {
      // Create the instance.
      $instance = array(
        'field_name' => $field_name,
        'entity_type' => 'node',
        'bundle' => $content_type->type,
        'label' => 'Image Insert',
        'description' => 'An image for the article.',
        'required' => TRUE,
        'settings' => array(
          'file_extensions' => 'png jpg jpeg',
          'file_directory' => '',
          'max_filesize' => '20 MB',
          'alt_field' => 1,
          'title_field' => 1,
          'max_resolution' => '300x200',
          'min_resolution' => '200x125',
          'default_image' => 0,
         ),
         'widget' => array(
          'type' => 'image_image',
          'module' => 'image',
          'active' => 1,
          'settings' => array(
            'insert' => 1,
            'insert_absolute' => 1,
            'insert_styles' => array_keys(insert_styles_list()),
          ),
         ),
         'display' => array(
          'default' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'full' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
         'teaser' => array(
           'label' => 'hidden',
           'type' => 'image',
           'weight' => 0,
           'settings' => array(),
           'module' => 'image',
         ),
       )
      );

      field_create_instance($instance);
    }
  }
 }
}


How to structure theme folder to make it more manageable?

I typically put all TPL's in a templates folder, further subdivided by categories such as views, node, page, etc.

Here's an example folder structure from one of my recent projects:

themename
- fonts
- images
- scripts
- styles
- templates
-- node
-- page
-- user
-- views

Basically, the only thing that goes into the root folder is the .info file, and the template.php file. Everything else is subdivided by category.


Thanks to @Jdrupal I finally found the solution in this link.

  body:
    plugin: sub_process
    source: body
    process:
      value: value
      format:
        plugin: default_value
        default_value: basic_html

(sorry I can't seem to get the mention appropriately formatted)


Increase maximum amount of characters for entity reference field (tag style)

I didn't manage to increase the maxlength of the input, but installed "Autocomplete deluxe" module, which implements the widget input field via jQuery chosen. Now I can set as many values as I like.


Check if the site allows new user registration

In a preprocess function for your template, add code something like:

$variables['is_registration_open'] = variable_get('user_register') == USER_REGISTER_VISITORS;

Then in your template:

<?php if ($is_registration_open) : ?>

Registration is open!

<?php endif; ?>


It sounds like you're looking for NodeSymlinks:

  NodeSymlinks allows you to display the same content to users at
  multiple locations in the Drupal menu system with unique URL path,
  unique navigation breadcrumb and without the SEO penalty that usually
  occurs with multiple copies of the same content.

  This is useful when you want to have the same page reachable though
  multiple menu items, each with its own URL, menu trail and breadcrumb
  path.


Redirect to Different URl on validation errors in form builder

You can use like

For Internal:

global $base_url;
$response = new TrustedRedirectResponse($base_url.'/landing-page#lead-form');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);

For External:
Use full link

$response = new TrustedRedirectResponse('https://facebook.com');
// You can use any one of these below to show error message.
$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);
$form_state->setResponse($response);


How can I implement a non-CRUD function in hook_service_resources()?

The key is to use the actions array instead of the operations array when creating non-CRUD resources.

Here's an example for DrupalGap: http://drupalgap.org/node/187

FYI, all calls must use POST when using actions.

When using operations, the calls are directed based on the HTTP method (GET, POST, PUT, DELETE).

Don't forget to attach the X-CSRF-Token header to your POST calls. Its value can be retrieved here: ?q=services/session/token

Since this is for DrupalGap, and you're passing along an argument to your service resource, I'd recommend following these instructions, that way jDrupal can be utilized and your function(s) can easily be re-used:

http://drupalgap.org/node/203


Drupal Commerce PayPal Express Checkout review and confirm step is skipped

The only code that would trigger a skip of the order confirmation page is in the checkout router hook implementation commerce_paypal_ec_commerce_checkout_router(). If you take a look at that, you'll see that it skips the confirmation page if the order either doesn't have a record in its data array that Express Checkout was used or if the customer used EC but did not use the EC flow (as opposed to the Mark flow, which is when the customer chooses PayPal from the payment method checkout pane and is then redirected to PayPal):

<?php
  // If the current page is the Express Checkout page but the current order did
  // not use the Express Checkout flow...
  if ($checkout_page['page_id'] == 'paypal_ec' &&
    (empty($order->data['commerce_paypal_ec']['flow']) ||
     $order->data['commerce_paypal_ec']['flow'] != 'ec')) {
    // Update the order status to the next checkout page.
    // ...
  }
?>

This means if it's being skipped for you, you should first ensure it's being skipped when the EC button is being used from the cart form (that's the EC flow) as opposed to when the customer redirects from inside the checkout form.

The second place to look will be the order's data array to figure it if / why the order doesn't have a record that it was paid for via EC.

If the module itself is to blame, please open a bug report explaining how to reproduce the issue. Last I used it, it was all working fine.


My ajax is altering form action/URL thus makes me impossible to read the $tid from it

At the very end, you could use a variable_set on if(!empty(arg(1))) and retrieve it with variable_get on if(empty(arg(1))), but I'm sure there's a cleaner way.


Why semaphore table is not using MEMORY as storage engine?

Drupal supports multiple database backends, but both MEMORY and the concept of storage engines as a whole is MySQL specific. Therefore, the Schema API has no support for specifying the storage engine.


Commerce: Don't calculate extra shipping for 1st item

From the screenprint of your calculation rule it's hard to tell what exactly the logic is that you implemented (an exported rule, created with the Rules UI, provides ALL the details).

Anyway, it seems that your Rules Loop is adding $1 for EACH line item, so also for the very first line item. While your requirement (in your question) states "+$1 for every extra item" ... If "extra" is to be translated to "but do not add $1 for the very first item", then clearly in your Rules Loop you should not have added $1 for the very first item.

The easiest way to correct this, is to subtract $1 after your Rules Loop is finished (consider it like a discount for the very first item). If you rather want to go for a slightly more complicated solution, then you could use the Conditional Rules module to add an extra test (Rules Condition!) within your Rules Loop to NOT perform that +$1 for the very first line item (I presume you know what such test should look like). My 2 cents: go for the easiest way via the extra correction after the Rules Loop is finished.


How to display all taxonomy terms as links and point them to nid in views

Assuming that the basis of your View is a node, you can add a field to your View: Content: Link (which is a link to the node of the View's row) and use the Rewrite results > Rewrite the output of this field with the contents of the taxonomy term (if I'm not mistaken [field_cities_we_serve1]).


How to change the view for a "Views: Filter by an entity reference view"-mode entity reference field on the node/add or edit form?

My code is wrong, now it works as below:

/**
 * Implements hook_form_alter().
 */
function sisucustom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'registration_node_form') {
    global $user;
    $account = user_load($user->uid);
    if (isset($account->field_default_class['und'][0]['target_id'])) {
      $entity_node = node_load($account->field_default_class['und'][0]['target_id']);
      $options = array($entity_node->nid => $entity_node->title);
      $form['field_register_for_class'] = array(
        '#type' => 'select',
        '#options' => $options,
      );
    }
  }
}

Finally I searched out a thread answering my question about modifying the widget info here.


Alter the username label in the login block

Your code needs to go inside a custom module. Assuming your module is called lae then you just need to make one or two small changes to your code:

function lae_form_user_login_form_alter(&$form, &$form_state, $form_id) {
  $form['name']['#title'] = t('User ID');
}

The edit- prefix that you get from the element's ID in HTML is actually provided by Drupal automatically, it's not the name of the key in the form array that identifies the element. Also the elements (at least for this particular form) will normally be at the root of the array so you don't want to reference $form['user-login-form']['edit-name'] (as it most likely doesn't exist).

I would advise downloading and installing the Devel module and using the dpm() function to print a nice representation of your form array to the screen, so that you can inspect it and see the correct array keys you'll need to target to effect a certain element.

// Add this to your form alter function:
dpm($form);


Can you prevent a module from being disabled?

If you're looking for a per-module solution, add the required property to its .info file.

  As of version 7.x, modules and themes may specify that they are absolutely required and should never be disabled by adding required = TRUE. These modules will be enabled automatically during install. In most cases it should only be used with the Drupal core required modules (e.g. Node, User, etc.).


Limited fields at registration time and full profile after logged in

You can do this without installing another module. It's good practice to avoid installing additional modules if you don't have to.

1) Go to the Manage Fields screen for user accounts at admin/config/people/accounts/fields

2) Edit the fields you want to hide/display from the user registration form. There is a setting at the top of the form called "Display on User Registration Form". View the attached screenshot for example.

3) If a field is marked as "required", it has to be displayed on the user registration form.

Certain form fields on the user registration form are not managed through the "Manage Fields" screen. So they can't be changed without getting in to modules. These include username, password, and a few others depending on your set up. But fields that you add yourself, like phone number, address, etc., can be edited.


Drupal site not loading any CSS/JS/Images

Ok found the problem, it was all to do with file/folder permissions. So I did some reading and I learnt that it's recommended that folders are 755 and files are 644 (with the exception of htacces)

So I went and made those changes to files/folders and it all seems to work fine.


How is $search_results in search-results.tpl.php generated

About theming results, you should have 2 templates: search-results.tpl.php and search-result.tpl.php (without s).

The first one allows you to theme the list, the second one (without the s) allows you to theme the results individually.

So I would advise you to use a hook to sort/filter the results the way you want (see answers from Clive and arrubiu), but use the templates to define the design you want.


How do I download/open a pdf file directly by clicking on lable/link

If want to Download File, then use DownloadFile module.

  a module to direct download files or images.

If want to open PDF, then use PDF Reader module

  will render your entity file fields with the selected PDF renderer.

and PDF module.

  Use HTML5 to display PDF files if users don't have pdf plugin for
  their browsers.


The only point is that you should disable and un-install the Pressflow modules, the rest is the same that drupal 6.

The big problem will be with the custom modules. The best always is try to make the migration.

If you don't want to migrate you can use feeds to move from drupal 6 to drupal 7. But in this way you must build the site in drupal 7.

Oskar


In Drupal Commerce, on what page does this order status fire? When an order is first paid in full

This event is triggered on whatever page request results in the named event - an order first being considered paid in full. This means it's going to vary based on the payment method. Sometimes a transaction is completed as part of a checkout form submission. Sometimes it happens while the customer is on a third party payment gateway page. Sometimes it happens after the fact when an administrator captures an authorization created during the checkout process.

When a payment transaction is saved, however it happens, Drupal Commerce compares the total of all payment transaction amounts for an order against the order total to determine whether or not the order has now been paid in full. If so, it triggers this event and updates the order to prevent the event from being triggered again - hence the "first" part of the event name.


You can either include the menu in your modules default configuration by adding a file to config/install folder of the module:

system.menu.menu-name.yml:

langcode: en
status: true
dependencies: {  }
id: menu-name
label: 'Menu label'
description: 'Menu description'
locked: false

You can also create the Menu entity, perhaps in the hook_install() hook.

use Drupal\system\Entity\Menu;

function MY_MODULE_install() {
  $menu = Menu::create([
    'id' => 'menu_id',
    'label' => 'Menu label',
  ])->save();
}


Try to check the settings of the "temporary directory" under File System (admin/config/media/file-system) admin page.

Usually should be folder: /tmp
Check if the folder has write access (specially for apache or the HTTP web server you are using).

You could find more info at Drupal documentation.


How do I enable and use a view mode for a product type?

Adding the answer to the question here as provided by @Bojan Zivanovic in a comment above. You can add View modes for products by clicking on the + Add view mode blue button at the top of the page.


How to edit the template of a node teaser that is sent in a newsletter email?

I think it would be easiest to change the teaser in the Manage Display tab under the appropriate content type. That will apply everywhere.

However if you have custom theme stuff you want to accomplish you'll have to make sure you're affecting the correct theme. It sounds like the e-mail generator may be using a different theme to send the e-mail?

A simple way to test for this is putting
HELLO
 in a template that you think it's using.


Custom Views filter for multi-level taxonomy

in Relationships you add:
 Taxonomy: Parent item

then in Filters add:
 Taxonomy: Term ID, set Relationship to the above Parent, and the Operator: Is empty(NULL)

This way you only get the top level terms, because they don't have parents. Or you set it to Not empty(NOT NULL) to get the child terms.

I hope this method helps you in some way.


How to distribute a Drupal website on a flash card?

You can run a dynamic, database-driven Drupal site from a DVD or Flash memory stick using a system like portable XAMPP, which is designed to run on removable drives, and includes Apache, PHP and MySQL.

If you only need static pages, you can use the HTML Export module, which will export all your image, JavaScript and CSS, and export your nodes as HTML pages. I've tried it and it works as advertised.


In the filter for the taxonomy term, try choosing no terms at all instead of choosing all.


How to make a facet search on a taxonomy term contained in a paragraph contained in a content type?

A solution is to associate the taxonomy directly with the content type (field_ingredient_search_index in the example below) and make a hook to update it automatically.
$nodeTerms = []; // 1,2,3 = terms IDs
$erase = [];
$node->set('field_ingredient_search_index', $erase);

foreach ($node->get('field_liste_ingredients')->referencedEntities() as $enty){

  if($enty->getParagraphType()->id == 'ingredient' && isset($enty->get('field_ingredient')->target_id)) {
      $nodeTerms[] = $enty->get('field_ingredient')->target_id;
  }

}

$node->set('field_ingredient_search_index', $nodeTerms);


Unfortunately, (as you discovered), the site-alias command is not flexible enough to do what you want. There are other ways, though.  For your specific example above, which happens to involve paths, you can use the drupal-directory (dd) command:

$ drush dd @www.mysite.org.au:%dump
/tmp/drush_www.mysite.org.au.sql
$ drush dd @www.mysite.org.au:%files
/vhost/www.mysite.org.au/sites/default/files

For a more general-purpose solution, you could use the php-eval (ev) command:

$ drush ev '$a = drush_sitealias_get_record("@gk.dev"); print_r($a["path-aliases"]);'
Array
(
    [%boo] => /usr/local/boo
    [%root] => /srv/www/dev.greenknowe.org
)

This can, of course, be customized to suit, as the ev command will evaluate any arbitrary php you care to throw at it (as long as you escape special characters correctly). This is more complicated to use than the dd command, but it will also work for elements other than paths in the path-aliases element.


Install Webform on Drupal 8 : checkboxes greyed out

The new webform 8.5 versions requires the "Contribute" module. If you click the little expander next to webform you'll see its a dependency. Have a look on the webform project page for more info
https://www.drupal.org/project/webform

Also just as a tip as I noticed from your question you've got your modules as /custom/contrib/webform its better if you do your module file structure as:

/modules/custom/

/modules/contrib/

with your own build modules in custom and anything from drupal.org in contrib.


How to set #default_value for radio button on Ajax Callback?

Please check if this works

$commands[] = ajax_command_invoke('#my-radio-button-id', 'val', array(array('checked' => TRUE)));

Ref: http://handsomedogstudio.com/setting-radio-button-values-drupal-ajax-call


Drupal add google analytics event tracking query strings to url

Create your links here and add them in your newsletter node content and/or mail template.


Whatever you want to happen via Rules module when some link is clicked, if you're using Rules Event 'Content is viewed', you'll probably be too late:

the content (or whatever the clicked link is about) is already being shown, so if the Rules Conditions are satisfied, the Rules Actions will be performed. That is what 'Content is viewed' is all about.
if you didn't want to content (or whatever the clicked link is about) to be visible at all, well sorry, but you're too late.

If however you did want something to happen BEFORE showing the content (or whatever the clicked link leads to), then you should use Rules Event 'Drupal is initializing'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this.

Attention: Rules Event 'Drupal is initializing' gets triggered on every (repeat: every) page load in a Drupal site. So for performance reasons, you really want to limit the number of active Rules that use this Rules Event to an absolute minimum, i.e. as your last resort (if anything else fails).


How to disable the submit button after clicking?

It's only in dev but the Hide Submit module would do the trick. One of the features is:

  Hide (or disable) the submit button after it has been clicked

I've just installed it on a dev site and it seems to work well for node add forms; when you click the submit button it's hidden and replaced with a loading image and a 'Please wait...' message, before the form is finally submitted. I haven't tried it on any other forms though.


Proper way to access data in a custom table

If this question was about D7, you could start from what's suggested in the Developers Guide that comes with the Forena module (disclosure: I'm a co-maintainer of the D7 version). Here is a quote from its introduction:
Forena implements custom hooks to allow the report engine to be extended in many ways. Forena does use OOP methodologies, but also leverages the observer pattern so prevalent in Drupal.

There is then a common pattern that is used to extend Forena:

Implement a custom php class that lives in your module directory. You may extend any of the Forena classes, or write your own from scratch.
Implement the expected registration methods in your class (e.g. templates, formats).
In your module implement a hook (e.g. mymodule_forena_controls) that tells Forena the location of your class definition file.

These days, Forena has a dev version for D8 also, for which it's current status can be summarized like so (from it's release notes):

Basic rendering of reports and document types are complete, however the GUI version of the report writer has not yet been ported. Sufficed to say, this version can be used by Drupal 8 report writers who are comfortable writing .frx files and sql elements by hand.

Some more details to help you digest these release notes:

"SQL elements" refers to Data Blocks and the Data Sources they relate to, as explained in the Data Guide.
The ".FRX files" are the actual specifications of how you want you report to look like, as explained in the FRX Reporting Reference.
The "GUI version of the report writer" is what is explained in the WYSIWYG Reporting Guide.


How to manage exported block configuration that site users can override?

Trouble is, site owners have permissions to update block configuration, and this overrides our exported configuration.

I thinks it's a bad idea to give site owner to change something in site-configuration. Site owner should take care only about site's content and should have permission to change site's configuration(block's configuration it's a site configuration).


Multiple ways of doing this depending on what you feel like doing.

Custom block type

Create a custom block type, add the fields you need, add them to a region and set to the homepage. Theme the twig files that relate to this block type.

Paragraph type

You can set up a paragraph type to build this into the node itself. Create a paragraph type that has title, image, summary, and link - then a reference field on the host node that limits the cardinality to 3 total. Theme up the twig files that relate to this paragraph.

Entity reference field on the node

You can even simply set a reference field to other nodes and let the editor enter what nodes they want to reference, and set the field formatter to a display mode (for example 'Call to Action' or 'Card'), and theme those twig files. Simply printing {{ content.field_foo_reference }} will render them as their view mode set in the field formatter. Fields like 'summary' can live on the referenced node - perhaps even a body field that is trimmed (look at adding Smart Trim for better trimming options on long formatted text fields).

Personally, I would go with the third method - it is the quickest of the three to do. I think you can even achieve this with core alone - something you can't do with the second method. It also puts all the work into the node form, instead of require editors to fool with the block system overview and create blocks to do this. Of course, you can also add this reference field on a block type and employ the same method - however since the homepage for me is almost always a node, I like to contain it in the same spot.


How can I return a 404 error page in a node view?

Drupal permission system provides fine grained permission control for "create", "edit", "delete" actions for every node content type, but viewing action is covered by general "View published content" permission option that covers all content types.

In order to deny access to anonymous users when they are trying to view a node of certain content type, you need to include a function in a custom module that implements hook_node_access():

/**
 * Implements hook_node_access().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_access($node, $op, $account) {
  if (user_is_anonymous() && $op == 'view' && $node->type == 'EXAMPLE') {
    return NODE_ACCESS_DENY;
  }
}

You need to replace MYMODULE with the module name that contains this function and EXAMPLE with the name of the content type that you wish to deny access to.

UPDATE: The code above would in fact return 403 (Access Denied) page, I'm sorry for confusion. The following code will return 404 (Page Not Found) page (only when user is trying to access the node of content type "example" in "full" view mode (usually by accessing the node by URL "node/NID]":

/**
 * Implements hook_node_view().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if (user_is_anonymous() && $view_mode == 'full' && $node->type == 'EXAMPLE') {
    drupal_not_found();
    drupal_exit();
  }
}


What you need is to use the Message Subscribe module, also in the Message Stack. This will allow you to subscribe users to a particular entity, e.g. - your job post.

You need to be able to link your "plumbing" (taxonomy tag, or direct entity ref) to Plumbing Group. You need to use Rules if the functionality exists, or a custom module to hook into the submission of a new job posting with the reference or tag to pointing to plumbing group. If this tag exists, then subscribe all users in the Plumbing group to that new job posting and issue a notification using Message Notify.


How to filter a field in the add content window in Drupal?

You can try the Conditional Fields module. It allows you to show/hide fields based on the value of other fields.

The Hierarchical Select module suggested in jimajamma's answer is meant only for hierarchically structured vocabularies. Conditional fields doesn't have a fancy animated interface like HS, but it provides more flexibility. For instance, you could make a text field depend on a taxonomy term:


how to filter and show fields of content types in custom page tpl.php file

Instead of modifying any template files, you should most probably be looking into the Views module, a module that, per its project page, is useful for a variety of tasks, one of which seems particularly on point here:

  You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of "Month, YYYY (X)" where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.


How do I set a node/page's background image to that content's image?

This can be done without installing extra modules:

Add an image field in the content types you want to enable a dynamic background image.
Use this code:
template.php:

function THEME_preprocess_page(&$vars) {
    if (!empty($vars['node'])) {
        $node = $vars['node'];
        if (!empty($node->field_background_image)) {
            $image = file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']);
            $vars['background_image_css'] = 'style="background: url(' . $image . ') no-repeat scroll center center / cover #FCFCFC;"';
        }
}
}

Add this in your div#content in page.tpl.php:

print (!empty($background_image_css)) ? $background_image_css : ''; ?>

Updated version: template.php:

function THEME_preprocess_page(&$vars) {
 $node = menu_get_object('node');
 if (!empty($node) && !empty($node->field_background_image)) {
        $image = file_create_url($node->field_background_image[LANGUAGE_NONE][0]['uri']);
        drupal_add_css('div#content {background: url(' . $image . ') no-repeat scroll center center / cover #FCFCFC; }', array('type' => 'inline'));
 }
}


Minimum password length for registration form

You might be looking of Password policy module

Features
Current constraints include:

Complexity constraint

Digit constraint

Letter constraint Letter/Digit

constraint (Alphanumeric)

Length constraint

Uppercase constraint

Lowercase constraint Punctuation constraint

Delay constraint Username

constraint Digit placement constraint

History constraint (checks

hashed password against a collection of users previous hashed

passwords looking for recent duplicates)

Also checkout this Quick demo.


Route not found error when using webform_rest to upload files

I got it working. two things I was missing.

Make sure you accept all the operations / JSON requests from here
/admin/config/services/jsonapi
I was confused with "binary file data". So basically you don't have
to do anything with the file. No formData, No base64, just pass your
file variable as it is.

And it worked.

Thanks


Hide comment box from node for Anonymous users

The comment module provides a permission, "Post comments" (post comments). Before using any code option, you should remove that permission for anonymous users.


How to inspect outgoing email content during a SimpleTest?

Simpletest automatically captures sent mails during a test and allows you to fetch them using $this->drupalGetMails() in the test class.

I did something like this recently in tests I wrote for the Simplenews project, to test subscription confirmation here.


Taxonomy i18n does not translate term name in a term page

This is a known issue: Vocabulary Name value doesn't get translated. It dates from 2005 (!), related to D6, status "won't fix". However comment # 2 in that issue states:

  I have used the locale module to translate the name of the vocabulary, and display it with t($vocabulary->name). If all modules would display the name this way (e.g. taxonomy_menu does it), then there is no need for a new database table i18n_vocabulary.

The t($vocabulary->name) seems like a possible/partial work around to consider, i.e. from within a (custom) module.

There is a more recent similar issue, i.e. Vocabulary names are not translated. That one is for D7, with status "needs work".

Another potential work around could be to have a separate taxonomy for each language (and with a "name" corresponding to that language). Of course, you'd have to think how to best use these separated taxonomies for each content type (a kind of "solution to the problem, changes the problem) ...

That's probably the best you can get these days. Does this somehow "answer the question"?


Check if the user is logged-in in a theme

If you just to check the current user is logged-in, you can use $variables['logged_in'], which is generally available in all the template files.

For example, the mark.html.twig file uses the following code, although the only documented variable is status.

{% if logged_in %}
  {% if status is constant('MARK_NEW') %}
    {{ 'New'|t }}
  {% elseif status is constant('MARK_UPDATED') %}
    {{ 'Updated'|t }}
  {% endif %}
{% endif %}

The variable is explicitly documented in other template files, such as html.html.twig, page.html.twig, and node.html.twig.

The variable is available in all the template files, since it is initialized in _template_preprocess_default_variables() that invokes user_template_preprocess_default_variables_alter() (an implementation of hook_template_preprocess_default_variables_alter()), which contains the following code.

  $user = \Drupal::currentUser();

  $variables['user'] = clone $user;
  // Remove password and session IDs, since themes should not need nor see them.
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

  $variables['is_admin'] = $user->hasPermission('access administration pages');
  $variables['logged_in'] = $user->isAuthenticated();

_template_preprocess_default_variables() is called by template_preprocess(), which is the function called for theme hooks implemented as templates; this guarantees the variable is available in all the template files.

Keep in mind that macros don't have access to the current template variables, so trying to access logged_in in the code of a macro would not have any effect.
Between the template files used from Drupal core modules, the ones using a macro are:

menu.html.twig

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

book-tree.html.twig

{% macro book_links(items, attributes, menu_level) %}
  {% import _self as book_tree %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ book_tree.book_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

menu--toolbar.html.twig

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}

For example, changing the last macro with the following code would not have the expected result.

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}

    {% else %}

    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          logged_in ? 'menu-item--logged-in-user',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}


The value for #default_value must have the date() format "Y-m-d H:i:s"; the value returned in $form_state is a string.

In your case, the code you should use is the following one.

  $form['billing']['expiry_db'] = array(
    '#type' => 'date_select',
    '#title' => t('Expiry Date'),
    '#default_value' => date('Y-m-d H:i:s'),
    '#date_format' => 'm Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '0:+20',
    '#required' => TRUE,
    '#prefix' => '<div class="field-wrapper-w1">',
  );

If the form has #tree set to TRUE, then $form_state['values']['billing']['expiry_db'] a string such as '2020-05' for May, 2020.

As far as I can see, the value of #date_format is only used to understand which components of a date must be returned, but the format of the returned value is always the same. Changing #date_format to 'Y-H:s' the returned value is '2020 00:00'. In you case, the code to get the month, and the year is the following one.

list($year, $month) = explode('-', $form_state['values']['billing']['expiry_db']);

References

_date_api_element_info()


"The pdf.js library could not be found." (PDF module)

The path will be like this /sites/all/libraries/pdf.js.

pdf.js is a FOLDER not a FILE. It is very strange to have a folder with a DOT in the name.

I have attached a screenshot on the folder hierarchy that works.

SUMMARY:

The folder in your libraries folder must be named: pdf.js, you will have to rename the top folder of anything you download to pdf.js (in this instance pdf.js is not a FILE, but the container of the library)
See screenshot for the correct file hierarchy.


The standard ckeditor alignment just adds a CSS float left or right, there is no float:center in css. You could add the plugin to ckeditor and that will give you more options.

A plugin is being worked on for this at the moment. You could download the beta and give it a shot. It goes in the

http://dev.ckeditor.com/ticket/10659

You'll need to install the plugin and add some javascript to make it work. There's another post here that shows the process for the justify plugin:
https://stackoverflow.com/questions/14782152/inline-ckeditor-toolbar-has-no-alignment-buttons-for-h2-elements/14810988#14810988


Creating separate list of a custom content type for every user

I would take a look a the flag module. It allows you to create an unlimited number of "flags" that can be placed on nodes that users can select/deselect. You could create one for "seen" and "unseen".

It has views support so you can create a view using the user id as an argument on each user's page that will show them which movies that have flagged.


Is there any management utility for multi-site deployment?

Take a look at Aegir:

http://drupal.org/project/hostmaster
http://www.aegirproject.org/

It's probably a bit more than what you are looking for, since it manages your web server vhosts (apache or nginx), which means that it kind of takes over part of the system configuration. It also works much better on Debian (with Debian packages, installation/upgrades are pretty easy.. kind of annoying otherwise).

Once it's installed, you can create your base site and clone it using the Aegir user interface (which is a Drupal site, called the "hostmaster", which is completely autonomous from the other sites you are hosting - it's just that as Drupal developers, they used Drupal for the front-end to their tool). Under the hood, Aegir uses Drush, so it's not re-inventing the wheel.

Anyway, fair disclaimer: there is a learning curve, but it has a pretty good community and it's well worth it when managing farms of small sites. It also has commercial training/support available from a few companies (listed on the project page).


Admin Module frontpage has gone - How do I get it back?

Try using phpMyAdmin. Backup again, then show the system table. Change the status of the problem module from 1 to  0 from phpMyAdmin. Then refresh Drupal pages to see if it resolves it. Other modules might be the issue so try process of eleimaination, toggling 1 to 0. If the 0 works, try and uninstall then reinstall if practical.


Is this views 3? If so if you go to the Settings for the format you can add a Row class (the description says "The class to provide on each row") which should do what you want without templates etc.


How do I use a different template for the anonymous users?

If you want to handle different templates for different scenarios the context module is a great tool. This case is quite simple, so you could handle it with code like suggested. But using the context module, makes it a bit more manageable, and allows you not only to decide what template to use, to also what blocks to insert. It's a great module and is one of those I use for almost all of the sites I make.


Auto URL Aliasing for Custom Menu Paths with Term Id

I am not sure whether we should take this way or not but I found this:

We can save new path alias using path_save() function.

Here is how I managed it:

I called the function after submission of node or group node.

Then I called a custom function and fetch the real URL of the node i.e in your case it will be group/tid.

Now I retrived term name from term id and created new alias with term name.

Called path_save() function with necessary information.


Disable price field when checkbox is checked (node add form)

For D7 you can go for
Conditional Fields

Define dependencies between fields based on their states and values.
Conditional Fields for Drupal 7 is an user interface to the new States
API, plus the ability to modify fields appearance and behavior on
certain conditions when viewing content.

Field Conditional States
The Field Conditional State module can be used when:

you have a text field you only want to be enabled when a certain checkbox is checked
you want to show a different set of fields depending on the value(s) selected in a certain select list


How can I update an user field via JSON:API?

You need to also put UUID in your request URL, so it should look like
EndPoint:https://domainname.com/jsonapi/user/user/xxxxxx-7798-45e5-a16c-xxxxxxxxxxxx


The specific vulnerability seems to be the ability of a requester to send one request path to the webserver, but use an HTTP header to make Drupal see a different path.

The rewrite happens early, so the access layer in Drupal/Symfony runs as intended. But it bypasses path-based restrictions that happen earlier ("on higher level caches and web servers", according to the CVE at https://symfony.com/blog/cve-2018-14773-remove-support-for-legacy-and-risky-http-headers).

For example, if you use .htaccess to restrict /admin/* from outside your IP range, that might be bypassed, but Drupal's own access system will still work as it should.


If you have created a custom user registration form my_module_user_register_form, then you can define one or more submit functions for it

function my_module_user_register_form($form, &$form_state) {
    $form['#submit'][] = 'my_module_user_register_form_submit';
    // and now add a second submit function if you like
    $form['#submit'][] = 'my_module_user_register_form_another_submit';
}

and then place the appropriate redirect at the end of the last submit function.

function my_module_user_register_form_another_submit($form, &$form_state) {
   // do other stuff here
   $form_state->setRedirect('node/123/edit');
}


Simplify Panels "Add content to" popup with fewer options for end users

Checkout https://drupal.org/project/Panopoly - they make a lot of customizations to this to improve the ui.

Some more details from the project page:

  Panopoly is powerful base distribution of Drupal powered by lots of Chaos Tools and Panels magic. The distribution is designed to be both a general foundation for site building and a base framework upon which to build other Drupal distributions


Search API: Custom processor not hitting addFieldValues

EDIT
I created an issue on the search API issue queue Custom Entity Reference processor does not trigger addFieldValues()* and the maintainer has pointed to an existing issue that it was duplicating. So there is an existing issue that is being worked on here - #2910638: Entity reference via processor sample code not working Jump on there and help test :)

I couldn't post the first link because of a lack of reputation and I figured the link to the issue where work is being carried out is more useful :D

I'm encountering the same behaviour and have an idea why this occurs but not an answer on how to fix it (I can't post a comment so needed to add this as an answer).

\Drupal\search_api\Item\Item::getFields is responsible for calling the instances' implementation of addFieldValues. Within that function there is this code block:

   foreach ($this->index->getFieldsByDatasource($datasource_id) as $field_id => $field) {
      // Don't overwrite fields that were previously set.
      if (empty($this->fields[$field_id])) {
        $this->fields[$field_id] = clone $field;

        $field_data_type = $this->fields[$field_id]->getType();
        // If the field data type is in the fallback mapping list, then use
        // the fallback type as field type.
        if (isset($data_type_fallback_mapping[$field_data_type])) {
          $this->fields[$field_id]->setType($data_type_fallback_mapping[$field_data_type]);
        }

        $property = $field->getDataDefinition();
        if ($property instanceof ProcessorPropertyInterface) {
          $processors_with_fields[$property->getProcessorId()] = TRUE;
        }
        elseif ($datasource_id) {
          $fields_by_property_path[$field->getPropertyPath()][] = $this->fields[$field_id];
        }
      }
    }
    try {
      if ($fields_by_property_path) {
        \Drupal::getContainer()
          ->get('search_api.fields_helper')
          ->extractFields($this->getOriginalObject(), $fields_by_property_path, $this->getLanguage());
      }
      if ($processors_with_fields) {
        $processors = $this->index->getProcessorsByStage(ProcessorInterface::STAGE_ADD_PROPERTIES);
        foreach ($processors as $processor_id => $processor) {
          if (isset($processors_with_fields[$processor_id])) {
            $processor->addFieldValues($this);
          }
        }
      }
    }

If the value of $property is not an instanceof ProcessorPropertyInterface then addFieldValues() is never called.

What I'm not sure of is what is the best path to take to begin solving this.

Should I add a new custom processor that only acts on this custom field and use addFieldValues() there? (I've yet to test this) OR
Is it an issue that addFieldValues() is never called and the Search API module needs to be updated so that it is?

I've tried implementing the other functions from the parent class (\Drupal\search_api\Processor\ProcessorPluginBase) ie alterIndexedItems but none of those are triggered.

I came across the same approach that you're using here on d.o - Adding an entity reference via a processor so it may be the docs need to be updated.


Programmatically setting a webform submission to draft in presave

Turns out I need to do this to save draft, the setData is only used to set element data.

$webform_submission->set('in_draft', TRUE);


Here is the updated jquery code that renders the colorbox properly the first time:

success: function (response) {
        $('#coaching_summary_ajax').html(response);
        $('.colorbox-node',context).once('init-colorbox-node-processed',function () {
          $(this).colorboxNode({'launch': false});
        });
        $('.colorbox-node',context).colorbox();

      }


drupal_render radios missing name attribute

the function of the form_process_radios as given by the documentation is as follows

  Expands a radios element into individual radio elements.

So the out put you are getting is correct as per the documentation.

So in your case you dont need to call the form_process_radios. You can directly call the drupal_render function.


You can get around the error about the abstract method by using entity::loadMultiple, but you'll get a new error, because this only works from an entity subclass.

Instead of using the static method, you would have to do this dynamically:

First get all content entity types:

  $entity_types = \Drupal::entityTypeManager()->getDefinitions();
  $content_entity_types = array_filter($entity_types, function ($entity_type) {
    return $entity_type instanceof \Drupal\Core\Entity\ContentEntityTypeInterface;
  });
  $content_entity_type_ids = array_keys($content_entity_types);

Then load all entities for each type:

  $entities = [];
  foreach ($content_entity_type_ids as $type) {
    $entities[$type] = \Drupal::entityTypeManager()->getStorage($type)->loadMultiple();
  }


Adding taxonomy filter at the top of image gallery

You can create menu block with items/links which you need and then add this block into views header via Views block area module


View displays no results for roles without Bypass Content Access

Based on my experience user1 (admin) bypasses everything , no matter what permissions the role administrator has granted (check to believe) , so just because you can see something in a view as admin and having same permissions for administrator and another role does not permits users in that role to access what admin can.

so check to see what what permissions may lead to accessing this view , this permission might be unchecked for admin but still bypassing it.


Different ways of logging in a user without having them to type anything?

You just need to use drupal_session_regenerate(), you can see the use of this function here. All you have to do is either play with Uid or if you want to do this for anonymous user then you just create a user xyz and use that ID for session regenerate. You can grab the UID from URL for different users like www.example.com/custom-url-to-login/125 or www.example.com/custom-url-to-login?uid=125

now supposing 125 be the ID of user whom you want to login on visiting the URL.

The code will go something like this:

global $user;
$user = user_load(540); // suppose 540 be UID of xyz account
drupal_session_regenerate();

This is just a suggestion, if it does not work for you please let me the know the correct solution.

Thanks


array_flip() error while creating a menu item with form

The code that is causing the error is the following one, executed from DrupalDefaultEntityController::load().

  // Create a new variable which is either a prepared version of the $ids
  // array for later comparison with the entity cache, or FALSE if no $ids
  // were passed. The $ids array is reduced as items are loaded from cache,
  // and we need to know if it's empty for this reason to avoid querying the
  // database when all requested entities are loaded from cache.
  $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;

I could not track down which function is calling user_load() or a similar function to load a user entity. As far as I can see, the form validation and form submission handlers added to the form use $form['#user'] or $form_state['user'] (which is set from the $account parameter passed to user_profile_form()). Keep in mind that $form and $form_state are used when saving the entity, such as in the following function call done from user_profile_form_submit().

entity_form_submit_build_entity('user', $account, $form, $form_state);

It is always a bad idea to unset a form item, as that would be causing problems with the code that expects those form items to be present.
Removing them, you are also avoiding that the corresponding items in $form_state['values'] are present. This is probably causing the error you see.

As side note, your page callback is getting a parameter, but that is not used. Instead, your code is using the global user object, which means the shown form is for the currently logged in user, not for the user whose ID is passed in the URL.

I would also change user/%/edit/profile-preferences with user/%user/edit/profile-preferences. The latter automatically validates the user ID and loads the user object, which is then passed to the page callback.


So you have 2 queues walking all over eachother. The timeout value is how long the item is Leased to have work done upon it. The lease-time does not guarantee your processing will finish it time. A Leased item will not be able to be deleted until its lease has expired.

So you should analyze the tasks being run and adjust your timeout to be larger than the longest processing time you have recorded as occurring. I typically do a 2x or 10x as much Lease-time as my longest evaluated processing time. Once an item has completed processing its Lease is expired (so over guessing doesn't really hurt you here).

Alternatively, instead of having 2 queues you could do all this with 1 queue. To try to get around contention. You could insert into a single queue all your NIDs with an additional value of task; and at the end of that queue append a new list of NIDs with an additional flag value of delete or purge. Adjust your worker function to examine a NID and the action to perform on the NID; task or delete.

For example your createItem could look like:

// Add all NIDs for task to be performed.
$queue->createItem(array('nid' => $nid, 'action' => 'do-task'));
// in the same list later on queue the same NIDs to be deleted.
// by setting a huuuuge lease time you will never accidently purge an
// uncompleted task.
$queue->createItem(array('nid' => $nid, 'action' => 'do-delete'));

You may find working with a single queue -- easier than juggling 2 queues.


If you're not doing a traditional 3 column with header and footer site layout, then no - you probably won't get much out of something like Zen.

That said, you can still leverage the awesome Zen Grids gem with SASS and get the benefits Zen's grid system without any of the cruft from the base theme.

Anyone who has themed enough Drupal sites understands that you're going to be dealing with machine-generated HTML at some point (either from Views, or some other contrib module). You could spend a ton of time overriding all the theme functions to get the exact HTML you need so you can apply the col-xx classes your grid system of choice needs, or you can use the classes that already exist on the pre-existing markup and make them compatible with your grid with Zen Grid's mixins.

I like to say that Zen Grids acknowledges the reality of Drupal theming and comes up with a system that works with Drupal as opposed to against it.


How to support .dcm image format file for uploading in an article?

Unfortunately, it is not possible to allow image extension that cannot commonly displayed by a browser. You would have to use a filefield instead.

This has been discussed at:

https://drupal.org/node/1081060

https://drupal.org/node/1014816

And for D6 at:

https://drupal.org/node/515152


How to select an address field city from dropdown list?

Consider using the Select (or other) module. Here is an excerpt about it from its project page.

  Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

So basically you could "start" from a few cities (City 1, City 2, City 3), and whenever somebody needs another one (not in the list yet), they just enter "City 4". Here is a sample about it (just replace "Option" by "City" to get the idea):


How to compute and display value of some fields?

Have a look at the (fairly new) Math Field module (for D7). Some more details about this module (from its project page), which also details when the calculations actually happen:

  The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
  that does not require the use of PHP Filter.

  Math expression fields are dynamically updated via ajax on the entity form as soon as all necessary fields are populated. If JavaScript is disabled, the field will be evaluated when the form is submitted. The result is stored in the database when the form is submitted.

For more details (step-by-step instructions), refer to either of these links:

the (amazing!) Community documentation about the Math Field module.
the interesting article about Introducing the Math Field module, which also includes some screenprints to see it at work (such as the the add/edit form example).

Bonus: you would not need the "PHP filter" (IMO only that should be a valid reason to investigate this alternative) ...


In Drupal, most of the customization is not done by overriding existing code but rather by extension or alteration.  Most contribution modules and Drupal core provides extension points (hooks) and configuration variables. Your custom modules (self-created and client customization) should re-use these hooks and configurations.

For your self-created modules, you can use the Features module to easily export configurations into code. To customize your features at the client customization level, you can choice to either use alteration hooks or to re-write part of the Features-generated code to make it customizable via in-DB configuration. See http://developmentseed.org/blog/2009/jul/09/development-staging-production-workflow-problem-drupal and http://www.archive.org/details/CodeDrivenDevelopmentUsingFeaturesEffectivelyInDrupal6And7 for more information on the Features module. Also, the Kit Specification provides information on how to build re-usable features modules (with Features)., see also http://funnymonkey.com/building-features-for-install-profiles and http://nodeone.se/blogg/an-alternative-way-of-structuring-features-for-distributions.


What is the correct URI syntax for using Forena to connect to a Postgres database?

This worked for me:

host='somesite.comOR_IP' dbname='YourDBName' user='DBUsername'


How to print page/node templates being used on a page?

For Drupal 7, there's a new 'theme debug mode'. This eliminates the need for installing the Theme Developer module and its dependencies, if all you want is to see the templates being used on a page.

  As of Drupal 7.33, Drupal core has a theme debug mode that can be
  enabled and disabled via the theme_debug variable. Theme debug mode
  can be used to see possible template suggestions and the locations of
  template files right in your HTML markup (as HTML comments). To enable
  it, add this line to your settings.php:

$conf['theme_debug'] = TRUE;

see https://www.drupal.org/node/223440


What do you mean by content page? if it is the node page and the fields name are field_number_a and field_number_b then install entity module and in the template.php and in hook_preprocess_node function and write this:

function YourTheme_preprocess_node(&$var){
    if($var['node']->type == "YOUR_CONTENT_TYPE"){
          $wrapper = entity_metadata_wrapper('node',$var['node']);
          $a = $wrapper->field_number_a->value();
          $b = $wrapper->field_number_b->value();
          $var['total'] = $a + $b;
    }
}

Then in the node page you can use $total variable as the sum of the a and b


How do I add a link to an operations dropdown menu in views?

Add the following to your hook_menu in your module to add an operation to the dropdown pulldown of commerce orders.

$items['admin/commerce/orders/%commerce_order/<your operation>'] = array(
    'title' => 'Your Title',
    'page callback' => 'your_callback_for_the_operation',
    'page arguments' => array(3),
    'access callback' => 'your_access_callback',
    'access arguments' => array(3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 30,
    'context' => MENU_CONTEXT_INLINE,
);


Using different field template suggestion in different view mode

You can do it like so in your themes MYTHEME.theme file:

/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#bundle'] . '__' .
  $element['#view_mode'];
}

You can remove $element['#bundle'] but I left that in there, it will create new template suggestions so you can target view modes by node type instead of apply it to every teaser view mode of every node type.

You could just create two suggestions as well if you want:

/**
 * Implements hook_theme_suggestions_field_alter().
 */
function MYTHEME_theme_suggestions_field_alter(&$suggestions, array $variables) {
  $element = $variables['element'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#bundle'] . '__' .
  $element['#view_mode'];

  $suggestions[] = 'field__' . $element['#entity_type'] . '__' .
  $element['#field_name'] . '__' . $element['#view_mode'];
}

This will create new suggestions, as:

field--ENTITY--FIELD-NAME--ENTITY-BUNDLE--VIEW-MODE.html and field--ENTITY--FIELD-NAME--VIEW-MODE.html.twig, so you would have:

field--node--field-a--article--teaser.html.twig and field--node--field-a--teaser.html.twig to use.

Then, of course, the normal code in the field template works just the same:

{% for item in items %}
  {{ item.content }}
{% endfor %}

Now you can markup fields for view modes of all node types, or also override it for each node type.


How do I override the default sorting when filtering a view by Taxonomy terms?

Maybe the MySQL IFNULL() function could be the solution. It allows you to check the selected field value and give it a custom one when null.
In your SQL statement, instead of

node_data_field_important.field_important_value AS node_data_field_important_field_important_value

you should have:

IFNULL(node_data_field_important.field_important_value,0)  AS node_data_field_important_field_important_value

Try the modified SQL statement in your MySQL Query Browser and see if it works.

I'm an old database administrator, but a Drupal beginner, so I don't really know how to put this function in a View using the web interface. Do you?

I'm searching a way to add custom SQL to views (because as a beginner I'm interested too) and found something about hook_views_query_alter(). It belongs to Views 2 API.
You should use that hook to change the corresponding array value using your exported view code as reference for array indexes. I have no time to try it, but probably this is the right way.

IMHO another way should be taking the exported view code, modify it manually adding the IFNULL() MySQL function on the field name and then reimport it into a new view. I'm not sure that Drupal will write a correct SQL query or that it won't discard some SQL it doesn't expect... This should be the same as using the hook above, but in a rude and not to so elegant manner...

Hope it helps.


Is there a reason to be using \Drupal::database() vs \Drupal\core\Database\Database::getConnection()?

Yes. The former returns a correctly instantiated service object, with all required dependencies automatically injected. You would need to load up all the relevant services yourself and inject them manually if using the latter method.

  How do I know when I can chain my query methods and when I can not?

There are 2 common approaches:

Read the docs for the methods you're using.
Use an IDE with good code completion.


The key was using two functions: drupal_get_normal_path() and i18n_get_path_translations(). Inside hook_language_switch_links_alter() you can modify the href attribute of each language switcher.


How to determine the source (views/modules/blocks, etc) of content in different URLs?

If you are comfortable looking through your database directly, the quickest way to find out where $content is coming from is to look at the menu_router table and reference the path and page_callback fields.  For example, path node is generated (normally) by node_page_default and it creates the default front page.  Looking through this table you can see where all the other paths on your system are referenced.

As for where all the other content comes from, eg, all the blocks in other regions of the page, there you have to look around through the blocks table and look at the various information there, eg, module and delta say which module creates the block and which one it is, region says where on the page it will be put, and pages have any restrictions as to what pages the core block module knows about.


I have used both Ember and Backbone along with Drupal - but not in the way you would think.
Ember and Backbone are both fine tools to create a web application - but Drupal is not really a good tool to be used along with them. What you desire when you built a web app is something light and fast. You want it to be fast to be able to give your users the feeling if immediate  response times. You want it to be light to make it scale better. Drupal is not fast - the full Drupal bootstrap takes a long time (compared to a lot of other options) if all you want to do is provide a REST API for your web app. Drupal is PHP, which also makes it quite RAM hungry limiting the number of concurrent users.
So if Drupal is so bad for this why use it?
You should really use Drupal for what Drupal excels at - a CMS. What I've done in the past with projects that needed a web app is to use Drupal to create the CMS around the web app. To build stuff like blogs, content lists and the likes. I also created modules to define some backend stuff - like schema definitions, and other stuff where it made sense to use Drupal - because it made my development much easier.
Instead of using Drupal to create the REST API that the webapp needed - I used Node.js to create the actual REST API and other checks AJAX calls that the webapp needed to make. Node.js excels in doing just this. It's blazing fast (response times as low as 30ms for a list of objects). It's also very lightweight, since JavaScript on the server uses asynchronous actions, a Node.js server can usually handle thousands of concurrent users where PHP can handle maybe 100. In addition to that - since Node.js is JavaScript, you can reuse a lot of the code server and client side. You can literally write the same validation code, instead of having to implement both client side in JavaScript and server side in PHP. If you are going to Drupal con in Münich in a few weeks - you should consider watching the node.js presentation.
So if you are a developer, I would strongly recommend doing a similar setup, and only use Drupal for what it is really good at. If you want to make a simple webapp and you don't expect a lot of user, using Drupal as a backend could be an option if it helps your development time.

Update Drupal 8
So with the release of Drupal 8 some of the above still holds true but not in the same extend as earlier. Drupal 8 is like Drupal 7 not a light weight tool, like Node.js, Rails, Django etc. Since JavaScript apps mainly consume various services, you still should consider if Drupal is the best tool for this.
With Drupal 8 a lot of things have been improved. Services is a lot more native, with Symphony driving the request/response. Drupal 8 has a lot of interesting possibilities with with the advanced caching and all of the great features. But even with all of the greatness of Drupal 8, it still is a lot heavier than light weight applications. It's hard to tell how successful Drupal 8 can be used as a fast webservice provider.
So still, with all being said and done, my general recommendation stays the same. Being a Drupal developer, it's easy to use Drupal for everything, since we're familiar with it. It feels safe and Drupal can be used for just about anything. Remember while it's possible to use Drupal for anything, it doesn't mean that it's the best tool for everything. Doing a sound analysis and understanding the strengths and weaknesses of the tools you want to use on an IT project, will always be a great help and can help you avoid ending in a deadlocked position with a result that doesn't live up to your expectations.


How to detect the newness of messages created with the Message module?

I ended up using a custom module with a table containing two columns: uid and lastaccess and two simple functions.

function notifmger_views_post_render(&$view, &$output, &$cache){
    if ($view->name == "notification" && $view->current_display == "page_1"){
        global $user;
        $check = db_query("SELECT * FROM notifmger WHERE uid = :uid",
            array(':uid' => $user->uid))->fetchCol(1);
        if (!empty($check)){
            $update = db_query("UPDATE notifmger SET lastaccess = :time WHERE uid = :uid", array(":time" => time(), ":uid" => $user->uid));
        }
        else {
            $insert = db_insert('notifmger')
            ->fields(array(
              'uid' => $user->uid,
              'lastaccess' => time()
            ))->execute();
        }
    }
}

function notifmger_counter() {
    global $user;
    $msgs = db_query("SELECT count(*) FROM message LEFT JOIN notifmger ON notifmger.uid = message.uid WHERE message.uid = :uid AND message.timestamp > notifmger.lastaccess AND message.type != :type", array(
        ":uid" => $user->uid,
        ":type" => "user_tagged_self"))->fetchCol();
    if ($msgs[0] != 0){
        return $msgs[0];
    }
    return NULL;
}


drush: How to upgrade to a stable module release instead of dev?

pm-updatecode (and pm-update, which calls it) will not ever switch from dev to stable.  If you're on a dev branch, and want to go to a stable release, use pm-download.  For example:

drush pm-download somemodule-7.x-1.2

OR

drush pm-download --select somemodule

Make sure that the stable release is newer than the dev release you are running, and then run drush updatedb.