How can I print the number of the current pager in Views template?

Global: Result summary is what you're looking for.

Simply add it into your HEADER or FOOTER wherever you need and then you're requirement is done.

$view = new view();
$view->name = 'demo';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Demo';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Demo';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Footer: Global: Result summary */
$handler->display->display_options['footer']['result']['id'] = 'result';
$handler->display->display_options['footer']['result']['table'] = 'views';
$handler->display->display_options['footer']['result']['field'] = 'result';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'node';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['uid']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'page' => 'page',
);
/* Filter criterion: Content: Author uid */
$handler->display->display_options['filters']['uid']['id'] = 'uid';
$handler->display->display_options['filters']['uid']['table'] = 'node';
$handler->display->display_options['filters']['uid']['field'] = 'uid';
$handler->display->display_options['filters']['uid']['value'] = '';
$handler->display->display_options['filters']['uid']['exposed'] = TRUE;
$handler->display->display_options['filters']['uid']['expose']['operator_id'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['label'] = 'Author UID';
$handler->display->display_options['filters']['uid']['expose']['operator'] = 'uid_op';
$handler->display->display_options['filters']['uid']['expose']['identifier'] = 'uid';
$handler->display->display_options['filters']['uid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'demo/%';

/* Display: Attachment */
$handler = $view->new_display('attachment', 'Attachment', 'attachment_1');
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);
$handler->display->display_options['attachment_position'] = 'after';
$handler->display->display_options['inherit_exposed_filters'] = TRUE;


Keeping the  part in the CKEditor and removing everything else

Drupal's text format has an option for "Limit allowed HTML tags," in which you can specify which tags you would like to keep. You could always create a list of tags you use in your emails. If you exclude the html and body tags, that might work for you.

Another option is you can simply write your own text filter. You'll need to implement hook_filter_info.

Basiclly you would want something like:

function my_module_filter_info() {
  $filters['filter_name'] = array(
    'title' => t('Some Nice Filter Name'),
    'description' => t('Filter out stuff'),
    'process callback' => "your_filter_function",
    'cache' => FALSE,
   );
   return $filters;
  }

Then it's just a issue of writing your filter function.

function your_filter_function($body_text){
   //do stuff to your body_text to remove the tags you want to remove
   return $body_text
}


After some trial and error, I have been able to find a solution.

In the example code for hook_views_data(), there was a relationship example that provided this snippet.

// ID of relationship handler plugin to use.
'id' => 'standard',

Having already discovered the EntityReverse class, I was pretty sure that I would need to use 'id' => 'entity_reverse'.

The part that tripped me up the most was that I was trying to define the relationship as part of the related entity inside getViewsData() in the ViewsData class I created for the related entity.

Then it dawned on me that the documentation for hook_views_data() says:

  The return value of the getViewsData() method on the interface is the same as this hook

It means I can describe views data for any table and not just my entity's tables. Instead of trying to attach this relationship to the related entity, I tried attaching it to the main entity and this worked.

For example,

{MAIN ENTITY} is the entity being related
{RELATED ENTITY} is the entity with a relationship to {MAIN ENTITY} where {RELATED ENTITY} class has the following fields

   $fields['{FIELD NAME}'] = BaseFieldDefinition::create('entity_reference')
     ->setSetting('target_type', '{MAIN ENTITY}')
     ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) // or a specific number higher than 1

The getViewsData() method of the ViewsData class for {RELATED ENTITY} is the following.

public function getViewsData() {
  $data = parent::getViewsData();
  $data['{MAIN ENTITY BASE TABLE}']['{useful non-conflicting name - I used the {RELATED ENTITY BASE TABLE}}'] = [
    'title' => t('{some useful title that displays in Add Relationships popup}'),
    'help' => t('{some useful description that displays in Add Relationships popup}'),
    'relationship' => [
      'field_name' => '{name of the field - same as {FIELD_NAME}}',
      'field table' => '{name of intermediary table - it is probably {RELATED ENTITY}__{FIELD NAME}',
      'field field' => '{name of intermediary field - it is probably {FIELD NAME}_target_id',
      'base' => '{RELATED ENTITY BASE TABLE}',
      'base field' => '{RELATED ENTITY ID FIELD}',
      'id' => 'entity_reverse',
      'label' => '{some useful label that displays in Relationship select in various views field settings popups}',
    ],
  ];

  return $data;
}


I am afraid you will have to write custom code in this situation to get this done.
What you can do here is create tpl file for your view with format as table and then in that tpl you can have your condition to make a table inside td.

You can fetch your views fields in tpl inside foreach ($row as $field => $content)

Make sure you have all the fields in your view which you want to display in table format.


Why do all product display nodes with same referenced product (SKU) appear in 1 order view

It's a result of your relationships: you're connecting each order item to the product it represents and then each product to each node that references it. Because of the way that database query works, it returns a unique result for every combination and renders them into your View.

Judging by your View's configuration, this was the simplest way for it to include the course type, teacher, etc. fields from the node. You're going to have to filter the result set somehow ... unfortunately, the data you need to be able to do that (the add to cart context from the $line_item->data array) isn't exposed to Views.

To see how that array gets built, check out commerce_cart_field_attach_view_alter(). You have two basic options for that data: create a custom Views filter that will allow you to filter the result set of your Views based on the values in the $line_item->data['context']['entity'] array or else remove the relationship from the View and switch to rendering the line item using a custom view mode, loading the data you need from the related entities manually.

(Note: I was going to suggest that if you only have one active node selling each product at any given point in time (unclear from your question), you could just add a filter to your View that checks to ensure the node referencing the product is published. That would get rid of the duplication but screw up your historical orders who now appear to show the wrong content.)


What is the safe way to update to latest version?

In theory you should update to the latest recommended version of your current site's minor release. So in this case you should update to version 8.9.13 then you should be good upgrade. Remember to also make sure you do the same for all contributed modules and themes.
You might find using the Upgrade Status module helpful before upgrading.
As with everything you do, make sure you create a full backup of the sites files and database/s before attempting any updates.


<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{HTTPS} off
        RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    </IfModule>
    <IfModule mod_headers.c>
        Header always set Strict-Transport-Security "max-age=31536000; $includeSubDomains"
    </IfModule>

Is what you are looking for. Make sure to place these rules before any other rewriting rules (that may e.g. come from your webserver config).


Is it still a partial port or does it take a different approach?

It looks like you've forgotten to install one of the modules that implement panels.
From: drupal.org/project/panels

Panels in Drupal 8
We’re actively working on Panels for Drupal 8 which works with the new layout_plugin module and mainly is an interface to configure and store these layouts.
Panels is an API in Drupal 8
In order to use panels, you must use an implementing module. Currently, Page Manager and Panelizer implement panels.
If you’re interested in following the Drupal 8 port in detail, follow #2169319: [meta] Drupal 8 port of Panels in the issue queue OR join us on IRC every Tuesday at 12 noon CDT (UCT-0500) in the #drupal-scotch channel for our weekly meetings.


Change plid of existing administration menu items

If you want your own top level admin menu group, you should probably create your own parent menu item and section there using hook_menu

e.g admin/website and put your menu items under that.

/**
 * Implements hook_menu
 */
function my_module_menu(){

  $items = array();

  // Provide own admin configuration menu section
  // using system_admin_menu_block_page for item groups
  // Top level section
  $items['admin/website'] = array(
    'title' => 'Website',
    'description' => 'Local website configuration.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child admin menu group
  $items['admin/website/config'] = array(
    'title' => 'Configuration',
    'description' => 'Configure website settings.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 50,
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child group menu item
  $items['admin/website/config/advanced'] = array(
    'title' => 'Advanced settings',
    'description' => 'Configure advanced website settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_website_settings_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/my_module.admin.inc',
  );

  return $items;

}

See system_menu for an example hook_menu using system_admin_menu_block_page


You should not have used List as your field type, you need to use Date as your field type. Using the Date module and enable Date UI and Date Views.

Then in MORE SETTINGS AND VALUES, Date Entry, select Custom Format and put F Y

Now in Views for filter add your date filter, in my example my Date field is called kewl

then use is in between previous month and next month


Question is, the profile field of which user? The node author, or the current user?

In both cases you need to fetch the $account you are trying to pass to field_view_field.

For the current user:

global $user;
$account = user_load($user->uid);

For the node author:

$account = user_load($form_state['node']->uid);


jQuery_ui slider doesn't load for anonymous user

I found the quick answer : Add this line in the module using jquery_ui to call jquery_ui when needed.

drupal_add_js('https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js', 'external');

or this:

drupal_add_js(drupal_get_path('module', 'jquery_update') .'/replace/ui/ui/minified/jquery-ui.min.js');

The question now is : is this the best way?


Drupal 7 default Forum styling for custom content type?

By 'have the same styling', I'm assuming what you mean is have the same structure and functionality as the Drupal core forum (i.e. threaded discussions). You can always modify the content template to match the same layout and css styling of the core forum module but just enabling comments won't give you the same functionality as forums. The forums module uses comments but adds another layer of management on top which is where you get your threaded discussion. A comments-only content-type would also not integrate with forum add-ons like Advanced Forum.

You're best option is to create two distinct forums and then (as @frazras notes) use Forum Access module to control access based on your criteria.


Cannot access data passed to $vars in theme function

OK, it looks as though you're using the $badge variables in a more general parent/container views template, when the $badge variables are added in a child template preprocess function. The tpl variables aren't available at that container point.

The solution is to implement

hook_preprocess_views_view

and add the badge data vars there instead.

e.g

THEMENAME_preprocess_views_view(&$vars){
  if (isset($vars['view']->name)) {
    switch($vars['view']->name){
      case 'badge_owners':
        if($vars['view']->current_display == 'page_1'){
          // Rename current function to this
          THEMENAME_preprocess_views_view_badge_owners_page_1($vars);
        }
      break;
    }
  }
}


How to theme simplenews newsletters in D7?

This happens because this is the default HTML to Plaintext conversion that Drupal is applying to all mails.

If you don't want this, either adjust the templates (you can find them in the theme folder, just copy to your theme and start adjusting it) to avoid HTML or enable a module like Mime Mail that allows to send HTML formatted mails.

No idea why the title is cut off.


Definition join on field and where other field has value

Drupal has an extra field in the join in which you can inject the extra where conditions, you can get to it by using a views_query_alter:

function my_module_views_query_alter(&$view, &$query) {
    if ($view->name === 'my_view' && $view->current_display === 'the_display') {
        $args = $view->args[0];
        $query->table_queue['my_joined_table']['join']->extra = array(
            array(
                'value' => $args, // pass the args through
                'numeric' => FALSE, // or true if it is
                'field' => 'the_field',
                'operator' => '='
            ),
        );
    }
}


Returning alternate HTTP codes for unpublished node

You can try to do this earlier in an exception instead of a response subscriber. Extend HttpExceptionSubscriberBase, so you need less code to do this. Then replace the 403 with a 404 exception with the method $event->setException()

/src/EventSubscriber/Unpublished404Subscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Unpublished404Subscriber extends HttpExceptionSubscriberBase {

  protected static function getPriority() {
    // set priority higher than 50 if you want to log "page not found"
    return 0;
  }

  protected function getHandledFormats() {
    return ['html'];
  }

  public function on403(GetResponseForExceptionEvent $event) {
    $request = $event->getRequest();
    if ($request->attributes->get('_route') == 'entity.node.canonical') {
      $event->setException(new NotFoundHttpException());
    }
  }

}

mymodule.services.yml:

services:
  mymodule.404:
    class: Drupal\mymodule\EventSubscriber\Unpublished404Subscriber
    arguments: []
    tags:
      - { name: event_subscriber }

This replaces all 403 exceptions for canonical node routes. You can get the node object $request->attributes->get('node') if you want to check if this is really because the node is unpublished.


You can use user/[current-user:uid]/edit once you have the menu_token module installed.


First, there's a typo. It's not attachment, it's attachments.

Next, you can't simply call a function without defining it.

In Drupal hooks are used to modify existing code when it's being processed.

See hook_page_attachments_alter for an example of what you are supposed to do.

Using hooks, you simply define a new function prefixed with your module's machine name, put your code/alterations in there, and in the end it's automatically being hooked up for execution. No need to call it again.

function hook_page_attachments_alter(array &$attachments) {

  // Conditionally remove an asset.
  if (in_array('core/jquery', $attachments['#attached']['library'])) {
    $index = array_search('core/jquery', $attachments['#attached']['library']);
    unset($attachments['#attached']['library'][$index]);
  }
}


How can I set a View contextual filter fallback?

Ok, decided to write my own context condition plugin for this, all in a single file for a custom module that would be called custom_context:

function custom_context_context_registry() {
  $registry = array(
    'conditions' => array(
      'views_result' => array(
        'title' => t('Views Results'),
        'description' => t('Set this context when one of these views returns a result.'),
        'plugin' => 'custom_context_condition_views_result',
      )
    )
  );
  return $registry;
}

function custom_context_context_plugins() {
  $plugins = array();
  $plugins['custom_context_condition_views_result'] = array(
    'handler' => array(
      'class' => 'custom_context_condition_views_result',
      'parent' => 'context_condition',
    ),
  );
  return $plugins;
}

function custom_context_init(){
  if ($plugin = context_get_plugin('condition', 'views_result')) {
    $plugin->execute();
  }
}

class custom_context_condition_views_result extends context_condition {

  /**
   * Generate a list of database and module provided views.
   */
  function condition_values() {
    $enabled_views = array();

    $views = views_get_all_views();
    ksort($views);

    foreach ($views as $view) {
      if (!isset($views[$view->name]->disabled) || !$views[$view->name]->disabled) {
        $displays = array();
        foreach ($view->display as $id => $display) {
          $displays[$view->name . ":" . $id] = check_plain("{$view->name} : {$display->display_title}");
        }
        $enabled_views += $displays;
      }
    }
    return $enabled_views;
  }

  function execute() {

    $view_name_displays = array();

    // Gather all required views for checking, to prevent duplicate checking
    foreach ($this->get_contexts() as $context) {
      foreach ($context->conditions['views_result']['values'] as $view_name_display){
        $view_name_displays[$view_name_display] = $view_name_display;
      }
    }

    foreach($view_name_displays as $view_name_display){
      list($view_name, $view_display) = explode(':',$view_name_display);
      $view = views_get_view($view_name);
      $view->set_display($view_display);
      $view->build();
      $view->execute($view->current_display);
      if(count($view->result)){
        foreach ($this->get_contexts($view_name_display) as $context) {
          $this->condition_met($context, $view_name_display);
        }
      }
    }
  }
}

Just to explain how this works, it loads all the views which context module should check on hook_init and checks whether each view has rows or not. I've combined this with certain views which obtain their contextual filters from the current node ID.


Varnish doesn't cache first hit at all, only second hit

It looks like a normal behaviour :

first url hit : Varnish puts the page in cache with some id
only following hits will serve the cached id instead of querying the backend.

If you want anonymous users to be always served by varnish, you need to implement a cache warmer logic.

Setup a sitemap. Then create a cron task that will parse the sitemap with curl for instance,  and run that cron task at a frequency synced with your cache expiry time...


Access custom theme settings from within views

Just for other people who come across this here is the answer:

<?php print theme_get_setting('tm_qrule_url'); ?> works using the views_php module

It doesn't show in the views preview but does in the actual page load.

Thanks goes to @sheena_d for helping with this.


Last time I encountered such thing, it was on Drupal 8. The culprit was caching. In a gist, if the page was viewed by a user who doesn't have access to that menu and that result gets cached, the page will be served from cache (without that menu) until the cache is cleared. Might want to disable page caching, then block caching, in admin to verify this. If you have any other caching mechanisms, try disabling those too. A good indicator that this may be the case is the fact that you need to clear an external cache for one of your setups.

Another culprit would be template-side logic (template.php or directly on the templates themselves). Since you're using D7, it's relatively easy to sneak in PHP into templates. You might want to review your templates for this.

Lastly... there's JS and CSS. You might want to do a View Source to see if the markup is actually there, but just removed by JS or hidden by CSS. Due to Drupal's steep learning curve, it's very tempting to just do everything in JS and CSS. Also, if the menu is dynamically generated or enhanced by a script, a broken script might have interfered with that generation/enhancement.


how to use a relative path with form API image_button?

You need to define an absolute path, a relative path won't work. But you can use the drupal_get_path() method to retrieve the path to your module, so you don't have to worry about where it will end up in the filesystem.

For example:

$image_path = drupal_get_path('module', 'mymodule') . '/images/show-my-score-button.png';


Thank you all.

In the end I added a new field to the user as Jimajamma suggested, which counts the number of state (active) nodes that user has. I used Rules to add and subtract from the number to keep it current. Views then filters, only reporting on users with 0 state (active) nodes.


Where does drupal_mail() get the return-path and sender?

drupal_mail() gets the value for those headers either from the the value of the site_mail persistent variable (set in admin/config/system/site-information), or from the sendmail_from setting found in php.ini.

The first line of drupal_email() show exactly how the default value for the sender is set.

$default_from = variable_get('site_mail', ini_get('sendmail_from'));

This is then the code that sets the email headers.

  if ($default_from) {

    // To prevent e-mail from looking like spam, the addresses in the Sender and
    // Return-Path headers should have a domain authorized to use the originating
    // SMTP server.
    $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $default_from;
  }
  if ($from) {
    $headers['From'] = $from;
  }
  $message['headers'] = $headers;


Fixed number of digits from Token module random number

You could use modular arithmetic.

$token_random; // This is the value returned from the Token module
$my_random = ($token_random % 9999);

Or if you need the 3 digit value:

$my_random = ($token_random % 100);


Give a try to Migrate module that is for Drupal 7 and comes as part of Drupal 8. It can import comments. You might also be interested in reviewing all migrate tools listed on https://www.drupal.org/docs/8/upgrade/drupal-8-migrate-modules


If you want to theme contact form then you can do it using  hook_form_alter().

Use hook_form_alter(&$form, &$form_state, $form_id) in your theme's template.php and alter the form the way you want to theme it.


how to add .install file to the new feature folder?

If you stay out of the files that Features generated, you can add code to the (Features generated) module the way you normally do things.

The problem is that your module is already installed when you're adding the schema via .install. You'll need to implement hook_update_N and add the tables using db_create_table. Run update.php or drush updatedb and your schema should be created.


How to restrict a module to a specific core version?

Using core only supports the major version, but you can add a dependency on the system.module with a specific version.

dependencies:
 - system (>=8.3)

Due to a bug in version parsing, you can only do this with the minor version. You can't specify a patch release like 8.3.1.


Are you certain that the path sites/default/files/galerii_imagini  exists and is a directory? You could see this error either if it doesn't exist or if it exists but is a file instead of a directory. If you expect Drupal to create the galerii_imagini directory, you need to add this line before your call to file_copy:

file_prepare_directory("public://galerii_imagini", FILE_CREATE_DIRECTORY);

Based on a search of the Drupal 7.x source code, the message File %file could not be copied, because the destination directory %destination is not configured correctly. is only ever produced in file_unmanaged_copy, which is called by file_copy. It calls file_prepare_directory first on the destination as passed to file_copy, then on its parent directory. It produces the error message you're seeing only if both calls fail. Since it calls file_prepare_directory with default flags, it can fail with that message if:

neither the destination path nor its parent directory exists
the destination path does not exist and its parent directory exists but is not a directory
either the destination path or its parent directory exists, is a directory, is not writable, and changing its permissions to make it writable failed

In the last case, however, you would see another message in the log immediately before the one you reported in your question: The file permissions could not be set on %uri. Since you haven't reported seeing that message, I can only assume that one of the first two cases is correct.


Need help or idea on how to setup a Drupal site on a given scenario

For the second objective instead of adding the actors to the movie, since you already are going to add movie appearances to each actor, make those movies taxonomy terms.  Then when you want to make a cast page for a movie, just display all of the actors that have that taxonomy term (the movie name) associated with it.


How do you target a specific type of content?

You need to configure your moderate_node flag in either the UI or in configuration management.
In the flag module, a flag entity is defined by the entity type (i.e. node) and bundles (e.g. article, page, recipe) that are allowed on it. If no bundles are specified, then all bundles are allowed.
In your example code, $flag->getBundles() method will return the bundles that are allowed (empty means all). Once set, the $flag_service->flag method will kickback exceptions if you try to flag bundles that do not apply to that flag. You'll need to adjust the code accordingly to handle those scenarios.


How to find the origin of variable in Drupal

Looks like you should debug the code not in theme but in the module.

I assume you use the metatag module. It adds all the metatags in metatag_html_head_alter().

Check what is your front page. If it is a View of a Panel, metatags are handled in a different way.

In the metatag module you can specify separate tags for the front page - check this setting. It might override your content metatags.


How to display the replies count of the each user comments with show/hide option in node view page in Drupal 7?

I tried to solve your problem . The best way to solve this is to create a new CUSTOM MODULE.
 - Create a new folder in Your sites/all/modules folder custom_module name could be anything.

In folder create two files custom_module.info and custom_module.module and  a folder js . In that folder create a .js file custom_module.js .
So now you .js file will be located at sites/all/modules/custom/js/custom_module.js . Now Go to custom_module folder and in custom_module.info file add the lines of code..

name = Custom_module
description = Displays total count of replies to a comment and add display toggler to the replies of the comment.
core = '7.x'
version = '7.x-1.x'
dependencies[] = comment

Now in your  custom_module.module file

<?php
drupal_add_js(drupal_get_path('module','custom_module') '/js/custom.js');
function custom_module_preprocess_comment(&$variables) {
  $query = db_query('SELECT COUNT(*) FROM comment WHERE pid = :cid', array(':cid' => $variables['id'])) ;
  $result = $query->fetchField();
  $variables['content']['links']['comment']['#links']['comment-reply']['title'] = 'reply  ('.$result.') Show';
}

So what the module did is fetched the total no of replies of a comment from the database and appended them to reply link.
A Simple jQuery file will get you what you wanted. Edit your js/custom_module.js file custom_module.js file

(jQuery)(document).ready( function() {
  jQuery('div.indented').css('display', 'none');
  (jQuery)('div.comment .comment-text ul li.comment-reply span').click( function() {
    if(jQuery('show-hide').html()=='Show') {
      jQuery('show-hide').html()='Hide';
      (jQuery)(this).parents("div.comment").next().slideToggle();
    }
    else {
      jQuery('show-hide').html()='Show';
      (jQuery)(this).parents("div.comment").next().slideToggle();
    }
  });
})(jQuery);

Click On Show in Comments and it will toggle . I have also added a screenshot..

SHOW
.

HIDE


hook_theme, custom data, passing to custom TPL file

Doh. $variables is passed by reference. I always forget this in template.php:

function satb_preprocess_satb_schedule_brackets(&$variables) {


Custom VBO Action only works when enqueued (Adding User Role and Organic Group)

If anybody runs into this in the future, I had to pass the group id into the og_user_node field and save the user after calling og_group():

$values = array(
    'entity_type' => 'user',
    'entity' => $user,
    );

og_group('node', $group->nid, $values);
$data['og_user_node']['und'][0]['target_id'] = $groupid;
user_save($user, $data);

You should check for any other groups the user is in and create an array of groups along with the new group id and save that into og_user_node, but in my situation, users are only allowed in 1 group, so this takes care of putting them in the new group and removing the old one.


Is FIELD COLLECTION VIEWS module only for showing data in table format?

At admin/structure/types/manage/[node-type]/display/full changed the view mode for my field_collection where format = "Table of field collection items". The view mode setting is ignored, as viewing the original node still shows all fields as configured in the "Full content" display mode.

field_collection_table.patch


Show node body fields for entity reference checkboxes widget?

You may want to try Entity Reference View Widget.

  This module provides an advanced Entity Reference widget that uses a
  view for selecting items. The view can be paginated and have exposed
  filters. It degrades, so it can be used even if Javascript is disabled


Mutlti level filter with search api and facet in commerce kickstart

It sounds like you need to enable the "Expand Heierarcy" option under Facet Display settings (for the search index you are working with).


You enable the field by adding a widget to the default form display mode:
$display_repository = \Drupal::service('entity_display.repository');

// Assign widget settings for the default form mode.
$display_repository->getFormDisplay('node', 'mybundle')
  ->setComponent('field_desc', [
    'type' => 'string_textfield',
  ])
  ->save();

See Add content type field programmatically


Export multilingual settings with features

Yes, you can do this with Strongarm.  You'll want to add all the variables that are prefixed i18n_, language_, and locale_.


How to convert Content Type Title into Term reference?

Title Field UI might work for you. I haven't used this module, but apprently it allows you to modify title fields. Not sure if it will allow you the change the type from text to term reference. Although, you can always disable titles and use another term ref field as your title.


List of User's Comments - show one latest comment on node only

I would use the Views Field View or a similar module for this.

The reasons is that you are trying to filter on two things:
* Most recent comment
* Unique node

I would create a "parent" view that shows all nodes the user has commented on and then a "child" view that filters the comments on each node to show the most recent one.

See my detailed answer here to a question about getting the latest node per user.

An alternative is to play around with Views aggregation settings.


How can I show an image in a view using the Search API Views integration?

You're on the right track. To achieve this in Views:

Add the indexed image field to the View Fields list
Set 'Display' to 'Show entity label'
Untick 'Link to entity' - this adds additional HTML in the token used below that will stuff things up
Select 'Rewrite output of this field', and use this code:

<img src="/sites/default/files/[field_files_file]" />

Check the token is right, under 'Replacement tokens', but this should allow you to render the image into the View output.

From here, you can specify any inline attributes you want, e.g. width, height and so on.

You could achieve a thumbnail look this way, or alternately you could use image styles to generate a thumbnail of the image your users upload, then index that field instead. Note that image styles will save your new image under a different directory, so sites/default/files won't work.


All you need to do is set up the exposed filters and then click Exposed form in block in the Basic Settings. This will then give you a block to use.


Views is the way to go. Create a view with a block that lists articles, add a contextual filter to the user id and configure it to provide a default argument from the url. Then add that block to the user profile page, you should be set.


How NOT to redirect using the Rules module?

A possible "remedy" for this is to use the Rules module (indeed ...). To do so, have a look at my answer to "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?".

Use the rule included there (within "Option 1"), and apply these changes to it:

Adapt the regular expression within the "Rules Condition", to make it match your (user/[uid]/comments.).
Adapt the "no_access" url to your user/[uid].
Probably you don't want to display any message, so just remove that "Rules Action".


Reordering values in a multi value field

If you need to do this in the context of adding/editing nodes, Drupal 7 core provides this functionality on node add/edit pages.


Multiple Date Argument Values with One Contextual Filter

Try with the following method using views_embed_view():

views_embed_view('viewname', 'display_name', array(123,'201302+201303'));

Or by using a hook_views_query_alter and modifying the where condition to span across both months.


How to implement a set of images / diagrams in a website?

To answer your question, I think it depends on how you plan to use those images ...

Option 1: use individual images to beef up specific content pages

In this case you just upload those images to a folder such as sites/default/files, and then you could just use them (refer to them) with a typical img tag. To make sure that these images will actually also be rendered (when viewing the page), make sure that the "text format" used in the node does allow the img-tag. Typically for a node using the "Filtered HTML", it could well be that the img-tag is not allowed (yet) as one of the available HTML tags. In that case, your HTML code does include an 'img" tag, but when viewing the saved node the image is not rendered (visible). To resolve it, within admin you must enter the img-tag as one of the allowed HTML tags for the text format used in the node.

Option 2: visualize them in the format of a Gallery

Talking Drupal #083 is a great podcast about this topic, and includes a lot of recommended modules in this areas. Just to mention a few of them (mentioned on the linked page):

  Gallery formatter - https://www.drupal.org/project/galleryformatter
  Views Slideshow - https://www.drupal.org/project/views_slideshow
  Flexslider - https://www.drupal.org/project/flexslider
  Node Gallery - https://www.drupal.org/project/node_gallery
  Multiupload  Filefield Widget - https://www.drupal.org/project/multiupload_filefield_widget
  Multiupload Imagefield Widget - https://www.drupal.org/project/multiupload_imagefield_widget
  Field Focus - www.drupal.org/project/imagefield_focus
  pl upload - https://www.drupal.org/project/plupload


Clean URLs with multi-site only with suffixes / sub-folders

think you will require a separate virtualhost entry for each of the sub-sites.  That should direct visitors to the correct location and negate any need for redirection.

At the moment you're using aliases to effectively send all traffic to the same place, I think using virtualhosts will separate the traffic a bit better and help you turn on clean URLs.

I'm going to assume your core Drupal files are at /var/www/html.

You definitely need to read the documentation in /var/www/html/sites/sites.php and set that up if you haven't already.
You do need to set the $basepath in each site's settings.php
In Apache it kind of depends what OS you're using but you basically want to turn on NameVirtualHost in Apache and then tell it where to send visitors:

Here's how to do it in Ubuntu
Here's how to do it in CentOS which probably also translates to RHEL/Fedora

Those links give the full setup, so you've probably already done the first few steps.  Keep going down the page to find the Virtual Host section.

Finally, clean URLs need to be enabled in each of your sites, one by one.


override views-view-fields.tpl.php in custom module

You need to define a theme hook for the field-template in your module and place a template in custom_module/theme/your-custom-template.tpl:

/**
* Implementation of hook_theme().
*/
function custom_module_theme($existing) {
  return array(
    'views_view_field__view_name__field_name' => array(
    'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
    'template' => 'your-custom-template',
    'original hook' => 'views_view_field',
    'path' => drupal_get_path('module', 'custom_module') . '/theme',
   ),
  );
}

To narrow down which field-templates you want to replace you can name your return key to:

views_view_field__view_name: Override all field templates of the view named "view_name"
views_view_field__view_name__field_name: Override only this specific field

This example is taken from grayside.org


Implementing preprocess function for custom template

I tried your thing on my local server. And its working fine. Just try in your template:

<?php
  // Print your defined variable here like this.
  print $title;
?>


how to set value of autocomplete field and trigger search event with jquery

Looking in misc/autocomplete.js, there's a function called populatePopup() (Drupal.jsAC.prototype.populatePopup). Since that function is bundled into the jSAC object, we can't call it directly. Instead, let's simulate the event that calls it which is found in the onkeyup() function.

<script>
/**
 *  Fill an input field and then display the autocomplete popup.
 *
 *  @param $field
 *    This is a jQuery field reference -- e.g. $('#my-input-field')
 *  @param searchVal
 *    The text to place into the input field
 */
function ShowAutoComplete($field, searchVal) {
  var e = $.Event('keyup'); // Create an event to trigger
  e.which = 32; // Add the keyCode (32 is a space, but it shouldn't matter)

  // Set the field value, focus on the field, then trigger the event
  $field.val(searchVal).focus().trigger(e);
}
</script>

FYI, I used this post as a reference to figure out how to fire the keyup event.


How can I make a view to show all own comments?

Follow below steps to create a view.

Login as admin
Go to admin/structure/views/import
Copy paste below code in "Paste view code here"

$Below code

$view = new view();
$view->name = 'user_forum_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'User Forum Comments';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE;

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'User Forum Comments';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Comment: Author uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'comment';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'default';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'current_user';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status_node']['id'] = 'status_node';
$handler->display->display_options['filters']['status_node']['table'] = 'node';
$handler->display->display_options['filters']['status_node']['field'] = 'status';
$handler->display->display_options['filters']['status_node']['relationship'] = 'nid';
$handler->display->display_options['filters']['status_node']['value'] = 1;
$handler->display->display_options['filters']['status_node']['group'] = 1;
$handler->display->display_options['filters']['status_node']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'nid';
$handler->display->display_options['filters']['type']['value'] = array(
  'forum' => 'forum',
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['path'] = 'user-forum-comments';

Click on Import
Go to user-forum-comments to see results
Go to admin/structure/views/view/user_forum_comments/edit to see how view is constructed.

Hope it answers :-)


Why won't this update in hook_update_n() run in batches correctly?

Why are you expecting it to work as a batch, it's doing exactly what you're asking it to do and processing all the importers in the foreach loop!  foreach ($importers as $importer)  It's not magic, it can't assume that's what you want to batch  :o)

Try this instead (obviously I haven't tested it, I've just typed it straight into the text editor here - but it's essentially your code so it should be fine);

/**
 * Fix importer mappings for file and image fields to use :uri convention.
 */
function feeds_update_7210(&$sandbox) {
  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['progress'])) {
    $sandbox['importers'] = feeds_importer_load_all(TRUE);
    $sandbox['progress'] = 0;
    $sandbox['max'] = count($sandbox['importers']);
  }

  $importer = array_pop($sandbox['importers']);
  $processor = $importer->processor;
  $config = $processor->getConfig();
  foreach ($config['mappings'] as $id => $mapping) {
    // Act on mappings that do not contain a colon.
    if (!strpos($mapping['target'], ':')) {
      // Get field data. Check if $info is empty to weed out non-field mappings like temporary targets.
      $info = field_info_field($mapping['target']);
      if (!empty($info)) {
        // Act on file or image fields.
        if (in_array($info['type'], array('file', 'image'))) {
          // Add ':uri' to fix the mapping.
          $config['mappings'][$id]['target'] = $mapping['target'] . ':uri';
        }
      }
    }
  }
  // Add the updated config and save the importer.
  $processor->addConfig(array('mappings' => $config['mappings']));
  $importer->save();

  $sandbox['progress']++;

  // Set the value for finished. If progress == max then finished will be 1, signifying we are done.
  $sandbox['#finished'] = ($sandbox['progress'] / $sandbox['max']);

  if (empty($sandbox['importers'])) {
    return t('@importers importers processed.', array('@importers' => $sandbox['max']));
  }
}

For hints about my alterations see the API documentation - note that the naming convention changes don't alter anything, I just made them for Drupal core consistency.  The most important thing to note is that all I've really done, is to remove the foreach loop so one importer gets used at a time.

NOTE: For clarification (as it's really not obvious) the percentage shown relates to the number of batch operations run - not the amount of passes through one batch operation.  See _batch_process():

// Total progress is the number of operations that have fully run plus the
// completion level of the current operation.
$current    = $total - $remaining + $finished;
$percentage = _batch_api_percentage($total, $current);

On a normal batch operation you'd pass in several separate operations like this;

$batch = array(
  'operations' => array(
    array('batch_example_one_process', array($options1, $options2)),
    array('batch_example_two_process', array($options3, $options4)),
  ),

And you'd see 50% completion only after batch_example_one_process has completed.  I guess you can see that your code is working correctly though, as it clearly only processes one processor per pass - as long as they all get processed, you can confirm that batch api is working correctly.


Is it possible to populate a field entity reference with query parameters?

To programmatically pass argument to my field entity reference with link node/add/page_interieur?dossier=512 :

use Drupal\node\Entity\Node;
use Drupal\Core\Form\FormStateInterface;

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id){

  if ($form_id == 'node_page_interieur_form') {
    $nid  = \Drupal::request()->query->get('dossier');

    if (is_numeric($nid) && isset($form['field_dossier_reference'])) {
      //autocomplete select field reference
      $form['field_dossier_reference']['widget']['#default_value'] = $nid;
      //disable field
      $form['field_dossier_reference']['#disabled'] = TRUE;
      //pass my ID like argument in my field to filter only pages referenced
      $form['field_liste_ref_dossier']['widget']['target_id']['#selection_settings']['view']['arguments'][] = $nid;
    }

    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
        $form['actions'][$action]['#submit'][] = 'science_po_page_interieur_form_submit';
      }
    }
  }
}

My contextual filter configuration in views :


This sounds like the kind of thing to Node References and the Node Relationships module in D6 or the References module for D7.  Both of those suggest other related modules that might helpful as well.


Retrieve hidden field value & expose to .tpl file

That could potentially break and it's pretty gnarly looking, so not the best, but I've been there!

Instead if you have the field_collection_item's ID you can do:

// I'd make a more meaningful name... like slider?
// If I understand your example, this should give you the entity Object for the field_collection_item
$entity = array_shift($items[0]["entity"]["field_collection_item"]);

$field_image_data = field_get_items('field_collection_item', $entity, 'field_image');
// I'm less sure here, it looks like the image is an entity and it has sub-fields?
// You'll probably have to dig through $image to see where the entity is kept, I'm guessing
$field_alignment_data = field_get_items('file?', $field_image_data[0]['#entity'], 'field_alignment');

// Now you should be at your field
// If safe_value exists, use that.
$alignment = $field_alignment_data[0]['value'];

This is annoying, but more legible. It's what happens when you have nested data objects, things just get kind of annoying.

The other option is you could make it a field that isn't hidden and use hide('field_alignment') in the tpl.php or template_preprocess_* function (guessing it'd be template_preprocess_entity?)


Render image field with custom image style in custom block template

This module is exactly what I need. https://www.drupal.org/project/field_image_style

:D


Commerce Address Book – need to reuse customer profile without address

It turns out that the Commerce Addressbook Extra module takes care of this. In case anyone else is searching after a smooth solution.
Link to module


Show Webform confirm message in my custom panel page

I guess the problem is that the Clientside Validation module shows the message in the default location defined in the template.

You can check Clientside Validation Usage. Then you can see Error Message placement and Default location. I hope you can tweak your default message location from this:

  Here you can select the default location to display your error
  messages. You can choose between the following options:

  jQuery selector: This option will place a div containing all the    error messages inside the div that matches the jQuery selector
  entered in the "jQuery selector" field below this option.
  Top of form: This option will place a div containing all the error messages    above the form the error messages are for.
  Before label: This option will place the error before the label of the matching element
  Afterlabel: This option will place the error after the label of the    matching element
  Before input: This option will place the error    before the matching element
  After input: This option will place the error after the matching element
  Top of first form: This option will    place a div containing all the error messages above the first form.    This means that when there
  are multiple forms on a page, the errors    of the second form will be
  added to the error div of the first form    and will be displayed
  above the first form
  Custom function: (Advanced) Selecting this option requires you to enter a javascript    function name in the textfield "Custom function
  name" below this    option. This function name will be given to the
  errorPlacement option    of jQuery.validate()

You could use jQuery selector or Custom function.


Using Ubercart Roles, there is an event defined to trigger on sending the user a notification that their role has expired. You can use that event to trigger a rule, or you can define a role expiration event if you wish to tie it to a discrete event rather than the sending of an email. There is a proposed patch for Role Expire which creates a Rules event upon role expiration that you might use as a model.

Once you have created your rule, it is a simple action to assign a role (Add user role action) to the expiration:user.


Cannot figure out what's wrong with my schema

Unsigned attribute is not supported with datetime. Following code will create table for you.

function artx_partner_schema() {
  $schema = array();
  $schema['artx_partner'] = array(
    'description' => 'The base table for artx_partner.',
    'fields' => array(
      'partner_id' => array(
        'description' => 'The primary identifier for a partnership.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'uid' => array(
        'description' => 'User identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'nid' => array(
        'description' => 'Node identifier.',
        'type' => 'int',
        'not null' => FALSE,
      ),
      'product_id' => array(
        'description' => 'Identifier for a product.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'reqtime' => array(
        'description' => 'time stamp of the request',
        'type' => 'datetime:normal',
        'mysql_type' => 'datetime',
        'not null' => FALSE,
      ),
      'restime' => array(
        'description' => 'time stamp of the response to request',
        'type' => 'datetime:normal',
        'mysql_type' => 'datetime',
        'not null' => FALSE,
      ),
      'status' => array(
        'description' => 'the status of the request, pending(0)/AC(1)/Rej(2)',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ),
    'primary key' => array('partner_id'),
    'unique keys' => array('unique' => array('uid', 'nid', 'product_id')),
    'foreign keys' => array(
      'owner' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
      'product_display' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'product' => array(
        'table' => 'commerce_product',
        'columns' => array('product_id' => 'product_id'),
      ),
    ),
  );
  return $schema;
}


Drupal and its modules kept in two different subfolders -- possible/how?

install it with the core and the modules kept in separate folders, rather than in a hierarchy

In short, no.

Drupal must be able to expect to find files in a certain location, and that is not dynamically configurable. The very first line of code Drupal executes is define('DRUPAL_ROOT', getcwd());, and file wise, most things are based on that constant.

Symfony, and PSR-0, doesn't inherently change that. PSR-0 only defines the directory structure around files, not where to find them. With that said, I haven't looked in enough detail at D8 to know if there's a simple way to alter where the autoloader looks for files.

If your filesystem (and webserver) supports symlinks, you can work around the problem by symlinking the appropriate directories in place.


The simplest way to ensure compliance for Drupal is to install the Cookie Control module, which has been created for exactly this purpose:

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.

There's also the EU Cookie Compliance module:

This module intends to deal with the EU Directive on Privacy and Electronic Communications that comes into effect in the UK on 26th May 2012.

This second one does a better job in my opinion.


What's the usual practice for providing several CMS-editable content in pages, particularly the home page?

You can try to use Views and make little blocks of content type flagged to the front page if you want.

Another options is Panels or Panelizer and using custom content in Panelizer to layout your frontpage however you want.

Or if you're really brave hook_page_build.

I've used your 2nd option on sites; if Workflows is an issue for you, you will want to try either Views or Panelizer as those tools play more friendly with workflows (it's all about the UX and how much you want to empower your site maintainers).


Config changes only propagated via manual form submit

I think I have solved it by myself. I am re-saving the search index by myself via hook_install().

  $index_storage = \Drupal::entityTypeManager()
    ->getStorage('search_api_index');
  $index = $index_storage->load('search_content');
  $index->save();


Drupal file manager that shows relations to content

I had that need recently for sorting my images since their file names were weird. What I ended up doing was to create a View of files, with relation to content that used the field that the file was assigned to.

After you do that you can either add the content's fields and properties (like title, nid, etc) and/or group by them.

Hope this helps.


How to show the number of times a page has been shared by all services total?

you could use:
Social Share Counter Module

This module is clearly inspired by the share buttons used by Mashable.
This module gives the share counts for only Facebook,Twitter and more
which has some excellent features in more elegant manner. If you have
a website, then you definitely need this module.

If you still want to use AddThis, then use Social Stats Module

This is a statistics module. It provides data from various social
media sites. The data which is saved per node. It includes data from:
Facebook : likes count, shares count, comments count & total count.
Twitter : tweets count.
LinkedIn : share count.
Google Plus : plus one
count, share count & total count Total Share Count : total across all
available social networks Note: This module is intended to collect the
statistics per node from the networks mentioned above.
It does not actually provide sharing widgets for the social networking
sites. They have to added manually, or using other modules. List of
the modules recommended to use alongwith Social Stats are:

Service links
AddThis


How can i add our own field in Ubercart billing address?

Entire order is an object, so having some extra fields for order object from checkout level will solve this.

Extra Fields Checkout Pane module will help to add additional fields.


You should remove the #value property. This is what is blanking it out. If you want it blank to start with, set #default_value instead.

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Textarea.php/class/Textarea/8.6.x


Why implementation of node access for different content type breaks my other type access control?

While browsing through the Drupal docs about hook_node_access_records, I stumbled upon this comment:

  Note that (as of 7.35) if your module and every other module in your
  installation implementing this hook return empty arrays, Drupal will
  automatically insert a record into the node_access table for the given
  node with GID 0, grant_view set to 1, and grand_update and
  grant_delete set to 0.

You can find it here (last comment).


Turns out it can be done with the config:export:entity command.
drupal config:export:entity paragraphs_type [PARAGRAPH_TYPE] --module="[YOUR_MODULE]" --optional-config --remove-uuid --remove-config-hash --include-module-dependencies


How do I integrate media (e.g. attaching audio) to nodes?

To use mp3 files with Media entity you need the additional module "Media entity audio".

Alternatively, you can attach audio straight to nodes with the "Audiofield" module.


Render scald atom with image style, without new scald context?

The module Scald style contexts aims to provide a context for an image style, I think it potentially addresses some of the additional configuration.


Request an Ajax form through Ajax [solved]

I got it: In a sidebar, there was another form with a submit button provided by another module. This submit button has also the key 'submit'. In the form builder function I changed the key 'submit' to e.g. 'mymodule_submit' and now it works! So I don't need this strange second form builder function anymore.


How can I make sure a javascript cookie is set before page load?

The solution in this case was to set a path on the jquery.cookie

$.cookie('modalServed', 'yes', {path: '/'});


Form API ajax add group of users and numbers

You just have to move the $i value.

Instead of

for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options']['number'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options']['Name'][$i] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }

Use

for ($i = 0; $i < $form_state['num_names']; $i++) {
            $form['options'][$i]['number'] = array(
                '#type' => 'textfield',
                '#title' => t('number:'),
            );
            $form['options'][$i]['Name'] = array(
                '#type' => 'textfield',
                '#title' => t('Name of user:'),
            );
  }


Change published status directly in database

You also need to change the status column in the node_revision table:

foreach (array('node', 'node_revision') as $table) {
  db_update($table)
    ->fields(array('status' => 0))
    ->condition('nid', $nid)
    ->execute();
}

Notwithstanding any aggressive caching you might have in place, the effect should be immediate once you've run both those queries.

Drupal has plenty of these little nuances, which is why it's highly recommended to use the API functions rather than manipulating the database directly. Yes there's extra overhead, but you don't need to give things like the revisions table/caching a second thought as they're handled for you.


Rendered markup different than template markup

The comments in this question were helpful, but I can't credit both people so I will post the answer.

My default views-view-unformatted.tpl.php had an extra closing tag inside of it somehow. Not sure how since it's a default views display. Removing the tag fixed the issue.


Using variable_get() in multiple places, without duplicating $default

There is no built in mechanism. In fact, there is a long standing issue to add one http://drupal.org/node/145164.

Defining constants, as you suggested, is the only method I've seen to make it a bit cleaner.


Using Test Mail Collector to avoid sending emails to users during testing

After my attempt to use Devel module for  DevelMailLog also failed using the configuration setting

$config['system.mail']['interface']['default'] = 'devel_mail_log';

I concluded there must be something in my environment that is blocking these features.

After uninstalling the module "MailSystem", then either of the two approaches worked as intended while mail was still received when the configuration setting was omitted.


How to remove partricules and apostrophes in url

I have been able to achieve it with the Pathauto module 8.x-1.3, using the following settings (/admin/config/search/path/settings).

For Strings to Remove I used a, an, as, at, before, but, by, for, from, is, in, into, like, of, off, on, onto, per, since, than, the, this, that, to, up, via, with, d'
Under Punctuation, for Single quotation marks (apostrophe) ('), I selected No action (do not replace)

I used /content/[node:nid]/[node:title] as pattern for the nodes, and created a node with Personnes d'Allemagne as title. The path alias for that node has been set to /content/1/personnes-allemagne.

The disadvantage is that the apostrophe will not taken off from the path aliases, except when it is present in a string given for the Strings to Remove setting.


Problem with enabling the Optimizing js files

Give AdvAgg a try. If JS Aggregation doesn't work, go to admin/reports/status and see what AdvAgg says; it has tests for just about every scenario that would cause JS optimizations to not work.


Content Type with People (list of people) in Select List to Choose From

Personally I often use Entity Reference, but I think this answer is the same regardless of the choice between Entity Reference and References modules. Both modules allow you to define a relation between two entities. If you need a reference from a node to another entity, this is a good solution.

  I still would like to know if using People area is best for storing all users / people associated with my Drupal site.

When you say "People area", I think you mean Drupal's built-in user management. Users are fieldable entities, just like nodes. If you need to store data about a person, you can use both the user entity or define a "Person" node type. If the persons you're adding should be able to log in, now or in the future, you definitely want to create users. If they will never need to log in (for instance, you're building a site about people in ancient Rome), I would choose nodes.


Setting $cookie_domain variable for specific folder structure

The short answer is that you cannot set cookie domain to such a value. See http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-domain

As a workaround, you can use this in settings.php (around where $cookie_domain is set:

$cookie_domain = ".example.com";
// Set cookie_path ourselves as Drupal doesn't.
ini_set('session.cookie_path', '/mynewsitefolder/');

$cookie_domain is eventually used to set session.cookie_domain but there is nothing in Drupal code base to set session.cookie_path and so we directly set that in settings.php itself.


Views - "Add no results behavior" not doing what I would like it to

Assuming you're using Views 3, on the Views config page under Exposed form, change Exposed form style from Basic to Input required. Optionally change the other related settings on this page. Apply the settings and save the View and it should be ok.


I don't know if it goes far enough for you, but the Content type groups module helps you categorise content types.

  Content type groups was designed to handle the use case when you need to populate select boxes or other interface elements with certain content types but not others. This module allows you to create an unlimited number of groups of content types through the UI. Once a group is created, it can be referenced in code using API functions and in Views.

  Example

  Let's say you're organizing your media collection. You have the following content types: book, movie, audio, article (for your blog about your collection), and page (for some static content).

  Create a content type group called Media and add the book, movie and audio types. You have just created a logical grouping between the content types to show that they are related. This makes it easier for future developers to understand the relationship between various content types.

  Now let's say you start collecting old magazines. You create a new content type called magazine and add it to the Media content type group. Any place where Media is referenced will automatically reflect the change; there is no need to track down all Views or lists.

  This module is being rewritten to turn content type groups into entities, with a dependency on Entity API. The 2.x branch is heavily under development and not ready for any site use.


How can I stop cron from deleting images I need

Try using

<?php
$file->status |= FILE_STATUS_PERMANENT;
$file = file_save($file);
?>

While you save the file

References

hook_insert


Facebook Friend List Import using fboauth

The code you have there is returning friend's names which could be problematic if any of the user's friends have the same name (names like John Smith and Mohammed Abdul spring to mind).

You should change your friend import function to get the facebook user id like this:

function mymodule_fboauth_action_friend_import($app_id, $access_token) {
  $result = fboauth_graph_query('me/friends?fields=id', $access_token);
  drupal_set_message(t('Import complete!'));
}

As you rightly pointed out fboauth has a useful API including this method which turns facebook user ids into Drupal user ids:

/**
 * Load a Drupal User ID given a Facebook ID.
 */
function fboauth_uid_load($fbid) {
  $result = db_query("SELECT uid FROM {fboauth_users} WHERE fbid = :fbid", array(':fbid' => $fbid));
  $uid = $result->fetchField();
  return $uid ? (int) $uid : FALSE;
}

To make an array of Drupal user profiles you could write this in your code:

$accounts = array();
foreach($result->data as $fbuid){
  $accounts[] = user_load(fboauth_uid_load($fbuid->id));
}

How you then use those profiles depends on where you want to display them, but something like this should do the trick:

foreach($accounts as $account){
  print l($account->name, 'user/'.$account->uid);
}

If you put it all together you will have something like this - you may need to adjust some of the specifics as I do not know how you wish the information to be displayed:

<?php
function mymodule_fboauth_actions() {
  $actions['mymodule_friend_import'] = array(
    'title' => t('Imports your friends'),
    'callback' => 'mymodule_fboauth_action_friend_import',
    'arguments' => array)
      'app_id' => MISSING,
      'access_token' => MISSING,
    ),
    'permissions' => array(
      'user_friends',
    ),
);
  return $actions;
}

function mymodule_fboauth_action_friend_import($app_id, $access_token) {
  $result = fboauth_graph_query('me/friends?fields=id', $access_token);
  drupal_set_message(t('Import complete!'));

  $accounts = array();
  foreach($result->data as $fbuid){
    $accounts[] = user_load(fboauth_uid_load($fbuid->id));
  }

  foreach($accounts as $account){
    print l($account->name, 'user/'.$account->uid);
  }
}

If this doesn't display anything that means print is the wrong function to use in this context.  How you get the items to display depends entirely on where and how you are calling this function.  If it's part of a hook such as hook_node_view() you can edit the node entity before it is rendered, but if (as I suspect) this function is being run in the background without refreshing the screen you will likely have to employ some JQuery or AJAX to get the relevant items to display.

I would start with this post on Javascript and JQuery for an explanation of how Drupal uses JQuery, and this post on building AJAX into non-form elements in Drupal.


What is best coding practices for providing an upgrade path to a new module version?

Add the install information required for the new module version in the hook_install and hook_schema.

Users upgrading presumably won't be re-installing the module, so you'll need to use hook_update_N for those users. Check if the upgrade path is required for that installation and proceed with the update as needed.


Why can't I see the settings for the customfilter module in the Drupal admin?

when I try to navigate to /admin/settings/filters like it suggests

I'm not sure where you've seen that, but looking at the code, it's wrong. Maybe you're following a tutorial for a previous version of Drupal.

Either way, the config path for the D7 version is admin/settings/customfilter.


To change Entities fields its better use MODULE_ENTITY_presave() function (more info in docs).

In this case that you need change a node field use this function:

function hook_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->set('title', 'Updated title');
}


You just need to look for the hook_block() implementation done from the module for which you are invoking module_invoke(). The last argument in the function call you reported is the $delta parameter that is used from Drupal to identify the block within the module.

For example, looking at the code of forum_block(), the part of the code that implement the "list" operation, 0 is the delta parameter for the "Active forum topics" block, and 1 is the delta parameter for "New forum topics" block.

The code you wrote in your question is invoking the implementation of hook_block made from a module whose short name is menu_block (which means the function implementing the hook is menu_block_block()). If you meant to invoke the implementation of hook_block() made from menu.module, then the code should be the following one:

$block = module_invoke('menu', 'block', 'view', 26);
print $block['content'];

The function implementing hook_block() is menu_block(). The values used as $delta from that function are the values of the "menu_name" field used in the "menu_custom" table.


Custom form submit handler is called, but node is not saved

As pointed out by @Ismini, the entity has to be saved in the submit handler.  The way to do this is, as pointed out by @4k4, to copy the submit handlers for the new button from the original submit handler.  The corrected code is shown below.

function MYMODULE_form_node_CONTENTTYPE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $form['actions']['submit_publish'] = array(
    '#type' => 'submit',
    '#weight' => 999,
    '#button-type' => 'danger',
    '#value' => t('Submit for approval'),
    '#submit' => array_merge($form['actions']['submit']['#submit'], array('MYMODULE_draft2submit_callback')),
  );
}

function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  // Getting the entity.
  $entity = $form_state->getFormObject()->getEntity();
  // Changing the moderation state.
  $entity->set('moderation_state', 'submitted');
  // Saving the entity.
  $entity->save();
}


You are running with php 5.3 or earlier.  Drush 8 needs php 5.4 or later. Unfortunately, php 5.3 does not understand array syntax, so the failure is raised before any Drush code runs.  For other sorts of errors, Drush will tell you that your php is too old.

I am guessing you are using php 5.5 for Drupal 8; check which php and php --version to see if your php-cli is the same version as your Web server php.

UPDATE:

Set the environment variable DRUSH_PHP to the full path of the PHP executable that you would like to run.  Note that this will only work if you are using a Composer or git install of Drush; if you are using drush.phar, this feature is not available. For the .phar, you would need to use a shell script named "php" that calls php5.6. Then, set your PATH such that your php script comes before the one offered by default on the platform.


'Add new comment' link/button does not display on custom entity

Turns out one needs to implement field formatter for other entities instead of hook_links_alter. So one can perhaps add a Pseudo field formatter to get this markup rendered on custom entities with an approach described here
The hidden gem is noted in the comments for the node entity.
  /**
   * Implements hook_node_links_alter().
   */
  function comment_node_links_alter(array &$links, NodeInterface $node, array &$context) {
    // Comment links are only added to node entity type for backwards
    // compatibility. Should you require comment links for other entity types you
    // can do so by implementing a new field formatter.
    // @todo Make this configurable from the formatter. See
    //   https://www.drupal.org/node/1901110.

    $comment_links = \Drupal::service('comment.link_builder')->buildCommentedEntityLinks($node, $context);
    $links += $comment_links;
  }


Base field provided by a module is not accessable

I'm going to guess and say that this is because of Unrevisioned base fields are ignored during entity load.

As a workaround (or maybe it actually makes sense to do so), add ->setRevisionable(TRUE).


A "possible" reason might be because Drush commands must be issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

So try navigating to the sites/default folder (assuming this is NOT a multi-site), and then retry your Drush comand.

If that doesn't help, it could well be an issue with the version of Drush that you are using. Would it be an option to downgrade to a lower version of Drush? FYI: Drush 6.x does support D7 also ...


is it ok to use system_check_directory in a custom module?

Of course it is ok to use this function in a custom module as long as you take care of securing the form where this is used in. You should keep in mind that the error messages generated by this function could give valuable information about your file system to malicious users. If you limit access to the form that uses this function to trusted users only then there shouldn't be problem.

The function is tailored for core use, you can already see that in the way that it generates the .htaccess file depending on the #name attribute of the form array. But if you want to provide a configurable private directory to store uploaded files for a custom module then it seems like a convenient solution.


Try Menu token

  Menu Token module provides tokens, that could be used in title or in
  path of menu items (links). For example, if you create a menu item
  with path: "user/[current-user:uid]", the url will be changed "on fly"
  to: "user/1" (assuming you are user 1).

  Tokens are provided by Token module. Menu Token allows to use both
  global tokens and entity ones: node, user, term, etc. Entity tokens
  have several methods of substitution: from context, random and user
  defined.

If that does not work, you will have to do a custom redirect, either in code or using page manager (part of ctools)


Open Layers Views - Separate Data on Page and Block

I just added a relationship to the Products entity in the view and then added the Product fields in the View. I then excluded most of the location data. This gave me a Products page with a map of locations!


You don't create the search page entity, you load it. SearchPage::load($id). Either hardcode the id that you use on your site or make it configurable through configuration/settings/URL.


Does Strongarm need to be enabled on Production site using Features?

Yes, you need the strongarm module on production site as the module implements hook_features_revert and hook_features_rebuild which is needed to do any reverts to the variables you have featurized or to apply new variables that u have introduced in your feature.


Although probably ok, rather than using the PHP filter, you may be interested in using

hook_block_info
hook_block_view

To define your blocks instead. Perfectly fine to use drupal_add_css there.

Eg :

<?php
drupal_add_css(drupal_get_path('module', 'custom') . '/css/custom.css', array('group' => CSS_DEFAULT, 'every_page' => TRUE));
?>


How to remove author name and date created from Simplenews emails?

I would suggest you two options:

You can put node.tpl.php specific to your simplenews content-type and remove the unnecessary content from it.
Add css file specific to the mailing system. I use mimemail system, so I did the following:

function THEME_NAME_preprocess_mimemail_message(&$variables) {
  drupal_add_css(drupal_get_path('theme', 'THEME_NAME').'/css/mail.css');
}

In the mail.css, you can hide those fields using display:none;


Facebook Connect button in Overlay (Drupal 7)

Make use of Facebook O auth module. It has a huge advantages over the module that you use. It will work fine with any overlay effect.


I'm not sure exactly what you mean by "custom admin pages", but to give complete control over the layout of the content you could use Panels and perhaps also Panelizer.  The Panels in-place editor is probably enough for the client's needs, but you might show them the backend editor instead because it looks (and is) far more powerful/complicated.  It may even have the benefit of scaring them away from having the control themselves and asking you to go back to your original plan.

EDIT:

Here's how I would go about this using Panels, Views, Rules, and Flag.  This may not be the most optimal way, but it uses well-supported modules.

Make a panel for the home page.
Make a flag for each section that needs to appear on the home page.
Make a view (content pane) for each section.  The view should display the most recent node tagged with the flag for that section.  Add each view to the appropriate place on the home page panel.
Add a rule that, when a node is flagged, uses the trim flag action to ensure that only one node is flagged with that flag at any given time.

If you do this, your content editors can simply flag the pages they want and they will be displayed in the appropriate sections automatically.  (I have used all these modules to do a similar thing in the past, though I have not built this exact workflow.)


return all content types name containing text files

function get_content_type_by_filename($filenames = array()) {
    $sql = "SELECT nt.name, fm.fid
    FROM file_managed AS fm
    LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
    LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
    LEFT OUTER JOIN node_type AS nt ON (n.type = nt.type)
    WHERE fu.type = 'node' AND n.nid IS NOT NULL AND fm.filename IN (:filename)";
    $results = db_query($sql, array(':filename' => $filenames));
    $results = $results->fetchAll();
    return $results;
  }

This function accepts an array of file names you want to find content types for and returns an array of matched objects with properties fid and content type.

Update:

Please take a note that I am not trying to give you the exact code rather point you in the right direction.

To achieve what you want, call the function you mentioned in the question (i assume it does what you say, that it returns an array of file names)

so :

function get_content_type_by_filename($filenames = array()) {
    $sql = "SELECT nt.name, fm.fid
    FROM file_managed AS fm
    LEFT OUTER JOIN file_usage AS fu ON (fm.fid = fu.fid)
    LEFT OUTER JOIN node AS n ON (fu.id = n.nid)
    LEFT OUTER JOIN node_type AS nt ON (n.type = nt.type)
    WHERE fu.type = 'node' AND n.nid IS NOT NULL AND fm.filename IN (:filename)";
    $results = db_query($sql, array(':filename' => $filenames));
    $results = $results->fetchAll();
    $types_array = array();
    foreach($results as $obj) {
      $types_array[] = $obj->name;
    }
    return $types_array;
  }
$files_array = get_projects();
$content_types_array = get_content_type_by_filename($files_array);

The $content_types_array will contain the array of content type names.
Hope this helps.If this does not give please debug by installing devel module and passing the variables and arrays through dpm() function to see contents of the array.


How to remove all the divs inside the $widget of a views exposed filter?

Go to the modules directory and look for the 'views' module.

There is a 'theme' folder within this.

In the theme folder, copy the 'views-exposed-form.tpl.php' file to your theme.

You can then edit the template as you require.

Note, when you copy a file like this you will want to clear caches for this to work.

*****UPDATE*****

To edit specific components of the form I suggest you override the following function in your themes template.php file.

template_preprocess_views_exposed_form(&$vars)

This can also be found in the views module folder 'theme.inc'.


You should check out What are Ctools plugin (content type, access, etc), and how does one create them?, and in addition make sure the content type has a required context on nodes so that you can't accidentally render it without a node. Check the examples on the ctools module to see how to add required contexts.


Count total number of values in a field of all nodes combined for a view

There is a module to assist with that: Views Field

  Allows field tables to be used as base tables with Views.

After you installed the module you need to visit the field setting on any content type that includes the field. Tick Expose as base table, then select all the columns to expose excluding revision_id.

Next create a view and at admin/structure/views/addat Show listbox you select the Field base table. This will now create a view on the field in question's base table.

Your view settings should have these settings:

Use aggregation: Yes
Fields: Entity Type (The entity type this data is attached to) with
Aggregation setting Count.

You can now add Relationship: Field tables: Field XXX => Node to get access to the nodes the fields are attached to and from there author etc.

ALTERNATIVE

Create a View of Content (ie nodes) showing fields. Set Aggregation to Yes. Remove sort Criteria, filter criteria and Pager. Add your field's delta (Delta - Appears in: node:xxx.) to the View fields with aggregation set to COUNT.


How do I exclude admin strings from interface translation?

There is no solution that I'm aware of. You can't change the context of strings in core or contrib modules without changing the code. Which you shouldn't do.

The fact that toolbar doesn't show the english strings if your admin language is english is a big that's trying to be fixed here: https://www.drupal.org/node/2313309

I don't know if that's still doable in 8.x.


Can you create a new block region using just a module?

hook_system_info_alter is your friend.

<?php
/**
 * Implements hook_system_info_alter()
 * Adds a new "tray" region to the current theme
 */
function MODULE_system_info_alter(&$info, $file){
  global $theme;

  // If non-default theme configuration has been selected, set the custom theme.
  $custom_theme = isset ($theme) ? $theme : variable_get('theme_default', 'bartik');

  if ($file->name == $custom_theme){
    $info['regions'] = array_merge($info['regions'],  array('tray' => t('Tray')));
  }
}


“Some files and directories in your install are writable by the server.”

6/4/4 means read+write/read/read - this is OK for files but not for directories. Directories must be executeable, so set them to something like 755 (read+write+execute / read+execute / read+execute).


Adding a validation step via hook_form_FORM_ID_alter()

Hi Bobby you can use custom validate submit handler to deal with this

$form['submit']['#validate'][] = 'custom_validate_function'

all you have to use is #validate in submit handler.

use the same callback function as above with replacing the callback name


I think you're on the right track. If I'm understanding your question, you won't need to add an extra class.  Instead, you'll want to use your existing Migration class's complete() method, which is called after the node has been created.  Within complete(), you can then use entity_create to create your field collection and entity_metadata_wrapper around your newly migrated node to set a reference to your field collection entity.

In psuedocode,

public function complete($entity, stdClass $row) {
  fc_entity = entity_create(...)
  $ewrapper = entity_metadata_wrapper('node', $entity);
  $ewrapper->fc_ref_field->set( $fc_entity->nid );
  $ewrapper->save();
}

Or something thereabouts. When in doubt, "whatever works" is the correct standard for migration code. Hope that helps get you started!


Drupal 7 Commons 3 Vs Drupal Core + Commons modules

Commons 2.x really had a lot of customizations in the install profile, deploying a well organized social network, but when i installed Commons 3.x, i had a sense of "hey, does it really customized anything?", that seems to be your feeling too.

I don't know the roadmap of the project, but it seems a little "naked" in this first version, compared to what they had inside the last Commons 2.x version.

For a project starting now, with what Commons 3.0 has to offer in the install profile(they can improve it, but if you install now, the newer versions of it will not came to you by just upgrading the modules), i think that what you're proposing could be a good thing, because my experience with Commons 2.x updates were really painful just to get some more views and panels improvements(and had to deal with so many Feature overrides), so it could be easier if YOU mantain your own profile, maybe creating one or using the Minimal or Standard themselves.


How to redirect to a page after submitting a form

In the submit handler you do

Drupal 7:

$form_state['redirect'] = 'url';

Drupal 8:

$form_state->setRedirect('route', $args, $options);
$form_state->setRedirectUrl(\Drupal\Core\Url);


Can I use view to filter by fields in referenced node?

You want to look at adding Relationship(s) to your View.

You also likely want to look at Views Field View:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

Or Views Field:

  Viewfield provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.

  Features

  Author chooses a view and display from a list.
  View arguments are supplied through tokens.
  Administrators may restrict which views may be assigned.
  Administrators may supply a common value that will be used for all entities in a content type.

Using either of these modules you can figure out your relationships for the views you want and for instance using ViewsField you can add a View to the Designer Content Type with 2 new Views: Contributed Project Nodes views, and a Similiar or Linked Designers View. You can pass the Designers uid as a token to filter these views.


What are the criteria to decide between modules ThemeKey and Switchtheme?

Switchtheme is a user-driven theme switcher with a couple of automatic options. It provides a couple of blocks (displayed via a custom Switchtheme permission) where a user can select a theme to choose on a per session (or user account) basis.

Its automatic (admin configured) solutions are:

A per-browser automatic switcher through the Browscap module
A per-URL switch through adding a ?theme=theme_machine_name query parameter to the page request (e.g. http://example.com/?theme=seven)

ThemeKey is a combination of user/admin driven theme switching based on various settings & rules.

Its theme switching solutions provided are:

A per-alias solution that allows to set a theme for each Drupal alias
A per-node solution that allows a permissioned user to set a theme for any node they create (as well a default option).
A per-user solution that allow a user to set a default theme for their configured account.
A chain of custom rules that evaluates various Drupal system, user, comment, node, taxonomy, and Views properties.


Configure Australian GST Taxes on Commerce Kickstart 7.x-2.14

Here is a module maybe is useful.

  The Commerce Australia module provides a number of customisations for
  Drupal Commerce (http://drupal.org/project/commerce) that allow it to
  be better suited for deployment in Australia.

  Most notably, these include basic currency formatting for Australia
  and workable GST (Goods and Services Tax) rules.

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


LoadTest fail due to "chmod(): Operation not permitted"

The thing is, the chmod wasn't really working.

It was an issue with the mounted drivers in the WSL Ubuntu installation. Based on Stefanos Petrakis' comment, simply trying to unmount and mount the driver with the proper options enabled wouldn't solve the issue by itself. What solved was a bit more drastic:

Factory reset the ubuntu (how-to);
re-mount the driver, with the metadata option included (source):

sudo umount /mnt/c
sudo mount -t drvfs C: /mnt/c -o metadata,uid=1000,gid=1000
Install php, Apache, and everything.

Only then, the phpunit tests did work properly.


How to add custom predefined content panes?

You need to a Drupal distribution called Panolopy. You may also want to review this page.


Disable emails turned into links but keep urls turned into links

The easiest way is to creat your own input filter. Do a PREG and obfuscate the email address.  Assign this filter to your input formats, and make sure it runs before the URL-to-link one.


How to change sender email Id using hook_mail_alter

According to the documentation:
/**
 * Alter an email message created with MailManagerInterface->mail().
 *
 * Hook hook_mail_alter() allows modification of email messages created and sent
 * with MailManagerInterface->mail(). Usage examples include adding and/or
 * changing message text, message fields, and message headers.
 *
 * Email messages sent using functions other than MailManagerInterface->mail()
 * will not invoke hook_mail_alter(). For example, a contributed module directly
 * calling the MailInterface->mail() or PHP mail() function will not invoke
 * this hook. All core modules use MailManagerInterface->mail() for messaging,
 * it is best practice but not mandatory in contributed modules.
...

Can we check if the mail is sent MailManagerInterface->mail() like this and not any other way.


Difference between router path and link path?

Pro Drupal Development, Second Edition describes them as:

  menu_links.link_path is the Drupal path or external path this link
  points to.

  menu_links.router_path is for links corresponding to a Drupal path
  (0 means external), this connects the link to a menu_router.path for
  joins.