Set parameter for internal or external traffic based on IP

To request the uncached client IP I recommend providing a JSON endpoint that has   drupal_page_is_cacheable(FALSE) set. Then get the IP from there with an Ajax request and do whatever you need to do now with JavaScript.

First, provide a route.

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['myip'] = [
    'page callback'   => '_MYMODULE_myip_callback',
    'access callback' => TRUE,
  ];

  return $items;
}

Second, provide the endpoint that returns the result of the IP comparison. (Bonus points for getting the internal IPs from an admin settings form. More bonus points for checking the user role as well.)

/**
 * Callback to provide an uncached JSON response.
 */
function _MYMODULE_myip_callback() {

  $internal_ips = [
    'x.x.x.x',
    'x.x.x.x',
  ];

  $data = [
    'internal_ip' => in_array(ip_address(), $internal_ips) ? TRUE : FALSE,
  ];

  // Mark this page as being uncacheable.
  drupal_page_is_cacheable(FALSE);

  drupal_json_output($data);
}

Third, add the JS.

/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  drupal_add_js(drupal_get_path('module', 'MYMODULE') . '/js/scripts.js', ['scope' => 'footer']);
}

Fourth, the Ajax request and DOM manipulation in the JS file.

(function ($, Drupal) {
  'use strict';
  Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {

      $.getJSON('/myip', function (result) {

        if (result.internal_ip) {
          function_to_call_if_internal_ip();
        }
      });

      var function_to_call_if_internal_ip = function () {

        // Do whatever you need to do.
        // ...

      };

    }
  };
})(jQuery, Drupal);

Note

One thing to mention. I adjusted the sample to follow your sample flow "do something if internal IP". In the original snippet I do the opposite "only add Google Tag Manager if external IP" to never have the tag manager script added at all if the request comes from an internal IP and it works just fine.

$.getJSON('/myip', function (result) {

  if (result.add_scripts_by_client_ip && result.add_scripts_by_user && result.add_scripts_by_host) {
    _add_google_tag_manager('GTM-XXXXX');
  }
});

var _add_google_tag_manager = function (gtmid) {

  if (!!gtmid && gtmid !== null && gtmid !== '') {

    $('html').once('myBehavior').each(function () {
      $('body').prepend('');
      $('head').append("");
    });
  }
};

If you use Varnish, Memchached or some other server-side caching strategy, don't forget to exclude /myip from them.


Flag module not joining flagging with EntityFieldQuery?

The flagging table is not available when querying for nodes using an EntityFieldQuery, that's why the flagging.fid column is missing in this query.

In order to get hold of flaged items, the flagging-entities need to be queried instead:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'flagging')
  ->entityCondition('bundle', 'name_of_some_flag');

Then use entity_load('flagging', ...) and obtain the nid from the entity_id-property of the flagging entities.

However keep in mind that it is impossible to sort / filter on properties of the target object (nodes in this case) because EntityFieldQuery does not support JOINs in Drupal 7.

I suggest to build a view instead of trying to battle the EFQ in this particular case.


Avoiding PHP timeout when geocoding many addresses - preferred method?

It seems to me that your only option is to go with a PHP CLI script implementation. You can learn more here: http://www.php-cli.com/

In PHP in general, whenever you have a long running task, it's best to go with PHP CLI as it doesn't impose a timeout limit and have larger memory limits by default. Note here that PHP CLI and the PHP used to server web pages have different settings that you can manage separately.

Once you have a PHP CLI script in place, setup a standard Linux CRON task to hit that script say every hour or every day.

In the context of Drupal, you might want to check this post: Do I need a cron task for processing a queue? and also check the Elysia CRON module https://www.drupal.org/project/elysia_cron as they might be helpful but I think in your case you're better of with a standard PHP CLI script.

Also, keep in mind that you can call Drush commands from a PHP CLI script very easily. I have a script that runs updates and CRON automatically on all Drupal instances running on web server and it's a huge advantage. You can also look into implementing your custom Drush commands.

Good luck.


Getting info from an external database - Base table or view not found

I know you answered your own question with a solution -- here is additional info.

The helper functions db_select(), db_update(), db_insert(), db_merge() all use the default database connection defined in settings.php. As you pointed out you can use db_set_active() to set an active database within a given scope of code. I personally dont like this approach, because X months from writing the code you will forget that, "oooohhh I used db_set_active X lines above" and run into annoying maintenance issues.

There is another solution, dont simply use the helper db functions. Use their parent Objects, which they are wrapping ... as in below:

    // 'remote_database' is a 2nd db connection defined in settings.php
    $query = Database::getConnection('default', 'remote_database')->select('survey_item', 'si');
$query->fields('si', array('item_id', 'presentation_order', 'question_type', 'stem', 'choice_1','choice_2', 'choice_3', 'choice_4', 'choice_5', 'choice_6', 'choice_7', 'choice_8'));
$query->condition('survey_id', $current_row->survey_id);
$query->orderBy('presentation_order', 'ASC');
$current_row->form_items = $query->execute()->fetchAll();

So you can create a Query as I have above by specifying the connection first. You may do this for all ->select() or ->update() or ->insert() functions which drupal supplies wrappers for.

Or, you can even pass as a 3rd argument to a SelectQuery() constructor the connection to use for the query, see the docs here:

http://api.drupal.org/api/drupal/includes--database--select.inc/class/SelectQuery/7

  // This is the constructor for SelectQuery() from select.inc
  public function __construct($table, $alias = NULL, DatabaseConnection $connection, $options = array()) {
$options['return'] = Database::RETURN_STATEMENT;
parent::__construct($connection, $options);
$this->where = new DatabaseCondition('AND');
$this->having = new DatabaseCondition('AND');
$this->addJoin(NULL, $table, $alias);

}

So you can also start a db_select() query as follows to tie it to a non default connection in another means:

$query = new SelectQuery('my_table', 'table_alias', Database::getConnection('default', 'remote_database'));
// other things you build onto your query
// $query->addJoins(...); $query->fields(...); ...
return $query->execute()->fetchAll();

So in a nutshell -- the db helper functions are convenience when talking to 1 database. Beyond that, you can specify per-query what connection to use ... if you like more fine control of your queries and not use db_set_active() all over the place.


Media module function overriting, user can see only own media

The best suggestion I can come up with is to use hook_form_alter() to alter the value of $form['admin']['#files'] (inspect the form array on the /admin/content/media page) by calling your own version of media_admin_list() with an altered query.

Something like:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'media_admin') {
        $form['admin']['#files'] = custom_media_admin_list();
    }
}

This is slightly inefficient as the original function has already run but I can't see a way to alter it before the initial form array has been built.


How to access parent site products in child site using drupal services ?

What you can do is set up different codes connecting to same database.

So all sites might have different CSS but same database so same products and other Drupal configuration.

Essentially it is one Drupal site. Does this solve your problem?


Issue with translating SQL query into Database API (count(*))

As @Clive said, just add an expression to your first query. countQuery() is only about getting a single count for a query and in many cases it is very inefficient.

$con = \Database::getConnection('old_db');
$query = $con->select('PRESTATIONS', 'prestations');
$query->fields('prestations', ['LIBELLE']);
$query->addExpression('COUNT(*)', 'count');
$query->condition($group);
$query->condition('PRESTATION', 'AIDES', '=');
$query->groupBy('LIBELLE');

foreach ($query->execute() as $row) {
}


Check out Mime Mail; that should do the trick.

  This is a Mime Mail component module (for use by other modules).

  It permits users to recieve HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
  If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
  Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
  If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
  Allows you to theme messages with a specific mailkey.
  Converts CSS styles into inline style attributes.
  Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.


Extra space at beginning of downloaded image

Vinodkumar's answer didn't solved my issue, but it pointed me in the right direction.

I still haven't found the extra space, but as Drupal already used ob_start() in bootstrap.inc, I can now call ob_clean() to ensure no extra characters are shown:

<?php

// ...extra code to populate $path and $filename

ob_clean();
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($path));
readfile($path);
exit;


How do I set the Views Plugin handler path different from the theme path?

You should create an addressfield/theme/theme.inc that contains the template_preprocess_addressfield_* functions. Then add: $theme_path = drupal_get_path('module', 'addressfield') . '/theme'; at the top.

'handler' => 'addressfield_plugin_style_jmapping',
'path' => $path,
'theme' => 'addressfield_jmapping_view',
'theme path' => $theme_path,
'theme file' => 'theme.inc',

That should work just fine.


File added programaticaly are not deleted when node is deleted

I think that file will be delete when you run cron. File can't delete because temporary file have time life. You can see code in file_cron.
function file_cron() {
  $age = \Drupal::config('system.file')->get('temporary_maximum_age');
  $file_storage = \Drupal::entityManager()->getStorage('file');

  // Only delete temporary files if older than $age. Note that automatic cleanup
  // is disabled if $age set to 0.
  if ($age) {
    $fids = Drupal::entityQuery('file')
      ->condition('status', FILE_STATUS_PERMANENT, '<>')
      ->condition('changed', REQUEST_TIME - $age, '<')
      ->range(0, 100)
      ->execute();
    $files = $file_storage->loadMultiple($fids);
    foreach ($files as $file) {
      $references = \Drupal::service('file.usage')->listUsage($file);
      if (empty($references)) {
        if (file_exists($file->getFileUri())) {
          $file->delete();
        }
        else {
          \Drupal::logger('file system')->error('Could not delete temporary file "%path" during garbage collection', array('%path' => $file->getFileUri()));
        }
      }
      else {
        \Drupal::logger('file system')->info('Did not delete temporary file "%path" during garbage collection because it is in use by the following modules: %modules.', array('%path' => $file->getFileUri(), '%modules' => implode(', ', array_keys($references))));
      }
    }
  }
}

You can see line if($age) and line ->condition('changed', REQUEST_TIME - $age, '<'). It's logic when run cron delete file.
And you can go admin/config/media/file-system to see time life of temporary file. Default are 6 hours.


You probably should look at the paragraphs module code, it does a lot of this.

That said, the basic process would probably be:

Identify the form fields that are entity_reference_revision fields.
Check that the field is limited to paragraph types (can just check
1st one).
If it is an update form, get the referenced entities from the field.
You will then need some recursive code to walk the paragraph tree to
get sub paragraphs.

This will require using a lot of the field definition classes to get the information needed.


How to change default message from user relationships module?

User Relationship module allows you to set your own message, you can override the default message by settting a variable using variable_set("user_relationships_msg_{$key}", "Custom Message"), check the functions user_relationships_get_message() and _user_relationships_default_messages().


How to use the admin theme for webform email

This has been asked before. You can use a webform email template.

https://drupal.stackexchange.com/a/82501/3279

For the template file you should be able to override the theme assigned to the template by trying one of the many approaches outlined on this page:

Force a page to be rendered in admin theme (overlay mode)


How can you print the field class you entered in a View 's style settings?

You can add a class through the views interface:

Go to views ui
Under "Fields", click on the field you want to change
Click on "Style Setting"
Choose "Customize Field HTML"
Click "CSS Class" and enter your new css class

Alternatively, you can also achieve this through theme pre rendering.

View machine name: "your_view_name"
Field machine name: 'yourfield'
New class: "your_new_css_class"

Add to the file template.php in your theme directory:

function yourtheme_views_pre_render(&$view) {

  if ($view->name == "your_view_name") {
     $view->field['yourfield']->options['element_class'] = "your_new_css_class";
  }

}

To debug, download and enable the devel module (http://drupal.org/project/devel), and write out the variables:

function yourtheme_views_pre_render(&$view) {
    if ($view->name == "your_view_name") {
        drupal_debug($view->field['yourfield']->options['element_class']);
    }
}

The output will appear in tmp/drupal_debug.txt (depending on how you configured your tmp directory).


How to replace the $title of one single page with a taxonomy term?

You can achievie that with contextual filters as well.

contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available:

provide default value -> type: Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy
blocks
check the vocabulary which you want to use

When the filter value IS available or a default is provided:

Specify validation criteria -> PHP Code

$term = taxonomy_term_load($argument);
drupal_set_title($term->name);
return $argument;

It's done!


Migration yaml - A colon cannot be used in an unquoted mapping value

I don't know about the details of the YAML content, but just looking at the YAML it seems to me that name: data should be just name: otherwise it is not valid YAML.


You could alter the form on the theme layer to wrap the form in a div...

/**
 * Implements hook_form_alter().
*/
function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {

    //dsm($form_id);

    if ($form_id == 'YOURFORMID') {
        // add prefix and suffix to form
        $form['#prefix'] = '
';
        $form['#suffix'] = '
';
    }
}


Perhaps the Feeds Tamper: String to ID module might in this situation?

A Feeds + Feeds Tamper plugin that resolves strings pulled in from feeds importers and maps them to Drupal entity IDs, so they can be used as entity references.
Adds support for freeform Entityreference linking when using Feeds.


You can use drush to re-build specific image styles. drush image-flush thumbnail will force the refresh of thumbnail styles; you can use drush image-flush to get a list of available styles to clear.

You can find more information on the Drush website.


Assuming you're using the Views Slideshow module, for each slideshow you create, you also get a corresponding block that you need to position in an appropriate region.

So say you have 3 slideshows, ie ShowA, ShowB and ShowC, and you want to show them like so:

Show A on page with node id = X.
Show B on page with node id = Y.
Show C on page with node id = Z.

In this case, all you need to do is to adapt the "Visibility settings" (pages) for each block like so:

For the block related to ShowA, only show this block on page node/X.
For the block related to ShowB, only show this block on page node/Y.
For the block related to ShowC, only show this block on page node/Z.

Possible enhancements

Even though the above should be sufficient to answer your question, there are all sorts of enhancements to the above approach you may want to consider:

Use a content type (eg "Slide"), to create slides that you want to be shown in a slideshow. And optionally also add an extra field to that content type to identify in which slideshow (ShowA, ShowB, etc) you want an extra slide to be shown. And/or add another field to indicate some type of sequence (like slide nr) of those slides to be shown.
Use the Rules block visibility module to make the visibility of the blocks more dynamic, by using some Rules logic to yes/no show a specific slideshow-block. Refer to "How to stop a Views block from displaying to admins, such as user/1?" for way more details about how to use Rules block visibility.


How can I programmatically deactivate multiple user accounts?

The problem is that you load the users two times. In the foreach loop you already have the loaded entity available in $user.

Change your foreach loop to look like this and it should work:

foreach ($users as $user) {
  $user->set("status", 0);
  $user->save();
}

You can also remove the $storageHandler since you don't use that any more.


Drupal Rules has a Trim-A-Flag action that lets you set a 'queue' size, or a 'max' number of flags allowed.  If you set the queue to 1, you can force a flag to be unique, and have it automatically update when a new entity is flagged.

Screenshot below.


How to get the node ID in jQuery/JavaScript

As mentioned above, Drupal core has no use for the node ID on the client side so it doesn't pass it through. if you want access to it you'll need to add it manually:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full') {
    $setting = array('MYMODULE' => array('currentNid' => $node->nid));
    $node->content['#attached']['js'][] = array(
      'data' => $setting,
      'type' => 'setting',
    );
  }
}

Then on the client side you'll have access to it through Drupal.settings:

var currentNid = Drupal.settings.MYMODULE.currentNid;


Really strange WSOD after submitting a form/add to cart

I had a similar issue a year and a half ago. But in my case, it was Drupal 7 with Ubercart. Drupal had the same behaviour that you has described in your post.

If my memory serves my right, the problem was that references to the products  when the cart is executed. They are stored in 2 different ways:

If you are a authenticated user (you have an account on a drupal site), the references to the products added to the cart are stored in database. Concretely, in a table called *uc_cart_products*. If you log out, the products remain safely in database until the user log in again. So, the user doesn't miss any information.
If you are an anonymous user (not authenticated), the references are stored in database as in step 1, but you have a radomly generated token that is stored in Cookies to identify you . The cookie has a limited time of life, so finally, the cookie will be deleted.

When the cart is built, Ubercart take that reference from cookies if it's needed and load the products. But, i had deleted some products manually from database ( i know, it's a bad deccision ), so when the system try loading a product that hadn't exist, the system failed and appeared WSOD.

To solve this problem:

I deleted manualy all lines in *uc_cart_products* database table. If you have lots of records, only delele your products. Each record has an user id or a token assigned to identify who is the user.
Log out and delete the cookies


What reasons are there for views not rendering a link?

This works if you set up a source field:

Create a source field with the date formatting.
Rewrite the output of the field with just the tag. [date_when_2] in my case.
Select "Strip HTML tags".

Then create a custom text field that rewrites the output as the link.


How to pass dynamic file location in Form API?

I would suggest using ajax to update the #upload_location on demand.

However, ajax on managed_file element is quite tricky. Because managed_file has its own ajax handling for uploading file. It only rebuilds the file element itself and returns lack of data from other fields during during file upload ajax. So it need to be fixed in some hacky way

Example code:

function mymodule_custom_form($form, &$form_state) {
  $input = &$form_state['input'];
  $values = &$form_state['values'];

  $form['folder_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Folder Name'),
    '#submit' => array('mymodule_custom_form_folder_name_submit'),
    '#ajax' => array(
      'callback' => 'mymodule_custom_form_folder_name_ajax',
      'wrapper' => 'edit-file-ajax-wrapper',
      'event' => 'keyup',
    ),
  );

  // HACK: manually construct the folder_name value.
  // $form_state['values'] is empty for other field in file upload ajax
  // because it only rebuild the element rather then the whole form.
  if (!isset($values['folder_name']) && !empty($input['folder_name'])) {
    $values['folder_name'] = form_type_textfield_value($form['folder_name'], $input['folder_name']);
  }

  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#disabled' => empty($values['folder_name']) && empty($input['folder_name']),
    '#upload_validators' => array('file_validate_extensions' => array('jpg')),
    '#upload_location' => !empty($values['folder_name']) ? 'public://' . $values['folder_name'] : 'public://',
  );

function mymodule_custom_form_folder_name_submit(&$form, &$form_state) {
  unset($form['file']['#disabled']);
  $form_state['rebuild'] = TRUE;
}

function mymodule_custom_form_folder_name_ajax(&$form, &$form_state) {
  return $form['file'];
}


How to tell Drupal to look for templates in module directory?

Maybe this one works:

/**
 * Implements hook_theme().
 */
function MODULE_theme($existing, $type, $theme, $path) {
  return array (
    'node__CONTENTTYPE' => array (
      'variables' => array( . . . ),
      'template' => 'node--CONTENTTYPE' ,
      'base hook' => 'node',
      'path' => drupal_get_path('module', 'MODULE'),
    ),
  );
}

Important here is the key 'base hook'.


Cannot log in to Drupal running alongside WordPress multi-site

I bet it was the COOKIE_DOMAIN in wp-config.php:

define('COOKIE_DOMAIN', 'sub.mydomain.com');

Define it without leading dot.


Is it possible to have placeholder text on a view filter with type date_text?

You are doing it wrong way

Form alter doesn't work here.
This is how it can be achieved:

It depends on which date element you are using
There are few hooks available

hook_date_text_process_alter()
hook_date_popup_process_alter()
hook_date_combo_process_alter()
hook_date_select_process_alter()

I am showing for hook_date_text_process_alter()

/**
 * Implements hook_date_text_process_alter().
 */
function MYMODULE_date_text_process_alter(&$element, &$form_state, $context) {
  if ($form_state['complete form']['#form_id'] == 'views_exposed_form') {
    //dpm($form_state);
    if ($element['#id'] == 'edit-field-appintment-date-value-value') {
      $element['date']['#attributes']['placeholder'] = t('Demo placeholder');
      //dpm($element);
    }
  }
}

For Other text elements
Below is the correct example of adding a placeholder to views_exposed_form to any other text field but date field can't be done like this.

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#attributes'] = array('placeholder' => array(t('Your Placeholder')));
}

Hope this helps


How to create Country, State, City and Zip Code field in D6

Try the Hierarchical Select Module which works with Taxonomy Terms, Menus, User Profile Fields, Generic Lists and External APIs.  The field types you use for storage would not matter.

There are demos available on the module developer's blog.

Warning: In the case of City Names and Zip Codes there is no hierarchy (at least in the States).  Many Zip Codes have multiple city names, many cities have multiple Zip Codes. For any hope of keeping this all current you'd have to use an external API.


Adding a field without the field_ prefix (Drupal 7)

The Organic Groups module has a nifty API method for this. You just need to do a:

og_create_field(OG_AUDIENCE_FIELD, 'user', 'user');

This first checks if the field exists and creates it if it doesn't, then checks if an instance of the field has been attached to the user entity and creates it if it doesn't.

You can check this answer out to understand where and how you can run this snippet from.


Include custom node id when POST'ing data through the REST API

I think the default REST services don't allow that. You could implement yor own. It would need logic that prevents that existing nodes are overwritten exactly.


How to use stye attribute in custom block markup?

This is a working example of adding the style attribute to the render array of a block via the build() method.

<?php
/**
 * @file
 * Contains Drupal\foo\Plugin\Block\FooBlock
 */

namespace Drupal\foo\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * @block(
 *   id = "foo",
 *   admin_label = @Translation("Foo block")
 * )
 */
class FooBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * If a block should not be rendered because it has no content, then this
   * method must also ensure to return no content: it must then only return an
   * empty array, or an empty array with #cache set (with cacheability metadata
   * indicating the circumstances for it being empty).
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    return [
      'inside' => [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => 'Hello world',
        '#attributes' => [
          'class' => ['some-class'],
          'style' => ['color:red']
        ]
      ]
    ];
  }
}


Add flag counter in views Module(Search API index)

Use these two modules drupal like and flag simultaneously

Go to /admin/structure/flags create flag ,and  configure it properly.

Go to your view add  Global: PHP field

 <?php
print flag_create_link('bookmarks',$node->nid);

 $counts = flag_get_counts('node', $node->nid);
if(isset($counts['bookmarks'])){
 echo $counts['bookmarks'] .' Likes';
 }else{
      echo"no user flaged a content";
     }

 ?>

And at last put this code in your themes js file

Drupal.behaviors.your-theme = {

 attach: function (context, settings) {

 //add your available class below
    jQuery('.view-id-top_users.view-display-id-page .views-field-php .flag-link-toggle').click(function(){

        jQuery(document).ajaxComplete(function() {
         location.reload();
        });
       });
      }
       };

To add the flag link in your content type use code:

   <?php
    global $user ,$base_url;
    if(!$user->uid) {
   $flag_link = flag_flag_link($flag, $action, $content_id);

   $flag_url = $flag_link['href'];
    if(isset($flag_link['query']['token'])) {

    $flag_url .= '?'.$flag_link['query']['token'];
}

?>

  <a href="<?php echo $base_url;?>/user/login?destination=<?php echo      current_path();?>">MY-LINK


How to add a referenced taxonomy term name to the node title in page-title.html.twig

Posting this answer to help those trying to accomplish the same thing. I was told the code above had security vulnerabilities (which has since been removed see comments below).  On the Drupal Slack channel, someone pointed out the following concern with runwithscissors' answer:

  "This code is potentially dangerous:$variables['title'] = \Drupal\Core\Render\Markup::create($new_title); A user could set  as the Node or Term title and potentially execute code on the site. Typically you don’t want to ever create Markup objects manually. For what you’re doing, I’d suggest setting $term_name to a new key in $variables, then forming your combined title in the Twig template like {{ term_name}} {{ title }}"

So what i ended up doing was adding this template_preprocess_page_title to my MY_SITE.theme file.

(Note:  field_manufacturer is the specific field for my use case, so you would need to change all instances of that to your taxonomy reference field name.)

/* Add field_manufacturer to all node titles with field_manufacturer and not empty */
function template_preprocess_page_title(&$variables) {
   $node = \Drupal::request()->attributes->get('node');
   if ($node && $node->hasField('field_manufacturer') && !$node->field_manufacturer->isEmpty()) {
     $term = \Drupal\taxonomy\Entity\Term::load($node->get('field_manufacturer')->target_id);
     $term_name = $term->getName();
     $variables['term_name'] = $term->getName();
   }
 }

This applies to all nodes with the field_manufacturer, but also checks that the term field is NOT empty with && !$node->field_manufacturer->isEmpty()). This was critical as the reference field was not required, so nodes that had the field but didn't have a value crashed the site with Error: Call to a member function getName() on null in template_preprocess_page_title()

Then I copied and overwrote the page-title.html.twig file from my bootstrap base theme which originally renders the title like this:

{% if title %}

{{ title }}

{% endif %}

And changed the H1 title line to this:

{% if title %}

    {% if term_name %}
      {{ term_name }}
    {% endif %}
  {{ title }}

{% endif %}

This adds a MY-DESIRED-CLASS-NAME span class to the term_name. Also by putting it within {% if term_name %}/{% endif %} statement, it prevents that class from being rendered in the html where there is no term_name present.

Hope this helps someone!


Drupal 6 Ubercart - cancel/remove payment on order

Rob, I'm afraid it may not be possible. In Ubercart, we handled shopping carts as pseudo order objects, tying cart items directly to a session. Once that cart has been checked out, as I recall, there's no way to run through checkout again with it. You may just need to contact the customers to resubmit the order or process their payment some other way (PayPal money request?).

Fwiw, this is why we made the decision in Commerce to manage all shopping carts as full order objects and use the order ID in the checkout URL. Much cleaner to support this type of behavior.


Remove all previous cart if have same product creator

You simply need to create a rule that reacts on order creation, searches for existing orders for that user, and cancels those orders.

Next, add the condition to make sure you won't pull all anonymous orders. If you allow anonymous orders, you might have to implement some sort of custom session searching for orders.

Next, add an action that brings in a list of entities (we're going to pull a list of orders based on owner).

Then, select Commerce Orders

This is what the full action looks like when you've set it up for selecting by order owner's user id:

Next, you want to add a loop based on the orders you've pulled:

Next, you want to add an action inside that loop that changes the status of the orders:

Finally, set the order status to canceled:

Here's an export of the rule:

{ "rules_cancel_previous_orders" : {
    "LABEL" : "Cancel previous orders",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_order", "entity" ],
    "ON" : { "commerce_order_insert" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "commerce-order:uid" ], "op" : "\u003E", "value" : "0" } }
    ],
    "DO" : [
      { "entity_query" : {
          "USING" : {
            "type" : "commerce_order",
            "property" : "uid",
            "value" : [ "commerce-order:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "entity-fetched" ] },
          "ITEM" : { "list_item" : "Current list item" },
          "DO" : [
            { "commerce_order_update_status" : { "commerce_order" : [ "commerce_order" ], "order_status" : "canceled" } }
          ]
        }
      }
    ]
  }
}


How to add fields to a form from a custom module

I think using the form #action is the wrong approach there.

You should instead use

drupal_http_request

  Performs an HTTP request.

  This is a flexible and powerful HTTP client implementation. Correctly
  handles GET, POST, PUT or any other HTTP requests. Handles redirects.

In your form submit handler, to pass on the required parameters to the payment gateway.

Ensure everything is done under HTTPS.

To get another form, you can simply use

$form = array(); // new form
$defaults = drupal_get_form('my_default_form_builder_function');
$form += $defaults; // add defaults to new form


I think you could use theme_breadcrumb($variables) in your template.php to remove duplicates.

Code could be something like this:

themeName_breadcrumb($variables) {
  [...]
  $breadcrumbs = array_unique($variables['breadcrumb']);
  [...]
}


Rate relies on the Voting API module, which exposes hook_votingapi_storage_add_vote():

  Save a vote in the database.

function hook_votingapi_storage_add_vote(&$vote) {
  _mongodb_votingapi_prepare_vote($criteria);
  mongodb_collection('votingapi_vote')->insert($vote);
}

I don't know of a Rate-specific hook but you might get somewhere using that one (all depends what you need to do I guess).


Use text field value on another text field on same node on save

What you are doing is happening in the browser, so drupal, or anything else on the server, obviously doesn't know what's going on until you hit submit.

So you have to use jQuery that is running there in the client, and one way would be along the lines of:

$('#IDOFYOURFIRSTZIPCODE').live('change', function() {
  $('#IDOFYOURSECONDZIPCODE').val($('#IDOFYOURFIRSTZIPCODE').val());
});

The #IDs will look something like #edit-field-FIELDNAME-0-value but basically what it is doing is changing the second value to the first when the first changes.

Put that in a module's or theme's js and you should be set.  (I suppose you could [should?] add it with a drupal_add_js() right from your form_alter().)

(For those jQuery experts out there, I suppose I should have used on() or delegate() instead of live() but this works on both D6 and D7 with stock jQuery)


We've contributed a small module which solves this issue: https://www.drupal.org/project/registration_link


how to restrict access in routing.yml based on roles

This should work

requirements:
  _role: 'administrator'

See more details here https://www.drupal.org/docs/8/api/routing-system/structure-of-routes


There's quite a few modules that relate two (or more) nodes together, Entity Reference and Relation are both popular.

I'd probably recommend the Entity Reference module as that comes with a couple of field formatters that display the referenced entity. If you used the Relation module you'd probably have to build a fairly complex view with contextual filters and relationships - this screencast series should help with that.


Delete/Exclude js/custom.js from the global-styling section in THEMENAME.libraries.yml and define it as a library at the end of the same file

# THEMENAME.libraries.yml
custom-js:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery

And then include the library conditionally to where you want it using THEMENAME_preprocess_page function in THEMENAME.theme

//THEMENAME.theme
function THEMENAME_preprocess_page(&$variables) {

    //include it if its front_page
    if ($variables['is_front'] == TRUE) {
        $variables['#attached']['library'][] = 'THEMENAME/custom-js';
    }

    //include it if its NOT node 4
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface && $node->id() != 4) {
        $variables['#attached']['library'][] = 'THEMENAME/custom-js';
    }
}

For more info read the docs


Tree with linked structure and node leafs

Solved!

I have used this piece of code, palced on the "header" of the view, to obtain my goal:

$term = taxonomy_get_term(arg(1));
$parent = current(taxonomy_get_parents(arg(1)));
$name = $term->name;
echo "
".$parent->name."
"; //topic
echo "
".$name."
"; //subtopic
$breadcrumb = array();
$breadcrumb[] = l('Home', '<front>');
$breadcrumb[] = l('Topic', 'Topicview');
$breadcrumb[] = l(drupal_get_title(), base_path() . request_uri());
drupal_set_breadcrumb($breadcrumb);


<?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>


Get term plain text aliased url from tid

You're probably looking for url()

  Generates an internal or external URL.

e.g.

$output = url($term_uri['path']);


Availability Calendars - change amount of months shown to visitor

It turns out I just needed to enable the 'Field UI' module. So basicly I did this to solve my problem:

Enable to 'Field UI'  module
Go through to "Structure --> content types"
Go to the 'Manage display' tab


Drupal commerce does not provide anything for this. Actually it must not do it since payment companies require (and often make it completely impossible) to know the credit card properties.

Your only hope is what might be stored in the commerce_payment_transaction table by the payment gateway. Often additional data is stored as a serialized PHP object in the payload filed.

If you don't find anything there, you might have to dive into the specification of the payment getway company and check whether they provide this information via the API. If you are lucky this might be integrated into the appropriate drupal commerce payment getway.


How to change the link target in a entity reference display?

You can configure a link field to open in a new window.

About halfway down the edit page for your link field, you'll see 'Link Target,' and that's where you set it.


Permission option for unblock the selected users not listed

You can create a view and give access to superuser role.

Below links will help you.

http://blog.safwan.in/post/69263954822/add-unblock-user-action-to-views-bulk-operation-vbo

http://dropbucket.org/node/486


Teaser is missing CKEditor when uncollapsed

Never use "Text and summary" fields. It's a sad/unfortunate fact that Drupal 8 didn't manage to remove them.

Instead, create a separate (independent) summary field.


You can try this module: https://www.drupal.org/project/ccl

or create your custom solution based on this code snippet


EntityQuery condition on translation status

This should do what you want.  Note that the id's will load the default language, you will need to use getTranslation(langCode) to get the translated node.

$query = \Drupal::entityQuery('node');
$query->condition('status', 0);
$query->condition('type', YOUR_TYPE);
$query->condition('langcode', 'de');
$ids = $query->execute();


There is no register form but spams are sending register request in Drupal 7!

Go to admin/config/people/accounts
and configure : Registration and cancellation for administration only


dsm vs drupal_set_message vs debug vs dpm vs watchdog for developing

If devel is available, i use mostly dpm. If not, I use drupal_set_message(print_r($array, true)). This helps me in the most cases. If both are not available or visible, I use the Watchdog.


Autocomplete selection in Rules Component

I'm assuming that your question is related to executing a Rules Component, and not creating it.

A possible approach might be to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of entities (such as nodes) that you want to be processed.
add a loop to perform a Rules Action, for each entity (such as a node) contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


There is no existing way to append data to an existing file. Only modes you have listed in the question.

You will have to go for native PHP functions (a mode in fopen() or FILE_APPEND in file_put_contents()).

Some pointers:

Consider using hook_watchdog(). You can filter what you need to log to the file using the type key of the passed array.

Don't forget that there is also a module, syslog, to log these watchdog entries to syslog.

You can also use dd() function from devel module to easily log specific data to a temp file.

  dd()

  Logs any variable to a file named “drupal_debug.txt” in the site’s
  temp directory. All output from this function is appended to the log
  file, making it easy to see how the contents of a variable change as
  you modify your code.

  If you’re using Mac OS X you can use the Logging Console to monitor
  the contents of the log file.

  If you’re using a flavor of Linux you can use the command “tail -f
  drupal_debug.txt” to watch the data being logged to the file.

  dd($data, $label = NULL)


Why is "drush cc all" failing with "undefined function user_load()"

The problem went away after I restarted memcached.

I discovered that by running drush with -d and seeing a PHP error about a $theme value not being a valid index. Tracing the code showed that access to cache_bootstrap was getting empty arrays for the module and theme data.

From now on I plan to restart memcached or flush its cache on my test server after rebuilding its database. (I've done this kind of rebuilding dozens of times before with no issues.)


I am not sure about your use case.

But the following module does exactly that.

Webform Default Fields

  With this module you can easily create much of nodes with same webform
  fields. It can be applicable in case of job vacancies with reply form,
  kind of quality feedback control or whatever your mind suggests you.

  Because you can create more than one webform-enabled content types,
  you respectively can attach different default fields for each of them.


I just tried to setup a fresh Drupal 7.44 with Postgresql and I haven't encountered any issues. The setup went fine. Here are the steps I did.

$ su root - Switch to root user.
$ su - postgres - Switch to Postgres user. Note that you need to be root first before doing this.
$ createuser --pwprompt --encrypted --no-createrole --no-createdb gerald - Create a new user called gerald.
$ createdb --encoding=UTF8 --owner=gerald drupal - Create a new database called drupal.
Run the installation and select the Postgresql type.

Another way to determine the culprit is by reading the logs.

For Postgresql

$ sudo tail -f /var/log/postgresql/postgresql-9.3-main.log. In you case it should be $ sudo tail -f /var/log/postgresql/postgresql-9.4-main.log.

For PHP (if you're using Apache)

$ sudo tail -f /var/log/apache2/error.log

Additional Troubleshooting

Also check if there is a problem with timeout in PHP. You may want to increase to default timeout settings.

My stack:

gerald@von-viel ~/ $ psql --version
psql (PostgreSQL) 9.3.13
gerald@von-viel ~/ $ php --version
PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57)

Note: I am using the default configuration of Postgresql.

Hope this helps!


There isn't a menu-specific function (that I know of) but you can use the aptly named menu_rebuild() function to rebuild the entire menu cache in one go.


Ok, I sorta figured this out. It might be a hack, but if I start with initial menu level: 1, maximum menu levels to display: 1 and fixed parent item to be the menu who's children i want displayed, then it sort of works.

Only caveat is I need to make a separate block for each separate child of the menu. Plus, it is still using the same template to display the menu in both places (header + sidebar). Perhaps using custom blocks and changing its name will generate a new template?

I'd love to hear a better answer if there is one.


How to show a page create with the view module in the administrative overlay?

Showing a view in the overlay just requires you to implement hook_admin_paths_alter().

function mymodule_admin_paths_alter(&$paths) {
  // Treat all user pages as administrative.
  $paths['the path of your view'] = TRUE;
}

Keep in mind this:

In the path you can also use asterisks (e.g. node/*/edit), useful in the case the view is using contextual filters
If the overlay is not accessible from the user, the page will be shown using the administrative theme, which could also be the default theme used by Drupal, if the site doesn't set a the administrative theme to be another one


How to trigger email, account/user and order creation actions when payment is made in paypal, not when user is redirected back

Q1

To test Paypal unfortunattely you need to test on a website which Paypal also can connect to. This is not necessaraly your live site. Maybe you should setup a test/demo environment somewhere else. If you don't want people to access that site you can setup an extra login with htpasswd, but it needs to be disabled during testing of the IPN.
An easy way to do this is using the shield module.

Q2

You can always test using another payment method. For other tests I always use the Payment Example module which is provided with the Payment module in Drupal Commerce.
This way you can test payments without having to deal with receiving IPNs.


PHP Fatal error: Class 'Drupal\Core\DrupalKernel' not found

Try the following:

Check if autoload.php file exists and it includes the right path to your vendor/ folder.
Clear any external cache services if in use (e.g. Memcached or Redis).
If you're using PHP 5.x, you should use PHP 7.x instead.

To rebuild your site from scratch based on your composer.json file, try the following steps:

Backup and delete the /core and /vendor directories completely.
Delete the composer.lock file.
Run: composer install.
Run: composer update.

Source: D8 conflict resolution.


How to get all database which can be used in 'db_set_active'

All database connection strings are in global $databases variable;

global $databases;
dpm($databases);

with drush:

drush php-eval 'global $databases; print_r($databases);'


Using "if statements" to add classes in Twig

1) Install and enable the Devel module.

2) Add your /sites/development.services.yml:

# Local development services.
#
# Place this file in the /sites/ directory.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    # Twig debugging:
    #
    # When debugging is enabled:
    # - The markup of each Twig template is surrounded by HTML comments that
    #   contain theming information, such as template file name suggestions.
    # - Note that this debugging markup will cause automated tests that directly
    #   check rendered HTML to fail. When running automated tests, 'debug'
    #   should be set to FALSE.
    # - The dump() function can be used in Twig templates to output information
    #   about template variables.
    # - Twig templates are automatically recompiled whenever the source code
    #   changes (see auto_reload below).
    #
    # For more information about debugging Twig templates, see
    # https://www.drupal.org/node/1906392.
    #
    # Not recommended in production environments
    # @default false
    debug: true
    # Twig auto-reload:
    #
    # Automatically recompile Twig templates whenever the source code changes.
    # If you don't provide a value for auto_reload, it will be determined
    # based on the value of debug.
    #
    # Not recommended in production environments
    # @default null
    auto_reload: auto_reload
    # Twig cache:
    #
    # By default, Twig templates will be compiled and stored in the filesystem
    # to increase performance. Disabling the Twig cache will recompile the
    # templates from source each time they are used. In most cases the
    # auto_reload setting above should be enabled rather than disabling the
    # Twig cache.
    #
    # Not recommended in production environments
    # @default true
    cache: false

3) Add your /sites/default/settings.local.php:

<?php
/**
 * @file
 * Local development override configuration feature.
 *
 * Place this file in the /sites/default/ directory next to settings.php.
 * This will include the development.services.yml file for twig debug use.
 *
 */
assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();

$config['system.logging']['error_level'] = 'verbose';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

4) Update your /sites/default/settings.php:

(uncomment this section)

# if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
#   include $app_root . '/' . $site_path . '/settings.local.php';
# }

This will allow you to add {{ dump(content.field_name | keys) }} to your template file so you can see just what keys you need to access the correct values.

Try:

{% for key, item in content.field_stat_value %}

    {{ dump(content.field_special_character | keys) }}

{% endfor %}

Then just add what you need to follow:

{% for key, item in content.field_stat_value %}

    {{ dump(content.field_special_character.mynextkey.0.whatever | keys) }}

{% endfor %}

I add this answer as being able to print out values will help a designer best. Plus, if your class is not printing, I just think content.field_special_character[key] is not evalutaing to %.

Having debug setup will also allow you to ensure you have the correct naming conventions for your twig template.


FieldCollection/PLUpload - Recurring error when uploading images on PROD - "No file by that name exists"

This is a note for people who face this problem. Maybe it can help them.

I had this error on a project. I see that it occurs on a plupload widget with a limit of file number set to 1. I replaced this field by a classic upload and the problem gone.


How to change logged-in user permission in hook_node_view?

using  hook_node_access(),here you can check user role by using

global $user;
$roles=$user->roles;


Check for hook_entity_info and entity_extract_ids. The former specified a base table and the id key, the latter allows to extract the ID from the entity.


How to load login, register and other forms and nodes in modal window?

No need to write single line of code.

To open node add/edit form in modal window, try below modules

https://www.drupal.org/project/ctools_automodal
https://www.drupal.org/project/ctools_automodal_admin

I tried & it works properly for me.

To open node add form in modal
admin/config/system/ctools_automodal_admin -> Modal content types and select content types.

To open node edit form in modal add
node/%node/edit in Extra modal links textarea.


REST export with no data over it's localhost IP

OK, solved. The problem was the domain access module.

I got no output because I didn't set the domain access for all nodes except one. The one I got in ouput.

There is no default value for the domain access field in field configuration in node type configuration. And it's not comfortable to set the domain access values for every single node in node edit. So I needed to disable this module.


How can I access a node's menu link and weight through EntityFieldQuery

I ended up using db_query JOIN to get the info straight from the database:

$sql = "SELECT menu_links.link_path, menu_links.link_title, menu_links.weight, node.nid
        FROM menu_links
        JOIN node.nid
        ON menu_links.link_path LIKE CONCAT('node/', node.nid)
        ORDER BY menu_links.weight ASC";
$result = db_query($sql);


I am not 100% sure, but I think you just need to create a new role and specify what the user can do and what he cant? I have for example a role which can add new content and nothing more. So they see the admin bar in the top and it only lists add content :) and which types of content they can add.


Webform css stylesheet overriding my css file

The 'div' in the webform's CSS makes it more specific than your CSS in IE7styles.css, thus overriding your styles. You should copy the CSS selector from the webform module's CSS exactly if you want to override it with a style in a file later in the cascade.

Here is a good article on general traits of CSS specificity and inheritance.


How to sign emails to setup DKIM and DMARC

Please check out the following two modules to have your Drupal mails send by a mailserver. Apart from that it may already be sufficient to just set a SPF record for your domain as DKIM and DMARC has actually nothing to do with Drupal.

PHPMailer

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

  Adds SMTP support for sending e-mails using the PHPMailer library.
  Comes with detailed configuration instructions for how to use Google
  Mail as mail server.

SMTP Authentication Support

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

  This module allows Drupal to bypass the PHP mail() function and send
  email directly to an SMTP server. The module supports SMTP
  authentication and can even connect to servers using SSL if supported
  by PHP.

How To use an SPF Record to Prevent Spoofing & Improve E-mail Reliability

https://www.digitalocean.com/community/tutorials/how-to-use-an-spf-record-to-prevent-spoofing-improve-e-mail-reliability

  A carefully tailored SPF record will reduce the likelihood of your
  domain name getting fraudulently spoofed and keep your messages from
  getting flagged as spam before they reach your recipients.


the article can't show the image in the full mode in drupal 7

Make sure to set the display on the content type (manage display link) as it ultimately sets the values of the teaser and full node.


Set different pricing attributes for each product

Thanks, Neograph734, but it's not exectly what I tryed to do.
Maybe it isn't a proper way to do it but I solve this problem using custom _add_to_cart_form_submit() function and hook_commerce_cart_line_item_refresh().
So it looks something like this (maybe it will help someone):

function custom_add_to_cart_form_submit($form, &$form_state){
  // line item field_size_pick
  $line_item = $form_state['line_item'];

  $field_size_pick = field_get_items('commerce_line_item', $line_item, 'field_size_pick');
  $size_pick = $field_size_pick[0]['tid'];

  //get product
  $product_id = $form_state['values']['product_id'];
  $product = commerce_product_load($product_id);

  //fc sizes
  $field_fc_product_sizes = field_get_items('commerce_product', $product, 'field_fc_product_sizes');
  foreach ($field_fc_product_sizes as $key => $value) {
    $item_id = $value['value'];
    $fc_item = field_collection_item_load($item_id);

    $field_fc_size = field_get_items('field_collection_item', $fc_item, 'field_fc_size');
    $size = $field_fc_size[0]['tid'];

    if ($size == $size_pick) {
      $field_fc_margin = field_get_items('field_collection_item', $fc_item, 'field_fc_margin');
      $margin = $field_fc_margin[0]['amount'];
      break;
    }
  }

  if (isset($margin)) {
    $commerce_unit_price = field_get_items('commerce_line_item', $line_item, 'commerce_unit_price');
    $price = $commerce_unit_price[0]['amount'];
    $price += $margin;

    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    $line_item_wrapper->commerce_unit_price->amount->set($price);
    $line_item_wrapper->save();
    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
  }

  $form_state['rebuild'] = TRUE;
}

function custom_commerce_cart_line_item_refresh($line_item, $order_wrapper) {

  $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

  $field_size_pick = $line_item_wrapper->field_size_pick->value();
  $size_pick = $field_size_pick[0]->tid;

  $field_fc_product_sizes = $line_item_wrapper->commerce_product->field_fc_product_sizes->value();
  foreach ($field_fc_product_sizes as $key => $fc_item) {
    $field_fc_size = field_get_items('field_collection_item', $fc_item, 'field_fc_size');
    $fc_size = $field_fc_size[0]['tid'];

    if ($size_pick == $fc_size) {
      $field_fc_margin = field_get_items('field_collection_item', $fc_item, 'field_fc_margin');
      $fc_margin = $field_fc_margin[0]['amount'];
      break;
    }
  }

  if (isset($fc_margin)) {
    $price = $line_item_wrapper->commerce_unit_price->amount->value();
    $price += $fc_margin;
    $line_item_wrapper->commerce_unit_price->amount->set($price);
    $line_item_wrapper->save();

    commerce_line_item_rebase_unit_price($line_item_wrapper->value());
    commerce_line_item_save($line_item_wrapper->value());
  }
  $order_wrapper->save();
}


Views: combining fields of one content type with another

Check out the module Relations. It will enable you to make relationships between the two content types.  You can see it in action at nodeone.se in the video series on Relations.


The connection to the server was reset after trying to log as admin to Drupal

Restart webserver

Might be a webserver issue. Try restarting you webserver and check if it solves your issue.

Check server logs

If that doesn't help either, check your webserver's error log to see if there is any special error message in these that helps.

Tune the .htaccess file

Modified the .htaccess file and replace the default clean URL rewrites with this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Coder module

Option a: Remove the Code module

A complete different reason for this issue is Coder makes Drupal go to "Connection was reset" browser error. So if you have the Coder module installed/enabled, then disable and uninstall it and ALSO remove that module from the module folder.
Option b (if using WAMP): increase the stack size

Be aware that preg_match_all uses the stack which may be too small. PHP crashes and then Apache crashes (and restarts). The fix is to increase the stack size to match a default Linux PHP Apache setup. To do so, increase the Apache stack size to 8MB by adding a line to the end of httpd.conf (surrounded by a IfModule mpm_winnt_module and matching /IfModule tag):

  ThreadStackSize 8388608

After restarting the webserver you can then use any version of the Coder module (and other modules which have this issue ...).

More details: https://www.drupal.org/node/1597820#comment-6094060


Attaching 'active' class to faqfield expanded question

This functionality is provided by FAQ Field using the jQuery Accordion UI.

In Structure > Content Types > Your Content type > manage display (admin/structure/types/manage/[your_content_type]/display), if you change your FAQ field display settings from Definition List to Accordion, an up/down caret is shown next to each question.

If you click on the gear icon corresponding to your FAQ Field you can configure which question is active by default, as well as whether the questions are collapsible.

Result:

The Accordion setting also adds the class ui-state-active to the active question element (an h3) and the class ui-accordion-content-active to the active answer element (a div).


I think you are going to use a View for the 'Select Entity' element's reference method but you might run into Issue #2174633: View output is not used for entityreference options


The provided host name is not valid for this server

If this is a dev - env, simply add

$settings['trusted_host_patterns'] = [$_SERVER['SERVER_NAME']];

But never do this in production.


theme superfish menu item link add query string

I think your problem is in how you add the query string. Check this article: Webemania | How and why to use l() function to create links in Drupal and specifically example 6.

<?php
// adding query string on example:5
print l(  t('PHP ini configuration'),  'node/33',  array('attributes' =>array('class'=>'php-ini-conf', 'id'=>'phpini-conf'), 'query'=>array('id'=>'5','status'=>'ok') ));
?>


Which file do I need to edit to implement a 'Back to top' link?

It depends where you want the link to be, but your best bets would probably be page.tpl.php, node.tpl.php or a variation of those templates (specific to content types, etc).

For more on templates see Drupal 6 template suggestions


You can do it by setting the appropriate permissions. For Drupal 6, content_permissions is part of CCK, and lets you set permission for every CCK field of your content type. For Drupal 7 you can use the Field Permission module.


Construct the src in a javascript tag from node fields

You can do this in a node.tpl.php file in your theme or to be specific to one content type.

Duplicate the default node.tpl.php file found in /modules/node/ and rename it to node-NODETYPE.tpl.php NODETYPE being the machine name of the node which you can find at structure -> content types, in the CMS.

Install the devel module and enable it, then do a dpm($node); in your copied node.tpl.php file to get the variables you need. Of course you would need to have a custom theme so it doesn't get overridden on an update.

To do this in a module you'd need be somewhat familiar with hooks.

And since the dpm is called after the output is rendered you need to reload the page twice.
Don't forget to clear cache after you add in the node.tpl.php to your theme.


Order confirmation email with html content?

Use Commerce Message. It's the best supported way to handle sending emails. It includes several message types out of the box.


drush installing drupal through root ssh is causing 500 internal server error

Thanks to Matt C from Known Host who helped me resolving this issue. Sharing his reply below so others can be benefited.

  I've run the fix permissions script and it looks like all files and
  directories are set as they should be. You can find the script in
  /public_html/fixperms.sh. I've also provided you with a link for
  fixpermissions:

  http://boomshadow.net/tech/fixes/fixperms-script/


Need help for Drupal 7 Ajax Add more form elements

It was not adding my field because #required is set to true. Now I removed it, and my problem is solved.


How do I force nodes to have revisions by default when using REST?

The node type setting mentioned by the other answers only applies to the node form, it does not affect programatically saved nodes.

You could try to implement hook_node_presave() and call setNewRevision(TRUE) or maybe the same in hook_node_load(). Or override the rest plugin (assuming you use that and not your own controllers).


Try $row['uri'] instead.  As 'uri'  is merely the key and not another object.

In this line of code:

$block['content'] .= '<img style="width: auto; height: 100px;" src="'.file_create_url($row->uri). '" alt="Vores support medarbejder" />';

you refer to another object, the uri ($row->uri). Within the $row array, that you printed with print_r, there is the key 'uri'. To get the value of that key you should use $row['uri'].


If [commerce-order:created] is a date token, then you can use [commerce-order:created:custom:<the format you want to apply>], where <the format you want to apply> is the string format accepted by date().

Otherwise, the more generic way to alter tokens implemented by other modules is implementing hook_tokens_alter().

function mymodule_tokens_alter(&$replacements, $context) {
  $options = $context['options'];

  $sanitize = !empty($options['sanitize']);
  $langcode = !empty($options['language']->language) ? $options['language']->language : NULL;

  if ($context['type'] == 'commerce-order') {
    foreach ($context['tokens'] as $name => $original) {
      switch ($name) {
        case 'created':
          // Set a value for $sanitized and $new_value.
          $replacements[$original] = $sanitize ? $sanitized : $new_value;
      }
    }
  }
}

Notice that in my code:

$sanitized is the sanitized value to assign to the token, used only when $sanitize is TRUE
$new_value is the new value for the token, used to obtain the value of $sanitized


I don't have a real explanation why my solution worked; I only replaced quick_links_staff with quick_links in both places.

function quick_links_block_info() {
  $blocks['quick_links'] = array(
    'info' => t('Quick Link'),
    'status' => 1,
  );
  return $blocks;
}//TODO add caching option

function quick_links_block_view($delta = '') {
  $block = array();
  switch ($delta) {
  case 'quick_links':
    $block['subject'] = t('Quick Link');
    $block['content'] = t('links go here');
    break;
  }
  return $block;
}

Make sure to clear Drupal cache after you implement the change.


Need module for notifications like privatemsg

There is messaging_simple  table which stores message values.

See the column timeread this provides time when the message is read. The entries which have 0 value shows unread message.

You can apply sql query to find out rows with timeread 0 for logged in user and can get the count of unread messages.


How can I apply changes to user permissions across several sites?

I found this snippet for copying permissions from one role to another, which you can easily rewrite to a drush sql command and integrate in your current workflow.


Change Product price based on discount set by site owners for different domain - Drupal Commerce

The easiest thing is to hook into rules, as there is a rules event, for when the price for a product is being calculated: commerce_product_calculate_sell_price. This event is designed to hook into, in order to change price for discounts and the like.

You can create your own custom action to provide the discount, or try to use the Rules interface to setup the logic there.


The site has a mix of modules installed manually and via Composer: Can I move all to Composer?

You can just add the modules to Composer as you would normally: composer require drupal/MODULENAME.

You can then confirm everything is working OK by making a new copy of your site with Composer and verifying that the site loads correctly.

Potential issue:
If you are looking at the list of installed modules to decide what to install, you don't necessarily need to add every module; some may be dependencies of others (for example, with Composer, if you are using Pathauto module, you don't need to install Token explicitly; it will automatically be installed with Pathauto.)  However, it won't hurt anything if you force some dependencies to be installed as well, so this isn't really anything to worry about.


I decided to create 3 sub-pages with normal filters, /widgets/all /widgets/past /widgets/current and /widgets/future.


Image grid from view with randomly inserted colored squares

My solution was fairly simple.  I created a new content type called "Homepage Grid Spacer" and used auto_nodetitle to suppress the title.  I created a single field of the jQuery Colorpicker type and deleted the body.  Now the admin can insert these decorative squares between actual flagged content by creating and flagging them in the same fashion.

I updated my view to select the color code and suppress the image field of the actual content and I used the rewrite to add a div with the color in a data field.  I couldn't add the field in a style because Drupal doesn't allow this.  Then I added a couple lines of JavaScript to take the data color and make that the CSS background color.


Since you're using a field with multiple options, you need to use a delta. So if your token looks like this:

node:field_product:commerce_price

It should include a delta after the field name:

node:field_product:0:commerce_price


How to make a text field box appear after clicking select option by using ajax?

You can use the Conditional Fields module, which allows you to show/hide fields based on other field's values.
From the module description:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.
When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
A simple use case would be defining a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked, but much more complex options are available.


Your function will give an array of entity objects, indexed by their entity_id's. So:

foreach ($archive_items as $entity_id => $archive_entity) {
  /* Process each entity */
}

will allow you to iterate through the entities and to do what you need to each. Beyond that, we will have to know what result you are trying to achieve.


Views 3 doesn't recognize a declared handler. Why not?

Which core version? In Drupal 7, hook_views_handlers() is gone, add your files to your .info file instead.

files[]=views/addressfield_views_handler_field_country.inc


Short answers:

Drupal should have no problem with 5000 terms.
Using a taxonomy for this is the best solution in Drupal.

You may also want to use Taxonomy manager as suggested by kala4e4k in a comment.

What is the upper limit?

Well, taxonomy vocabularies are managed by the database, so this limit is determined by the maximum number of rows you can store in a table in the database you're using.

If you're using MySQL, there is no built-in limit to the number of rows per table (just pick a big enough number type to manage the primary key), but there are other constraints on table size besides number of rows. If you have a 500 Gbyte hard drive and each record is 1 KB is size, your maximum number of rows will be 500 million (if you dedicate the entire drive to this single table, which is not a very realistic scenario). If you buy a 10 Tbyte hard drive, you may run into your operating systems file size limitation (for instance, I believe Ubuntu's maximum is 5 TB, so your limit will be 5 000 million terms instead of 10 000 milion - given the same assumptions about record size).


You can use javascript to get the browser timezone. Assuming their computer timezone is updated, their browser timezone will change.

var offset = new Date().getTimezoneOffset();

Or if you want the name you'll have to do something like https://stackoverflow.com/questions/2853474/can-i-get-the-browser-time-zone-in-asp-net-or-do-i-have-to-rely-on-js-operations

Sadly there is no way to do this without Javascript.


What is the best way to achieve this result?

I would do it with content type using entity reference to products.
Entity reference allows you to reference other nodes in your "deal of the week" node and use this relationship in your view. No PHP should be needed.
With this setup, you can do almost anything:

only Staff is allowed to create new content of this type
view can show author name (and picture)
custom comment? no problem, just a text field in content
old content is still available


How do I make a custom block that has an image background with hotspots?

You can try the module jQuery Map Hilight which uses jQuery maphilight plugin (visit the link to view demos).

Download from David Lynch blog / GitHub.


You cannot do this using native Drupal 7 functionality. You need to do that grouping in PHP. You should be using a foreach, not a while loop :)

  The most common case is to iterate over the result set with a
  foreach() loop.

Source: https://drupal.org/node/1251174


How to display node number in content items that only show up to administrators on ALL content items?

I need it to create links on menu items, to assign blocks to specific
nodes, to create links to content items in articles ect...many
reasons!

You're going the wrong way about this. Having your urls named node/1, node/2 etc.. looks ugly and it's bad for SEO.
What you need to do is give your Content Types an url alias. You don't want your How To Use Drupal article url to be node/1. You want it to be /articles/how-to-use-drupal
You should use the Pathauto module. This module allows you to automatically create an url alias using tokens.
Then when you assign a block, you can use articles/* this will make the block show up on all articles urls.
Pathauto Video Tutorial

I knew about path auto, I just thought it was better practice to use
node items for links and so on, in case I change the page name later,
node number never changes...

You can use the redirect module which will auto redirect the old path to the new path if you change the path name. Thus, you don't have to worry about updating links.
To make life easier, I would also recommend
CKEditor Link - A plugin to easily create links to Drupal internal paths


How can I consolidate the views that are auto generated by nodequeue

Are there performance implications to have in potentially hundreds of views created?

Views are just queries. If you're concerned about performance use caching in Views under the advanced settings for each view. There are contrib modules that enable caching for all views.

  Isn't there a better way to display nodequeues in a view? why does there have to be a different view for each nodequeue ? isn't there a way to pass the relationship in through a contextual filter?

Possibly, but then your view(s) would only be accessible from say 1 url via the contextual filter ... a freedom of the Page view provided by the nodequeue is that as a site builder you can define unique url routes per view.


Create custom entity type programmatically

As some have commented, Entities are VERY complicated. The reason your code is not working is because entity_create() is used to create an INSTANCE of an entity of an already defined entity type. What you are doing in the UI creates the entity type.

You must first create your entity type in your module before you can create an instance of that entity. Refer to the links in the comments above on how to do this. And get ready to spend a little time if this is your first time doing this -I assume it is.


How to enable a payment method as soon as an order is saved in Drupal commerce programmatically?

To get it to go onto the review page you can do.

$order = commerce_order_new($uid, 'checkout_review');

When creating your order that sets the status to checkout_review.

Then you can use the following to driect yourself to the page

drupal_goto('checkout/' . $order->order_id. '/review');

As the status has been set you go to the review page. I did something similar recently and it is working well.


Here are a few links that may help you learn more about patching:

Applying a Patch Manually
Making a Drupal patch with Git (also covers applying)
HowTo: How to apply a patch to a contributed module - Beginner's version (Windows)
Apply Patches on Windows (more methods)
Apply patches on Mac OS
How to apply patches for Drupal modules and files


How do I remove text format information from the bottom of my text areas

You can use the Simplify module for this.

It describes itself as follows:

Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.


Product migration with group and execute-dependencies options

Perhaps https://www.drupal.org/node/2830357 comes into play here? Apart from that, the usual use of --execute-dependencies is to migrate a single migration making sure any migrations it depends on have been executed, the group scenario hasn't been tested so there may be some broken assumption in the code.


You can use db_merge() function. Here is the example.

db_merge('my_table')
  ->insertFields(array(
    'name' => 'George',
    'last_name' => 'Niels',
  ))
  ->updateFields(array(
    'last_name' => 'Niels',
  ))
  ->key(array('name' => 'George'))
  ->execute();

If there is no key ("name") with value "George", "name" and "last_name" values are inserted to the database table. If there is a record with key value "George", only the field "last_name" is updated with the specified value.


How to add the paragraph parent field in the theme suggestions alter

You can get the parent field name directly from the paragraph:

Replace

// get the parent field of the current paragraph
// assuming that the parent field name is field_test_paragraph
$parent_field_name = 'field_test_paragraph';

with

$parent_field_name = $paragraph->parent_field_name->value;

As a side note, this is an entity base field like parent_id and parent_type you load the parent entity with in getParentEntity().


Problem with Views 7.x-3.0 - Column not found

The problem was in the references module, I found this patch wich solved the problem.


Site seems to miss the "private" wrapper, how can I fix it?

Here are the necessary steps:

Create a directory on the server. This is typically done via SSH. For instance assuming Apache under Ubuntu, the following command can be used: sudo -u www-data mkdir -p /var/www/html/web/sites/default/files/private
Tell Drupal about your directory by editing your settings.php file. You need to have a line like the following:

 $settings['file_private_path'] = '/var/www/html/web/sites/default/files/private';

Important: clear the Drupal cache, for example with drush cr or by going to the page /admin/config/development/performance in your browser.
In the browser's address bar, go to /admin/config/media/file-system. You should see "Private local files" in the "Default download method" option. If not, then please visit the /admin/reports/status page to see any error messages.  Make sure that PHP can write in the directory. Often, for this to work, the directory has to be writable for the www-data user.

For more documentation, go to https://www.drupal.org/docs/8/core/modules/file/overview#private-file-system.


How to add an image upload field to a node programmatically?

Add a CCK imagefield to the node.

If you need to show / hide it, use your form_alter to set ['#access'] = FALSE on the field.


Is there any problem with writing a menu callback that does this, and processing in PHP?

If you must use JavaScript for the processing, why not intercept the user's value in JavaScript and never "really" submit the form?


How do I give a role permission to set a site variable?

One method would be to use something like https://drupal.org/project/config_perms to add a custom permission to the admin/config/system/variable/edit/my_custom_variable path. You can then use this custom permission to grant access to it.


I'm suddenly getting the error :EntityMetadataWrapperException

Your site has not been running on Drupal 7.21 for several months. You have recently upgraded.

There was a security fix in the drupal core image module in 7.20 which broke several contributed modules. 7.21 has a new variable to mitigate the problem, but if your issue involves images, it is probably related to the security fix. For more information read the release notes.


How to automatically add http prefix to links in a form?

Thanks to those who provided answers; I couldn't quite get those to work, but they got me to my answer. My final solution ended up being this:
function my_module_form_alter(&$form, $form_state, $form_id) {
  // add a global validator to fix stupid Link fields - add to all Link fields
  // only worry about entity forms
  if (isset($form['#entity_type'])) {
    $bundle = $form_state->getFormObject()->getEntity()->bundle();
    $entity_type = $form['#entity_type'];
    $entityFieldManager = \Drupal::service('entity_field.manager');
    $fields = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);
    foreach ($fields as $field) {
      if ($field->getType() == 'link') {
        $field_name = $field->getName();
        $form[$field_name]['widget'][0]['#element_validate'][] = '_fix_link_field_value';
        array_unshift($form[$field_name]['widget'][0]['uri']['#element_validate'][0], '_fix_link_field_value');
        $form[$field_name]["widget"][0]["uri"]["#description"] = t('This must be an external URL such as http://example.com, https://example.com, example.com, www.example.com.');
      }
    }
  }
}

and then the validator/fixer:
function _fix_link_field_value(&$element, FormStateInterface $form_state, &$complete_form) {
  $url = $form_state->getValue($element['#parents'][0]);
  $urlOriginal = $url[0]['uri'];
  if (!$urlOriginal) return;

  if (!stristr($url[0]['uri'], '//')) {
    $url[0]['uri'] = 'http://' . $url[0]['uri'];
  }
  if (filter_var($url[0]['uri'], FILTER_VALIDATE_URL) === FALSE) {
    $form_state->setErrorByName($element['#parents'][0], t('%url is not a valid URL format. This must be in a format like
      http://example.com, https://example.com, example.com, www.example.com.',
      ['%url' => $urlOriginal])
    );
  }
  else {
    $form_state->setValue($element['#parents'][0], $url);
  }
}

The array_unshift isn't right but doing an unset() didn't seem to cut it. I am sure all this is doing is preventing the original validator from running; which is good as the error message it generates is stupid. Not sure why 5 years into D8 they still don't have this fixed.
Also, this will need an extra loop if you are dealing with multi-valued fields.


How to not have "-None-" as default in the entity reference display widget

As soon as you make this field required it will have no - None - option anymore.


You are logging in correctly by POSTing the username and password. After you've logged in, a Drupal session is created.

The csrf_token can be used to authorise future requests requests by sending it as a header:

X-CSRF-Token: XXXXXR5HQwidW7CKIDL52tOg4JGKi7Pa-j87KKlr8Mg

You can send this instead of a cookie if you've configured the backend to allow it. I've only used the CORS contrib module as CORS in Drupal core doesn't have the same flexibility.

  I understand that the logout token is used with /user/logout in order
  remove the cookie and log the user out.

Correct.

Also see my answer here: https://drupal.stackexchange.com/a/235712/34673


List of nodes limited by last node created from each user

Views 3 has the perfect new relationship type for this "Obtains a single representative node for each user, according to a chosen sort criterion."

To do this, begin with a new view which is a list of Users in fields format. By default you will see a list of usernames.

Then add a relationship 'User: Representative node (search for 'represent' when adding the relationship. You can choose the sort criteria as perhaps 'updated date' order by descending.

You can now add extra fields using the related data - such as 'Content: title' and 'Content: Updated date' using the relationship 'representative node' for each new field.


There is the loadByProperties method in the \Drupal\Core\Entity\EntityStorageInterface that allows to define required condition in searching the file entity by the given file URI:
/** @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
/** @var \Drupal\file\FileInterface|null $file */
$file = reset($files) ?: NULL;


Is there any way to combine views block to homepage?

I am not sure which Drupal you are using. But the procedure is pretty same for D7 & D8.

Normal Drupal Approach:

1. Create a block/views-block and set it's visibility to  as shown below, do it for all blocks which you want to show on front.

2. Go to Structures/blocks & place all views-blocks/normal-blocks under the content region as shown in following image, in order in which you want to display.

3. Front page: Now, all three blocks with their content are visible only on the front page as shown below.

For Second-home page: Do the same thing as above just apply the visibility to second-home-page url in the first step.

Using Panels module

You can use Panels module to get more settings, but if your purpose serves with above approach, do not add extra module in your site. But with Panels module, you can achieve any display setting what you can think of.


How to add custom class to a  fileds on the renderable array of user_profile_form

You can do it 2 ways. One is to modify the element attributes, like this:

$form['textfield'] = [
  '#type' => 'textfield',
  '#attributes' => [
    'class' => [
      'ul',
    ]
  ],
];

Or, another way, wrap the elements with '#prefix' and '#suffix'.

$form['textfield'] = [
  '#type' => 'textfield',
  '#prefix' => '
',
  '#suffix' => '
',
];

I would use the first preferably when I can.


View with pagination to have a single url per pagination page

The url's are unique. If the page view has a url of /news, then each page can be referenced individually as /news?page=0 for the first page, /news?page=1 for the second page and so on.


You might also want to take a look at http://drupal.org/project/author_pane. That shows author information as shown in the picture you have posted.


Is it possible to use drush to save a theme setting?

Drush does not have any facilities for manipulating elements of arrays in the variable table; however, you can use drush php-eval to call variable_get() variable_set(), and include a bit of php to manipulate the json yourself.

It would also be pretty easy to make your own Drush command to manipulate the items you'd like to set regularly.  See the drushify tool for a fast way to get started.


Printing individual components of comment-form in comment-wrapper.tpl

You forgot to render hidden form fields that are required for the correct work.

Just add this line of code after outputting all visible form fields:

<?php
  print drupal_render_children($form);
?>

Also if you output form elements outside form template you need manually add {form} tag
In your case you will get

<form id="comment-form" class="comment-form" accept-charset="UTF-8" method="post" action="<?php print url('node/' . $node->nid); ?>#comments">
<?php
  print render($content['comment_form']['author']);
  print render($content['comment_form']['field_email']);
  print render($content['comment_form']['comment_body']);
  print render($content['comment_form']['actions']['submit']);
  print render($content['comment_form']['actions']['preview']);
  print drupal_render_children($content['comment_form']);
?>
</form>


fetchAssoc fetches a single record as an associative array; you're then looping over that one array and setting a message for the single column in that array, field_cage_id_vbc_target_id. Hence just the one result, an integer instead of the expected array(s).

You can use fetchAllAssoc instead:

$result = $query->execute()->fetchAllAssoc();

foreach($result as $record){
  drupal_set_message($record);
}


'#states' => array(
  'visible' => array(
    ':input[name="your checkbox"]' => array('checked' => TRUE),
  ),
)

add this to the element you want to hide.this will be visible only when the checkbox is checked.


Drupal 8 - how do I extrat the URL path from node title

Try {{ path('entity.node.canonical', { 'node' : row.nid}) }}. Also it is better to use kint or devel_dump for twig debug.


How to define multiple blocks in a module?

Simple as:

function myblockmodule_block_info(){
    $block['myadblocks'] = array(
        'info' => t('My first ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );

    $block['myadblocks2'] = array(
        'info' => t('My second ad blcoks'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $block;
}

/**
 * Define what our block is going to look like.
 * Implements hook_block_view().
 */
function myblockmodule_block_view($block_key){
    $block = array();

    if($block_key == 'myadblocks'){ //We only want to define the content of OUR block
        //This is the title of the block.
        $block['subject'] = t('First ad block comes here');

        //Define the block content.
        $block['content'] = 'some fancy script comes here';
    }
    elseif ($block_key == 'myadblocks2') {
      $block['subject'] = t('Foo');
      $block['content'] = 'var';
    }

    return $block;
}

And clear the caches.


How can I programmatically create a select input whose values come from a foreign key using Form API?

I went with this solution that uses entity_load then adding the loaded entities as options to the select field for now:

$foreign_entity_items = entity_load('foreign_entity');
$foreign_entity_options = array();
foreach ($foreign_entity_items as $foreign_entity_item) {
    $foreign_entity_options[$foreign_entity_item->some_field] = $foreign_entity_item->some_other_field;
}

$form['some_form_element'] = array(
    '#title' => t('Some title'),
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => $foreign_entity_options
);


Access custom billing field in rules using Commerce

If you have added the e-mail field on the commerce profile type as you said, you should access is via the profile type as well. (It is not a property of the commerce order.)

Normally, the commerce profiles are already available when the commerce order is loaded. But you might not recognize them as such. Nothing indicates it it a profile.

For instance I have access to these profiles:

And then you can use a condition like this:

  { "entity_has_field" : {
      "entity" : [ "commerce-order:commerce-customer-quotation" ],
      "field" : "commerce_customer_address"
    }
  }


String passed to the T function in inline_template not accessible for translation

This was caused by the configuration for language detection and selection configuration at admin/config/regional/language/detection.

For the t() function to work, the language detection and selection for the user interface must be set to "Language from the URL (Path prefix or domain)". There is an issue on drupal.org that may address this one.


Image slideshow with onclick on thumbnails

You can use the Views Slideshow module.

  Views Slideshow can be used to create a slideshow of any content (not
  just images) that can appear in a View. Powered by jQuery, it is
  heavily customizable: you may choose slideshow settings for each View
  you create.


Views Dependent Filter Module integrates this functionality with views

  Allows the presence of exposed filters on a view to be controlled by
  values in another exposed filter. Dependent filters are hidden when
  not relevant, and their values are not considered when the exposed
  form is submitted.


What you set as ['#ajax']['progress']['url'] is wrong: It's not the URL for a JavaScript file, but it's the callback path to use to determine how full the progress bar is. The menu callback should return a value that indicates if the operation has been completed, or it is completed at 10%, 20%, 50%, etc. Looking at the code contained in the progress.js file, I notice the value is expected to be between 0 and 100.

As side note, the value passed in ['#ajax']['progress']['message'] should be passed to t().


How to alter a form element's properties before rendering?

In hook_template_preprocess_form_element the (input-)tags is already rendered.
You can use

function hook/template_preprocess_input(&$variables) {
  $variables['attributes']['title'] = 'my-title';
  $variables['attributes']['placeholder'] = 'my-placeholder';
}

to alter the input tag. use the same method for all other desired tags.
Here's a nice tutorial.

  You could make use of hook/template_preprocess to go a more generic
  way.


You need to enable og access control module.

see below:

Then navigate to admin/config/group/fields, add an visibility field to your og bundle

Then edit the og bundle content type, there is a new field added to it, make your change for public or private


ERROR:Cron run exceeded the time limit and was aborted. why?

Often a drupal_goto() call in a page or module will be sending the execution of the cron run off course.

This often happens when the core Search module tries to index a page with such a drupal_goto() call. The solution is to find that page (or module) and remove the call, or change it so it doesn't fire during a cron run.

Try installing Elysia Cron to allow you to run each Drupal cron task in turn to work out what's causing the problem. From there you'll be able to debug it or look for ideas on the Drupal.org issue queue.


Understanding the Basic Context of Trusted Hosts

Trusted hosts refer to the domain that your Drupal site is hosting, not your remote PC's domain that is administering the site. For example, if your site running on Drupal was www.thedrupaldude.com, the trusted host regular expression would be ^www\.thedrupaldude\.com.


as your question doesn't have any proper explanation, people most likely cant help you. but I can guess that what you are doing wrong is that you make a region--footer.tpL.php file (you missed the L in the end), you also need to render it on the page you want it there to be, so practically it wont show you anything since its not rendering at all.

my suggestion is forget about region--footer.tpl.php and add

<?php
    print render($page['footermenu']);
?>

right into your page.tpl.php or any other theme hooks you might want it there.

by the way a very rookie mistake is that you already done everything right but after editing your .info file you forgot to clear the cache in admin/config/settings/development/performance


With Ultimate Cron you can problably disable it from running using its configuration form.

If you look at its API, it adds a hook_cron_alter that you could implement if you wanted to do it by code.


Since you already found that post, make sure you also read the comments. It clearly explains why checking for a permission is recommended over checking for a role. When you use permissions, you can assign that permission to multiple roles, which makes your system more flexible. Also, remember that roles can be renamed, which would break your code.

That said, if you want to check for a role, you can do this:

// Load the currently logged in user.
global $user;

// Check if the user has the 'editor' role.
if (in_array('editor', $user->roles)) {
  // do fancy stuff
}


How to check if a library is present during installation?

this is one of the working example from my module. I hope this helps you

function sfs_requirements($phase) {
  $requirements = array();
  $t = get_t();
  if ($phase == 'install' && function_exists('libraries_get_path')) {
     $plupload_path = libraries_get_path('plupload');
     $chosen_path = libraries_get_path('chosen');
     if (!$plupload_path) {
       $requirements['plupload'] = array(
         'severity' => REQUIREMENT_ERROR,
         'description' => $t('Secure File Share module requires !plupload, which is missing. Download and extract the entire contents of the archive into the %path directory on your server.',  array('!plupload' => l($t('Plupload Library'), 'https://github.com/moxiecode/plupload/archive/v1.5.8.zip'), '%path' => 'sites/all/libraries/plupload')),
       );
     }
     if (!$chosen_path) {
        $requirements['chosen_js'] = array(
          'severity' => REQUIREMENT_ERROR,
          'description' => $t('Secure File Share module requires !chosen, which is missing. Download and extract the entire contents of the archive into the %path directory on your server.', array('!chosen' => l($t('Chosen Library'), 'https://github.com/harvesthq/chosen/releases/download/v1.3.0/chosen_v1.3.0.zip'), '%path' => 'sites/all/libraries/chosen')),
        );
      }
  }
  return $requirements;
}

Karthik


Those are not bugs and have nothing to do with locale.

The standard install profile sets up the administrator role, the theme configuration and many other things, see standard_install() and its default configuration files like the overriden system.theme.yml.

I guess you mean the local tasks with "middle part of the GUI", that is a block and also set up by Standard, like many other blocks too.

If you create a new theme, it makes sense to look at standard on how it does things and copy the parts you need from it.


Should be next:

function custom_morebuttons_menu() {
  $items['node/%node/calendario-corsi'] = array(
    'title' => 'Calendario corsi',
    'page callback' => 'custom_node_calendario_corsi_page',
    'page arguments' => array(1),
    'access callback' => 'user_is_logged_in',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
  );

  return $items;
}

function custom_node_calendario_corsi_page($node) {
  $node = node_load($arg);
  if (($node->type == 'centro') || ($node->type == 'sede')) {
    // I assume you will add some behaviour code for this, next make no sense.
    return $node;
  }
  return false;
}


How to change to another image when mouseover using Views?

You can try Views Slideshow module with its ThumbnailHover slide feature. You can find its full documentation page in here.

Basically create a view with fields and a pager, set it as slider (Content: slide) and check Activate slide and pause on pager hover option.

For more details, see: What you'll need to crete a jQuery slideshow in Drupal.


Printing field item attributes with Twig / Drupal 8

The syntax to print the alt tag in that case is this:

{{ item['#item'].alt }}

Twig in Drupal 8 doesn't deal with hash keys like #item in render arrays cleanly. Part of the problem is that # signifies a comment in Twig, so {{ item.#item.alt }} wouldn't work.

There is the possibility of working around this with a Twig extension to allow drilling down into hash attributes with the syntax {{ item.item.alt }} but I'm not sure if anyone is working on that. I should mention that Twig extensions can be added in contrib as well.