PDOException error - Google AdWords Conversion module My Drupal site is having a serious issue. Whenever I try to add content, such as a Basic Page, I receive this error:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_adwords_conversion_id' in 'field list': INSERT INTO {field_data_field_adwords} (entity_type, entity_id, revision_id, bundle, delta, language, field_adwords_conversion_id, field_adwords_conversion_language, field_adwords_conversion_format, field_adwords_conversion_color, field_adwords_conversion_label) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9, :db_insert_placeholder_10); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 45 [:db_insert_placeholder_2] => 45 [:db_insert_placeholder_3] => page [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 992249945 [:db_insert_placeholder_7] => en [:db_insert_placeholder_8] => 3 [:db_insert_placeholder_9] => FFFFFF [:db_insert_placeholder_10] => ) in field_sql_storage_field_storage_write() (line 451 of

I know things don't just happen without a reason, but I'm not sure how it happened. Looking at my change notes,  I did make a change on 01/27/2014: "Removed 'AdWords' from Webforms to work-around an error." Vague, I know. But this seems to be related to the "Google AdWords Conversion" module I am using (v7.x-2.0-beta). I went to their site and no one else appears to  be having this issue.

I tried to tinker with the field definitions, but every time I do I end up with a SQL error.

Unfortunately, I cannot remove the AdWords Conversion module from the admin panel; it is grayed out because it's in use. I tried removing it manually (from the file system), and that rendered the site inaccessible; I had to restore from back-up.

I could, in theory, restore to my 01/27 back-up... but I've made many cosmetic changes since then, somehow without noticing this critical SQL error. So my preference would be to fix this rather than back-out to 3 weeks ago.

I'm running Drupal v7.26. I'm at a loss on how to fix this. Does anyone have any suggestions?

Thank you very much!

OK I would take this approach. First off you need to look at the system table within your Drupal DB. Since you can't for whatever reason disable the module from the UI you'll need to disable it from here. You can do this by navigating to the row representing the module, and setting the status column to 0. Once you've done this clear your cache.

The error message you're getting is due to a database schema inconsistancy, so what I would try do is navigate to the Modules -> Uninstall (/admin/modules/uninstall) and see if I can now uninstall the module. Depending on how the module is written, this should invoke hook_uninstall and undo any database scheme alterations made when the module was initially installed.

Hopefully this will get rid of the nasty PDOException you're running into when editing your webform.


Debug plugin discovery A plugin that I have written is not being discovered.

For eg : https://www.drupal.org/node/2847639

Is there a general suggestion for debugging failing plugin discovery?

Most of the time it is because the file is not picked up, there are a few common cases for that:

Ensure that the filename matches the class name exactly, case sensitive. Without the extension of course.
Ensure that the namespace matches the folder path exactly, case sensitive.
Restart Apache to clear apcu cache, I've had issues with this when renaming/moving files with a class quite a bit in Drupal 8. Also setting class_loader_auto_detect to FALSE in settings.php should solve this one.

There are even more things to check if you're actually the one providing the plugin type such as the plugin manager.


Display node with specific revision I am trying to load a node using the revisioning module to display an unpublished piece of content, by passing a version ID to node_load(). We also use the i18n module which may or may not have an affect on what I am trying to achieve. We are looking to implement a "preview" of a page which may be sent out to departments that do not have a user account of any sort (We do not want to create a login for this). The preview page is requested with the version &vid=12345 and a &preview URL parameter.

At the moment, if the specific revision is not published, the preview page will load the currently published content instead of the version we are passing to node_load().

I have tried to create a preview user with view unpublished permissions, but this does not work (still loads the published content).

Is it possible to prevent the fallback and load the specific revision?

UPDATE:
Thank you for the renewed interest. So we are using the "entity_translation module" and have extended this to include the preview functionality. This allows a page URL to be called with the node id and version id. These are both passed to node_load.
The node is then displayed via calls to $output = _revisioning_view($node); and finally drupal_deliver_page($output);

If you are doing this by custom method try below code to get published revision id.

$query = db_select('node_revision','nr');
$query->join('node','n','n.nid=nr.nid');
$query->fields('nr',array('vid','status','nid'));
$query->condition('nr.status',1,'=');
$query->condition('nr.nid',$nid,'=');
$result = $query->orderby('vid','DESC')->range(0,1)->execute()->fetchAll();

Pass $nid in condition, here you will get the latest published revision ID.

Then load node as

  entity_revision_load('node', $result->vid)

This will load particular revision id with content type.

Here you will get all node data related to that revision id.

Hope this helps.


Show a page with child Terms when parent Term clicked in block? I want to Display child terms when a parent Term is clicked with Views in Drupal 7.
         Example

     Parent1
          .child11
          .child12

      Parent2
          .child21
          .child22
          .child23

So when Parent1 page is Visited, i will display the content of parent1 but with a block showing

          .child11
          .child12

Any insight in Achieving this will be Appreciated. Thank you.

Try the Views tree module. It is great for taxonomy trees.

This module provides a tree-based style plugin for Views. It is equivalent to the tree-based style template from Views 1.
It is based off of the list style. Although it generates a nested view, there is still only a single query run for the view making it quite performant.

There is also a patch for adding collapsible support but I'm not sure how complete it is. See http://drupal.org/node/1538414


How can I encapsulate Drush command with option to use arguments I have a drush command for installing a Drupal website with configuration in it. I do not want to type this command with all the configuration all the time because it is long so I would like to encapsulate the command as alias but I still want to pass additional arguments to the original command.

Specifically I need to pass at least the db url since that will always be different.

I was thinking something like this: drush install-mysite --db-url="..."

So basically any argument that is provided to my alias would override the defined argument defined in my alias.

From what I have read this could be done with drush aliases but I am not sure about the syntax and the arguments themselves. Another way is to create a new drush function but I think alias is simpler and I don't need any additional functionality.

This is for Drupal 8 so Drush 7 but I think it is not that relevant.

The best way to provide default options to a Drush command, whether it is a core Drush command or a custom command you have written, is to place your default values into a drushrc.php file under a command-specific option.

For example, if you wanted the Drush site-install command to always name the site admin 'superuser', and you wanted to always install with the password 'secretsecret', then you could add the following definition:

$command_specific['site-install'] = array(
  'account-name' => 'superuser',
  'account-pass' => 'secretsecret',
);

If you later decided you wanted to use a different account name for a site you were installing, then you could just run drush site-install --account-name=su, and the option from your configuration file would be overridden.

If the only purpose of your install-mysite command was to select default values for site-install, then the above configuration is all that you will need.  If you want to add additional code that does other things after the install, though, then you could go ahead and write your custom command, and place a $command_specific['install-mysite'] entry in your drushrc.php file to provide the default values for your command's options.

If you only want to make minor changes to the way the site-install command works, you might want to also consider providing a "policy file" that provides a hook that runs after the install command finishes.  See policy.drush.inc for details.


Drupal $custom_theme caching issues? I have a hook_boot() module that detects certain circumstances and changes the theme using $custom_theme to a specific theme. All works good, however if Drupal has a cache of the page that page will be served regardless of the fact it is not the correct theme.

Is there anyway to force drupal not to use and caches for that specific theme? Or is there a way to force drupal to keep two caches? One for each theme?

I am using Drupal 6 btw.

From my point of view, the better way is to use your own cache system, but don't worry is nothing very complicate.

Copy the includes/cache.inc and put it somewhere in sites/all/libraries or whatever you want. After in your settings.php you've to add $config['cache_inc'] = 'sites/all/...'; and Drupal will replace is own cache system by yours. This file contains three functions, clear_cache_all, cache_set and cache_get. Here the idea is to add the name of your theme before all $cid.

I never tried it, so I'm not sure if you can have access to this informations, but you can try .


How do I enable the Twig extension? In Drupal 8, Admin-Report > Status report > Twig C extension:   Not available
Enabling the Twig C extension can greatly increase rendering performance. See the installation instructions for more detail.

I installed Twig C Extension, but it's reported to not be enabled.

How do I install and enable the Twig extension for PHP, in Drupal 8?

This should just work. Make sure to follow http://twig.sensiolabs.org/doc/installation.html#installing-the-c-extension and run the commands from within /path/to/docroot/vendor/twig/twig. Next, you should check again that extension=twig.so exists in your php.ini file and that Apache has been restarted/reloaded.

To confirm that the extension is being loaded, you can run php -c /path/to/php.ini -i | grep twig


What is the difference between Pantheon DROPS and vanilla Drupal? Is it just the added config wrappers, or is the Drupal site code itself changed? Are there any changes to Drupal module and filesystem compatibility compared to a more traditional Drupal hosting environment?

Pantheon's variant of Drupal is openly hosted on GitHub:

https://github.com/pantheon-systems/drops-7

The main variation that matters is in drupal_settings_initialize():

https://github.com/pantheon-systems/drops-7/blob/master/includes/bootstrap.inc#L720

This is how Pantheon runs sites without making users handle DB or Redis credentials. This change is now in Pressflow as well.

The other material addition is an apachesolr integration package and a way for the site to query the Pantheon API. Those are in modules/pantheon.

The good news is none of this will prevent a site from working anywhere else. The changes are all designed to revert to normal when not on Pantheon.


Variable default_bundle in migration? Field collection to varying paragraph types I'm trying to migrate a D7 field collection to D8 paragraphs, but to a different paragraph bundle type depending on the value in one of the field collection's fields.

The logic is as follows: If the field collection's field_type value is "header", the migration should create a header paragraph type. If the field collection's field_type value is "card" it should migrate to a card paragraph type.

I'm trying to set a variable in process, and assign the value of that variable to default_bundle in the destination, but it's not working, the paragraph type is empty for the entities created by this migration:

langcode: en
status: true
dependencies: { }
id: d7_field_collection_list_items
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
 - 'Drupal 7'
migration_group: migrate_drupal_7
label: FC
source:
  plugin: d7_field_collection_item
  key: migrate
  field_name: field_list_item
process:
  temp_bundle_type:
    plugin: static_map
    source: field_list_item_type
    map:
      card: card
      header: header
    default_value: card
destination:
  plugin: 'entity_reference_revisions:paragraph'
  default_bundle: '@temp_bundle_type'
migration_dependencies:
  required: { }
  optional: { }

What is the correct way to achieve what I am trying to do? I have tried several other methods without success.

Don't use the default_bundle at all, instead set the bundle type like other field values in the process section:

process:
  temp_bundle_type:
    plugin: static_map
    source: field_list_item_type
    map:
      card: card
      header: header
    default_value: card
  type: '@temp_bundle_type'


Drupal 7 Commerce - How would you increase or decrease a checkout total price depending on payment type? I want to be able to provide alternative payment methods during checkout, but I also want to be able to discount or add on top of the total checkout price by a percentage depending on what the user chooses to pay with. How can this be done? I know you would use rules, but which sections would i need to edit?

** edit - I was able to edit up the the "pricing rules" page, but now i get an error for Order Total. I want to be able to mutltiply the order total as seen below. I'm not sure what to put after the colon : of order total.

In the checkout methods rules you should be able to add an action that decreases the total or subtotal cost.  So when a certain payment method is used, the subtotal will decrease.

If one of those rules actions isn't available you might need to look at some other modules like Commerce Rules Extra.

Another option would be to apply coupons automatically to orders with those selected payment methods with the Commerce Coupon and Commerce Coupon Fixed Amount modules.  That might give you better control over how many times a user or how many users can use a discount like this.


Twig templates are not loading I am using Drupal 8 from github:drupal/drupal@a9ac0fbf17, but having problems creating custom template, using Twig template engine.

Here is template file structure:

.
├── README.txt
├── screenshot.png
├── templates
│   └── html.html.twig
└── custom.info.yml

html.html.twig file is not being loaded. I have tried to change ownership/permission of the files, but it didn't help. I turned on twig_debug and getting:

<!-- THEME DEBUG -->
<!-- CALL: _theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--front.html.twig
   * html--node.html.twig
   x html.html.twig
-->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/html.html.twig' -->

which, I assume means it is loading default template from core/modules/system/templates/.

Here is the content of my html.html.twig:

{#
/**
 * @file
 * basic html structure of a single Drupal page.
 */
 #}

 <!doctype html>
 <html lang="en">
 <head {{ html_attributes }}>
   <title>{{ head_title }}</title>
   {{ page.head }}
   {{ page.styles }}
   {{ page.scripts }}
</head>
<body {{ attributes }}>
    {{ page_top }}
    {{ page.content }}
    {{ page_bottom }}
    {{ page.scripts('footer') }}
</body>
</html>

What might I be missing? let me know if you need more info.
Thanks

To disable cache for development(tiwg + Drupal cache) :

first copy and rename the sites/example.settings.local.php to be sites/default/settings.local.php

then open settings.php file in sites/default and uncomment these lines:

# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

Now open settings.local.php and change the below lines to "TRUE".

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

and uncomment all these to Disable the render cache and Disable Dynamic Page Cache

# $settings['cache']['bins']['render'] = 'cache.backend.null';
# $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

for twig cache open "development.services.yml" and update the below parameters.

  twig.config:
    debug : true
    auto_reload: true
    cache: false


Writing to a specific or new element in a multi-value custom field We're trying to key track of software license keys issued to a specific user in Drupal 7.  We've created a custom user field called "field_key" with unlimited values.  We'd like to add a new element to field_key every time a new license is issued, and save the new key into the new element.

As expected, the following code saves our new key into the first element of the array every time, overwriting the original:

$edit['field_key'][LANGUAGE_NONE][0]['value'] = $key_save;
user_save($account, $edit);

If we remove the index value, changing [0] to [], what I thought should happen was that the index would be incremented and we'd write to the next element.

$edit['field_key'][LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, $edit);

That ends up behaving exactly like the first example using [0], overwriting the original.

If I force the index (delta) value, using [1], for example, the result is the same. This occurs even if I create a new empty element in the user GUI.  I can add additional elements and populate them in the GUI.  If I do this and have, say, 5 keys listed in the user GUI, the next time we run the code using [], [0] or [5], the result is that all of the original elements are deleted, the field is reduced to a single element, with the new value overwriting the original.

I obviously have the command syntax wrong here.  Any tips?

You're nearly spot on, the only problem is whatever field array you put in $edit will overwrite the array that's in there now; no merging happens behind the scenes. This is probably the correct behaviour as you should be able to overwrite the field completely if you need to.

At the moment each time you use

$edit['field_key'][LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, $edit);

The field is being re-initialised as whatever's in $edit['field_key'], i.e. a single element.

To append to the array you could do something like this:

$field_items = $account->field_key;
if (!is_array($field_items)) {
  $field_items = array();
}

$field_items[LANGUAGE_NONE][]['value'] = $key_save;
user_save($account, array('field_key' => $field_items));


Access Denied even if permission is given I have this module, as admin users I can access this module normally. But when I add permission to other roles (and it saved), other users who have the permimssion couldn't access it. Please help me.

This is the code.

include_once(drupal_get_path('module', 'tb') .'/tb.menu.inc');
include_once(drupal_get_path('module', 'tb') .'/tb.inc');

function tb_perm() {
  global $user;
  return array('trial_balance');
}

function tb_menu() {
  global $user;
  $items = array();

  $items['akuntansi/tb'] = array(
    'title' => 'Trial Balance',
  'type' => MENU_NORMAL_ITEM,
    'page callback' => 'tb_neracapage',
    'file' => 'tb.inc',
    'access arguments' => array('akuntansi'),
    'access callback' => TRUE,
    //'type' => MENU_CALLBACK,
  );

  $items['akuntansi/tb/pdf'] = array(
    'page callback' => 'tb_neracapage_pdf',
    'file' => 'tb.inc',
    'access arguments' => array('akuntansi'),
    'type' => MENU_CALLBACK,
  );
$items['akuntansi/tb/xls'] = array(
    'page callback' => 'tb_neracapage_xls',
    'file' => 'tb.inc',
    'access arguments' => array('akuntansi'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

?>

Your implementation of hook_perm() (which is not valid for Drupal 7), only defines the trial_balance permission, not the akuntansi permission your code is trying to use.
The fact the user #1 has the permission to see those pages is just because the user #1 by-passes all the permissions; in fact, user_access() returns TRUE for that user.

  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

To make it clear, without explicitly setting an access callback, the access arguments are expected to be an array with the user permission string, which in your case would be trial_balance.

If the module is for Drupal 7, then hook_perm() is not even used; instead, Drupal 7 uses hook_permission(), which is not a simple renaming of the previous hook. It is expected to return a differently structured array; using the same array as Drupal 6, will cause it to not properly work.


Run second site in the same VM: Is it possible? I would like to run all my Drupal 8 sites in one Vagrant VM instead of just one. Is this possible?

I tried to remove the default drupal site from the "web" folder and pulled(git) 2 of my current probject into it.

For any reason drush does not recongnize the drupal roots as proper drupal sites.

I am not sure how other modules react...  Is it normal to create each time a new VM for each Site you are developing. Seems a bit overkill.

Yes, this is possible, but take it from me as a guy who did it for about 12 sites - it gets tedious fast to manage it.

Setting up and tearing down VMs is so fast and cheap, it's simply more practical to me to create one per project. It's less to manage, and it just becomes a 'part' of the project codebase (you can fetch Drupal VM with Composer now for example, or download and keep it in a 'tools' folder outside of docroot).

Also it does not sound like you are setting up Drupal VM properly... I suggest re-reading the docs or posting more information.


How to access all images uri in node's field in custom module? I already know I can get an url for field of node this way:

$src = file_create_url($node->get('name_of_image_field')->entity->uri->value);

The problem is, my field name_of_image_field has multiple images. How to access them all?

You can try this code:

$img_urls = array();
foreach ($node->field_image as $item) {
  if ($item->entity) {
    $img_urls[] = $item->entity->url();
  }
}

Then all field_image image urls available in $img_urls variable.


How to add an image field to a custom fieldtype? I see that there is an ImageType field, machine name 'image', with a namespace of Drupal\image\Plugin\Field\FieldType. However, I can't seem to make use of it when creating a custom field and defining the property in the FieldType class.

I tried putting DataDefinition::create('image') but this later causes an abort complaining about the field type not existing, and I notice that the namespace is not referenced.

What are the correct types to use for an image field in the property section of the FieldType, in the schema of the FieldType, and in the FieldWidget?

Exporting an image field config from a bundle yields:
uuid: eecbe6e5-89d5-4708-b9c9-79f77b3cedf8
langcode: en
status: true
dependencies:
  module:
    - file
    - image
    - node
_core:
  default_config_hash: SkXIPKZYiIMMtnBmfnxk58RYfbZ8cHSw5NZPY_JByME
id: node.field_image
field_name: field_image
entity_type: node
type: image
settings:
  uri_scheme: public
  default_image:
    uuid: null
    alt: ''
    title: ''
    width: null
    height: null
  target_type: file
  display_field: false
  display_default: false
module: image
locked: false
cardinality: 1
translatable: true
indexes:
  target_id:
    - target_id
persist_with_no_fields: false
custom_storage: false

and looking at the image module's fielditem:

 * @FieldType(
 *   id = "image",
 *   label = @Translation("Image"),
 *   description = @Translation("This field stores the ID of an image file as an integer value."),
 *   category = @Translation("Reference"),
 *   default_widget = "image_image",
 *   default_formatter = "image",
 *   column_groups = {
 *     "file" = {
 *       "label" = @Translation("File"),
 *       "columns" = {
 *         "target_id", "width", "height"
 *       },
 *       "require_all_groups_for_translation" = TRUE
 *     },
 *     "alt" = {
 *       "label" = @Translation("Alt"),
 *       "translatable" = TRUE
 *     },
 *     "title" = {
 *       "label" = @Translation("Title"),
 *       "translatable" = TRUE
 *     },
 *   },
 *   list_class = "\Drupal\file\Plugin\Field\FieldType\FileFieldItemList",
 *   constraints = {"ReferenceAccess" = {}, "FileValidation" = {}}
 * )
 */

The image field type has no property image, the main property is target_id inherited from the file field type. The easiest way to define a custom image field would be to extend the three core image field classes another time, now in the namespace of your module.

See how ImageItem defines a new compound field by extending FileItem overriding propertyDefinitions() unsetting two properties and adding four new image specific properties.

An alternative solution would be Paragraphs, more overhead (while a compound field stores the data of all fields in one table, Paragraphs needs a table for each field and also for the paragraph entity itself), but it provides unlimited nesting of field types.


Synchronize drupal database with a traditional database I have a installation of plain Drupal 6 with its own database. I have also another database,  different from the one used by Drupal.

I want to connect this database (with its own structure, tables and relations) with the database used by Drupal, and use the information in that database for creating views, for example.

I have a table "Persons" with 2 fields (Name, and Age) in the external database. I want to transfer (or connect, or synchronize) that information to my database in Drupal, or handle this information with some module. In my Drupal site, I have a "Persona" content type with two CCK fields: Name, and Age.

Is there any existing solution?

Easy answer: use the data module for drupal 6.x

http://drupal.org/project/data

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

The included data_ui module will let you setup the connections to your external database and map the fields.


Add class to top-level ul using menu_block I am using the Menu Block Module to generate my main and sub navs.  I want to add a class to the ul for just the top level of the main nav.

As I understand it, I can do something like this:

function theme_menu_tree__menu_block($variables) {
  return '
' . $variables['tree'] . '
';
}

or this:

function theme_menu_tree__menu_block__main_menu($variables) {
  return '
' . $variables['tree'] . '
';
}

However, that seems to wrap every level of the navigation with the above html.  How can I restrict the modification to the first level?

It doesn't look like I am given much data in $variables. Am I missing something?

Here's the trick: theme_menu_tree__MENU_NAME() and theme_menu_link().

<?php
/**
 * Implements theme_menu_tree().
 */
function THEMENAME_menu_tree__MENU_NAME(&$variables) {
  return '
' . $variables['tree'] . '
';
}

/**
 * Implements theme_menu_link().
 */
function THEMENAME_menu_link__MENU_NAME(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    // Wrap in dropdown-menu.
    unset($element['#below']['#theme_wrappers']);
    $sub_menu = '
' . drupal_render($element['#below']) . '
';
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}
?>


Services Browser in Services 3 I just switch from drupal 6 services 2 to drupal 7 services 3. I'm having  little trouble figuring out how to configure services, I'm used to being able to test different services using the services browser, but it seems like there is no services browser in services 3, does anyone have a good method for do these test?

See http://drupal.org/node/790416.  There is a Firefox addon called Poster which you can use or there is one for Chrome called REST Console.


Is db_query() limited to MySQL? I know db_select and Drupal's Database Abstraction Layer work across database implementations as long as there is a driver (mysql, postgresql and sqlite drivers included in core). But what about db_query? Should I patch contributed modules to make sure they work with sqlite?

Any function that is part of the database abstraction layer in Drupal 7 works with every database engine for which there are the necessary classes to work with that database engine.

If you look at the code of db_query(), you will notice it is generic enough to work with every database engine.

function db_query($query, array $args = array(), array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }

  return Database::getConnection($options['target'])->query($query, $args, $options);
}

This code is not different from the code executed by db_select().

function db_select($table, $alias = NULL, array $options = array()) {
  if (empty($options['target'])) {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->select($table, $alias, $options);
}

If you compare those functions with the code executed from db_delete(), you will notice the functions are essentially wrappers around Database::getConnection().

function db_delete($table, array $options = array()) {
  if (empty($options['target']) || $options['target'] == 'slave') {
    $options['target'] = 'default';
  }
  return Database::getConnection($options['target'])->delete($table, $options);
}

It is Database::getConnection() that, indirectly, builds the object necessary to execute the queries in the database engine, using the following code.

  $driver_class = 'DatabaseConnection_' . $driver;
  require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
  $new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
  $new_connection->setTarget($target);
  $new_connection->setKey($key);

As SQLite is supported in Drupal 7, db_query() doesn't need to be altered to execute optimized code for SQLite, as the code that it is optimized for that database engine is already contained in the DatabaseConnection_sqlite.


Remove duplicate messages How to remove any duplicate messages of a certain type.

For example when performing 2 searches using the search api module before rendering the page the message "To perform a search you must enter at least 3 characters" may be displayed twice.

Use the following function to remove any duplicate messages of a certain type:

/**
 * @param $type - the type of messages that should be checked
 *
 * Removes any duplicate messages from the messages session
 */
function remove_duplicate_messages($type) {
  $stack = array();
  if(isset($_SESSION['messages'][$type])) {
    foreach($_SESSION['messages'][$type] as $k => $msg) {
      if(in_array($msg, $stack)) {
        // Message is already set - remove it
        unset($_SESSION['messages'][$type][$k]);
      } else {
        // Add message to stack
        $stack[] = $msg;
      }
    }
  }
}

Example use:

remove_duplicate_messages('warning');


Building something like an affiliate shop? We want something very much like Amazon in that some providers define their products in a (site-)global catalog and customers can buy from this catalog.
Customers and providers have the standard features expected from such a system (history, various reports etc etc).

A little peculiarity is that there are no payments or shippings in this system. We are responsible for gathering the orders from customers and notify the providers. The rest is not up to us.

Which modules do you think we should use to implement such a system ? (Drupal 6)

You've tagged this with ubercart and you're using Drupal 6 so this should be fine - http://drupal.org/project/ubercart_marketplace

If you're not processing payments directly and have some 3rd party integration you're probably best off implementing a custom payment gateway and method using the hooks provided by ubercart than trying to track down a contrib module.


How can I pass a variable to javascript from a preprocess function? How do I pass $variables['is_front'] from template_preprocess_page() to a jquery script in Drupal8?

send it:

function mytheme_preprocess_page(&$variables) {
   $variables['#attached'] = [
        'drupalSettings' => [
          'myLibrary' => [
            'is_front' => $variables['is_front'],
          ],
        ],
    ];
}

access it in jquery:

  Drupal.behaviors.myBehaviour = {
    attach: function (context, settings) {

      console.log(settings.myLibrary.is_front);

    }
  };


How to override template for a Profile2 page I'm working on a project which request, for a particular type of user, the need to choose a different template for the main profile page (public page).
I need to override the main profile page but I can't find the php file to edit.
Can you help me.

You need to put user-profile.tpl.php in your theme  directory.


Drupal 6 end of life Is there a documented date, or a believed date for the end of life of Drupal 6?
In other words, when will official development stop on Drupal 6?

I think the advice from Choosing a Drupal version is probably the best to follow:

  At any given time, there are two major release series of Drupal which are supported. Currently, these are Drupal 6 and Drupal 7.

Essentially, official support for Drupal 6 will stop when Drupal 8 is officially released.

You can find further discussion on the So long, Drupal 5.x (End of Life Announcement)


How to set If-Modified-Since HTTP header in my drupal site I want to implement If-Modified-Since HTTP header in my drupal site. How do I ensure the If-Modified-Since HTTP header is supported and that it is active?. If it is supported but not active then how to make it active?

As you can see in drupal_serve_page_from_cache function, Drupal knows and uses this headers. Exact quote is:

  If the request is conditional (using If-Modified-Since and If-None-Match), and the conditions match those currently in the cache, a 304 Not Modified response is sent.

How can you test? Obviously you can forge HTTP request in your user agent and see. Or you can believe in built-in tests.

Of course if you will not turn any cache on, there is no reason to react to If-Modified-Since, because you have no cached data to serve if content is not modified. Default cache is located under http://example.com/admin/config/development/performance, and you can use other cache modules and mechanisms, too. Then, it's up to them to react to cache-related headers properly.


Cannot get role information in twig file I cannot seem to get the role of the current user in my twig template. I have tried the following:

{{ user.getRoles }}

{{ user.hasRole('content_administrator') }}

and neither return anything.

Notes:

I use a subtheme of radix.
I want to include stuff in the theme if the user has a certain role. Specifically, I have regular viewers and a content admin, and the content admin shall see extra things. I created a view called /revisionhistory which has a contextual link, and shows revisions. The theme should generate a link to /revisionhistory/{{node.id}} if the user has the administer_content role.

Displaying content if the user has a certain role:

{% if 'content_administrator' in user.getroles %}

Only displayed for the role Content Administrator

{% endif %}

More info: Restrict content to a user role in a template file


Updating few thousand nodes in one time I have script which updating 2000-5000 nodes in loop and performance is poor.
At the moment the code looks like:

foreach($nids as $nid) {
  $node = node_load($nid);
  // updating $node fields
  node_save($node);
}

It's possible optimize it? I don't need revisions, call node_* hooks, just update data.

There's a module called Views Bulk Operations.

This will update more than thousand node at a time without memory limit exception.


Drupal Commerce custom pane as payment and shipping address Currently, Drupal Commerce does not have a solution for "shipping address is the same as payment address" checkbox, which is very unlucky. I was thinking of creating a custom pane with my custom addresses form, where I could easily create such a checkbox. However, I could not find anywhere how to trigger a payment (from commerce payment module) after the addresses form is successfully submitted. Could you help me? Thanks!

This feature does not exist in core yet but it is in progress right now. Look for it in Commerce 2.13.


make taxonomy terms more human friendly I work on a  news site that has hundreds of articles and all the article urls are written by hand. eg. example.com/world-news-today-28-march-2018
The site has various news categories like: business, economy, technology, etc
but they are named taxonomy/term/1 and so on.
Is it too late now to activate pathauto module on a live production site that has tons of content?
All I want to do is change the urls of the news categories and make them more human friendly, so example.com/taxonomy/term/1 becomes example.com/business
without touching the article urls which are in each category.
Any ideas how can I do this and if it's safe at this stage?

You can use Pathauto module and follow these steps:

Enable pathauto module
Go to admin/config/search/path/patterns and set the patterns for specific taxonomy using Token module and save the form
Go to admin/config/search/path/update_bulk and generate URLs for taxonomy

Don't worry about the existing URLs (no matter wherever you added it) it will remain same, Pathauto will not effect anything. Now, visitors can access by both URLs (default and newly generated).

I hope this will help you.


Product with empty attribute values There are a couple of attributes in my product. If the product is added to the cart without choosing one or two attributes, the product goes to the cart, but unselected attributes are also showing up.

I want that attributes without values are not shown. How can I do this?
I tried using hook_product_description(), but it doesn't help.

I'm using Ubercart 6.x-2.7, and its Product attributes module.

Create a module to customize the cart form. Here's how I usually do it.

function custom_cart_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'uc_cart_view_form') {

    for($i=0;$i<count($form['items']);$i++){
       //these are rows in your cart... that includes the "total" line etc, so make sure to check that the row has the data you need

       //I believe what you're looking for is in $form['items'][$i]['desc']['#value']
       //you're going to need to look for the empty tag, probably using a regex pattern and remove the whole <li> element
    }

  }
}


Change Image Alternative text on select box change Fields:

Image Field - field_image
Selectbox Field - field_custom_language

Testcase: On selecting a different value from Selectbox, Alternative text of the image field should be changed.
Issue: Alternative text is not changed on ajax call.

    function custom_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
      $form['field_custom_language']['widget']['#ajax'] = [
        'callback' => 'AltChange',
        'event' => 'change',
        'wrapper' => 'custom-image-wrapper',
        'progress' => [
          'type' => 'throbber',
          'message' => t('Loading...'),
        ],
      ];
    }

    function AltChange(&$form, FormStateInterface $form_state) {
      $form['field_image']['widget'][0]['#default_value']['alt'] = $form_state->getValue('field_custom_language');
      $form['field_image']['widget'][0] = ImageWidget::process($form['field_image']['widget'][0], $form_state, $form);
      return $form['field_image'];
    }

I don't think it can be done using AJAX with php, image field doesn't expose the alt as field with value to change it.
But there is a way to do it by using custom Javascript in an AJAX callback like the following:

/**
 * Implements hook_form_alter().
 */
function MODULENAME_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['field_custom_language']['widget']['#ajax'] = [
    'callback' => 'AltChange',
    'event'    => 'change',
    'wrapper'  => 'edit-field-image-wrapper',
    'progress' => [
      'type'    => 'throbber',
      'message' => t('Loading...'),
    ],
  ];
  // Add library.
  $form['#attached']['library'][] = 'MODULENAME/alter-alt-image';
}

and the callback function should be like:

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\InvokeCommand;
function AltChange(array &$form, FormStateInterface $form_state) {
  // Get the language value.
  $lang_code = $form_state->getValue('field_custom_language')[0]['value'];
  $response = new AjaxResponse();
  $response->addCommand(new InvokeCommand(NULL, 'AltChange', [$lang_code]));
  return $response;
}

and Then create the library:
MODULENAME.libraries.yml

alter-alt-image:
  version: 1.x
  js:
    js/script.js: {}

and your Js script:
MODULENAME/js/script.js

(function($) {
  // Argument passed from InvokeCommand.
  $.fn.AltChange = function(argument) {
    // Set alt value to the passed arguments.
    $('input#edit-field-image-0-alt').attr('value', argument);
  };
})(jQuery);


Serve compressed JS and CSS with S3 as filesystem We have a Drupal 8 site using S3 file system integrated via the S3 File System module.

The aggregated CSS and JS are uploading on S3, however I am not seeing any configuration to serve compressed files.

Can someone suggest a way or any configuration that I am missing?

As Clive mentioned there is no config on s3 which could automatically compress the assets on s3.

The way we fixed it in our case was to add cloudflare CDN service(already in use) in front of s3 file system.

In order to route the s3 assets request via CF we added a proxy subdomain for our drupal origin. So if Drupal site was running on site-url.com we added a proxy subdomain as s3-<env>.site-url.com. We added a page rule in CF to override host to s3 bucket for any request to  s3-<env>.site-url.com/*.

Now, the challenge was to override s3 hostname configuration in Drupal to spit out resources on s3-<env>.site-url.com/* instead of s3 bucket url.
Big thanks to S3FS module maintainers for providing easy configuration to override that by adding following in settings.php

  $config['s3fs.settings']['use_cname'] = TRUE;
  $config['s3fs.settings']['domain'] = 's3-<env>.site-url.com';


Cache in hook preprocess page I'm trying to get a value of GET variable in hook_preprocess_page(), but I'm having problems with the cache. Only the first time the code is executed, I can get the value of the variable to put it in a cookie; if I try to load the same page with different values, the code doesn't execute.

I need to put this value in cookie to identify the source of leads.

If your preprocess doesn't affect the result of the page, and needs to execute even when the page is served from the page cache, you should move your logic to a Kernel Event subscriber, which replaces hook_boot() and hook_exit() from Drupal 7.

DrupalizeMe has an article on Event Subscribers, but the basic components are creating a class that implements EventSubscriberInterface, and then registering it as a service.

MYMODULE/EventSubscriber/MyEventSubscriber.php

class MyEventSubscriber implements EventSubscriberInterface {
  static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = ['onResponse'];
    return $events;
  }
  public function onResponse(FilterResponseEvent $event) {
    $request = $event->getRequest();
    $response = $event->getResponse();

    $parameter_value = $request->query->get('parameter_name');
    $response->headers->setCookie(new Cookie('cookie_name', 'cookie_value'));
  }
}

MYMODULE/MYMODULE.services.yml

MYMODULE.my_event_subscriber:
  class: Drupal\MYMODULE\EventSubscriber\MyEventSubscriber
  arguments: []
  tags:
    - { name: event_subscriber }

The request event can modify the request before other components receive it, but cannot affect the response.  The response event cannot modify the request, but is able to alter the response after it has been composed.
If you need to do both, your service object can store some state during the request event, and then alter the response based on that state during the response event.


Modifying an Existing Entity Column in hook_update_N This is a tricky problem but here is the jist of it. I have an entity that has a property called revision_id. Through hook_update_N I want to do 2 things.

Change the db column name to node_id
Convert the data in this db column from VIDs to NIDs

The code that takes care of this is...

function research_annotator_update_7100(&$sandbox) {

  // Change the db column.
  db_change_field(
    'research_annotator_annotation',
    'revision_id',
    'node_id',
    array(
      'description' => 'The node the annotation belongs to.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
    )
  );

  cache_clear_all();

  // Change revision ids into node ids.
  $arr_annotations = entity_load('research_annotation');

  foreach ($arr_annotations as $o_annotation) {
    $o_annotatedNode = node_load(NULL, $o_annotation->node_id);
    $o_annotation->node_id = $o_annotatedNode->nid;
    entity_save('research_annotation', $o_annotation);
  }
}

I also updated the entity property definition to represent the new node_id column...

research_annotator_entity_property_info() {

  $arr_propertyInfo = array();

  $arr_propertyInfo['research_annotation'] = array(
  'properties' => array(
    'node_id' => array(
      'label' => t('Revision'),
      'type' => 'integer',
      'description' => t('The revision id this annotation belongs to.'),
      'setter callback' => 'entity_property_verbatim_set',
      'required' => TRUE,
      'schema field' => 'node_id',
    ),
    ...snip

The problem is, when I run the update the first time, it gives me the following error...

Failed: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.revision_id' in 'field list' ...

In the database, the changes have been made to the column but the data has not been converted. If I clear all caches and run the update again then everything works as planned. I suspect that because the entity cache is not cleared after the db column change, the error appears.

If this is the case, how can I ensure the entity cache is cleared immediately after db_change_field is called in the update hook?

cache_clear_all() with no arguments clears cache_block and cache_page only; entity and schema cache both live in the cache table, so clearing that bin explicitly should do the trick:

cache_clear_all(NULL, 'cache');

Or if you want to clear the specific entries:

cache_clear_all('entity_info', 'cache', TRUE);
cache_clear_all('entity_property_info', 'cache', TRUE);
cache_clear_all('schema', 'cache', TRUE);

I'm assuming you've already updated your hook_schema() implementation to match the new scheme, or implemented hook_schema_alter() for the same if you're doing this on behalf of a different module.


How should I define Spatial field type? I have set of coordinates in EPSG 4326 / WGS84(ie. longitude and latitude in degrees) and I would like to store it as spatial information in DB so that I can perform spatial computations and use spatial indexes.

Currently I have a FieldType item that has longitude and latitude decimals but I would like to extend it and add this type of information. Since FieldType items do provide schema I can define the type via mysql_type/pgsql_type but I am not sure how to tell Drupal to use expression when inserting the value into database since there is no data manipulation available in the FieldType object and I do not see anything as well in DataType(in case I would create a new one instead of using string).

Looking ad DB drivers, I do not see anything particular that would need me to create my own version so I think this should be handled by the FieldType somehow but am not sure how.

This does not answer the question exactly but: it is possible to create the field simply by using proper schema BUT the issue is writing and reading data. It is possible with \Drupal::database()->query() but not with \Drupal::database()->select() or any other method since we have no control over value escaping so spatial functions are not interpreted.


How do I get the price of a line item for the transactions which are already completed? There are some transactions which are made using drupal commerce module along with commerce ccavenue module. I have the order ids, transaction ids and list of line items purchased in each of the orders. But the problem is I if a product price is updated in past then I am not able to find the cost of the product in the past order when the product was purchased.

Is there any place where drupal stores product price for a particular order anywhere.

Yes, Commerce Module does store product amount of past order... You can retrieve using below details...

To get full details of order

$order = commerce_order_load($order_id);
$view_mode = "administrator";
print entity_view('commerce_order', array($order->order_id => $order), $view_mode, NULL, TRUE);

To be more specific

  $order = commerce_order_load($order_id);
  foreach ($order->commerce_line_items['und'] as $line) {
    $line_item = commerce_line_item_load($line['line_item_id']);
    drupal_set_message("<pre>" . print_r($line_item,1) . "</pre>");
  }

There is no chance it gets new price instead of old price since it gets tracked in field_data_commerce_unit_price table in database ... All you need to do is divide by 100 if decimal places are 2 in order line item amount...


How to read input username to drush script? I need to complete a script  which gets a username from terminal to a php script and then deletes the user's comments.

So I am wondering how the username should be read by the php script, the same way that one can read a value in a bash script.

Thanks

In your Drush command you need to call drush_get_option('myoption'); to get the value of an input parameter.

To call your Drush command you need to specify your input option as below:

drush mycommand --myoption=myvalue


Creating a marketplace for tour activities I am tying to setup a website that will sell tour activities.

People (local guides) can login in and create a profile and define 1 or multiples activities (i.e. a waking tour of Manhattan) with a description, a price and a calendar of availabilities (maybe just now a simple calendar system not linked to availabilities).

Tourists will come on the web site, choose an activity (by category, location...) and will choose a date for it and book it online.

I need to track the orders in the admin area and have it in the Profile of the person who created the activity.

I tied to do this with D7, marketplace module, calendar module and Ubercart but I have lots of difficulties to do it.

Do you have tips on which modules would be the best to do that (Ubercart / Drupal Commerce)... ?

I have also been looking to "rooms", "simple reservation" modules but it seems that they does not fit my needs.

Regarding the invoicing, payment, commission revenues tracking, I will plug the API of an external system like LemonWay.

Thanks.

Emmanuel.

As someone else suggested: take a look at the Booking and Availability Management Tools for Drupal (BAT).

Roomify.us, the business providing the BAT framework announced that they are also providing solutions specifically for tours and activities rather than just rooms and fixed places.

The BAT system integrates with Drupal Commerce and its various payment gateways. It also takes over the Drupal logic very well with 'types', 'type bundles', 'events' and 'units'.

Once you understand how it works conceptually it should not be too difficult to modify BAT so that it can become a kind of marketplace where users can create their own units on the basis of pregiven tour types you have defined.


How to create a custom handler in view? I am trying to alter a field's argument handler. But It is showing me broken/missing handler in view's argument. I have tried it in following ways :

I am adding the following two code block in hook_field_views_data_alter where :

$table_name = node__field_test;
$field_col = field_test_value;

I want to change handler for a field.

First method by reviewing time spent module's code :

$data[$table_name][$field_col]['argument']['id'] = 'MyClassName';

I didn't understand the concept of id above and how it will recognise the class of my module?

Second method as in D7 :

$data[$table_name][$field_col]['argument']['handler'] = 'MyClassName'; // Second

How It works in D8?

The id is a plugin ID. You either need to define your own views argument plugin and change the id to that or alter the plugin definition and replace the class there.

The first will just update a specific field, the second would replace the plugin everywhere where it is used.


Create custom field programmatically I'm trying to re-create a field in my custom form with a date-picker. A dpm of my already existing form learned me the form looks like this:

Is it correctly to assume you can create the field with following code? Because I get an empty result...

$form['my_field_field_periods'] = array(
    '#title' => t('Periode 1'),
    '#type' => 'container',
    '#attributes' => array(
      'class' => array(
        'field-type-datetime', 'field-name-field-periods','field-widget-date-popup')
    ),
    - and so on -
  );

You can add a regular select box style date field with the form api like this:

$form['date1'] = array(
  '#type' => 'date',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
);

Drupal core doesn't have a date popup FAPI element, but you can add jQuery UI datepicker to a regular text field as well

$form['date1'] = array(
  '#type' => 'textfield',
  '#title' => t('Date 1'),
  '#description' => t('Date 1 description'),
  '#prefix' => '
',
  '#suffix' => '
'
);

// Attach JS datepicker library and init js for textfield
$form['#attached']['library'][] = array('system', 'ui.datepicker');
$form['#attached']['js'] = array(
  drupal_get_path('theme', 'my_theme') . '/js/datepicker-init.js',
);

Then in your theme /js/datepicker-init.js

(function ($) {
  // Add calendar popup to date textfield
  Drupal.behaviors.setDatePicker = {
    attach: function(context, settings) {
      var options = {
        'dateFormat':'yy-mm-dd',
        'changeYear':true,
        'changeMonth':true
       };
      $(".datepicker-wrapper input").once('datepicker').datepicker(options);
    }
  };

})(jQuery);

The result is something like this:


Webform: states dropdown vs textbox plain text in case of other country autoswitch? How can I make a webform so when a user selects the country US it will show the states in a list with a mandatory select from list
and when other countries it will show Province as textedit also mandatory..
i don't want to mess arround with Jquery and hide the controls resulting into multiple fields

addressfield module does that perfectly.

What I don't like about it is that it will also show "address 1&2" fields. You can hide those with css.
When you output the field it will show the complete address. You can also hide the parts you don't need with css.


How to redefine a message type for drupal_set_message? By default, there are 3 (status / warning and error). I will wish to add the info type, with a blue background for example. What to do?

The status is arbitrary, so:

drupal_set_message('A message', 'custom_status');

Will produce

A message

Notice the "custom_status" class, which you can target with CSS.


How to get content language abbreviation ("en" instead of "English") in a View? Im trying to get the content language abbreviation in a view, when I select "content: Language" field then it shows me "English" but I need to get its abbreviation "en", I though there was an option in the view field but there isn't.

Assuming this is the language of a node. It should actually be stored in the database as en, es, etc and then being rendered.

To get the content from the database without it being rendered here are the steps.

Go to your view. Here's a sample one I'm using:
Check the Information link on the bottom right hand side.

When you click it, you should see a screen like so:

Here my two fields are listed as well as two other parts of the view where different things are occurring.
The names on the right hand side are different overrides you can implement to intercept the process of generating the display.  Depending on the name is the precedence. The further a name, the more specific it is.
Now, you need to decide how specific you want your change to be. I think using something like views-view-field--testlang--language.tpl.php is good. In my example, testlang is the name of the view and language the name of the field.
Click on the link next to the name of the field you want to override. It might be something like Field Content: Language (ID: language):. Once you have this, copy the content it's showing you.

Now that you have the name and the content of the field, go to your theme and create a file with the name you selected. If you have a templates folder on your theme, put it there.

Paste the code that your website generated for you,

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php print $output; ?>

And now you modify it.

At the top you can see that you have the following variables available: $view, $field, $row, $output. The $row variable is the SQL result.
This is why I asked where you how it's stored on the database. I'm assuming up to now, we are using a node's language.

Well, if you take that <?php print $output; ?> and change it for <?php var_dump($row); ?>, it will give you the result from the database. If now you go to where you view is shown, or to the preview, you should see a line with something similar to:

object(stdClass)[94]
  public 'node_title' => string 'Consequat Nostrud Occuro Quadrum' (length=32)
  public 'nid' => string '26' (length=2)
  public 'node_language' => string 'es' (length=2)
  public 'node_created' => string '1479304373' (length=10).

Now, if you change your line to: <?php print $row->node_language; ?>, it should print the value as it's stored in the database in 2 letter country codes.

Good luck! Hope this helps.


Views contextual filter using entity reference field I have two content types.  An image content type and a photographer content type.  I have linked the photographer to the image content type by using entity reference, so that each image has a reference to a photographer.

I have created a view which shows all the images.  I want to be able to use a contextual filter so that when I add the photographer title field into the URL it only shows images for that photographer.  I have got this to work by adding a relationship in the view to the photographer and then using the photographer title field as the contextual filter.  However, it doesn't work if any spaces in the title are replaced with dashes.  Is it possible to make it work so that I can replace the spaces in the photographer title field with dashes?

So for instance the URL "photos/john smith" works, but the URL "photos/john-smith" does not, and I would like the last URL to be able to work.

The usual approach for this would be to expose the images view as a block, and to show that block in the 'context' of the photographer page. In the Contextual Filter configuration for the entity reference, select 'Provide default value > Content ID from URL' under 'When the filter value is NOT available'.

This will display each photographer's gallery as a part of his page. If the URL is important, give the photographer content type a default alias of "photos/[node:title]" under "/admin/config/search/path/patterns".


Creating mulitple contact forms in drupal 7 I have installed the contact and contact_forms modules.
I have created different categories in the contact settings page.

I want multiple contact forms as I have multiple domains. For each domain I should have a separate contact form.

But that categories displayed in the drop down of the contact form.

Is it possible with the contact module to create multiple contact us forms like contact/site1, contact/site2, contact/site3 etc?

Did you consider using Webform Module. I generally prefer this over contact forms on my websites.


Related events block I have a content type, Venues and a content type Events. In the Events post type, I have 'field_hosted_by' - allowing me to select the relevant venue.

On each venue page (/venue/venue-name), i'd like to create a block listing the events they are hosting – what would be the best way to do this?

I had a solution using taxonomies but this seemed inefficient, i'd rather not have to create a term for each venue, as well as a node.

Using Drupal 8.

Taxonomy terms are still entity reference fields, just like the field you have connecting your events and venue nodes. So there is no need to duplicate the same functionality.

You can list the Events referencing the Venue with a Views Block:

Create Content Views with Block display listing Events
Add a Contextual filter for the field_hosted_by field and configure it:
When the filter value is NOT available
Provide default value
Content ID from URL
When the filter value IS available or a default is provided
Specify validation criteria
Content
Venue
Save the Views and place the Block in a region of your choice to be displayed on Venue pages

You cant test the views output by entering the node ID of a venue node into Preview field, before placing the Block to test it's working.


How can I get a different version of a webform to show dynamically based on a selection value? I have a contact form currently set up with select options for the nature of the customer's inquiry. The conditionals and email handlers are set up for each selection value. Just now the user has to manually select a subject from the drop down before it displays the corresponding fields. Is it possible to take the user to the form using a parameter in the URL based on the selection option value so all the relevant fields are shown? I have tried using variants and references to show the fields and display them in webform nodes but I wondered what was the best way to go about this as I cannot get the fields to hide using variants. I'm still new to variants so still working all of that out. I have looked through the previously asked questions but I can't find anything for Drupal 8.

If I'm understanding correctly, you want to show/hide certain fields based on the value of the Subject field, and you also want this value to have the ability to be set via a URL parameter?
If that's the case, this can be done in a single form using conditional fields and form settings.
First, in your form Settings, under Form >> Form Behaviors >> Prepopulate, check Allow all elements to be populated using query string parameters.
If this is checked, all elements can be populated using query string parameters. For example, appending ?name=John+Smith to a webform's URL would set the 'name' element's default value to 'John Smith'. Please note that individual elements can also have prepopulation enabled, so you could skip this and allow only the Subject field to be prepopulated if desired.
Next, in "Build" screen, edit one of the conditional fields that depend on the Subject field value. In the "Conditions" tab, you can describe the logic to display or hide the field based on the value of another field, something like
Visible if All of the following is met:
Subject[Select] Value Is 'Some subject value'
I hope I've understood your question correctly! While it doesn't use 'variants', this approach can still help you show a variation of your form depending on how the "Subject" field is filled.


Is it possible to export my website to a native iOS/Android application? I'm new to the EZPublish CMS and I see that he give you the facility to export your website into an Android or iPhone application.

Is there any way to do the same with Drupal?

Mobile App Generator exports a website to plain .html pages so that PhoneGap can compile it into native mobile apps.

  Mobile App Generator assists in creating native multi-platform
  PhoneGap mobile applications for Apple iOS(iPhone, iPad), Google
  Android, Palm, Symbian, BlackBerry and more.

If you want to manage the website through mobile App then take a look at this module Drupad

  Drupad.module is the companion module for the iPhone™ / iPod touch™
  application


How to create links from term to node On the node display I would like to create a list of services but for some of the services, I would like the list element to be displayed as a link to a certain node, and some will not have links.

I tried creating a vocabulary called Services with an additional Link field, but with no luck.

Ideally it would be good to reference the NID, incase the path changes in the future, and display the link URL without the NID as its final path. But if there is a simpler way using final paths, then I am happy with this.

Below is the desired outcome.

Services:
- Website Design <--Linked to node/2
- SEO <-- no link
- Hosting <-- linked to node/4

The module Special menu items lets you create menu items that aren't links.

Using Taxonomy doesn't seem like it would do anything to solve this, unless you want a different list of links to show depending on what node it's being displayed on.

So basically you just create a new Menu and add menu items you want in the list. A Block showing the list is automatically created for each new Menu, so you just have to go to Block configuration and place it in a region of your theme to make it appear. On Block configuration you'll also be able to restrict which pages to display the links on, maybe just the one node.

The thing you asked about using NID is concerning Path aliases. You can use the module Global redirect to make the system always output the alias instead of the NID link. With Pathauto you can configure patterns to automatically create path aliases when creating new content.


How can I programmatically populate a drop-down list field's options? I have a paragraph bundle with several fields, on of them being drop-down list.

How would I go about populating this dropdown list via code, programmaticaly?

I don't really know where to begin with this...

Ok, here's what I figured out:

Use hook_field_widget_form_alter()

My case:

function my_module_field_widget_form_alter(&$element, &$form_state, $context) {

  // Check if element is paragraph type, belongs to a specific paragraphs
  // bundle and contains a specific field.
  if (empty($element['#entity']) || $element['#entity_type'] !== 'paragraphs_item' ||
    $element['#bundle'] !== 'content_block' || $element['#field_name'] !== 'field_dropdown_text_single') {
    return;
  }

  // Get entity metadata
  $form_field_wrapper = entity_metadata_wrapper('paragraphs_item', $element['#entity']);

  // Set default value. If there is already a set value use that,
  // else set to '_none'
  $default_value = $form_field_wrapper->field_dropdown_text_single->value();
  $element['#default_value'] = !empty($default_value) ? $default_value : '_none';

  // Code to get your custom select options goes here

  // Inject custom options into paragraph's dropdown selector.
  $element['#options'] = $my_options;
}


Password Reset Redirect I've been trying to redirect the password reset page to my custom login page by creating a small custom module; however it's not resolving properly.

Has anyone done this before with success?  The code that I'm trying to use is:

function m2f_password_reset_form_alter(&$form, &$form_state) {
  if ($form['#action'] == "/user/password"){
    $form['#submit'][] = 'user-pass';
  }
 }
/**
* Redirects user after password reset form is filled
*/
function m2f_password_redirect(&$form, &$form_state){
  $form_state['redirect'] = 'node/20';
}

There are at least three possible issues that I can see:

You are probably not prefixing the function with the right string.
If the module/theme name is m2f_password, then m2f_password_reset_form_alter() is not recognized at implementation of hook_form_alter().
If you are trying to alter the form that is shown at user/password, you should not check $form['#action']; you should implement hook_form_FORM_ID_alter(), and write a function called m2f_password_form_user_pass_alter(). (I assume the short name of the module/theme is m2f_password; if it is not correct, replace m2f_password with the short name of the module/theme.)
user-pass is not a valid form submission callback name: PHP functions cannot contains hyphens. You are then defining m2f_password_redirect(), and that seems a form submission callback.
The correct code is probably the following one.

$form['#submit'][] = 'm2f_password_redirect';


How to create a user object of a custom form and add a user in drupal 7? i am new to drupal ,basically wanted to create a user object for my custom form and add a user.

This is my custom form

function registerme_newform($form, &$form_state)
{
$form = array();
$form['account details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Account Details'),
    '#description' => t('Enter Personal Credentials'),
    );
$form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#default_value' => t('Be sure of your first name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your first name'}",
    'onfocus' => "if (this.value == 'Be sure of your first name') {this.value = ''}"
      , ),
       );
     $form['account details']['last name'] = array(
    '#type' => 'textfield',
    '#title' => t('Last Name'),
    '#default_value' => t('Be sure of your last name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your last name'}",
    'onfocus' => "if (this.value == 'Be sure of your last name') {this.value = ''}"
       , ), );

     $form['account details']['email'] = array(
    '#type' => 'textfield',
    '#title' => t('E-Mail'),
    '#required' => TRUE,
    '#default_value' => t('Email acts as username.Dont forget it!'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Email acts as username.Dont forget
     it!'}",
    'onfocus' => "if (this.value == 'Email acts as username.Dont forget it!')
 {this.value = ''}"
       , ),
    );

    $form['account details']['password'] = array(
    '#type' => 'password',
    '#title' => t('Password'),
    '#maxlength' => 60,
    '#size' => 60,
    '#required' => TRUE,
    '#description' => t('Password should be atleast 6 characters long.'),
    );

$form['home'] = array(
    '#type' => 'fieldset',
    '#title' => 'Home Address',
    '#description' => t('Enter Personal Residential Credentials')
);

$form['home']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);

 $form['home']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);

 $form['work'] = array(
    '#type' => 'fieldset',
    '#title' => 'Work Address',
     '#description' => t('Enter Official Address')
);

$form['work']['street'] = array(
    '#type' => 'textfield',
    '#title' => 'Street Address',
);

 $form['work']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
);

 $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Register Me'),
);

 return $form;

}

function registerme_newform_validate(&$form, &$form_state)
{
if($form_state['values']['account details']['first name']=='Be sure of your first name')
{
form_set_error('first name',t('Please enter your first name'));
}
}
function registerme_newform_submit(&$form, &$form_state)
{
dsm($form_state);
}

Is user_save method for creating an object? How to implement this please guide or suggest otherwise. Thanks

You can save the details of the user in an array and can use "user_save" function to create new user.
You can get the values from the $form_state elements

    $details = array(
      'name' => '',
      'pass' => user_password(),
      'mail' => '',
      'init' => '',
      'status' => 1,
      'access' => REQUEST_TIME,
      'field_fname' => '',
      'field_lname' => '',
    );
    user_save(drupal_anonymous_user(), $details );

drupal_anonymous_user() will generate the default anonymous $user object.


Illegal choice detected with Unlimited Image field I have an image field in a content type that uses the image widget. Whenever I select an image to upload, it gives the error: "An illegal choice has been detected. Please contact the site administrator."

The image thumbnail appears as normal, however, there is no way to submit the form (returns errors) and you can't add more images.

I haven't made any changes to the form (just some CSS stuff for presentation).

How can I fix this?

I had similar issue, fixed it by changing one of my required field from radio buttons to "select list".


what actions to take when someone uploaded php files in random drupal folders and sending out spam I'm not sure how this happened, but my server techs notified me about some php files inside the includes folder sending out 50k worth of emails. I'm not sure how anyone would be able to upload that. I doubt its because my username/password was compromised for the domain. im finding these files littered through out the directories: http://prntscr.com/rhf93

In those files they contain all similar encoded php code:

http://prntscr.com/rgzmo

http://prntscr.com/rhfmq

Does anyone know what its doing or how i can decipher the code? And most of all how was it uploaded?

Notice how most of these code snippets begin with "preg_replace('/(.*)/e'"? That's because it's an alternative to the eval() function for executing PHP. The rest of the string is hexadecimally encoded; you can decode it using this script. That string will decode to PHP that probably executes other scripts or performs other actions to hijack your site and make it part of a spam mailing net.

Check out this StackExchange post for more details and suggestions. There are a bunch of good articles out there too that can give you tips on securing your server.


How does one check if user has created a node of a content type in rules? I would like to check if a user already authored a node from a content type before creating one for the user in rules. How do I create a condition for this? Thanks!

After seeing these big answers for Rules, I think you can try to do the same via code. Its much smaller and extremely faster than Rules!

/**
 * Implements hook_node_prepare()
 * @param type $node
 */
function mymodule_node_prepare($node) {
  if ($node->type == "my_type") {
    if (!isset($node->nid)) {
      $existing_nid = db_query("SELECT nid FROM {node} WHERE (type = :type1) AND uid = :uid", array("type1" => "my_type, "uid" => $node->uid))->fetchField();
      if ($existing_nid != FALSE) {
        drupal_goto("node/$existing_nid/edit");
      }
    }
  }
}

This code checks if the user already have created a node, if yes, instead of allowing him to create a new one, we redirect him to the edit form of the existing node.

If you want this feature without Rules or code, you can try the Profile module. It has this magical feature to configure any content-type as 'profile'. And when a content-type is configure as 'profile', users are not allowed to have more than one node of that particular type.

Thanks!


Cache rebuild causes an error with missing plugin On rebuilding the cache, a Drupal 8 website goes down and displays the message "The website encountered an unexpected error. Please try again later." I used drush cr to rebuild the cache, which shows the following error message.

  The "field_item:boolean" plugin does not exist.

I also tried to rebuild the cache right after installing a new Drupal 8 site without any additional module, and it shows the same error.

How can I get the site back to working?

This morning I had similar problem and drush cr was actually not clearing the discovery cache but after

drush sql-query 'TRUNCATE TABLE cache_discovery;'

I was able to get rid of this error


Taxonomy menu with custom path for taxonomy terms I am trying to make a taxonomy menu using the Taxonomy Menu module with a custom path for the taxonomy terms. Instead of /taxonomy/term/tid I want /proj/!tid (or ultimately /proj/!term-name but I'll settle for what I can get). I have the taxonomy menu working fine when I leave the "menu path type" setting to default, which leaves it as /taxonomy/term/tid. Whenever I try to use the "vocabulary path" option though, the menu terms all disappear. I've tried to follow the instructions in the documentation here.

I have a view with Taxonomy: Term ID (with depth) and Taxonomy: Term ID depth modifier arguments and a page display with the path set to proj/%. I've tried additionally making a url alias at proj and proj/% but that didn't seem to make any difference. But basically whenever I set the menu path type to "vocabulary path" ("custom path" in the documentation), the menu items all disappear. The terms are still there, and I can navigate to /proj/%, but there are no menu items.

Any help with how to have a custom path for the vocabulary while keeping the menu items would be greatly appreciated.

If you want to alter taxonomy term paths for taxonomy terms implemented by your module, then you can implement hook_term_path(), which is the hook that allows a module to alter the taxonomy term paths.

The function that returns the taxonomy term paths is the following:

    function taxonomy_term_path($term) {
      $vocabulary = taxonomy_vocabulary_load($term->vid);
      if ($vocabulary->module != 'taxonomy' && $path = module_invoke($vocabulary->module, 'term_path', $term)) {
        return $path;
      }
     return 'taxonomy/term/' . $term->did;
  }

Implementing that hook would also help to modify the path of any vocabularies, if the field $vocabulary->module is changed to the short name of the module you created.

Alternatively, you can write the custom_url_rewrite_outbound() and custom_url_rewrite_inbound() that allows to rewrite the URLs being shown to the "outside" world, and convert a URL into the one used by Drupal.
The example given in the documentation should make clear how to use this functions.

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  global $user;

  // Change all article/x requests to node/x
  if (preg_match('|^article(/.*)|', $path, $matches)) {
    $result = 'node' . $matches[1];
  }
  // Redirect a path called 'e' to the user's profile edit page.
  if ($path == 'e') {
    $result = 'user/' . $user->uid . '/edit';
  }
}

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  global $user;

  // Change all 'node' to 'article'.
  if (preg_match('|^node(/.*)|', $path, $matches)) {
    $path = 'article' . $matches[1];
  }
  // Create a path called 'e' which lands the user on her profile edit page.
  if ($path == 'user/' . $user->uid . '/edit') {
    $path = 'e';
  }
}

In other cases, you can use a module like Pathauto, or Views Term Path Override, which allows to override the taxonomy term paths in views.
Other modules that could be of help are Path redirect, and Taxonomy Redirect; The project page for Views Term Path Override suggests Taxonomy Views Integrator as alternative.


Adding Content to the top of a form Page I just want to add an easily editable block of content to the top of a Form page in Drupal 8.

This can either be adding text to the form or adding the form to a content item, I don't mind.

What's the most straight forward way of doing this?

Create a simple block (/block/add?destination=/admin/structure/block/block-content) and make it appear on the form's page.

If you can not setup the necessary restrictions for the block to appear, you have to go for hook_form_alter (but this means programming your own module).


Load “my blog entries” on profile pages I have created the view “my blog entries” which should be displayed on a user’s profile page. In terms of displaying not all but only the currently viewed user’s blog entries I have added the Contextual Filter called Content: Author uid.

In a second step I created a block, which is only present on listed pages: “profile/*”

So now I can go to a user’s profile page (root/profile/3) and the block is enabled, the view is loaded and will load only entries from that very user.

In terms of improving SEO I used URL-Aliases to get something like this: root/profile/the-actual-user-name

For obvious reasons my view won’t work anymore. How to get it work again without the user-ID in the URL?

For your contextual filter use Provide default value, User ID From URL. (this automatically extracts the uid from the url (page) and the uid does not need to be in the url).


How to send an email to multiple recepient with contact form? I want to send an email to multiple recepients when the contact form is submitted. By default when contact form is submitted it is sending mail to default email id which is saved in system configuration.

How can we add multiple email addresses which will receive messages when any user submitted the contact form?

Here is a possible implementation to achieve what you're asking about:

define a new eMail ID, say x@sample.com.
configure this x@sample.com to automatically forward all incoming eMail to your "multiple eMail addresses".
in your form, use x@sample.comas the email ID where these forms should be eMailed to (which will then be forwarded after you completed the prior step).


Cache busting for images in Drupal 7 and lightbox 2 Scenario: I have content type with a field 'images' (Widget: plupload). View created and displayed on Home page. View has Formatter: LightBox2, LightBoxType: Single Lightbox, Image-Style: thumbnail image-style for the images. Whenever user click on image, LightBox2 shows original image.

Problem: Everything working fine. But the images are getting cached in browser cache. Hence I followed https://www.drupal.org/node/2313539 Cache Busting discussion and changed theme.inc theme_image() function. Now the thumbnails have time(cache busting string) in their name but lightbox still the same.
I get the point that i have write or hook the formatter as well to make it work in views. Not sure where and what should change in LightBox module or elsewhere.

This is what HTML looks like on page

<a href="sites/default/files/images/3.jpg" rel="lightbox[field_images][
Download Original
]" title="" class="lightbox-processed">***

where  tag has src url appended with '&hash=2563415' i.e. cachebust string, but anchor-element doesn't have the same.
Any ideas how to make Lightbox2 anchor element to include cachebust string element as well.
Drupal version:7.41, LightBox2

OK, I solved it. Cachebuster can be implemented as discussed in shared url for drupal 7 by editing includes/theme.inc, and theme_image function. Just add attributes['src']with a random string say time().
Further, lightbox2 module can be tweaked to append random string in a href, by editing lightbox2/js/lightbox.js, just edit start: function(imageLink, slideshow, lightframe, lightvideo, lightmodal) {} and append anchor.href with new Date().getTime().

These two tweaks will make sure that drupal is giving img src appended with time and lightbox2 inserting time() in anchor href.
Browser will never cache these images.


Working with views and revisions I need to display field data for a given revision in a view for example the body.

To archive this I created a view which displays content revisions.

This view has a relationship by default: The revision ID of the content revision.

I then added the body field using this relation.

When i run the view the body field is empty for all revisions but the active one.

When I change the relation to The revision NID of the content revision. I get all fields filled out, but they are all filled with the data from the active revision.

I don't know if this a bug or the expected behavior.

Is there a way to get the field data for revisions that are not active or do I need to rewrite the queries?

I'm using the revisioning module, but it doesn't make a difference if it's active or not. The results of the views are the same.

While adding fields to your view, you will see fields named like Content (historical data) : Field name select those and you will get the revision data.


Drop-down Menus in Standard Drupal 7.4 Zen theme? I'm new to Drupal so forgive me if I'm missing something obvious.
I'm trying to implement a drop-down menu in Drupal 7.4 in the Zen theme with only a standard install (I'm trying to avoid installing other modules).
There appears to be no easy way to do this.
Is the only option to manually code one of the CSS files in the subtheme directory for this effect?

Thanks!

If you don't wNt to install other modules then your only option is to create the CSS / JavaScript needed for it in your theme.

If you don't want to use a module, take a look at nice_menus.


Using OAuth2 on non-REST endpoints I have a custom module which includes a ControllerBase. The controller has a content() function that returns a JsonResponse(). The code for this function returns a complete list of a certain entity type.

I've tried using REST for this, but the entity structure is decently complicated and contains several field collections. By default, REST will just include the ID of a field collection as part of its presentation of this entity, so I've written a FieldFormatter plugin that replaces the field collection ID with a JSON object of its contents. Unfortunately, that requires significant overhead when returning an entire list of the entity type via REST, and takes 40 seconds to load. However, OAuth2 works fine with it.

Alternatively, my existing custom connector takes approximately two to three seconds to load, as it is a single sanitized SQL statement that outputs its results as a JSON. However, I only have Basic Auth working with this, attempting OAuth2 returns a 403 error. I am using the simple_oauth module.

I'm wondering if there is a way to:

A) improve the response time on the REST endpoint to be as good as the custom controller

or
B) use OAuth2 with the custom controller. I've been looking for instructions on this but every OAuth2 resource I've come across so far assumes I'm using a REST endpoint.

edit to update: The REST endpoint is caching, which seems good as it's now loading much faster after the initial fetch, but (as is expected behaviour) the cache is flushed along with all other caches which is something we need to do fairly often, meaning the next person to access the endpoint will see an unusually slow response time. This isn't ideal, and I'd like to still investigate the custom controller I made, however adding _auth: ['oauth2'] to the YAML file is not fixing the 403 error.

2nd edit to update: This is my YAML for the custom controller, which is also not working:

connector.modulename:
  path: '/connector/modulename'
  defaults:
    _controller: \Drupal\connector\Controller\ModuleNameConnectorController::content
  requirements:
    _permission: 'view modulename entity'
  options:
    _auth: ['simple_oauth']

It does not work with _auth: ['simple_oauth'] or _auth: ['oauth2'] (403 error), but does work with _auth: ['basic_auth']. I'm using Postman to connect with a fresh (~30 sec, expiry 5 min) token. The same oauth2 token works for the REST connector. The error message I'm getting in my admin logs states:

League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in League\OAuth2\Server\Exception\OAuthServerException::accessDenied() (line 173 of C:\directory_to_my_site\vendor\league\oauth2-server\src\Exception\OAuthServerException.php).

and also issues a PHP warning stating that access was denied to Guest (not verified).

A) improve the response time on the REST endpoint to be as good as the
  custom controller

For the REST endpoint, you can use $response->addCacheableDependency() check this block for example:
https://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/
https://spinningcode.org/2017/05/cached-json-responses-in-drupal-8/

Make sure to add cache context and cache tags, carefully.

  B) use OAuth2 with the custom controller. I've been looking for
  instructions on this but every OAuth2 resource I've come across so far
  assumes I'm using a REST endpoint.

Check the example from "simple_oauth_extras" sub module of "simple_oauth"
https://git.drupalcode.org/project/simple_oauth/blob/8.x-3.x/simple_oauth_extras/simple_oauth_extras.routing.yml#L22

Controller is:
https://git.drupalcode.org/project/simple_oauth/blob/8.x-3.x/simple_oauth_extras/src/Controller/DebugController.php#L39


How to add a percentage column to drupal views? I use Views Aggregator Plus to calculate sum of a column.

items    data
A         20
B         40
C         10
____________
Total     70
Then I want to add additional column for percentage.

-----------------------------------------
Item        Data        Percentage
-----------------------------------------
A              20
B              30
C              50
-----------------------------------------
                100
----------------------

I know Global:Math expression. But I don't know how to get the sum, the sum field(Total) is not available. Only [value], [value_1] and [value_2] available for A, B and C respectively.

Is there a way to add a percentage column?
I have seen this question in another page with unclear answer.

Use php_view module to add column to calculate the percentage

$field_one = 50;
$field_two = 350;

$new_column = ($field_one / 100) * $field_two;


Image and Media Best Practices I am looking for suggestions on Best Practices for D8 and files / media entities. I originally added this as a answer but kiamlaluno evidently felt that it should be a new question in itself so here goes.

I trying to figure out the best way to handle files and media entities. With the increase of development in the file entity module if appears that things are once again getting way over complicated since files can now be a full blown entity. In my opinion this is going to put a lot of people off as to which way is the most practical way to go.

What I would love to see is a tutorial or a write up on best practices of when to use the file field versus the media field and the pros and cons of each. Drupal 8 by default gives us a Article content type which is a file entity. So should we use this for images or delete it and use media fields.

Does anyone know of a recent tutorial or discussion for review?

Use media_entity. End of discussion.

People are actively working on getting it into core and once that happened, there is no reason to use file_entity anymore.

We (as in me and @slashrsm/MD Systems) will continue to minimally maintain it, as we have a number of big sites (a distribution actually) that relies on it, but it will most likely never get out of alpha while media_entity is already stable.

We're actively blogging about the status and progress on getting media into core:

http://www.md-systems.ch/en/blog/md-systems/2017/01/09/current-status-of-media-in-drupal-8-core-and-next-steps
http://www.md-systems.ch/en/blog/md-systems/2017/01/30/media-initiative-is-official-and-we-are-one-of-its-leading-parts


How to add Text Resize button to theme? Whats the best way to add a Text Resize feature in the theme instead of using contrib modules.

I have tried Text Resize but it dosn't work for my custom theme. I told it to resize in entire "body" of my page but it ends up resizing only one paragraph.

are there other themes who have done this?

I would recommend against including this functionality on your site. Re-sizing text is best handled by browsers and assistive technology. Check out this discussion: https://groups.drupal.org/node/85254

The key thing is to use relative CSS units (em and %) when defining font-sizes and typography-related dimensions in your theme.


How to show only the comment form, not the comments Right now in Drupal, at the end of each article, there are the comments which users has put on that article and also the comment form. I just want to have the comment form at the end of each article, I do not want the comments be shown at the end of each article. Does any body know how can I do it?

Implement hook_node_view() and check for $node->type == 'article' and $view_mode=='full' then unset the comments as follows

unset($node->content['comments']['comments']);


Can I use taxonomy term as relationship in view? I created a content type called 'Job' in which I added:

a 'Company name' field of term reference type
a vocabulary 'Organizations' containing company names as terms

I want to create a view of nodes of type 'Job' in which I want to display the email of the user who have created it?

How can I do so?

Notes:

When I try to create a relationship using the company name field, it does not show user email in fields and when I use author as relationship its showing?
I have both relationships (ie relationship on user + relationship on taxonomy term), but is it possible to use only one i.e company name?
I have created 'company page' as content type containing email id and user reference field so it can relate to this?

You can create a view of jobs:

with a taxonomy term relationship on your field_company_name in order to show the taxonomy term name and any other fields it might have.

In order to show the email of user that is referenced from the taxonomy term you will also need a relationship (via the field_company_name relationship) on user so that you can access the user fields (eg email). The option to add this relationship will now be available from the relationships list, if you filter by user.

Sidenote: You may want to consider using an additional email address on the user for this in case the user does not want to receive job applications at their own personal email address, but wants to use their personal email address to manage the account.


Error Finding Home page for Drupal 7 Site on Ubuntu Linux I installed Drupal more or less successfully in /var/www/html on Ubuntu Linux. However when I go to 'localhost' it still just shows the Apache home page. However, if I go anywhere WITHIN my drupal site it works fine. So the home page is the problem. In fact if I click 'home' in the admin toolbar it takes me (again) to the apache home page.

Here's what I set in my 000-default.conf file on Ubuntu:

<VirtualHost *:80>
    . . .
    ServerName  mysite.dev
    ServerAdmin webmaster@example.com
    DocumentRoot /var/www/html

    <Directory /var/www/html>
        AllowOverride All
    </Directory>
    . . .
</VirtualHost>

I tried following the directions here but didn't see any reference to index.htm or .html in my apache2.conf file:

https://www.drupal.org/node/1484514

Not sure what else to try.

Suggestions?

You need to enable php in your apache conf. You can try

$ sudo a2enmod php5


Variable with placeholder I am implementing a couple of translatable variables that are exposed via hook_variable_info().

Can I use placeholders in these variables, and process them to replace with the actual values?

As an example: I have a variable that holds the following informational text that will be shown on a page that has a registration form below.

  Please signup here to gain access to the restricted area for @yourcompany

I have been googling around for this, but cannot seem to find any good leads on how to do this (if at all possible?)

The simplest way is using format_string(), you can have 3 kind of replacement token for different sanitisation and formatting.

  @variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.

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

  !variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).

Example code:

$message = variable_get_value('variable_name');
$message = format_string($message, array('@yourcompany' => $company_name));