Alter html output of a term reference form field

Doing it that way round will cause problems with the form submission; the value for a term reference field needs to be an integer and throwing a string at it will undoubtedly upset things. You could massage values back into place in a validate function but it seems a bit...messy.

The alternative would be to load the taxonomy term up in the form, so you can use the ID from there:

$terms = taxonomy_get_term_by_name('External', 'vocab_machine_name');
$term = array_shift($terms);
$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => $term->tid),
  ),
);

That should make it reusable across different environments (provided the vocab only has one term with the name "External").


Creating linkable images using Flexslider and Slideshow View

I have always had to modify the view template for the specific display to wrap everything in a link properly. The issue is compounded even more when using Picture for responsive image variations.

The custom template changes aren't extensive, but I've not found a re-usable or GUI based method to do this with sliders.


How can I access block field values in mytheme_preprocess_block?

Here is a code snippet that we use to create block template suggestions based on the block content type (bundle), doing something similar based on a field should be fairly easy (...->yourfield->value):

/**
 * Implements hook_theme_suggestions_HOOK_alter() for block templates.
 */
function ourtheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle();
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle() . '__' . $variables['elements']['content']['#view_mode'];
  }
}


I don't believe that's possible with the Find Content page. You may have to resort to making a View to accomplish the task. I've created several views for the same purpose, and actually prefer it as I can create my own admin links (edit, delete, view, publish, etc.) customized to what my goal for the page is.


You can obtain the field type using Entity field manager.

$definitions = \Drupal::service('entity_field.manager')
  ->getFieldStorageDefinitions('node');

$field_type = $definitions['field_image']->getType();


Add new menu item in drop down admin menu

You can create more admin menu link from navigating to Management Menu, which you will find at this location -- admin/structure/menu/manage/management


How to force the canonical URL to use http?

Drupal 7

You can implement hook_html_head_alter() to change head tags; the following is untested but should do the trick:

function MYMODULE_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => &$tag) {
    if (strpos($key, 'drupal_add_html_head_link:canonical:') === 0) {
      if (strpos('https://', $tag['#attributes']['href']) === 0) {
        $tag['#attributes']['href'] = str_replace('https://', 'http://', $tag['#attributes']['href']);
      }
    }
  }
}


You cannot do this with Omega as its not part of the structure of the 960 grid system. Your best bet is to do it via CSS.

First you you would take the largest section, which would be the middle one. Say its 1000px, now the header and footer would also be 1000px. You would then modify the inner div in those regions to be 980px (10px on each side) to get the effect your looking for.


How to prevent the form from redirection after submission in order to see the kpr() results?


As it turns out HTML email was infact enabled. The problem was the stylesheets that the email was being bundled with.

If you head to admin/config/system/mimemail you can choose to either bundle the email with your website stylesheets, or set-up a mail.css in your default theme directory.

I suspect if you're using a sub-theme and haven't got mail.css it'll just use the original theme mail.css which is probably not what you want.


I would like to know whether corporate portal can be built with
  drupal.

Yes it is possible.

  Please let me know if there any modules for the above requirement or
  any opensource for this.

The question cannot be answered properly without knowing the exact requirements and then digging very deep. The result would be mostly writing a book.

To be honest as you are new to drupal and the way your question "sounds" to me" you are likely to fail with the project. Therefore I would recommend you check out how far open atrium (Drupal 6) or other install profiles / distributions meet your requirements and try to sell one of these (plus customization) to your client. Or at least first look how the authors of open atrium, Drupal Commons and others do things and then ask specific questions.


How to associate an image node with taxonomy term?

why don´t you use the taxonomy image module
then simply get the taxonomy id from the node (use node_load(nid) then identify with var_dump how can you refer to the taxonomy..he might be using the CCK or the taxonomy module ) then get the id(s) of the term, load that term with and see it´s image (again use var_dump to know it´s structure)


Using Drupal Default jQuery only on node form?

You cannot use an updated/upgraded version of jQuery 'just like that' with Drupal. Believe me, it might look everything is working fine, but eventually its gonna break.

As Suggested by Motot, you can use https://drupal.org/project/jquery_update module to use an updated version of jQuery. But I don't think the even the dev version of jquery_update module supports 2.0

What you can do is, use jQuery's no-conflict feature. Here is a detailed documentation on using different JS libraries along side jQuery https://drupal.org/node/1058168 (You want to use jQuery 1.x & 2.0)

And yes, there is a module for that as well - https://drupal.org/project/jqmulti


Is it possible to notify users by e-mail when receiving a private message except when a specific user sends a message?

Note: this is answer for Drupal 7.

As Letharion said, you can use hook_mail_alter() but you should detect somehow is this a welcome message from admin or not.
I suggest Context module for this task, but you really can just compare a subject of message in this hook.

Update

  First I suggested to use Context module, but it is no so simple to set context in Rules. If you are interested in that way, you can see history of an answer.
  Current code is using information about Author id and subject of message:

/**
 * Implements hook_mail_alter().
 */
function YOURMODULE_mail_alter(&$message) {
  $WELCOME_USER_ID = 1; // PM author from your rule
  $WELCOME_SUBJECT = 'Welcome to the site'; // PM subject from your rule
  // 'pm_email_notify_notice' is an ID for message notifications
  // from Privatemsg Email Notification module
  if($message['id'] == 'pm_email_notify_notice') {
    $privatemsg = $message['params']['message'];
    if ($privatemsg->author->uid == $WELCOME_USER_ID && $privatemsg->subject == $WELCOME_SUBJECT) {
    // If special context is set it means that we don't want to send an email
    //if(context_isset('context', 'my_privatemsg_stop_email')) {
      // Stop email
      $message['send'] = FALSE;
    }
  }
}


Best way to store custom values in Drupal 7?

No, there's no need to create your own table for that. Your use case is a perfect example of what should be stored in the variables table (in my opinion).

Since the data isn't particularly volatile, and you only have a couple of values, I can't see any benefit to adding a custom table for it.

If you start finding yourself storing a lot of data in variables, for example a single different variable for each node of a certain content type, that's when you need to start looking at a custom table.


How to disable the add to cart button if the shop owner does not have the premium role?

Yes, you can do this in twig file. So you will have to create a commerce product twig file(you can copy it from commerce module template). In the preprocess hook you will have to pass a value whether that product can show cart button or not. In your twig file you can use value of that flag around {{ product.variation }}. Add to cart button is rendered by this variable.


Drupal Commerce - Sort products in view priced lowest to highest

It isn't clear to me why you're sorting based on some sort of standard deviation here (or why you're using aggregation at all). If you really just want to sort a list of products by price in a taxonomy term, you should just keep aggregation off and sort on the price directly.

If you need aggregation on, you're going to need to explain the intent behind this sort method.


changing a MySQL query to a drupal query any ideas

I believe you need to change

$firstname_substr = $query->addExpression('SUBSTRING(cc.first_name,1,3)','cc.firstname_substr');

to

$query->addExpression('SUBSTRING(cc.first_name,1,3)','firstname_substr');

and

$db_or->condition($firstname_substr, $name);

to

$db_or->condition('firstname_substr', '%'. db_like($name) . '%', 'like');

So it will look like this:

function search_pcp($name, $from = 0, $count = 5){

  $query = db_select('civicrm_pcp', 'pcp');
  $query->join('civicrm_contribution_page','cp', 'pcp.page_id = cp.id');
  $query->join('civicrm_contact','cc','pcp.contact_id = cc.id');
  $query->addJoin('LEFT OUTER','civicrm_entity_file','cef', 'cef.entity_id = pcp.id');
  $query->addJoin('LEFT OUTER','civicrm_file','cf', 'cef.file_id = cf.id');
  $query->condition('pcp.is_active','1','=');
  $query->condition('cp.is_active','1','=');

  // changed cc.firstname_substr to just firstname_substr
  $query->addExpression('SUBSTRING(cc.first_name,1,3)','firstname_substr');

  $db_or = db_or();
  $db_or->condition('cc.first_name',  $name, 'like');
  $db_or->condition('cc.last_name',  $name, 'like');

  // corrected the condition statement
  $db_or->condition('firstname_substr', '%' . db_like($name) . '%', 'like');

  $query -> condition($db_or);

  return $query->execute();

}


Prevent editing for role after date in field

Yes, you can do that with

hook_node_access

For example, something like:

/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account) {

  // If editing target node type
  if ($op == "edit" && $node->type == 'target_type') {
    // Check against passed account or current user
    if (empty($account)) {
      $account = $GLOBALS['user'];
    }
    // If date field is set, user has target role and date is in the past
    if(isset($node->field_target_date[LANGAUGE_NONE][0]['value'])){
      $date = $node->field_target_date[LANGAUGE_NONE][0]['value'];
      if((in_array('target_role', $account->roles)) && (REQUEST_TIME > strtotime($date))){
        // Deny edit access
        return NODE_ACCESS_DENY;
      }
    }
  }

  return NODE_ACCESS_IGNORE;

}


Mention/Reply to users in comments using @ (@name)

I think you might be looking for this module but the 7 version is still in dev.

Mentions

  The Mentions module offers Twitter like functionality, recording all
  references to a user's username - using the [@username] or [@#uid]
  filter format - from various locations, providing a centralized page
  to track all mentions.


Is there a way to get field associated with content type?

You can use field_info_instances('node', $content_type).

With field_info_instances('node', 'article'), I get the following.


What is the correct way to get the link url?

I find the best way to get a url especially when I'm using it in cases where I need to wrap custom html around it is to get the url object and then use the toString Method.

$node_field_link_url = $node_field_link->getUrl()->toString();

The getUrl() method of the LinkItem object returns a Url object. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/class/Url/8.2.x
And Url objects have a toString method that returns the string representation of that url.


Creating a profile sub page and filling with Webform data

If i understand well your question, what you want is a view that show the answer to a webform.

So you can create a view filtred by user, display it in a block and invoke it in the template of your profil page.


location fields are not appearing on feed mapping while location module is used inside field collection

I found the solution, in location_feeds.module under function(location_feeds_feeds_processor_targets_alter) under first 'if statement' there is only mention that when node is selected in feeds on that case show all location fields so for solving this issue we just need to add when node or field_collection_item is selected on that case location fields should be appear...
steps:
Go to

  path= modules/location_feeds/location_feeds.module

add $entity_type == 'field_collection_item' || to first statement of "if condition"
like this:

function location_feeds_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {

if ($entity_type == 'field_collection_item' || $entity_type == 'node') {

// location.module logic

$settings = variable_get('location_settings_node_'. $bundle_name, array());

// Only add fields when collecting locations

if (isset($settings['multiple']['max']) && $settings['multiple']['max'] > 0) {
_location_feeds_location($targets, $settings);
}

Save and clear all caches(admin/config/development/performance) and then check it...


How to implement a nomination process for nodes?

How about using modules Node_convert, and Flag (which is obviously a must have for what you're looking for)? About Node convert (from it's project page):

  adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

I'm using Node_convert already for long time, works great. It allows for implementing a lifecycle (or workflow?) to start from a node that is only just something like an idea (or suggestion, question, issue, abstract, etc). Those ideas that get the highest votings, are the ones that seem to make sense to handle with highest priority. Compare it to a 'Question' with a lot of votes, but with hardly any (or no) answers.

When the node's content evolves (read: the more effort/details added to it), I convert its content type to finished products like (eg) a recipe, a redbook (already from my Drupal 6 days a few years ago).

By combining it with some type of access module (related to either taxonomy or content type) I can make it more restrictive to give access to it. E.g. public to start from, then "authenticated", and in the end only for roles such as "subscribers", "students", etc.

Maybe you also want to consider Fivestar and/or Voting API (I have the impression that "Voting" is a kind of synomym of what you mean with "Nominate").

And of course: use Views as you are considering already. To continue my samples above: using some basics Views reports, you can easily massage it all in a todo list also.


With a route name on a Controller:

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

With an absolute URL:

return new RedirectResponse('https://google.com');

On a form RedirectResponse doesn't work, then:

With a route name:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setRedirect('user.page');
}

With an absolute URL:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setResponse(new TrustedRedirectResponse('https://google.com', 302));
  // You can change the response code from 302 to whatever you need
}


Select the same number of results for every group

Yes, query alter helps.  Views flexible pager might serve as an inspiration for the code changes. Do contribute back if you find a solution, it has been requested before.

This problem is usually "solved" by creating different Views displays, as many as you have Groups, and filter each field value in its own display. Then show all 3 displays one after another and use styling to make them seem like they're from the same Views.


How could I select all the authenticated users and just only them?

Using the Views Bulk Operations (VBO) module it is possible, by creating a view to select all the people not in the desired roles.


Webform Status in Webform Submission Twig Template

Indeed, calling {{ webform }} inside webform-submission-information.html.twig only contains a link. But since you have the webform_submission you can get the webform and from there can call isOpen and isClosed.

  {{ 'Current Webform status'|t }}: {{ (webform_submission.getWebform.isOpen) ? 'Open'|t : 'Closed'|t }}

or

  {{ 'Current Webform status'|t }}:
  {% if webform_submission.getWebform.isOpen %}
    {{ 'Open'|t }}
  {% else %}
    {{ 'Closed'|t }}
  {% endif %}


Grant permission for publishing options without full 'administer content' permission

You can use the Save Draft module. It adds a 'Save as Draft' Button to the node_form for content types, allowing the user to click the 'Save as Draft' button to save the node as a draft. It has it own separate permissions aside from the 'administer content' core permission.


Drupal 7 Private Files - How to override security in custom module

Image styles are served from the public file system, and there's no hook to control access to public files, so unfortunately not.

There's no simple solution, but there is a working solution: Image Style Access

  Allows granular access control to images and image style derivatives.

I've had a quick look through the code and you won't find a better starting point than that module. Quite a straightforward idea actually, it introduces a menu router item for each ./styles/[image-style] folder, controlled by an access callback.

It does mean you now have the overhead of a full bootstrap for all image styles, but since you want to check access based on the DB there's no other way to do it.


Configuring Commerce in an existing drupal install

I would recommend that you install and play with Kickstart 2 in order to study best practices and find out what contrib modules you need for the most common Drupal Commerce features.

To install Drupal Commerce on any existing Drupal site, start by first installing its dependencies, and then activating Commerce modules in the order indicated here. Also, make sure that you activate all the Commerce UI modules. This should get you to the point where you can create basic products, orders, and a checkout workflow.

You should first learn about the separation between product displays and products here.
In short, you need to create a new node type, let's say "Product display". For it to act as a product, you need to add a "product reference" field and configure it to suit your needs. Make sure that on the "Manage display" section of your Product display you have selected the "Add to cart form" format for your product reference field. Your view should display products with add to cart forms as long as you configure it to display nodes of type "Product display" with the correctly configured view mode.

After you understand the concept, I fully recommend installing Inline Entity Form. It will spare you the effort of explaining the above concept to your clients, and make their life much easier.


Taken from http://www.drupal.org/node/2350819:

If you import a field, it automatically goes into the disabled section because the fact that a field is shown or not is now stored in the entity display config entities, which fields do not now anything off. I should check what our default behavior is, but this is probably by design - which makes sense actually. And if not, it'll be a feature request.


Migrate Alt and Title text from a D6 image file field to D8

So this worked for me not sure why. But my file migration id was upgrade_d6_file and when I change this in line 54 of Drupal\file\Plugin\migrate\process\d6\FieldFile and ran the migration with the settings below I got the correctly referenced files and the alt/title text.

Diff

  // Configure the migration process plugin to look up migrated IDs from
  // a d6 file migration.
  $migration_plugin_configuration = $configuration + [
-   'migration' => 'd6_file',
+   'migration' => 'upgrade_d6_file',
    'source' => ['fid'],
  ];

Migrate yml

field_primary_image:
    plugin: d6_field_file
    source: field_image
    process:
      target_id:
        plugin: migration_lookup
        migration: upgrade_d6_file
        source: fid
      alt: alt
      title: title

Or even better is write your own process plugin like this: https://github.com/mikeryan776/d8-migrate-example-001/blob/master/migrate_carlyle/src/Plugin/migrate/process/CarlyleCckFile.php


How to set rel="alternate" hreflang="x"?

You tagged your question as Drupal 7 so I'm guessing the only problem is that you're using drupal_set_html_head() which doesn't exist in Drupal 7.

It's been replaced with drupal_add_html_head(), which you can use like so:

$element = array(
  '#tag' => 'link',
  '#attributes' => array(
    'hreflang' => 'some_language',
    'rel' => 'alternate',
  ),
);
drupal_add_html_head($element, 'mymodule');


Adding JS to field widget being created in my module

You forgot the library key:

$element['Subject_IDs']['#attached']['library'][] = 'get_libguides_listings/get_searchby';


Create mymodule.services.yml

services:
  mymodule.custom_services:
    class: Drupal\mymodule\Services\CustomService
    arguments: []

Now create Services folder under your mymodule/src. After that create CustomService.php in Service folder.

In CustomService.php

<?php

namespace Drupal\mymodule\Services;

/**
 * Class CustomService.
 */
class CustomService {

  /**
   * Constructs a new CustomService object.
   */
  public function __construct() {

  }

  public function getServiceData() {
    //Do something here to get any data.
  }
  /**
   * Here you can pass your values as $array.
   */
  public function postServiceData($array) {
    //Do something here to post any data.
  }
}

And for accessing service in your module file

$service = \Drupal::service('mymodule.custom_services');
$service->getServiceData();


Jquery for form with multiple save/submit buttons

One approach I used to achieved this was using the same callback function.  Then within this method, use $form_state['triggering_element']['#id'] or something similar to execute the proper function... i.e.

function my_form_submit($form, &$form_state) {
  $id = $form_state['triggering_element']['#id'];

  switch ($id) {
    case 'edit-submit':
      submit_my_form($form, $form_state);
      break;
    case 'edit-save':
      save_my_form($form, $form_state);
      break;
  }
}


You can find out from the implementing module's implementation of hook_menu.

In your case, look for where Flag implements hook_menu (in the case of Flag 7.x-3.x you're looking at flag.module at around line 301.
Next, look for where the module declares $items['flag/%/%flag/%'], and look for the page callback array key. You can see it says flag_page, so you can tell the menu callback is calling the flag_page.

You can find the Drupal 7 documentation for hook_menu here.


Have to delete cron_last every time for cron.php to work

Basically, you can't delete it with your code - it's set up after last cron hook finishes, so no matter what you do inside Drupal, it'll be set. If the last line that gets executed is module_invoke_all('cron') (in Drupal 6) or module_invoke_all('cron_queue_info'); (in Drupal 7 real cron tasks are wrapped in try catch so this is the only really risky point), or if your server logs timeouts, it's probably a faulty module that fails to execute it's hook_cron, or too many modules defining it, so at some point it times out.

I see two ways to deal with it:

Use Elysia Cron and with it's GUI manually run cron tasks you need to test. That way even if single task will fail, other will get executed. they will be executed one at a time, if you set it up correctly, so less risk of a timeout. And you will be able to test which hook, exactly, fails to execute. Then simply uninstall faulty module, or fix it, and you'll be OK.
In MySQL, create a trigger that will delete cron_last value for you. PostgreSQL supports triggers too, and most of RDBMS support them or something similar to them. It will not solve your problem, but it's way faster than point 1. and it will get you going if all you need is quick and dirty hack.


Relationship between node and taxonomy term using migrate_d2d_ui

If you're getting values from the d6 db, but it is not mapping properly you can likely use public function prepare($node, $row) {...} on your migrate object to map the taxonomy terms from the d6 site to the d7 version. Off the top of my head I don't know how that looks, but that is where I would start. prepare !


Why all core services cannot be registered in core.services.yaml?

Why cannot all the core services be registered in core.services.yaml?
Why do we need a service provider class to register services or modify existing services, when we can register services in module.services.yml?

I think the answer to both these questions is that likely some of the services are dynamic. Yaml files can only be used for static registration of services.


Thanks to Berdir I got it working. This is how it works in more detail.

Tablesort is triggered "automatically" if the (column) arrays in the $headers array contains the keys 'data', 'field' and optionally 'sort'. This will create links with 'sort' and 'order' in the column headers and show the little arrow and such.

To do your own sorting, get the current sort settings with tablesort_get_order and tablesort_get_sort and use those values for your own sorting function. The key 'sql' in the array returned by tablesort_get_order contains the field name to be used for sorting.

A piece of (untested) example code with the array $users containing some details for each user:

// setup the table data that we want to show
$tableData = array();
foreach ($users as $userDetails) {
  $tableData[] = array(
      'name' => $userDetails['name'],
      'visits' => $userDetails['visits'],
      'views' => $userDetails['views'],
      'comments' => $userDetails['comments']
  );
}

// headers array, sorting by default on comments
$headers = array(
    array('data' => t('Name'), 'field' => 'name'),
    array('data' => t('Visits'), 'field' => 'visits'),
    array('data' => t('Views'), 'field' => 'views'),
    array('data' => t('Comments'), 'field' => 'comments', 'sort' => 'desc')
);

// getting the current sort and order parameters from the url
$order = tablesort_get_order($headers);
$sort = tablesort_get_sort($headers);

// sort the table data accordingly (write your own sort function)
$tableData = my_array_sort($tableData, $order['sql'], $sort);

// create the array with rows for theme table
$rows = array();
foreach ($tableData as $entry) {
  $rows[] = array(
      array('data' => $entry['name']),
      array('data' => $entry['visits']),
      array('data' => $entry['views']),
      array('data' => $entry['comments']),
  );
}

// add any attributes and sent everything to theme table
$attributes = array('class' => array('my_class'));
$table = array('header' => $headers, 'attributes' => $attributes, 'rows' => $rows);
$html = theme('table', $table);


Reasons for using a webform node rather than just linking directly to the webform

The main reason being you can't use any functionality that comes with a node being the page. E.g. add custom fields/paragraphs and allow users to edit them to customise the page. All of that would need to be done as blocks which isn't as efficent/easy for content loaders to manage
If you need to add metatags and other things like that also become more difficult.
And from the webform perspective it allows you to reuse the same form on multiple pages and the results are segmented to the webform node. Meaning if you need multiple copies of a form on your site you can have 1 form and reuse it on multiple pages rather than duplicating the actual webform itself


How to hide a custom user field in user profile?

I think Field Permissions is what you are looking for. Here is a quote about it (from the module's project page):

... allows site administrators to set field-level permissions to edit, view and create fields on any entity.
Features:

Enable field permissions on any entity, not just nodes.
Role-based field permissions allowing different viewing patterned based on what access the user has.
Author-level permissions allow viewing and editing of fields based on who the entity owner is.
Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed.
Field permissions overview


Server connect time significantly increased over the time

You can use block cashing for users
you can check this link for more details https://www.drupal.org/node/326504
Check your MySQL server memory.


Can't Update Contrib Modules via Admin UI

No guarantee it will help, but I think it's worth trying (inspired by some of the suggestions in this comment in issue nr 1022558):

Increase the php memory limits by editing the following lines in the php.ini file as:

max_execution_time = 30 --> 60 ;
memory_limit = 32 --> 128, or even 256M ;

Add the following lines to the end of .htaccess file:

php_value auto_append_file none
php_value memory_limit 128M


Cached variable remains after truncating cache table

Got it - the call to variable_get() was during the bootstrap process, so cache_bootstrap table also needed to be truncated.


Assign Multiple roles to Ubercart Product

Yes, the UC Roles module can assign multiple roles on purchase. All you need to do is add each role assignment you want at /node/XXX/edit/features.

If the roles aren't being assigned after purchase, you might want to check the SKU options you have for each feature. It could be that your product purchase is a SKU that isn't configured for role assignment. If that isn't it, you should check to make sure that your checkout rules are configured to set the right order status to trigger role assignment.


Only display image field when administrator approves it

Have a look at File admin .

  File admin extends the File entity module to add administrative
  options to files, including published, promoted, and sticky status.

It has a dependency on File entity, which is a prerequisite when working with files as first class citizens.

Please also look at File admin's issue queue. A lot of extra functionality can be added via a few select patches.


How can I dynamically refresh the price on product page when changing quantity based on price table

Commerce Cart Ajax

  Features

  The “remove” button on cart view removes the item from the cart
  immediately, without a page refresh. The row is removed from the
  table.
  The “Qty” is updated when the "update" button is clicked. The totals are recalculated. No page refresh.


Embedded views into another view via twig_tweaks, but the results only update after clearing drupal caches

Use the Views Field View module instead.

There are a lot of cases in views where you want to embed a list inside each row. One
example could be, you have a list of groups, and for each groups you
want to list the first and last name of all of their members.

Then in the Views UI add view embed as field.


Can Ubercart be adapted to print a letter?

Yes. In D7 there's a 2 step process to this.

Copy ubercart/uc_order/uc_order-invoice-page.tpl.php to your current theme directory and flush your cache; this will let you create your own custom version of the the order template.
Add this snippet to your new template after <?php print $content; ?>; this will add some markup/CSS that will be rendered as a new page when treated as a printable document.

<?php /* Print only from administration page*/ ?>
<?php if(preg_match('/admin\\/store\\/orders\\/\\d+\\/invoice\\/print/', current_path()) == 1): ?>

NEW PAGE

<?php endif; ?>

If you're running a D6 site, it's a little more of pain (D6 UC ignores some theming conventions).

You'll need to copy ubercart/uc_order/templates/uc_order-customer.tpl.php to ubercart/uc_order/templates/uc_order-custom.tpl.php
Have a module define a new custom template via hook_uc_invoice_templates(): function MYMODULE_uc_invoice_templates() { return array('custom'); }
Set the new invoice in order setting page (admin/store/settings/orders/edit/basic).
Use the code in the above D7 example inside uc_order-custom.tpl.php. You'll have to modify since I don't think current_path() exists in D6. However, the same frontend logic still exists (add some extra markup in the template with CSS to generate a 2nd page).

There might be a better way to do this, but I've not touched D6 UC templating in a long time.


I don't know if this always is needed, but I recommended keeping Drush in sync with Drupal - the same version or newer. The current (stable) version of Drush is 8.1.2.


Error while mass subscribe using simplenews

You are getting this error because when it is trying to insert the taxonomy term ID:

INSERT INTO {simplenews_subscription} (tid ...

The value that is being passed is null:

Array ( [:db_insert_placeholder_0] =>

Best plan to fix this is to try and determine why it is not passing this taxonomy term. Did you select the term as an option when mass subscribing? This may be a bug or quirk in simplenews itself according to this thread or maybe an issue with corruption of your dataset.

Another way to resolve this if that is the case would be to alter that column to allow nulls (temporarily!), do your mass subscription action, manually add the correct taxonomy term to the database and then finish by restoring the null constraint to the column.


Cannot use object of type stdClass as array

You are able to change menu attributes using Menu Attributes module . If any customization is needed on top of that then you can follow the below process.

You can able to override theme links using theme_menu_link in template.php. Follow below step to override.

Go to your active theme folder might be in sites/all/theme or if you are using default theme then themes folder
Go to the active theme folder
Look for template.php
Override theme_menu_link by copy pasting entire function and replacing theme with your theme name.
Do your changes inside function wherever necessary!


When using {{ content.field_author_name.0 }} it works because field is rendered with the twig.
The ~ operator converts all operands into strings and concatenates them. Given that content.field_author_name.0 is a render array you need point to the string value of this field. To do this you can inspect it with the devel or twig_vardumper module using dump(content.field_author_name.0). More about debugging twig templates: https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates#s-viewing-variables

Assuming that field_author_name is simple text field with the Plain text formatter, this should work:

{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ content.field_author_name.0['#context'].value }}

To display node creator name you can use this:

{{ node.changed.value|date('m.d.y') ~ ' | By, ' ~ node.uid.entity.name.value }}


How can I render a result row using the Views API

The tokens in views requires $view->row_index to be set to be able to get the right rendered fields.

$view = views_get_view('nearme');
$view->execute('default');
$view->preview();

$renderer = $view->style_plugin->row_plugin;
foreach ($view->result as $index => $row) {
  $view->row_index = $index;
  echo $renderer->render($row);
}


SMTP module: The following From address failed

I believe the problem lies with Yahoo not having your permission to send from the gmail account.  You could try setting up Yahoo to send from your gmail account but I'm not sure Yahoo will do that.

You could look into a mail service like MailJet, which is cheap and scalable.

Or, assuming you're using the drupal_mail function, simply set your $from variable in 'params' to 'my_yahoo_mail_address@ymail.com'.


How to set all values of a field as body classes

Instead of reinventing the wheel, you could take a look at Display Suite.  DS has this functionality built in.

DS comes with a sub-module (DS extras) that has a feature that allows users to select a style right from the node edit page.

After enabling ds, ds_ui, ds_extras you can enable /admin/structure/ds/list/extras -> Other Tab -> View mode per node to use the feature.

Description of the feature:

  Change view modes for individual nodes. A new tab 'Display settings'
  will appear on the content create form. You can also pass the name of
  a view mode through the URL, eg node/x?v=full. If you install the Page
  manager module and override the node view, Page manager will win.

Update: If you still want to do it the way you started, you can just change this bit to use a foreach:

Change:

if($term = field_get_items('node', $node, 'field_layout')){
  $vars['classes_array'][] = drupal_html_class(reset($term));
}

To:

if ($term = field_get_items('node', $node, 'field_layout')) {
  foreach ($term as $item) {
    $vars['classes_array'][] = drupal_html_class($item['taxonomy_term']->name);
  }
}


Is this Drupal 7? If so, you can do this:

function ohm_preprocess_user_register_form(&$vars) {
   $current_path = current_path()
   $variables['theme_hook_suggestions'][] = 'user_register_form__' . str_replace('/', '-', $current_path);
}

This should allow you to use user-register-form--user-register-recruiter.tpl.php


This works for me:
$pager = \Drupal::service('pager.manager')->getPager();
$count_results = $pager->getTotalItems();


How do I add attributes to an entity reference field?

The best and standard way to do this is with paragraphs.

Enable the paragraphs module, then add a paragraph type called ingredient with the two fields, an entity reference field and a field for the quantity.

if you want an ingredient to be reusable, keep in mind that paragraphs are not reusable.  If you want to reuse an ingredient, say "1 cup flour", then you could use an entity reference field to another reusable entity type, such as media or taxonomy, or another node type.


Go to http://drupal.org/node/<yoursandboxnid>/edit and at the bottom of the edit page is a delete button.


Not sure what exactly you mean with "creating" views.

First, if you have custom tables/data, you can use hook_views_data() and custom plugins and handlers to tell views how to access these tables. Some Tutorials/examples: http://treehouseagency.com/blog/neil-hastings/2010/01/19/views-handler-easy-way (Drupal 6) and http://larsolesen.dk/node/273 (Drupal 7). But again, you only need this if you want to expose your own tables to views.

Then, there are a number of pre-render and alter hooks, which allow you to alter some things that you can't do in the user interface. List of views hooks in Drupal 6.

That said, there is no "API" to create actual views (that I know of). I think everybody uses the views UI for that (After all, it's a great UI now in Drupal 7). What you can do is export the views you created in the UI to distribute them with your module or as a new module. This is also useful for contributed/standard modules to not only expose their tables to views but also provide example views, which can be customized/extended for a specific site.

Instead of exporting them manually, you can also use the Features module, which allows you to export all kinds of configuration (views, content types, fields, permissions, ...) into so called features (which is basically an automatically generated module). That is especially useful when moving configuration like views from a development to a production installation, or re-using the same views/configuration on multiple sites.


Likeit module count for an entity refrence field in drupal 8

Just use hook_preprocess_hook() and get the referenced entities values.

function YOURTHEME_preprocess_node__recipe(&$variables){
  kint($variables);
}

For kint() you need to enable devel kint module.

Pass each entity like below:

$like_count = likeit_get_count($entity);

This will provide the likes of the entity that you have passed. Once you get the count pass it in your node--recipe.html.twig


How to import content to Drupal 8 site by inserting it directly in the database?

Turned out that I also had to update node_revision table, so all I have done was:

node (D7) -> node (D8)

select nid,vid, 'article', UUID(), language
from node
where type = 'story'

field_data_body (D7) -> node_body (D8)

select 'article', null, entity_id, revision_id, language, 0, body_value, body_summary, 'basic_html'
from field_data_body
where bundle = 'story'

node (D7) -> node_field_data (D8)

select nid, vid, 'article', language, status, title, uid, created, changed, promote, sticky, 1, 1
from node
where type='story'

node (D7) -> node_revision (D8)

select nid, vid, language, created, uid, null, 1
from node
where type='story'

node (D7) -> node_field_revision (D8)

select nid, vid, language, status, title, uid, created, changed, promote, sticky, null, language
from node
where type='story'

Of course, these are just simple queries for just one particular article type without any additional fields, but the point was to show which tables need to be updated to at least get the content in the Drupal 8. Other (field) tables will require more sophisticated SQL exports.


In node.tpl

    hide($content['comments']);

This hides both the comment form and the comments.

To render the comment form alone use

    print render($content['comments']['comment_form']);

Then you can create your view for them nice comments and display them below the form.


How to display fields from different entities in views

Start with either the base table of user entity or profile 2 entity, then just add a relationship in views to the other. It is found under the "advanced tab" in views.


Copy filefield image to different filefield field

I fixed it by running SQL on the database directly through phpmyadmin.
First I added the destination field to the content type.
Then, I went into phpmyadmin and ran this: (change your field names as appropriate.

INSERT field_data_field_image SELECT * FROM field_data_field_event_image;

and

INSERT field_revision_field_image SELECT * FROM field_revision_field_event_image;

After it ran successfully, I went in and checked the content. All good. Then I was able to delete the old field. Problem solved! Thanks.


Add the same field multiple times to a display suite node display

Since you're using display suite you can use hook_ds_fields_info for defining a new display suite field that you can use to clone your existing field.

/**
 * Implements hook_ds_fields_info().
 */
function MODULE_ds_fields_info($entity_type) {
  $fields = array();

  $fields['node']['journal_clone'] = array(
    'title' => t('Journal clone'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'function' => 'MODULE_journal_clone',
  );

  if (isset($fields[$entity_type])) {
    return array($entity_type => $fields[$entity_type]);
  }
  return;
}

/**
 * Render a clone of journal.
 */
function MODULE_journal_clone($field) {
  $build = '';
  if (isset($field['build']['field_journal'])) {
    $build = $field['build']['field_journal'];
  }
  return render($build);
}


How to send an email notification reminder based on a user's date of entry field?

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the steps below. These steps are based on a date field which is added to the user profile, so that for each user you can indicate an appropriate date.
Step 1: Create a field to store the reminder date
Similar to that "Entry date" field you already have, add another field to the "user" entity with machine name (say) field_next_reminder. Allow only 1 date (to store the date of the "next" reminder), I don't see any reason why you'd want to make it required (it doesn't matter in the context of this answer). And set its initial value to "5 years after the entry date", using the same procedure you have in place already for that "Entry date".
Step 2: Create a Rules "Component"
Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at admin/config/workflow/rules):
{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_be_reminded" : { "label" : "User to be reminded", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : "[site:mail]" ,
          "subject" : "Time flies ...",
          "message" : "This is a reminder about another 5th anniversary for user with eMail id [user-to-be-reminded:mail] on [user-to-be-reminded:field_next_reminder] ...",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other To eMail ID.
Step 3: Create a "Rule" using the Rules Component
Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste, which you can do using the "Import rule" link located at admin/config/workflow/rules):
{ "rules_on_new_user_registration" : {
    "LABEL" : "On new user registration",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_insert" : [], "user_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_reminder" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_send_email_notification",
          "task" : "[account:name]"
        }
      },
      { "schedule" : {
          "component" : "rules_send_email_notification",
          "date" : {
            "select" : "account:field-next-reminder",
            "date_offset" : { "value" : 2592000 }
          },
          "identifier" : "[account:name]",
          "param_user_to_be_reminded" : [ "account" ]
        }
      }
    ]
  }
}

Note that the above rule refers to the Rules Component from the previous step.
Also note the machine name of field_next_reminder in this rule, which is the field's machine name created in Step 1 (if in step 1 you used another machine name, then also replace the machine name field_next_reminder in this rule with the machine name of the field created in Step 1 (if you don't have such field yet, or the field names don't match, then the import of this rule might not work).
The schedule_delete part of this rule ensures that previously "scheduled" reminders are removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).
Step 4: Add 5 more years to the reminder date
With what's above you should receive such reminder eMails after 5 years. But you also want that to happen after 5 (or 10) years later on (for 10 years or 15 years).
Probably the easiest way to do so, is to have some mechanism in place so that around the time you actually perform some action (to process your reminder), you also add 5 more years to the field_next_reminder. In doing so, the above magic will get triggered again (via that very same rule).
You can apply such update manually (don't forget it though). Or (my preference) you could use the Flag module to implement a designated (global) flag to flag users. And combine this with an extra custom rule with these specs:

Rules Event: User gets flagged (with the designated flag).

Rules Actions:

Do whatever you want to happen to actually send congratulations (or anything like that?) to that user. E.g sending an appropriate eMail, grant user points, grant a special user badge (yearling?).
Update the field_next_reminder (using "set a data value") to add 5 more years for your next reminder.

True, this would be a minor extra effort to get it implemented (it may take up to 5 minutes, say 15 at most ...). But the ROI of doing so would be that authorized users would only have to flag those yearling-type of users (somewhere after they receive the reminder eMail ... in which you could even include a relevant hyperlink to make the magic happen). Even better: you could use this flagging facility to start nagging yourself to not forget to flag that user ... (logic: reminder date is below 30 days, and user is not yet flagged).
Step 5: Further tuning and enhancements

The date_offset (=2592000) in the above rule corresponds to "30 days in advance", which may need review / tuning (it's about 1 month, right?).

You might want to also use the Field Permissions module to set field-level permissions to edit, view and create fields on any entity. In your case maybe you only want admins to edit that reminder field.

5 years is a long time ... remaining homework: what if the user account has been deleted.

Instead of just sending an eMail (as in the Rules Component), you could replace that by a more advanced option using the Message module (which has great integrations with the Rules module also). Here is an quote about that module (from its project page):

... enables logging and displaying system events in a number of different use cases. Events that are recorded over time are sometimes call activity streams. Exportable messages subtypes can be created for different use cases with custom fields and display (view) modes.

Step 6: User boarding
With the above solution in place, you have a solution for (a) all future new user accounts that will be created and (b) all existing accounts for which a date is entered (manually?) in that  field_next_reminder field. However you could take advantage of that existing "Entry date" you mentioned, to also get a similar process in place for your existing user accounts, by performing an (one time only) appropriate mass update (bulk) operation. If you wonder how to also get that to work, then use this link.
Note: Using Rules to send an email X days after a user registers also contains quite some details that may help you.


Custom content type with a gallery and its "subgalleries" (or categorized gallery) in D7

I don't know how well exactly this will fit in with your use case, but this is how I'd do it:

Create a content type called "SubGallery", add an Image field to it with unlimited cardinality.
Create the content type you want to contain the sub-galleries ("Building")
Add an Entity reference field to the "Building" type that references an unlimited number of "SubGallery" nodes.
Choose "Inline Entity Form" as the widget for that field, which will allow users to create the "SubGallery" content types within the same form as the "Building".

You can make use of the standard node title field for the name of the sub-gallery, or you might add a vocabulary called "Gallery Type", and add a field referencing that to the "SubGallery" content type. Then when your users add a new sub-gallery via the inline edit form, they can choose one of your pre-defined gallery types to associate with it.

If you do add the vocabulary and no longer need a node title for the sub-galleries,you could use Automatic Nodetitles to fill it in automatically and hide it from the users.


How to display an entity property 'type' with form api 'type' for display in a form and then setting with the submitted value?

In response to Clive's comments under my question I have setup a project on drupal.org and issue to the Entity module issue queue as adding this functionality appears to be the best action. This would be the first contribution I've made so I'm eager for others to take on co-maintenance.

After I've thought a bit on how to go about doing this (still very open to suggestions) I'll add code etc. For the time being Clive's suggestion of using Entity module might be right but I've not yet checked it all out.

In the meantime, here is the code I was using (just as a fairly straight-forward form callback) with a form and call_user_func_array() passing through the callback the user would have used. That's just in a basic custom module I called entity_to_form because tbh that's all I know how to do at the moment).

code:

/**
 * Form callback
 *
 * @param entity type, existing entity type as in entity_load() $entity_type
 * @param callback, as in call_user_func_array() $callback
 * @param array, as in call_user_func_array() $param_arr
 */
function entity_to_form_new_form($form, &$form_state, $entity_type, $callback) {
    // if not a valid entity type, set error and return
    $info = entity_get_info($entity_type);
    if (!is_array($info)) {
        global $user;
        $variables = array(
            '%uid' => $user->uid,
            '%timestamp' => time(),
            '%callback' => $callback,
            '%param_arr' => json_encode($param_arr),
        );
        watchdog('entity_to_form', 'callback not existing: error during function
            entity_to_form_new_form() timestamp = %timestamp, uid = %uid,
            callback = %callback, param_arr = %param_arr', $variables,
            WATCHDOG_ERROR, $link = NULL);
        drupal_set_message('An error occurred and processing did not complete',
            'error');
        return;
    }
    // if not a valid callback, set error and return
    if (!function_exists($callback)) {
        global $user;
        $variables = array(
            '%uid' => $user->uid,
            '%timestamp' => time(),
            '%callback' => $callback,
            '%param_arr' => json_encode($param_arr),
        );
        watchdog('entity_to_form', 'callback not existing: error during function
            entity_to_form_new_form() timestamp = %timestamp, uid = %uid,
            callback = %callback, param_arr = %param_arr', $variables,
            WATCHDOG_ERROR, $link = NULL);
        drupal_set_message('An error occurred and processing did not complete',
            'error');
        return;
    }
    // get information about the entity properties and custom fields
    $property_info = entity_get_all_property_info($entity_type);

    // dynamically set elements for the properties and custom fields

    // fullfil the final requirements for the submit handler
    $form['entity-to-form']['submit-callback'] = array(
        '#type' => 'value',
        '#value' => $callback,
    );
    $form['entity-to-form']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

/**
 * Form submit handler
 */
function entity_to_form_new_form_submit($form, &$form_state) {
    $callback = $form_state['values']['submit-callback'];
    $variables = '';
    call_user_func_array($callback, $variables);
}


Effectively this is a multistep form. Display the form showing a "Preview" button. On submit save something to the session or $form_state and redisplay the form. If the value has been set in the session show a "Submit" button. On this submit you can save the form values to the database and clear whatever flag value you had in the database.


To debug more on WSOD, you can always go to Server (Apache2/httpd) error logs or if accessible Recent logs Messages (Admin => Reports => Recent Log Messages) in Drupal.

You can find more details about WSOD and debugging it on below link:
Blank pages or "white screen of death" (WSOD)

Hope this helps.


How can I flag (follow) user by REST API using service resources?

Try the following

Flag

URL: http://example.com/apiauthd/flag/flag

Method: POST

Parameters:-
    flag_name: like
    action: flag
    uid: { uid of the logged in user}
    entity_id: { uid of the other user to be flagged}

Unflag

URL: http://example.com/apiauthd/flag/flag

Method: POST

Parameters:-
    flag_name: like
    action: unflag
    uid: { uid of the logged in user}
    entity_id: { uid of the other user to be unflagged}


It depends on what event you have subscribe your rule for.

If you choose event as 'Drupal is initialised' and then choose action as 'Show message on site',the message will be showed on every page request, only thing you would like to make sure is disabled the repeat behavior of message, so that message does not stack up on every page request.

Here goes the export of such rule, that might give you a good starting point.

{ "rules_system_wide_message" : {
    "LABEL" : "System Wide Message",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "DO" : [
      { "drupal_message" : { "message" : "Site wide message", "repeat" : "0" } }
    ]
  }
}


You can do this by using HTML TITLE module

  Drupal node titles are restrictive and do not support italicized text
  or superscript text (e.g., Book titles, trademark symbols). The HTML
  Title module allows a limited set of HTML markup (em, sub, sup, b, i,
  strong, cite, code, bdi, wbr) to be used in node titles. It filters
  all other markup from titles to prevent XSS vulnerabilities or
  irrational nesting (e.g., links within links).


For Drupal 6, there was Conditional Fields.

There is no Drupal 7 version yet, but there is an issue which links to field conditional state which at this point is only a sandbox project but seems to be widely used already.


Force redirect if a valid taxonomy term is not at the start of the URL?

I wouldn't recommend using such system because I also have the gut feeling that this would create some major confusion for modules relying on the drupal path system.

I think you should better deal with subdomains like city.site.com.


importing XML file to create/update nodes, relation nodes/users, and taxonomy terms (to several vocabularies)

The migrate and migrate extras modules are your best friend for this (for Drupal 6 and 7).

The downside is all configuration is done in PHP Classes so you must have a reasonable amount of knowledge about them.

The upside is the documentation. The migrate module comes with an excellent example module that has examples for importing taxonomy, users, nodes + comments, files and roles from a SQL database and XML (it can also import from CSV, JSON and more but is not part of example module)

If you're looking for a nice UI to handle all this, migrate is not for you. You won't find anything else as flexible and full featured though.


Use of a global variable ('submission counter')

I would recommend implementing the Serial Module:

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and
  shared by nodes belonging to all content types, serial fields are
  managed per content type (D6) / entity (D7). For example, the serial
  field of an Invoice instance will generate a unique sequential number
  (starting at 1, then 2, etc.) exclusively for Invoice instances.

  The allocation of serial numbers by this module is atomic. In other
  words, the serial values are unique even when multiple instances of
  the same content type / entity are created simultaneously.


While $GLOBALS['base_url'] will give you the domain, it really isn't a good idea to use it directly.  URLs should either use url() or file_create_url().  For example,

$path = drupal_get_path('theme', 'MYTHME');

drupal_add_html_head(array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => file_create_url($path . '/images/touch-icon-iphone.png'),
    'rel' => 'apple-touch-icon',
  ),
), 'MYTHME-touch-icon-iphone');

will add the iPhone icon meta to the <head> from the images/ directory from a theme.  Leveraging the API will allow paths to be altered, which is necessary for module like CDN to do their thing.


Concatenate $base_url and path_to_theme()

In hook_preprocess($vars) create a new variable called path_to_theme in $vars by including the following (where $hook is page, node, block etc)

function mymodule_preprocess(&$vars, $hook) {
  $vars['path_to_theme'] = base_path().path_to_theme();
}

Now in virtually all of your theme's template you can use the variable $path_to_theme and it will be the contents of base_path().path_to_theme()

Note, that you can put this in a custom module, or replace mymodule with the name of your theme and you can place it in your theme's template.php

You can use node, page, and other "hook" specific preprocess functions if you only wish to add this variable to specific content of your site.

There are many options for preprocessing nodes, pages etc. which can be read up in:
Setting up variables for use in a template (preprocess and process functions)

Also be sure to read up on the Default baseline variables such as:

  $directory The theme path relative to
  the base install. example:
  "sites/all/themes/myTheme"


When you redirect to the login or registration page you can add a destination GET parameter to the url, which Drupal will redirect to after form submission.


Get the uri/path value of an image in the field template

you want file_create_url().

Note: Usage of drupal_realpath() is discouraged.

Similar question: What is the alternative to drupal_realpath()?


Ah. Finally figured it out. The Left Sidebar is actually called sidebar_first. DSM'ed the $page variable.


How to display form submitted values without storing in database

I suggest:

deleting all the default submit handlers in the submit array in the $form variable - to stop the data being stored in the database
add your own submit handler to do the calculation and store the result in the standard PHP _SESSION variable
add a #redirect property in the (correct place) $form array variable to redirect the to URL of the result page
write code for the result page output the result in the _SESSION variable. To do this determine what type of page will display the result so that you can implement appropriate code to display the result  - there are several ways to do it: e.g. code in a template file, or a custom programmatically created block


I assume that as soon as you add a contextual filter, that is not a fixed value, the View becomes uncachable since it becomes dynamic, right?

No.

That just means that the view's output varies based on the URL. Specifically, a query argument.

This is why we in Drupal 8 have the concept of cache contexts: https://www.drupal.org/developing/api/8/cache/contexts.

For the Views module to efficiently determine whether a view can have a cached version or not, we need to know ahead of time which contexts a particular view display varies by. So, upon saving a modified view, the Views module iterates over all plugins that a particular view display uses and gathers its cacheability metadata. It then stores it in the view config entity.

Concrete example: the "Taxonomy Term" view that ships with Drupal 8 core. It has a path of /taxonomy/term/%, with that % being a particular taxonomy term ID. Open core/modules/taxonomy/config/optional/views.view.taxonomy_term.yml and scroll all the way to the bottom. You'll see this:

page_1:
    id: page_1
    display_title: Page
    display_plugin: page
    position: 1
    display_options:
      query:
        type: views_query
        options: {  }
      path: taxonomy/term/%
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_interface'
        - url
        - 'user.node_grants:view'
        - user.permissions
      max-age: -1
      tags: {  }

Note the presence of the url cache context. That describes that this view varies by URL, in particular by the value for the % wildcard in the /taxonomy/term/% URL.


Normally you should be able to translate the placeholder in configuration translation as described in https://drupal.stackexchange.com/a/191927/47547. @Berdir pointed out that there is an open issue that prevents this: https://www.drupal.org/node/2546212

A workaround is to make the placeholder translatable in a form alter hook:

function mytheme_form_contact_message_feedback_form_alter(&$form, $form_state) {
  $form['subject']['widget']['0']['value']['#placeholder'] = t('Please enter a subject');
}

After visiting the translated form you can translate this string in the user interface translation.

If you want to translate all placeholders in the form and use the untranslated strings from the widget settings:

function mytheme_form_contact_message_feedback_form_alter(&$form, $form_state) {
  array_walk_recursive($form, function (&$value, $key) {
    if ($key === '#placeholder' && is_string($value) && $value !== '') {
      $value = t($value);
    }
  });
}


Links in stage environments are absolute and send users to live enviroment

So ive solved it with js

$('a').each(function() {
    if(!$(this)||$(this)=="undefined") return;
    var href = $(this).attr('href');
    if(!href)return;
    if (href.includes("live-environment.org")){
        var live_env_url = href;
        var stg_url = new URL(live_env_url);
        stg_url.hostname = Drupal.settings.basePath.substring(0, Drupal.settings.basePath.length-1);;
        $(this).attr('href', decodeURIComponent(stg_url.href));
    }
});


How can I render a menu item as a span (or other elements) instead of a ?

You can use Special menu items module.

  User can create a new menu item and place either  or
   to the Path field, without quotes.

Also, you can look at another handy module called Menu attributes which allowed you to have control over menu link attributes.

Both modules use hook_menu_alter to adjust the changes to the menu item, you can take look at the module's code to understand how it works exacitly if you are interested.


Form element title is not displaying translation

I think you need  add t() in #markup and translate the string 'Estimated time:'

$form['informacie_o_incidente']['field_incident_doba'] = array(
  '#title' => t('Estimated time'),
  '#markup' => '
'.t('Estimated time:').'
'.$doba.'

',
);


What is the best way to verify controller arguments?

Here my working example:

.routing.yml

forcontu_pages.calculator:
  path: '/forcontu/pages/calculator/{num1}/{num2}'
  defaults:
    _controller: '\Drupal\forcontu_pages\Controller\ForcontuPagesController::calculator'
    num1: 20
    num2: 10
    _title: 'Calculator Page'
  requirements:
    _permission: 'access calculator'
    _custom_access:  '\Drupal\forcontu_pages\Controller\ForcontuPagesController::access'

ForcontuPagesController.php

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
...
  public function access(AccountInterface $account, $num1, $num2) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    return AccessResult::allowedIf($num1 > $num2);
  }
...

I just verify that $num1 is greater than $num2, but you can add your other params and your validations.

See that you can add more params:

  The access method arguments are resolved similar to normal
  routing. The following arguments are optionally available; they will
  be populated if they are properly type hinted:

  The slugs, like with normal routing.
  \Symfony\Component\HttpFoundation\Request $request
  \Symfony\Component\Routing\Route $route
  \Drupal\Core\Routing\RouteMatch $route_match
  \Drupal\Core\Session\AccountProxy $account

Read: What is a slug?

Reference:
Access checking on routes


If you want the .es and .mx content to be unique, you should treat them as different languages.

create a new mx-spanish language type.  even though it is "spanish" the system has no idea,  you can just load the unique content there.


Calling user/token and system/connect through CORS returns anonymous user

You just haven't logged in to the remote site yet; you can do that with something like:

$options['headers']['X-CSRF-Token'] = $data->token;
$options['method'] = 'POST';

$post_data = ['username' => 'foo', 'password' => 'bar'];
$options['data'] = drupal_http_build_query($post_data);

$response = drupal_http_request($base_url_api . '/user/login', $options);
$data = json_decode($response->data);

Assuming a successful login, subsequent requests within the session timeout will be made in the context of that user.


Change title of certain paragraphs in a form

If you want to change the title of certain paragraphs in the form:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'foo') {
    // insert more conditions
    $element['top']['paragraph_type_title']['info']['#markup'] = t('New title for paragraph type Foo');
  }
}


Is it possible to set a role specific value for "allow_insecure_uploads?"

Module suggestions are usually frowned upon on DA, but regardless the answer is yes; role-specific config values are possible via the D8 config override system.

The Drupal 8 docs has a section on the config override system with a relevant example in the Providing overrides from modules section. After you've declared the override class in your module's .services.yml & created the override PHP class, you'll do something like this in the loadOverrides() method:

 public function loadOverrides($names) {
    $overrides = array();
    // @TODO: define a hasRole($role) class method that checks Drupal::currentUser() for a given role
    $has_role = $this->hasRole('my_role');
    if (in_array('system.file', $names) && $has_role) {
      $overrides['system.file'] = ['allow_insecure_uploads' => TRUE];
    }
    return $overrides;
 }


How to create a view that searches nodes and users at the same time?

You can't really do what you ask the way views is built, not without overriding a lot of classes etc which probably would be more complex than building it all by hand.

A simple workaround would be to create two views and thus have two forms. Then you can show the form for user search when user is selected and node search when one of the node types is selected. That would also allow you to create custom filters for the user/node search, like date posted or last login.

You can use some simple JS to control hide/display of the forms.


Print image field path in views-view-fields--key-projects.html.twig

To get the path of an image in a view, use the image format 'URL to Image' in the field setup. I have not found a really good way to get the site absolute, rather than relative url, but prefixing the returned value in a rewrite block with {{ url'(<front>') }} is almost there:

{{ url'(<front>') }}{{ field_image }}

To use that in a different field (content), mark it 'Excluded from display' and then reference that field using a rewrite in another field, or using a twig field template.


Managing Drupal Core in Git for Aegir Platforms

Our current (simplified) practice at work:

Pull down the drupal core git repo http://drupalcode.org/project/drupal.git/
Add upstream to your local project that tracks the above repo
When a new version of drupal is released, fetch the drupal repo and merge the appropriate tag

e.g.

cd /var/www/your-platform/
git fetch upstream
git merge 7.7


Ideally I'd have it such that once the https session was started, any access to the http site bounced them over to https again, until they logged out.

Maybe it can be done on web server side, but I'm not sure.

  How to redirect logged in users accessing /user/login to specific page?

Don't forget you can alter any drupal_goto() calls:

/**
 * Implements hook_drupal_goto_alter().
 */
function YOURMODULE_drupal_goto_alter(&$path, &$options, &$http_response_code) {
  global $user;

  if (current_path() == 'user/login' && $path == 'user' && user_is_logged_in()) {
    // Redirect to front page.
    $path = '';
    drupal_set_message(t('Welcome back, %username!', array('%username' => $user->name)));
  }
}


Does the drush up command work on multisite?

Yes!  But maybe no!  Be careful!

If you run pm-updatecode on any code in a given Drupal site, it is necessary to run updatedb afterwards in order to make the database schema(s) match the current schema in code.  So, while drush -l mysite1.com will in fact correctly run pm-updatecode followed by updatedb on mysite1, if you have any modules in sites/all/modules that is updated, or if Drupal core is updated, then you will also need to run updatedb on every other site in the multisite install.  If you skip this step, then mysite1 will work, but you might break the other sites in the multisite install.

When dealing with a multisite installation, the safest policy is:

Copy live to dev
Run pm-updatecode on every site in the multisite on dev
Run updatedb on every site in the multisite on dev
Test!  Test!  Test!
Take all of the sites in the multisite offline on production
Push your updated code from all multisites on dev to production
Run updatedb on every site in the multisite on production
Test again!
Bring all of the sites back online

You can avoid doing all sites at once if you know that all of your updated modules are in sites/mysite1/modules, and Drupal core is not updated.  In general, though, it is better to avoid multisite installs so that you do not need to worry about the interdependence of the shared code on multiple databases.


Can behat log in as an administrator for testing while using LDAP?

I had this issue as well. It turned out to be a problem with LDAP. Switching to Mixed Mode allow the DrupalExtension to function properly. Since we don't want mixed by default, I added a pre-test setup function

public static function prepare($scope)
     {
        $data = array(
          'sids' => array (
            'directory' => 'directory',
          ),
          'authenticationMode' => 1,
          'loginConflictResolve' => 2,
          'acctCreation' => 4,
          'loginUIUsernameTxt' => NULL,
          'loginUIPasswordTxt' => NULL,
          'ldapUserHelpLinkUrl' => NULL,
          'ldapUserHelpLinkText' => 'Logon Help',
          'emailOption' => 3,
          'emailUpdate' => 1,
          'allowOnlyIfTextInDn' => array (),
          'excludeIfTextInDn' => array (),
          'allowTestPhp' => '',
          'excludeIfNoAuthorizations' => NULL,
          'ssoRemoteUserStripDomainName' => NULL,
          'seamlessLogin' => NULL,
          'ldapImplementation' => NULL,
          'cookieExpire' => NULL,

        );
        variable_set('ldap_authentication_conf', $data);
     }

The key is the line 'authenticationMode' => 1,


How to hide country in Address Field display?

I overrode the field.tpl.php file as described in this video:

Drupal 7: Theming Fields and Nodes with Templates by linwclark

I copied the field.tpl.php file from <site_root>/modules/field/theme/field.tpl.php and put it into the templates directory of my zen subtheme (<site_root>/sites/all/themes/somezentheme/templates/field--field_address.tpl.php)

In that template I used the hide() function on country:

  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
    <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php hide($item['country']); print render($item); ?>

    <?php endforeach; ?>


How do I stop the page refresh on pressing "enter" in a form's text field?

You need JS/JQuery assistance in this regard.

var stopSubmission = false;
jQuery('#q').keydown(function(e){
   if(e.keyCode == 13){
       stopSubmission = true;
   }else{
       stopSubmission = false;
   }
});

jQuery('form[action="/help/search"]').submit(function(){
    if(stopSubmission){
        return false;
    }
});


How can I make Search Terms in a View to look fo into the edited Summary?

I have discovered how to get it work: just selecting in the Manage Display --> Search Indexing, Body Summary or trimmed. Isn't it confussing? It seems that it will search only in the summary, while it searches in both Summary and Body. And now it works with edited Summaries.


First thing is this its not a good practice to write the php code in CKeditor because it impact the execution of page and increase the page load time.
So it would be better to create the specific page tpl and and render all the drupal variable there.

Reason ::  Why its not rendering the drupal in CKeditor because after the complete page load its execute the content section of CKeditor and at that page has not page drupal variable (now page has only html content).

Thanks


Disable Elysia Cron task programmatically

I realize this is pretty old but if you are only concerned with one task and not a whole channel...

elysia_cron_set_job_disabled('mymodule_cron', true);

will disable a cron job. Not surprisingly,

elysia_cron_set_job_disabled('mymodule_cron', false);

enables it again.


Drupal Content Type Data Become Label for Field on Another Content Type

A better way is to use Entity reference

  Provides a field type that can reference arbitrary entities:


How to add /admin/people as a tab to a custom menu?

In a custom module (mymodule), create a mymodule.links.task.yml file, and add the following:

mymodule.admin_people:
  route_name: entity.user.collection
  base_route: route.of.your.custom.menu
  title: 'Tab text goes here'

Here's what each part does:

mymodule.admin_people Is the identifier of your menu tab item (the file being *.links.task.yml means its the menutab file)

route_name  is the route the tab points to, and entity.user.collection is the route that corresponds to /admin/people .

base route displays your tab on the specified route. To find the route for your view, download the Devel module, turn it on, and go to "Routes info" to get your route. Usually a view is of the format view.[view_machine_name].[view_display_id], i.e. view.myview.page_1 . Check the "advanced" section of your view's management page for the display ID.

title is the text that will go into the tab.


Connect to remote DB using global php drupal 7 views

Nothing is a security risk in and of itself. If you know basic PHP and the basic usage of mysql_query and how to sanitize your input -- you're fine.

What you're proposing is not by any means a best practice, proper use of Views or the Drupal API (sorry).

If you want to make Drupal aware of other databases see:
https://drupal.org/node/18429
If you want Views to be able to query an external DB table see:

https://api.drupal.org/api/views/views.api.php/function/hook_views_data/7

if you want to know how to describe your table to Views using the Drupal Schema API for an existing table see the Schema contributed module which leverages the built in Schema API of Drupal 7:

https://drupal.org/project/schema

If you want to make a view and alter its SQL or resultset see: (possibly interacting with another DB, or using PHP to alter the row results somehow, maybe by examining another db query result)

https://api.drupal.org/api/views/views.api.php/group/views_hooks/7
https://api.drupal.org/api/views/views.api.php/function/hook_views_pre_render/7
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7

All of these options make use of Drupal core features for interacting with 3rd party databases, Drupal API or Views contributed module API.

Your approach is taking an embedded php field in a view and ignoring Drupal and its architecture to achieve what you want. It's as secure and safe as your experience and knowledge make it. I prefer to stand on the shoulders of others and leverage the security built into Drupal and its supported APIs.

You may find the Data module useful in making your 3rd party data play nicer with Views.

  Data module helps you model, manage and query related sets of tables.
  It offers an administration interface and a low level API for
  manipulating tables and accessing their contents. Data module provides
  Views integration for displaying table data and Drupal search
  integration for searching table content.


No, cannot be empty.
You can generate one with
$uuid_service = \Drupal::service('uuid');
$uuid = $uuid_service->generate();

If you use User::create it will automatically generate one for you.
Drupal\user\Entity\User::create([
  'uid' => $uid,
  'name' => '$user_name,
  'mail' => $email,
  'roles' => [],
  'pass' => [
    'value' => $hashed_drupal_7_password,
    'pre_hashed' => TRUE,
  ],
  'status' => 1,
])->save();

Rather than code it from scratch. The proper, Drupal way, to migrate is
using all of these:

core's migrate
migrate plus
migrate tools

I suggest your read this article A Quick Guide to Migrating Drupal Content from D7 to D8 which goes over how to migrate users and other scenarios.


change where Authoring information and Publishing options Checkbox is displayed

In the admin/content page
1. at the top there is filters provided to sort content by number of options like for e.g filter by content type, published or unpublished.
2. then below that there is drop down containing list of actions like "publish selected content", "delete selected content", etc
3.You can select the check box corresponding to the content you want the action to perform and submit.


How to condition SelectQuery by field value?

Yay, I dit it:

$query = $view->build_info['query'];
$query->leftJoin(
  'field_data_field_referenced_user',
  'field_referenced_user',
  'taxonomy_term_data.tid = field_referenced_user.entity_id'
);
$query->where(
  'field_referenced_user.field_referenced_user_target_id = :uid',
  array(':uid' => $user->uid)
);

$view->build_info['query'] = $query;


Move title below image in Views grid format with CSS

You could simply edit the "Teaser" view mode and place the title below the image using Display Suite Here are the instructions:

Download Display Suite and enable the "Display Suite" and "Display Suite UI" modules.
Go to admin/structure/types/manage/article/display/teaser where "article" is your content type.
In the "Layout for article in teaser" fieldset, select the "One column" layout and click Save.

You will now see a lot more fields, provided by the Display Suite module. One of those fields is the title field.

Now drag the title field up to the top, below the Image field, just like you requested. From what I understand from your question, you could remove the Body field as well.

All done! No custom theming required.


How to show a specific amount of multivalue fields depending on a value of the parent node?

Don't know what the proper way is to handle answers where the solution comes from another posting. So I only make the reference here: https://drupal.stackexchange.com/a/140861/24957

The code below works perfectly and only shows $amountOptions fields.

if (!isset($form_state['build_info']['args'][0]->field_toinvest[LANGUAGE_NONE][0]['value']) && !isset($form_state['default_fields'])) {
for ($i = 0; $i < $amountOptions; $i++) {
// First field is already in form.
  if ($i > 0) {
    $form['field_toinvest'][LANGUAGE_NONE][$i] = $form['field_toinvest'][LANGUAGE_NONE][0];
  }

  // Set form values
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#default_value'] = 0;
  $form['field_toinvest'][LANGUAGE_NONE][$i]['value']['#value'] = 0;

  // Set row weight
 $form['field_toinvest'][LANGUAGE_NONE][$i]['_weight'] = array(
  '#type' => 'weight',
  '#title' => t('Weight for row ' . ($i + 1)),
  '#title_display' => 'invisible',
  '#delta' => $i,
  '#default_value' => $i,
  '#weight' => 100,
 );
}
$form_state['default_fields'] = 1;
$form_state['field']['field_toinvest'][LANGUAGE_NONE]['items_count'] = amountOptions - 1;
}


entityQuery to get Nodes referenced by other nodes like an SQL JOIN

You can use 'entity' field query

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'article');
$query->condition('field_some_field.entity:node.title', 'Referenced node title');


How to enable users editing their CiviCRM profiles details from their Drupal user page?

Create a CiviCRM Profile (or reuse one of the existing ones) by going to Administer >> Customize Data and Screens >> Profiles and set it to be enabled on "View/Edit Drupal User Account". Then the user will be able to edit their details from their Drupal user page.

See this Demo Profile on CiviCRM Demo site and notice that "View/Edit Drupal User Account" is checked. Take a look at this tab on the Drupal user page. The fields in the Profile can be edited.

For more details see: the CiviCRM book section on Profiles.


'Add another' fieldset on a multi-step webform

Try using Field Collection in the form. It got the feature of adding multiple fieldset on the fly.


Creating rollover tooltip for a view (Netflix Style)

You probably want to use the Views Tooltip module, which allows you to do exactly that. It depends on the Tipsy tooltip module, and works with Drupal 7.


Return a view's total_rows in Drupal 7 without php filter?

On my D7 site with php-filter disabled ...

From a View configuration page:
HEADER section, add, Global Result Summary

pick total row count or whatever, whatever you want:

You may use HTML code in this field. The following tokens are supported:
@start -- the initial record number in the set
@end -- the last record number in the set
@total -- the total records in the set
@name -- the human-readable name of the view
@per_page -- the number of items per page
@current_page -- the current page number
@page_count -- the total page count


If you are sure that your password is correct go to the Data base and empty( truncate) Sessions & Flood and all cache(I mean all tables has prefix cache_) tables,finally  clear your browser cookie then try to login otherwise(If you are not sure about password) try to reset password programmatically


different drop down list for different nodes

Views + Node Reference. Create new Views, that handle arguments of current node and filter agents by required bank.


How to format the raw date formats when using Google Analytic Reports?

Feature request #1900994 (from early 2013), with title "Date Format in Views", seems to have been delivered (fixed) near the end of 2014 via issue #2368159, with title "Add support for datapoints types". Refer to description of the issue for more details about it (the problem description, and the actual solution that got implemented).

Issue #2368159 also resolved the issue about Format time duration, a typical variation of the question here.


Checkboxes, Radios, 'select or other' wont render inside table select element

I believe you are missing some details in the way you structure your data. Check this example, specifically the data array tree.

Also, check the structure of the array that defines the tableselect. For radios it should look like this:

$form['table'] = array(
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $options,
  '#multiple' => FALSE,
);

(the #multiple property is the one that defines whether these are checkboxes or radios)

Your data in the array $options should look something like this:

$options = array(
  '1000' => array(
      'field_price' => '$1000',
  ),
  'other' => array(
      'field_price' => 'Other',
  ),
);

Notice the nested structure, and the field name (this could be anything, but it needs to exist, one for every column of the table, starting with the second column.


Add the field Taxonomy term: Term ID to your list. On the settings of this field you have options for Rewrite results check the box Output this field as a custom link on the path option you can write it taxonomy/term/{{ tid }} and below to can check the box Use absolute path if you want too.

This will automatically convert the link into alias if it exists.


Replace \Drupal::service with Dependency injection in FieldWidget class

This requires three steps:

Declare a property to hold the service.
Implement a __construct() method to populate the property from step 1.
Implement a create() method, to generate the service that is passed to __construct().

1) Declare a property to hold the service

In your class, declare the property that will hold the service.

/**
 * The example service.
 *
 * @var \Drupal\example\Service\ExampleService
 */
protected $exampleService;

With this, you can now refer to $this->exampleService within your class. However, at this point it is still NULL, so it needs to be populated.

2) Implement a __construct() method to populate the property from step 1

This is done by overriding WidgetBase::__construct(), and adding the service to it.

public function __construct(
  $plugin_id,
  $plugin_definition,
  FieldDefinitionInterface $field_definition,
  array $settings,
  array $third_party_settings,
  ExampleServiceInterface $exampleService
) {
  // Initialize the parent class:
  parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);

  $this->exampleService = $exampleService;
}

Now the property from step one can be populated when the class instantiated. However, the service itself needs to be generated, and passed to the __construct() method.

3) Implement a create() method, to generate the service that is passed to __construct().

The service is generated in the create() method. This is done by copying the code from WidgetBase::create(), and adding the service to it. WidgetBase::create() looks like this:

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $plugin_id,
    $plugin_definition,
    $configuration['field_definition'],
    $configuration['settings'],
    $configuration['third_party_settings']
  );
}

Notice that the values returned are the same values passed to the __construct() method, but without the example.service service. The example service needs to be retrieved from $container and added to the above, by implemented create() in your class as follows:

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $plugin_id,
    $plugin_definition,
    $configuration['field_definition'],
    $configuration['settings'],
    $configuration['third_party_settings'],
    $container->get('example.service')
  );
}

This function call generates the example service, which passes it to __construct(), which in turn populates $this->exampleService, so it can be used in your class in place of \Drupal::service('example.service').


How do I get fields attached to a user to display to anonymous viewers?

After poking around on this for a while I discovered that it is definitely an organic groups permission issue. For the record, I have the 7.x-1.5 version of OG installed.

In OG global permissions (admin/config/group/permissions) the fields attached to the user (and nothing else) are all listed under Organic Groups Field Access along with fields attached to groups and fields attached to group content types. When I give access to non-members the fields appear for anonymous.

I suppose this functionality is designed so you can limit user access to people who are connected through a group. This isn't entirely senseless, but can be frustrating if you don't anticipate that control over some objects will be trumped by OG permissions.


When you check Output this field as a link there is a Target input box available (Further down). In that input box you can write _blank. (D7)


Drupal uses Twig's autoescape feature, which in turn uses escape, which itself uses htmlspecialchars to prepare markup safe for output.

SafeMarkup::checkPlain() preceded the autoescaping (deprecated now), so you may see that used, and HTML::escape can be used if you need to do it manually for whatever reason.

As with all versions of Drupal, filtering is done on output only, not input, so filter_var and friends aren't involved.


You might want to consider Webform. It functions differently from Poll, but it's also much more robust and has plenty of additional modules that extend it.

And, of course, creating a question that allows multiple choices is a snap.


First of all, I'm assuming that you are referring to the SMTP Authentication Support and the Elastic Email modules. The answer to your question is rather straightforward: you only have to use one of the 2 modules. So, if you are sending all your emails using the Elastic Email module, you can pretty much disable the SMTP Authentication Support.

The reason is that the 2 modules are actually doing the exact same thing: they give you a way of bypassing the default PHP mail() function. If you have decided that you want to use Elastic Email, you don't need the SMTP Authentication Support module (and I'm not sure how they interact with each other so, it's better if you disable SMTP just to be on the safe side on this).


Passing values from EntityFieldQuery to db_select

Try this approach. after getting your entities using EntityFieldQuery, create a for loop in order to check the val that was stored in your variable $entities. Then use dsm or dpm to check if it returns a result.

$results = '';
for ($i=0; $i < count($your_entity) ; $i++) {
    $query = db_select('yourtablename', 't');
    $query->fields('t');
    $query->condition('t.entity_id', $your_variable);
    $results = $query->execute()->fetchAll();
}
dsm($results);

Hope this helps you.


I can't get the correct current language in node URLs

After narrowing down the issue, I think I've stumbled into an actual existing, known issue: Entity Links fields does not have translation support.

https://www.drupal.org/project/drupal/issues/2877994

I still need to figure out how to apply a patch, but I suspect this is actually a duplicate of the above issue.


How to resolve error Unable to install the responsive_tables_filter module since it does not exist

If the module was never installed in the target environment, it is safe to do so.

If the module was installed before however, and it features uninstall hooks for cleaning up possibly installed database tables, key/value pairs (State API), and the like, then your approach may leave data behind.

The more appropriate way would have been to uninstall the module after you restored its module files, then export the configuration again in development, push it to production and do the import there.

Afterwards you can safely delete the module files from your environments.

The error you've seen indicates, that your code base was not in sync with your configuration. You possibly tested modules and removed its files before uninstalling them.


Is there a way to order by COUNT('column') without returning an integer?

Try this :

  use Drupal\Core\Database\Database;
  $connection = Database::getConnection();
  $sth = $connection->select('eventform', 'm');
  $sth->addField('m', 'event');
  $sth->addExpression('COUNT(m.event)', 'count');
  $sth->groupBy('m.event');
  $sth->orderBy('count','DESC');
  //- Execute the statement
  $data = $sth->execute();
  //- Get all the results
  $results = $data->fetchAll(PDO::FETCH_ASSOC);

you will get the $results as an array something like:

array:5 [▼
   0 => array:2 [▼
     "event" => "Brewery"
     "count" => "10"
   ]
   1 => array:2 [▼
     "event" => "Conference"
     "count" => "8"
   ]
   2 => array:2 [▼
     "event" => "Concert"
     "count" => "7"
   ]
   3 => array:2 [▼
     "event" => "Dinner"
     "count" => "6"
   ]
   4 => array:2 [▼
     "event" => "Musical"
     "count" => "4"
   ]
 ]

if you want to get only the event name loop thought the $results something like :

 $events_name = [];
 foreach ($results as $result){
    $events_name[] = $result['event'];
  }


How to apply the page-hiding snippet for Google Optimize?

Well, since posting my question, there is now a Google Optimize Hide Page module, which provides a code example of how to do this.

There is also a patch to add this functionality to the Google Tag Manager module.


What does it mean if expire is set to null in a cache table?

Any value for the expire column that is different from CacheBackendInterface::CACHE_PERMANENT (-1) is considered a timestamp, indicating when the cache entry could be deleted. In the case of NULL, the value means the cache entry could be deleted in any moment.
As @4k4 said in his comment, data in cache tables are deleted when cron tasks run, and that doesn't necessarily means immediately.
The only issue with NULL is whether a module is using a not initialized variable which is expected to contain the expiration time. In that case, the cached value is kept in cache less than required.


Naming conventions for fields machine name in Drupal

TL;DR Always use a short succinct but entity agnostic machine name for your fields because requirements will change.

I would never put the entity name in the field name. While today you might think that a field will only ever be used on a node. Requirements change over time. Today's assumptions will bite you tomorrow.

For example you might have a "Hero image" field and decide to use "node_hero_image" (or worse "node_blog_hero_image") because it is only used for nodes.  Later someone decides that they want to use hero images on another entity type - say taxonomy terms to create nice "category landing pages".  You have hard coded the entity type into the field. You have 2 choices, either keep the poorly named field or create a new one - both options are less than idea an increase the technical debt in your project.

If you had've used "hero" as the machine name for your field it would remain flexible. The purpose of the field is clear to anyone who sees it in the UI. You don't need "_image" in the name either as most places in the UI will tell you it is an image field.