How do I remove the "where" clause from a structured query object in hook_query_alter()? Jumping off of this question, I'd like to know how to gracefully detect and remove each snippet in the WHERE clause of my query object in plain old hook_query_alter(), not hook_views_query_alter() (as the Views query object seems structured in some entirely different way (frustrating!).  The documentation vaguely suggests that this is possible by showing how you can create a reference to your query conditions that you can then manipulate, by starting with this:

$where =& $query->conditions();

... but the object(s) within are utterly confusing, and I've been struggling to remove or replace existing snippets.  I've explored /includes/select.inc and /includes/query.inc but the classes therein don't seem to provide any methods for fine-tune manipulation.

That's pretty much all there is to it: in hook_query_alter() you only have access the query object from "outside" and, since there is no public API to remove conditions, it's kinda confusing.

However, there's some clever php hackery going on so if you call $where =& $query->conditions(); or any of the other examples in the documentation you linked it will return a reference to that corresponding variable.

So, in the where example above, you gain access to $query->where protected class variable.  If you inspect them you will see they are just basic php arrays containing all of the information and you can literally just unset something on that reference and be done.

So:

$where =& $query->conditions();
// Remove the second condition.
unset($where[1]);

Finally, specifically with where queries, you want to be mindful of the #conjunction and eventual more complex and/or grouping stuff.


Drupal Rest Service - Create node problem I'm using POSTER add-on (Firefox) to create a node.(REST service). I couldn't able to create node having select/checkbox item. Getting following error in response.

["An illegal choice has been detected. Please contact the site administrator"]

How to resolve this? I'm able to create node if post data doesn't contains select/checkbox data. My problem is exactly related to the following link. But I couldn't find solution.

drupal 7 + services 3 - inserting nodes with select fields

If I replace 'und' to 'en' in json format, the node is being created but with null values.

I've found following messages under Recent log messages.

Warning: htmlspecialchars() expects parameter 1 to be string, array given in check_plain()
Warning: Illegal offset type in isset or empty in list_field_validate()
Illegal choice in LABEL element.

Here 'LABEL' is the label(name) of the filed

Yes.. finally I got solution for my problem. Here is the solution.

In JSON format, Here is the correct way to handle LIST type fields

"field_select_options":{"und":["4"]}

(Initially I tried "field_select_options":{"und":[{"value":"4"}]} which results error in response.)

Thanks, I got the solution from https://drupal.org/node/1971484


How do I attach AJAX click events on  or  tags? There are many examples how to make ajax form submits and also many examples how to make drupal ajax links.
How do I attach AJAX click events on, for example, <button> or <div> tags?

You need to write code for this element. Copied from d.o..

STEP BY STEP

Select the element to attach Drupal.ajax object to.
Lets create HTML element first.

/**
 * Menu  callback.
 *
 * Build container to load ajax content to.
 */
function my_module_remote() {
  $wrapper = array();
  $wrapper['#attached']['js'] = array(
    drupal_get_path('module', 'my_module') . '/my_module_ajax.js'
  );
  $wrapper['#attached']['library'] = array(
    array('system', 'drupal.ajax')
  );
  $wrapper['container'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'remote-content-wrapper',
      'title' => t('click to reload')
    )
  );
  $wrapper['container']['content'] = array(
    '#markup' => t('Loading data...')
  );
  return $wrapper;
}

This callback will create simple page with div container and text "Loading data..." on it. Pay attention to element with id "remote-content-wrapper". This div container we will be base DOM element for our Drupal.ajax object.
In JS code we select it is with #:

$('#remote-content-wrapper').once('remote-content-wrapper', function() {
  var base = $(this).attr('id');
...
});

NOTE: I use '$.once()' method here to attach behaviour only once. Read more.
So, the HTML element selected and it is div#remote-content-wrapper.

Build object of options for new AJAX element.
    ...

    var  element_settings = {
          url: window.location.protocol + '//' + window.location.hostname +  settings.basePath + settings.pathPrefix + 'ajax/remote',
          event: 'click',
          progress: {
            type: 'throbber'
          }
        };

...
    The only required keys is:

'url' - the path to make ajax call to, any drupal full path.
'event' - the javascript/jQuery event to react to, any string or one of the registered like 'click', 'change', 'keypress'
'progress' - the progress type. Object contain 'type' key, which can be either 'throbber' or 'bar'.

Other settings:

    keypress: true,
    effect: 'none', // jQuery effect.
    speed: 'none', // setting for jQuery effect.
    method: 'replaceWith', // Will be rewritten with ajax command.
    // The additional data to submit.
    submit: {
      'js': true
    }

Add the new AJAX object to global Drupal.ajax object.
It is simple easy:

Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
Drupal.ajax() function-constructor takes 3 parameters:
- element id,
- DOM object,
- settings object

NOTE: The new element should be stored in global Drupal.ajax array of ajax objects under the element id key. Every Drupal.ajax object on the page are stored in this array.

That it! The Drupal.ajax element created.
To trigger new ajax reaction we should call registered in element_settings object event:

$(this).click(); // $('#remote-content-wrapper').click();

I use here click, but you could pass as parameter any event you want, and then trigger it with .trigger() method.
    AJAX callback should return array of Drupal commands or any custom registered AJAX commands which will be executed after success ajax call.

The complete js part:

(function ($) {
  /**
   * Load remote content after the main page loaded.
   */
  Drupal.behaviors.my_module_load_remote_content = {
    attach: function(context, settings) {
      $('#remote-content-wrapper').once('remote-content-wrapper', function() {

        var base = $(this).attr('id');

        var element_settings = {
          url: window.location.protocol + '//' + window.location.hostname +  settings.basePath + settings.pathPrefix + 'ajax/remote',
          event: 'click',
          progress: {
            type: 'throbber'
          }
        };
        Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
        $(this).click();
      });
    }
  };
})(jQuery);

The complete PHP part:

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items['ajax/remote'] = array(
    'title' => 'Data',
    'page callback' => 'my_module_remote_ajax',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  $items['page'] = array(
    'title' => 'Data',
    'page callback' => 'my_module_remote',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Menu callback.
 *
 * Output the page with the container to load AJAX content to.
 */
function my_module_remote() {
  $wrapper = array();
  $wrapper['#attached']['js'] = array(
    drupal_get_path('module', 'submit_ajax') . '/submit_ajax.js'
  );
  $wrapper['#attached']['library'] = array(
    array('system', 'drupal.ajax')
  );
  $wrapper['container'] = array(
    '#type' => 'container',
    '#attributes' => array(
      'id' => 'remote-content-wrapper',
      'title' => t('click to reload')
    )
  );
  $wrapper['container']['content'] = array(
    '#markup' => t('Loading data...')
  );
  return $wrapper;
}

/**
 * Ajax callback.
 *
 * Load remote information.
 */
function my_module_remote_ajax() {

  $commands = array();

  $selector = '#remote-content-wrapper';
  $html = my_module_function_to_request_data_form_remote_server_and_build_html();
  // Debug messages, we can use dpm() here.
  $messages = theme('status_messages');
  $commands[] = ajax_command_prepend('body', $messages);
  // Add command with insert new requested content
  $commands[] = ajax_command_html($selector, $html);

  print ajax_render($commands);
  drupal_exit();
}


"View unpublished content" permission for non-author I googled a bit to see if there's a permission-level way to allow a logged-in (but non-admin) user see unpublished content (marked with the CSS node-unpublished class). This appears to be scheduled for Drupal 8 only. But maybe someone was clever enough to do a workaround?

I have a role named Content Editor which should be able to see all unpublished content, regardless of whether they were the author or not.

If you're ok writing a very small custom module you could use a combination of hook_permission() and hook_node_access() to do this:

function MYMODULE_permission() {
  return array(
    'unconditionally view unpublished content' => array(
      'title' => t('Unconditionally View Unpublished Content'),
      'restrict access' => TRUE
    )
  );
}

function MYMODULE_node_access($node, $op, $account) {
  // We're only bothered about the 'view' operation at the moment
  if ($op == 'view') {
    // If the user has access to our new permission, let 'em at it
    if (user_access('unconditionally view unpublished content', $account)) {
      return NODE_ACCESS_ALLOW;
    }
  }

  // For everything else let the system decide.
  return NODE_ACCESS_IGNORE;
}

Any role you assign the new permission to should now be able to view any node, regardless of whether it's published or not.


Adding website logo as the first top level menu item in tb megamenu I am usting tb megamenu module to get a main menu on my site.
Is there a way to add the website's logo as a top level menu item (NOT SUBMENU ITEM)

You are looking for Menu Icons module.

  This module allows you to upload an image in the menu-item's
  configuration form. After uploading the image, the icon data will be
  added to the menu link's options array.

  When a menu link is goes through the theme layer, it will receive an
  extra class which by default is used to attach the images as a
  background image to the corresponding menu item. These class names are
  also compatible with Nice Menu's.


Why does the default image for an image CCK field not show in a view? I have a File/Image CCK field with a default image set and the Use default image checkbox is checked.
I am rendering this field in a view- but the default image does not show for nodes where an image has not been uploaded.

How do I get the default image to show in a view?

Ive tried re-uploading the image, re-setting the checkbox, clearing cache. FYI, if I do upload an image, it does show in the view.

Any further ideas?

OK. So my solution was to use Customfield to write some PHP to check if the image field is empty. If it is, then I output some HTML to render a default image. I had to hard-code the image URL which is not ideal.


files[]=lib.php fails to autoload classes of different namespace? In my custom module, I've included a file using files[]=foo.php in the .info file. foo.php declares classes in a namespace.

Drupal does not seem to be autoloading this class: in my main module file $foo = new Foo\Bar(); causes a Class Not Found error.

Is this because Drupal 7's registry can't cope with namespaces?

Yes, Drupal 7 knows nothing of namespaces unfortunately (namespaces were only introduced in PHP 5.3 and D7 is compatible with earlier versions than that).

However, life gets infinitely better with the XAutoload module, which is PSR-0 compliant an thus knows all about namespaces.

  xautoload is a comprehensive and yet highly efficient PHP class loading suite.
  Most importantly, it provides Drupal-8-style PSR-0 autoloading for Drupal 7.

The latest release is even moving towards PSR-4 which is great news.

If you install that module you can remove all of the files[] references from your info files, as long as you follow the \Drupal\my_module namespacing pattern. Even if you don't, XAutoload has hooks to let you define your own patterns.


Workbench moderation and check permissions tab Reading through the workbench_moderation module readme file I came across this:

For reference, these are the permission sets recommended by the "Check
Permissions" tab:

Author:
  Node:
    access content
    view own unpublished content
    view revisions
    create [content type] content
    edit own [content type] content
  Workbench Moderation:
    view moderation messages
    use workbench_moderation my drafts tab

However, going to /admin/config/workbench/moderation/check-permissions on my drupal 7 instance, when I select the drupal role of editor, I don't see any of the options listed in the readme file (as above).

All I see is, Moderation task dropdown menu, and then a list of Content types (which I previously enabled in the structure section)

Why am I missing all these options in the Check permissions tab?

You're not missing the permissions, just looking in the wrong spot. Log in as an admin user and head over to yoursite.com/admin/people/permissions. This is the main permissions management page which shows all permissions defined by all modules.

You'll see 'sections' of permissions defined by various modules. There will be 'Node' and 'Workbench Moderation' sections mentioned in the file you read, as well as the relevant permissions.


Can't get token replacement to work I have nearly this exact case but as it applies to Drupal 8:
 Store token replacement values in the database rather than tokens themselves).

I have a content type 'article' with a 'body' field which has been populated with tokens via the Token Filter module.  I believe the code should be something like found here https://www.drupal.org/project/drupal/issues/2043055 but can't get it to work.

function MYMODULE_node_presave(Drupal\Core\Entity\EntityInterface $node) {
  if ($node->bundle() == 'article') {
    $body = $node->get('body')->value;
    $token = Drupal::token();
    $body = $token->replace($body);
  }
}

Thanks for considering, -c

You need to set the new value on the body, and save it.

function MYMODULE_node_presave(Drupal\Core\Entity\EntityInterface $node) {
  if ($node->bundle() == 'article') {
    $body = $node->get('body')->value;
    $token = Drupal::token();
    $body = $token->replace($body);
    $node->get('body')->value = $body;
    $node->save();
  }
}


How to set custom block to not in any region, therefore user can selete region by ownself? This is my custom block hoo_block_info():

 function myblock_block_info() {
   $blocks = array();
     if (variable_get('hare_block', 0)) {
       $blocks['abc'] = array(
         'info' => t('test block'),
         'visibility' => 0,
         'status' => TRUE,
         'region' => 'none',
         'weight' => 99,
         'cache' => DRUPAL_NO_CACHE,
       );
     }
   return $blocks;
 }

Now by setting 'region'=>'none' there is an error that block region is not defined. Please let me know how to place block in none region?

Simply remove 'region' => 'none' from hook_block_info().

region: (optional) Initial value for theme region within which this block is set. Most modules do not provide an initial value, and any value provided can be modified by a user on the block configuration screen.

  Note: If you set a region that isn't available in the currently
  enabled theme, the block will be disabled.


How to add number of records per page filter in views I want to add a filter to customize the number of records to be show on per page in views.

Can anyone assist me on this?

I found the answer.

You can add items per page filter from pager option views

Views->pager options->EXPOSED OPTIONS


Twitter sign in module session token values lost in twitter/oauth path in HTTPS - Invalid Twitter OAuth request The twitter sign in module works on my local and staging server on HTTP fine. But when I install the same module in production mode which is https://example.com, it stops working. The error says "Invalid Twitter OAuth request". I debugged the code a little bit, and I could understand that the session variables stored in token before redirecting to twitter are lost when control is redirected to my site in twitter/oauth path.

/**
 * Submit handler for Twitter signin.
 */
function twitter_signin_redirect() {
  module_load_include('inc', 'twitter');
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  $twitter = new Twitter($key, $secret);
  $token = $twitter->get_request_token();
  $_SESSION['twitter_oauth']['token'] = $token;
  $_SESSION['twitter_oauth']['destination'] = $_SERVER['HTTP_REFERER'];
  $_SESSION['twitter_oauth']['signin'] = TRUE;
  watchdog("twitter_sign_in", "Session Values Set => ". print_r($_SESSION, 1));
  drupal_goto($twitter->get_authenticate_url($token));
}

And on the validate function in twitter.pages.inc, the session values are clearly lost. I used watchdog entries on both functions. Its working fine in my local and staging server.

/**
 * Validate results from Twitter OAuth return request.
 */
function twitter_oauth_callback_form_validate($form, &$form_state) {
  global $twitter_token;
  $key = variable_get('twitter_consumer_key', '');
  $secret = variable_get('twitter_consumer_secret', '');
  watchdog("twitter_sign_in", "Session Values Set => ". print_r($_SESSION, 1));

if (isset($_SESSION['twitter_oauth'])) {
    $form_state['twitter_oauth'] = $_SESSION['twitter_oauth'];
    unset($_SESSION['twitter_oauth']);
  }
  else {
    form_set_error('oauth_token', 'Invalid Twitter OAuth request');
  }

Any help appreciated. Thanks.

The error could be related to:

Using API on the wrong domain/subdomain (www prefix can be relevant).

See: Why do I get a Oauth error?
Temporary Twitter issue.

See: Twitter module Oauth 'TwitterException' with message 'Unauthorized'
Make sure your code is passing the valid oauth_verifier.

  For OAuth 1.0a compliance this parameter is required unless you are using xAuth. Currently Twitter supports both OAuth 1.0 and OAuth 1.0a which means we do not error if this value isn't included. It is strongly recommended that applications not using this parameter are immediately updated with support for oauth_verifier added. OAuth 1.0a will be enforced soon and applications not using the oauth_verifier will fail to complete the OAuth flow.

See: Oauth/access_token Stopped working today
Your Twitter module may be outdated, please consider upgrading it.

If it's still happening, check the logs for any detailed responses. Otherwise contact Twitter support.


How can you use multiple lines in a text area? I'm probably missing something really simple here, but I can't seem to find it at all!

I want to have a text area for lyrics in my "Songs" content type.  Naturally, lyrics should be displayed one line per line, and with a space to distinguish verses, choruses etc... e.g.

  I got my head checked By a jumbo jet It wasn't easy But
  nothing is No

  Woohoo!

When I put the above in a text area, I get:

I got my head checked By a jumbo jet It wasn't easy But nothing is No Woohoo!

How do I get this to display correctly?  I am using Drupal 6.

Change the input format (just below the textarea) to Filtered HTML or Full HTML.


How do i set limit query into url from views output In drupal i need to output json fields. So i used views_datasource. In my situation, i need to call same api source to multiple section, but i don't want to create multiple view only for 5 items or 10 items or all items for same content types data. So in views_datasource i need to use limit filter from all of views results like "http://example.com/serve/all-articles?limit=10".

Can anybody help me to do it?

Ccreate a custom module and implement hook_views_pre_build.

To create the module follow these steps:

In sites/all/modules create a new folder with the name of your module. As you are not contributing this module back to Drupal and it is specific to your project just give it the name of your project and other code tweaks can also live in there.

Let's assume you called your project custom_project and it is at sites/all/modules/custom_project.

Add a file called custom_project.info to it with this content:

name = Custom Project Module
description = This module is for project related tweaks
core = 7.x

Add a file called custom_project.module with this content:

<?php
function custom_project_views_pre_build(&$view){
  if ($view->name == "NAMEOFVIEW") {
    if (isset($view->args[0]) && is_numeric($view->args[0])) {
      $view->set_items_per_page($view->args[0]);
    }
  }
}

Now install this module (and in future if you add any hooks then clear the cache)

You call this on a friendly url ("http://example.com/serve/all-articles/10").

If you wish to add a query parameter to the url as in "http://example.com/serve/all-articles?limit=10" then your function will need to inspect drupal_get_query_parameters for that parameter instead of pulling it out of $view->args[0].

ie.:

<?php
function custom_project_views_pre_build(&$view){
  if ($view->name == "NAMEOFVIEW") {
    $query_params = drupal_get_query_parameters();
    if (isset($query_params['limit']) && is_numeric($query_params['limit'])) {
      $view->set_items_per_page($query_params['limit']);
    }
  }
}

You need to replace NAMEOFVIEW with your views name. You get it like this:

Note that a view has a name, but also a display id. The display id in this case is page. If you add a block it will get a block display id. So the above code will work for all displays that you add to this view, even for blocks etc. To limit it to just the page you will change the one line to this:

if ($view->name == "all_content_of_article" && $view->current_display == "page") {


Limit number of nodes able to have custom field selected I have a content type named "Story" with a boolean field "Featured".

When users create/edit a story they can check the featured checkbox. Stories that are featured appear in a block throughout the site. The block only shows two stories.

Ideally, if there are two stories featured and a user creates a new story and selects the featured field, it would deselect the featured field for one of the two original stories. Only two stories can be featured at once. Is this possible?

The traditional route is to have the views block show the two most recently created stories that have the featured field selected. From an administrative perspective I want to make it easy for site editors to keep track of what's featured (these users are new to web publishing) so it'd be great if there was a limit on the number of nodes that can be "featured".

Any thoughts are appreciated! Thanks!

A view can be used with a limit on the number of items to two with a filter that requires that story to be featured, then sorted by publish date (descending to show the latest). Otherwise, if you want an administrator to have total control over exactly which two stories are featured, use Nodequeue or use the node sticky bit and make sure only admins have access to set the sticky bit.

You can reuse the same view to create a page view that shows all stories that have the featured flag set.


Taxonomy translation Localize option not working correctly. thoughts? I have a multilingual drupal 7 site. I have a series of taxonomy terms to choose from. I have the il8n Translate Taxonomy enabled and using it.

For my taxonomy I have selected "Localize. Terms are common for all languages, but their name and description may be localized."

However, despite being able to use the translate interface to correctly translate them, the terms still show up in English, the default language, regardless of what language I am viewing the content in. Here are links to the issues. Please see the tables.

http://tourismbuilder1.hokkaido-select.com/content/dai-ichi-takimotokan

http://tourismbuilder1.hokkaido-select.com/ja/content/%E7%AC%AC%E4%B8%80%E6%BB%9D%E6%9C%AC%E9%A4%A8

Thoughts as to why?

EDIT:
I found this link to the issue, which is unresolved.
drupal.org/node/1070256

The answer to this is to change the taxonomy link preferences under 'Manage Display' in the content type - here is a link to a thread on the issue.

http://drupal.org/node/1070256


How to get a separate form_id for each of the taxonomy/term/%term exposed form? I'm trying to combine in a smart way Contextual filters Has taxonomy term ID with Remember the last selection feature of exposed form filters in a view.

Context

A taxonomy vocabulary called destinations (countries & regions)
A view of content tagged with destinations terms : Contextual filters : Content: Has taxonomy term ID (with depth)
Exposed filters such as travel duration, price...
Important point, Remember the last selection is ticked for all the filters
Ajax enabled, and the whole thing displayed as a content pane

The issue

Let's say I visit taxonomy/term/spain and filter the view by price < 700$, then go to taxonomy/term/india e.g, the view will be already filtered by price < 700$, and may return empty result, which is an unwanted behaviour.

This is because across all the taxonomy/term/% paths, the exposed form form_id remains the same views_exposed_form.

How could I get a separate form_id for each of the taxonomy/term/% exposed form, so that the last selection would be kept for each term ?

Or setup my view in order to get the expected features ?

Without patching the module you can't...but the View object is always available in the form state, so you can use that to check where you are. e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'foo' && $view->current_display == 'bar') {
      // ...
    }
  }
}


Devel user & decrease number queries I'm trying to decrease the number of my queries with the devel module but I have two questions.

1) Why do I have 281 dblog_watchdog queries? How can I get rid of them?
Why should I keep them, I already have the apache logs?

INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) 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)

2) How to show the number of queries for anonymous users?
Right know it doesn't show anything.

1) By default, dblog module is enabled. It is real performance bottleneck for big sites. But you can use syslog module (from core) or contrib analogs to write logs in /var/log/drupal.log and etc.
Rsyslog config can be something like this:

    local0.warning /var/log/drupal_site_err.log
    local0.info;local0.!warning /var/log/drupal_site.log

You should analize your logs and fix errors, warnings and even PHP notices. I think 281 messages per page — this is a lot.

2) On your dev site you can allow anonymous users to see devel information with permission “Access developer information”. Don't forget to disallow Devel on production.


Confused about Entity bundles I'm trying to convert a Drupal 7 site to Drupal 9 before D7 reaches EOL, and I had a custom module that had a lot of custom tables defined in Hook Schema, that would be joined together in different ways to handle a multi-step form made with the ctools form wizard. This site was originally created in Drupal 6, and updated to Drupal 7 while doing the minimum changes to the custom modules, so it predates the concept of Entities. The database structure of those tables is normalized, in 3rd normal form, because if you flattened it, would your end with millions of rows with mostly redundant information. The problem was that those tables existed in their own microcosm, not accessible to the rest of the site.
I've decided to rebuild everything from the ground up when doing the site upgrade, and I've also decided to drupalize this so the contents of these tables can be accessed by regular views, avoiding content duplication. This means that every old table will have to have it's own entity type. Fields will be basefields for performance, since I will need 50-100 fields in total, and every fiend added through the UI requires a join as far as I understand. If I need to add fields in the future, I will do it through a module update, not by adding them through the UI, so I don't need the entities to be fieldable.
After giving you this context, my actual question is, if I will only ever need 1 type of every entity bundle, do I really need entity bundles? What would entity bundles do for me?

After giving you this context, my actual question is, if I will only
ever need 1 type of every entity bundle, do I really need entity
bundles? What would entity bundles do for me?

No, you don't need bundles. Configurable fields are stored in bundles. Since you don't want to configure fields you don't need bundles.

I still wonder, if I will have only one bundle per entity type, do I
need to set up a configuration entity for the the bundle?

The core user entity is an example for a bundleless entity type for which you can configure bundle fields. It looks like having one bundle but there is no bundle config entity. The bundle fields use the entity type id as placeholder.
So even if you later need to add configurable fields, through UI or YAML, you don't need to set up a configuration entity for the bundle. See Adding Field To Bundle-less Entity On Installation Not Working


Contextual filter by taxonomy term not using language We have a site with 3 different languages and each language is detected by sub-domain. One of the taxonomies we use is representing types of products and have terms in all 3 languages inside:

CategoryQ (se)
   CategoryW (se)

CategoryE (no)
   CategoryR (no)

CategoryT (da)
   CategoryY (da)

I faced with problem regarding contextual filters and taxonomy terms. I have view with contextual filter accepting term name and displaying nodes related to this term:

Content: Has taxonomy term ID (with depth)

Also added validation and "Filter value type" set to "Term name converted to Term ID".

All worked fine until we discovered that we have couple of terms that have same names in all languages (we are not translating terms, all terms are added separately for each language - BL requirement):

CategoryG (se)
   CategoryY (se)

CategoryG (no)
   CategoryX (no)

CategoryG (da)
   CategoryZ (da)

Processing contextual filter Drupal takes first term tid he found in database (with lowest tid) and use that constructing view's query. In our case Drupal takes SE term instead of NO. So basically there is no language control in contextual filter at all. Is it possible to somehow add this control with hooks or some modules maybe?

Temporary solution for was to create patch file to override views module functionality a little bit. Patch can be found under issue on drupal.org
https://www.drupal.org/node/2466001#comment-9795191.


Trouble with contextual links after node teaser refresh via ajax Contextual links appears on page load, but upon node teaser refresh it disappears, I can see the dom is generated for even after the ajax refresh but the links are not appearing.

May be the problem is that after node teaser refresh the contextual links js needs to be processed.

Please guide me if anyone having idea about it.

Thanks.

Once new HTML has been added to the DOM in a custom way, then to attach all Drupal behaviors defined by active modules, you need to call Drupal.attachBehaviors().

It may be possible that you are not calling Drupal.attachBehaviors() after new content is injected into the DOM. Until you do this, NO Javascript will be applied to the newly inserted elements.

Example of attaching behavior ('YOUR_DOM_SELECTOR' will the element which you are refreshing via ajax):

Drupal.attachBehaviors('YOUR_DOM_SELECTOR');


user choice for events im creating community event site where i have city and events in that city. i would like to give option for user to select which cities he would like to see the events for. whats the best way to do this? i have created content type of city and events, and using entity referrence to tie events to the city, now im kinda stuck on how do i give a user ability to chose which city/cities he wants to view events for. thanks in advance

I'd say you need the views module.

I haven't used it with entity reference before, but I think you will need to set up a new view that displays events and use the relationship settings to link them to your city nodes.

If you don't actually need the cities to be nodes, you could make them a taxonomy instead which is much simpler to create a view for because you can make a field on your event that directly references the taxonomy.

Finally, to 'allow the user to choose' anything you need exposed filters in your view.


Change text on "Create new Account" button makes administration created user registration fail In the form provided by user_registration_form(), I modified the text for the "Create New Account" button to "Sign me up!" via the following code:

$form['actions']['submit']['#value'] = t('Sign me up!');

Creating a new account as anonymous user from the main site works fine: new button text, customized validation and submission included. Now, if I want to create a new user as administrator via "People -> 'Add User'," the form and button are correctly displayed, but NOTHING happens once I hit the button! Somehow, all validation and submission routines seem to be deactivated by renaming this button. Do you have any idea why this is happening?

That code works without a problem for me. I hope you didn't change the code in Drupal's user module directly?

You should make this change by implementing hook_form_alter() in your own custom module or theme.

function MODULENAME_form_user_register_form_alter(&$form, $form_state, $form_id) {
     //your changes here
   }


Cannot get currentUser after custom Drupal boot I have a /foo.php on the Drupal 8 root which programmatically boots Drupal:
chdir('web');
$autoloader = require_once 'autoload.php';
$request = Request::createFromGlobals();
print_r($request->cookies);             // ... ( ... ( [SSESSabfa7...] => _Eu_28jS3Vr8Y... ))
$this->kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$this->kernel->boot();
var_dump(\Drupal::currentUser()->id()); // int(0)

$this->kernel->preHandle($request);
var_dump(\Drupal::currentUser()->id()); // int(0)

The problem is that it doesn't seem to be able to access the current user (see the var_dumps). By visiting a regular Drupal URL though (e.g at / or /about) I confirm that the session cookie is correct with a logged in user.
What do I need to do so my custom PHP script boots Drupal in a way that it can return the currently logged in user?

You have to authenticate the user. This is what a normal Drupal request would do as one of the first things after the kernel is booted:
Drupal\Core\EventSubscriber\AuthenticationSubscriber
  /**
   * Authenticates user on request.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The request event.
   *
   * @see \Drupal\Core\Authentication\AuthenticationProviderInterface::authenticate()
   */
  public function onKernelRequestAuthenticate(GetResponseEvent $event) {
    if ($event->isMasterRequest()) {
      $request = $event->getRequest();
      if ($this->authenticationProvider->applies($request)) {
        $account = $this->authenticationProvider->authenticate($request);
        if ($account) {
          $this->accountProxy->setAccount($account);
          return;
        }
      }
    }
  }

Adapting this to the procedural code:
web/foo.php
<?php

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

$autoloader = require_once 'autoload.php';
$request = Request::createFromGlobals();
print_r($request->cookies);             // ... ( ... ( [SSESSabfa7...] => _Eu_28jS3Vr8Y... ))
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->preHandle($request);

$container = $kernel->getContainer();
// Ensure our request includes the session.
$request->setSession($container->get('session'));
// Authenticate the user, see AuthenticationSubscriber::onKernelRequestAuthenticate().
$account = $container->get('authentication')->authenticate($request);
if ($account) {
  $container->get('current_user')->setAccount($account);
}

var_dump(\Drupal::currentUser()->id());


Programmatically insert an image with caption I'm trying to attach programmatically an Image with caption to my node.
I'm using image_field_caption module.

    $node = node_load($nid);

    $path = "images/gallery_articolo/".$value['foto'];
    $filetitle = $value['desc'];
    $filename = $value['foto'];

    $file_temp = file_get_contents($path);
    $file_temp = file_save_data($file_temp, 'public://' . $filename, FILE_EXISTS_RENAME);

    $node->field_steps['und'][($value['order'] - 1)] = array(
        'image_field_caption' => array( 'value' => $value['desc'], 'format' => 'full_html'),
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => 1,
        'uri' => $file_temp->uri,
        'status' => 1
    );

    node_save($node);

I followed the stucture seen in devel, but I have a lot of issues..

This is the recent log entry:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'caption' cannot be null:
INSERT INTO {field_image_field_caption_revision} (field_name, entity_type, entity_id, revision_id, bundle, delta, language, caption, caption_format)
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, :db_insert_placeholder_11, :db_insert_placeholder_12, :db_insert_placeholder_13, :db_insert_placeholder_14, :db_insert_placeholder_15, :db_insert_placeholder_16, :db_insert_placeholder_17);
Array ( [:db_insert_placeholder_0] => field_steps [:db_insert_placeholder_1] => node [:db_insert_placeholder_2] => 455 [:db_insert_placeholder_3] => 863 [:db_insert_placeholder_4] => article [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => und [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => [:db_insert_placeholder_9] => field_steps [:db_insert_placeholder_10] => node [:db_insert_placeholder_11] => 455 [:db_insert_placeholder_12] => 863 [:db_insert_placeholder_13] => article [:db_insert_placeholder_14] => 2 [:db_insert_placeholder_15] => und
[:db_insert_placeholder_16] => Wild Roses: fiori che sembrano appena sbocciati, che sottolineano ancora una volta la sua grande cifra stilistica, composizioni perfette per ogni dolce e speciale occasione.
[:db_insert_placeholder_17] => full_html ) in image_field_caption_field_attach_update() (line 234 of /sites/all/modules/image_field_caption/image_field_caption.module).

But, as you can see, the :db_insert_placeholder_16 is valorized.
Can someone locate where the error is?
I can't find it..

Thank you ^^

in the log entry it shows that [:db_insert_placeholder_7] and [:db_insert_placeholder_8] elements of the Array were empty - that might be the reason why Insert statement failed for the caption field:

Array
(
[:db_insert_placeholder_0] => field_steps
[:db_insert_placeholder_1] => node
[:db_insert_placeholder_2] => 455
[:db_insert_placeholder_3] => 863
[:db_insert_placeholder_4] => article
[:db_insert_placeholder_5] => 0
[:db_insert_placeholder_6] => und
[:db_insert_placeholder_7] =>
[:db_insert_placeholder_8] =>
[:db_insert_placeholder_9] => field_steps
[:db_insert_placeholder_10] => node
[:db_insert_placeholder_11] => 455
[:db_insert_placeholder_12] => 863
[:db_insert_placeholder_13] => article
[:db_insert_placeholder_14] => 2
[:db_insert_placeholder_15] => und
[:db_insert_placeholder_16] => Wild Roses: fiori che sembrano appena sbocciati, che sottolineano ancora una volta la sua grande cifra stilistica, composizioni perfette per ogni dolce e speciale occasione.
[:db_insert_placeholder_17] => full_html
)
in image_field_caption_field_attach_update() (line 234 of /sites/all/modules/image_field_caption/image_field_caption.module).

also, [:db_insert_placeholder_16] - contains a string with 173 characters - is the caption field big enough?

hope this helps


Redirect to a page in a modal I have follow this tutorial to make a modal:
http://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

But when the submitModalFormAjax method is called I want redirect the user to a specific page:

/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    // <<<--- redirect to homepage
    // $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}

How can I do it?

/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    $response->addCommand(new RedirectCommand(Url::fromRoute('<front>')->toString());
    // $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}


Right to left theme: Bootstrap or Zurb Foundation? I am developing multilingual site (English and Arabic) in Drupal 8. I want to use bootstrap or zurb foundation, which out of these is good for developing Right to left theme. Site will mainly work in Arabic.

"Foundation was built to support right-to-left text direction out of the box, but you'll need to make a couple of adjustments to your markup and Sass to get everything up and running." This is just some minor changes, nothing special.
For bootstrap there's a special version that is focused on RTL support: https://github.com/Kaakati/RTL_Bootstrap


Alternative for .inc files I was wondering what is the correct alternative of .inc files in Drupal 8? That is to say, if I want to create some functions that should be only be loaded when required, like it was with module_load_include() in D7. Though this function is still there in D8, I hear that this is not the best procedure. Is that so?

I have read somewhere, that using PHP traits is considered a better practice here. However, not sure if useing a trait inside a .module file is a good approach.

Any help?

Actually there seems to be nothing wrong about using *.inc files in D8. Have a look at the Update core module. Quite some *.inc files present: cgit.drupalcode.org.

Nevertheless I tend to follow Symfony's best practice examples when it comes to stuff like that.

[Symfony Docs] Organizing Your Business Logic

[Stack Overflow] Where to put model helper functions in Symfony2

Means you'll add a new class under src/Utils. For example:

src/Utils/HelperFunctions.php
src/Utils/FooBar.php

And then wherever you need it, you reference it:

use Drupal\MYMODULE\Utils\HelperFunction;
use Drupal\MYMODULE\Utils\FooBar;

And then you'd call a certain function like so:

$site_color = HelperFunctions::getSiteColor();
$foo_bar    = FooBar::returnFooBar();

And when I'm still unsure, I'll search inside the core and contrib modules how they did it.


Problem CKFinder with multilingual site I have installed the CKEditor module, the CKEditor library and the CKFinder library.
I have modified correctly the file config.php and the file settings.php, but when I want login in my site, I don't get the permission for access. If I comment the variable cookie_domain I can access at the site and all working properly, but I get a message error that say: "You are using a feature that requires $cookie_domain to be set, but it is not set in your settings.php file (CKFinder is enabled in the Advanced profile)". What can I do?

set the $cookie_domain variable in sites/default/settings.php

<?php
$cookie_domain = $_SERVER['SERVER_NAME'];
?>

Uncomment the $base_url variable and set the base URL of your website (without the trailing slash).

Another option if you have the Drupal Domain access module installed use

<?php
$base_domain = explode('.', $_SERVER['SERVER_NAME']);
unset($base_domain[0]);
$base_domain = '.' . implode($base_domain, '.');

$cookie_domain = $base_domain;
?>

Here is the reference to the answer


Execute cron job automatically after a specific interval of time in windows I've created a custom module in drupal and implemented hook_cron. My hook is working perfectly, when I click on run cron button from admin interface.

How can I automatically execute my hook after a specific time interval is passed,  without clicking on the Run cron button from the administrative interface?

Drupal supports two types of cron jobs:

Poormanscron

This is the default Drupal 7 cron, where at the end of a page request after a certain amount of time, hook_cron is called. This is controlled by the Run cron every ... setting at admin/config/system/cron.

This means that if cron is configured to run every 3 hours, the first user to visit the page after 3 hours will trigger cron. This also means on a low-traffic site that it can many more hours before cron is actually called.

Scheduled cron

This is a much more reliable method which does not involve the user. The principle is that the cron page is called from an external source (usually crontab on the server) at a set interval. As long as the server is up, it will run guaranteed every 3 hours.

In order to enable this, make sure to disable Poormanscron at admin/config/system/cron (set it to run never). And create a cron job (General and Linux manual).

In case of a Windows environemt, one can use Windows' built in scheduled tasks. Please refer to this manual page.

UPDATE
Be aware that the manual is a little outdated, since Drupal 7 the cron script is protected by a token (to prevent DDoS). So where you see to call http://www.example.com/cron.php, add your site specific token. This can be found on your site's status page and looks like this: http://www.example.com/cron.php?cron_key=xxxxxxxxxx.


Automatically attaching/relating one view to another view based on same value in one field My Drupal site draws data from a CRM system that stores info on contacts and companies. In the CRM, the contacts are related to the companies by a common ID. I have set up Drupal to automatically import the contacts and companies as separate content types and keep them up to date. Both the 'contact' and 'company' content types have an ID field, which is used to relate which contacts work for which companies.

I can create a view, with a page that shows an individual company. I am not sure how to attach a view of the contacts that work for the company. I know it would be possible to use node reference and EVA to relate the contacts with the companies manually. Unfortunately when new companies and contacts are added to the CRM the Drupal site needs to be able to create the relationship between the two automatically, probably based on the fact they both share a common value in the ID field.

It would be great to know how other people have managed to create relationships between two content types. I am not sure if there are any modules that can help with this, if I should create a theme template page for the company view page, and hand code some php that queries the database to return the related contacts, or if need to figure out how to build a module to do the above.

Thanks for your help, Paul

You can do this by using Contextual Filters in Views. Contextual Filters allow you to filter Views results by "Context" (context usually means the currently displayed page or currently logged in user). Assuming you want to display Contacts on a Company page:

Create a new View (admin/structure/views/add) to show content of type Contact. Make sure the Create a block checkbox is checked. If you forget and skip that checkbox, you'll have to add a Block display on the next screen.
Fill out the View so that it looks as you want it to, with the appropriate fields, etc. displayed.
Under Advanced, click to add a Contextual Filter. You're going to be filtering Contacts to display only Contacts which match a certain value for the company ID field. Scroll through the list of fields in the popup window that appears until you find the company ID field. Check the checkbox next to that field and click the Add button.
You need to define the value of the contextual filter. Under WHEN THE FILTER VALUE IS NOT AVAILABLE choose Provide default value. Choose PHP Code for the dropdown Type and enter the following code in the PHP textarea:

$node = menu_get_object('node');
if (isset($node) && $node->type == 'COMPANY_CONTENT_TYPE') {
  $company_id = field_get_items('node', $node, 'COMPANY_ID_FIELD_NAME');
  if (!empty($company_id)) {
    return $company_id[0]['value'];
  }
}

Replace COMPANY_CONTENT_TYPE and COMPANY_ID_FIELD_NAME with the appropriate machine names for your company content type and the field name used to store the company ID.

This PHP loads the currently displayed node and loads the value of company ID field from that node. The value returned is used by the contextual filter to display only contacts which have a company ID field which matches this value.

You can preview the Contacts that will be displayed by manually entering a company ID in the Preview with contextual filters: input while editing the View. The preview should show only Contacts for which the company ID matches that entered value. On a live page view, this value is provided by the PHP above.
Save the View, and go to the Blocks admin page (admin/structure/block). Your new View should appear in the list of available blocks. Drag-drop the block you created into the Content region and save. Optionally configure the block and set it to only display when viewing Company nodes.

At this point you should be able to navigate to any Company node and see the list of contacts as a block, provided by Views. The PHP code entered loads the company ID from the Company node, and filters out all displayed Contacts which don't have a matching value for the company ID field of that Contact.

If you run into any issues or if I missed any steps, please comment below :-p For more information about using contextual filters, I recommend the Taming the Beast: Learn Views with NodeOne video series (parts 19-24 cover contextual filters).


Taxonomy images display in different view rows I have a vocabulary that has an image field. To access this field in views, I added a relationship and then added the field in the fields section.

However, I have multiple terms and each term creates a new row... As this is highly undesirable, I would like to know how to fix it without making and embedding an additional view.

Received answer from @Lendude on drupal forums here:

  Yeah, adding relationships will add rows, that is the way of SQL
  queries.

  If you enable aggregation and then group the results on the right
  column, that works in some use cases (make sure to set/save the column
  for your image field or you will run into this #2815881: Switching on
  aggregation on generates fatal "Column not found: 1054 Unknown
  column" SQL error when using multi-column Fields) Using the 'rendered
  entity' field with a specific view mode can work. This would possibly
  allow you to remove the relationship from the View itself.


Is Paypal payments pro gateway available for Drupal Commerce I am aware of the module Commerce PayPal
 but according to the description it only handles redirects to Paypal and not the Payments Pro gateway which allows site users to stay on the site and have their payment processed by Paypal.

What I'm wondering is - has anybody crossed this bridge?
It seems like a pretty major issue for any commerce system worth its salt to address.

I'm also curious if there is any code out there that folks are using which may not be ready for contrib, but could be plugged into the back end of a site.

Are there any development efforts in this direction?

In Commerce Paypal's issue queue, there is a patch that is a start on WPP. http://drupal.org/node/1155768


drupal 7 template suggestions based on path alias I am using this function on a D7 site to template based on url alias and everything works except when a page has a dash in it.
For example mysite.com/test-page doesn't work. I tried page--test-page.tpl.php and no luck. If I change to testpage and use page--testpage.tpl.php it works.
Any ideas?

Here is the function that works:

function mytheme_preprocess_page(&$variables) {
    // Get the alias for the page being viewed
    $alias = drupal_get_path_alias($_GET['q']);
    if ($alias != $_GET['q']) {
        $template_filename = 'page';

        //Break it down for each piece of the alias path
        foreach (explode('/', $alias) as $path_part) {
            $template_filename = $template_filename . '__' . $path_part;
            $variables['theme_hook_suggestions'][] = $template_filename;
        }
    }
}

Found solution here:
http://cheekymonkeymedia.ca/blog/gene-bernier/how-create-page-tpl-suggestions-based-path-alias-drupal-7

Here is what I used to fix the dash in titles error. I also added no node-content-type solution:

function mytheme_preprocess_page(&$variables) {
  // Get the alias for the page being viewed
  $alias = drupal_get_path_alias($_GET['q']);
  if ($alias != $_GET['q']) {
    $template_filename = 'page';
    //Break it down for each piece of the alias path
    foreach (explode('/', $alias) as $path_part) {
      // Added the str_replace becayse path parts with - were not being picked up properly by the theme_hook_suggestions
      $template_filename = $template_filename . '__' . str_replace("-", "_", $path_part);
      $variables['theme_hook_suggestions'][] = $template_filename;
    }
  }

  if (isset($variables['node'])) {
    // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
  }
}


Accessing content variables through the page variable I have a template that extends the page.html.twig base template. I wish to render a field variable from the node as a heading in other parts of the page template.

I've tried {{dump(page.content)}} but the variable does not seem to be there, it is already rendered into HTML.

What's the syntax - if it exists - for accessing a node variable from the page.content variable?

For example, at the node level, I can access {{ content.field_heading }}.

At the page level, what can I use? ({{ page.content.??? }})

Per the docs on the core page.html.twig:

 \* Page content (in order of occurrence in the default page.html.twig):
 \* - messages: Status and error messages. Should be displayed prominently.
 \* - node: Fully loaded node, if there is an automatically-loaded node
 \*   associated with the page and the node ID is the second argument in the
 \*   page's path (e.g. node/12345 and node/12345/revisions, but not
 \*   comment/reply/12345).

The node variable is available in page.html.twig. If you need to access one its fields you can use {{ node.field_myfield.value }} to print it out.


How to calculate the user's average rating on all his/her nodes with Fivestar? On my website, users can rate each other's nodes via a Fivestar field called Stars in a comment. I'd now like to calculate the overall average score of a user. That means, I'd like to display the user's average score for all his/her nodes.

For example. Let's say a user created 2 nodes: Node 1 and Node 2. Some people rated his content:

Scores of Node 1: 4/5, 5/5, 3/5
Scores of Node 2: 4/5, 4/5

The overall average would then be (4+5+3+4+4)/5=4.

Preferably, this result should also be displayed as stars.

How can I do that?

Edit 1: Working with the Computed Field module seems to be a general idea to solve this matter. It looks fine to me and I think it's best to store the users' average score in a user field, in order to make it easily accessable. (Working with a view is also fine.) I'm planning to display the average score on their profile page, but perhaps I'm going to use it elsewhere on the website in the future too.

Can you please help me with (a scetch) of the code I'm supposed to use?

Edit 2: I created a user field called Gemiddelde and pasted @Thomas4019's code in my custom module hiderating (the module's title refers to an earlier question), but it gave me the following error:

  Warning: Missing argument 5 for    computed_field_field_gemiddelde_display(), called in C:\wamp\www\mysite\sites\all\modules\computed_field\computed_field.module
  on line 341 and defined in computed_field_field_gemiddelde_display()(line 24 of
  C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).
  Notice: Undefined variable: entity in    computed_field_field_gemiddelde_display() (line 30 of C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).
  Notice: Trying to get property of non-object in computed_field_field_gemiddelde_display() (line 30 of C:\wamp\www\mysite\sites\all\modules\hiderating\hiderating.module).

The Gemiddelde field in the view on my profile page has the following value:

0

No votes yet

Edit 3: After reinstalling the Computed Field module and clearing caches, the error messages are gone, but the Gemiddelde field in my view still displays the following CSS code:

3

Average: 3 (1 vote)

What went wrong?

I know that something like this can be done with computed field. It will require some PHP code though. See some discussion here

Here's what you need to do:

Install Computed Field and Fivestar
Go to admin/config/people/accounts/fields and create a computed field on the user entity type. In my case I named it "field_computed_rating". On the settings form for the field make sure the checkbox "Store value in the database" is unchecked.
Click on "Manage Display" for the content type you created the field on. Then make sure the format for that field is set to "Unsanitized".
(if you already have a custom module you can skip this step) In your code base within sites/all/modules, create a new folder titled fivestar_user_aggregate. Within that folder you will need to create  fivestar_user_aggregate.info with the following contents.

name = Fivestar User Aggregate
description = Assign users an aggregate rating based on all their nodes
core = 7.x
package = Custom

Add this custom php function to your module file or create fivestar_user_aggregate.module within fivestar_user_aggregate with the following contents. If you named your field differently then you will need to modify the function name accordingly.

<?php

function computed_field_field_computed_rating_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
    $result = db_query("SELECT n.uid, n.nid, vote1.value AS count, vote2.value AS average FROM {node} n
INNER JOIN {votingapi_cache} vote1 ON n.nid = vote1.entity_id
AND vote1.function =  'COUNT'
INNER JOIN {votingapi_cache} vote2 ON n.nid = vote2.entity_id
AND vote2.function =  'average'
WHERE n.uid = :uid", array(':uid' => $entity->uid));

    $rating_count = 0;
    $rating_total = 0;

    $nodes = $result->fetchAll();
    foreach ($nodes as $node) {
        $rating_count += $node->count;
        $rating_total += $node->average * $node->count;
    }

    if ($rating_total == 0) {
        $weighted = 0;
    } else {
        $weighted = $rating_total / $rating_count;
    }

    $variables = array(
        "rating" => $weighted,
        "average_rating" => $weighted,
        "votes"  => $rating_count,
        "stars" => 5
    );
    $variables["widget"]["name"] = "basic";
    $variables["widget"]["css"] = "sites/all/modules/fivestar/widgets/basic/basic.css";
    drupal_add_css(drupal_get_path('module', 'fivestar') .'/css/fivestar.css');
    return theme('fivestar_static', $variables) . theme('fivestar_summary', $variables);
}

Enjoy! You should now see a weighted average of all a user's node's ratings on their page.


Drush Update to a patched module? What happen when you drush up update a module with Drush because of security issue and the module contain few patches for other features?

The reason why I'm asking is because I have patched few modules and now they have security update which does not contain the features that I wanted.

What is the best practice to update a module that have a security updated and you have patch this module ?

The best practice is to find some way to implement your feature that does not require patching the original module.  Sometimes this is not possible due to lack of available hooks to provide the functionality that you want.

In these instances, you can try out some of the patch-management solutions, such as bandaid or drush-patchfile, which might help you out here.

Sometimes, though, the changes made in the security update will prevent your patch from applying cleanly; in this case, you have no choice but to re-roll the patch, and figure out what changes need to be made to get it working again.  This makes your site maintenance much less convenient, so it's always best to try to work with the module maintainer, and see if you can get your feature added as a standard part of the module, or, failing that, perhaps get the maintainer to add the hooks that would be needed to add in the feature without patching.


Programmatically create field instance of field and content type created in module code In my module, I define a custom content type, and custom fields by using hook_node_info() hook_field_info(), and so on. I'd like to programmatically add field instances of my field to the created content type when my module is enabled/installed.

I know there is the possibility of creating the content type, and the field in the database by using node_type_save() and field_create_instance(), but this is not what I want, since during the development the field definitions will change, and in the latter scenario I would have to uninstall and reinstall the module every time I change a field/content type.

I tried using field_create_instance() in my module's hook_install() and hook_enable(), but Drupal says that the field I try to add does not exist or is inactive.

Is there an elegant way to let the module define fields, and attach them to content types when enabled (and of course detach them on uninstall or disabling it)?

Field helper attempts to handle the creation/deletion of fields and instances for you and allows you to define them in hooks. It will not update the field definitions since that is not something Drupal core supports. Otherwise Features handles creation of field instances on content types if you were to make your module a feature.


How to debug closed connection error I run a panopoly project currently with many many addidtional modules. How to debug a closed-connection-error while uploading an image?

Disable all modules, including all core modules, that are not absolutely necessary for the failing functionality (uploading images). If the minimal configuration is working, enable each module one-by-one and test until the error occurs again, then you got the culprit.

In particular, disable Database logging.

If the basic install still causes the problem, start reading the server logs (it wouldn't hurt to check them immediately, but they might be empty), and check the server configuration.


The link/button "Add content set" was disappeared (Drupal6) According to the post http://drupal.org/node/907542, It mentioned [Go to Admin > Content Management > Migrate and click on "Add content set"].

However, I can't find the link/button of "Add content set", I have install migrate module to another test server, but not works. Could someone advise how to fix it?

Thanks

Reference:

Solved by installing the migrate module of version with 1.x

http://drupal.org/node/966190


Change Pager-ItemsPerPage over URL argument I use Views to get Nodes in JSON format via REST service. I can switch the pages with;

http://myside/?q=my/path&page=1

but I want to change the limit of one page like;

http://myside/?q=my/path&limit=100.

Has anybody a good solution or one alternative.

there is default option in views pager as "EXPOSED OPTIONS" while adding pager to views.

You can add range output.

So you can show per page option. set results using URL argument like http://example.com/path?limit=100


How to display one of Drupal's default forms I have a module that i want to use to display a modified version of one of Drupal 7's default forms. The form ID is user_profile_form and it is the form used to edit a user's account information.

So this is the structure of my module:

hook_menu with a page callback to a function --> user_exe_edit() -->
function user_exe_edit() calls drupal_get_form(input_simple_form) -->
function input_simple_form($form, &$form_submit)

Now I need the function input_simple_form to return the Drupal form with id "'user_profile_form".

How do I do that?

user_profile_form() is an existing function, but it's not defined in a module file; that means that the file where the function is defined needs to first be loaded, in a way or the other.

Instead of defining a page callback that then calls drupal_get_form() to get a form defined in a form builder implemented in the same module, I would rather define the menu callback using the following code (the code I am writing is for Drupal 7, but can easily adopted for Drupal 6, if there is the need.

$items['path'] = array(
  'page callback' => 'drupal_get_form',
  'page arguments' => array('input_simple_form'),
  'file path' => drupal_get_path('module', 'user'),
  'file' => 'user.pages.inc',
);

The code for the form builder could be something similar to the following one:

function input_simple_form($form, &$form_state) {
  $form = array_merge($form, drupal_get_form('user_profile_form', $account));
  // ...
}

user_profile_form() uses a third argument, the category of the profile to show. Its default value is "account"; if you are getting an error about a missing third argument, then you can explicitly pass that parameter too, for example using its default value, as in drupal_get_form('user_profile_form', $account, 'account').
"user.pages.inc" is the file containing the user_profile_form() form builder, in Drupal 7, and Drupal 6. The reason that you get the error you see is that such files are loaded only when Drupal is instructed to load them; that is done by using the "file" and "file path" array indexes. ("file path" is only required when the file is not between the files of the module implementing hook_menu().)
I used input_simple_form() as form builder, in the case you need to use its own validation and submission handlers.
There is a $account variable that has not been defined in the example code I wrote. That is one of the required arguments that user_profile_form() needs, as the function needs to know for which user account the form is being build. That is the other reason to use your own form builder, which should load the user object for the account used for the user profile form, or pass the value of the global $user to drupal_get_form('user_profile_form').


How to change views exposed filter default value So I have this view with exposed filter of taxonomy terms with depth, I had selected some of the terms to limit the selection.

everything works just fine but the issue is that the default value of the exposed filter (combo-box) is set to the latest entry (taxonomy term), and I want to set it to that -All- thing.

I know that if I don't select any of the terms to limit the selection, it'll be set on -All- as default value for the exposed filter, but I don't wanna do that!

the question seems quite simple but I couldn't figure this out! thanks.

in template.php:

function MY_THEME_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'MY_EXPOSED_FORM_ID') {
    // Modifications go here.
    // example: (change the field name to yours)
    // $form['field_adv_cat_1_tid']['#default_value'] = 'All';
  }
}

then clear the cache.


Hiding empty section of a custom content type if field is left empty I am relatively new to Drupal so I need someone to school me here.

I have created a custom theme and using theme key to attach it to a new content type (HTML Email). It roughly has about 12 sections consisting of a header graphic and a text area.

I’ve created a view and added all the fields to it displaying as a block in my custom theme using the views-view-fields—[name].tpl.php.

It displays perfectly but my issue is not all the section of the content type will be used so If the text area in a section is left blank I want that section not to show up in the block.

Below doesn't seem to work

<? if ($fields['field_text']->content): ?>

           <?php print $fields['field_header']->content; ?>

         <?php print $fields['field_text']->content; ?>

<? endif; ?>

If I'm understanding your question correctly, you're testing for a string in $fields['field_text']->content and finding that even when it seems to be blank, it still prints the table.
You might try outputting the contents, like

var_dump($fields['field_text']->content);

Perhaps there is some "invisible" content, like

If that's the case, then you could strip that out before testing for the existence of a string in the variable.

$tmp_content = strip_tags($fields['field_text']->content,'
');
if($tmp_content):
// print table, etc.


Set username to the field firstname untill the field first name is filled I am using profile2 module for user profiles and created a profile with first name and last name fields which are used for configuring real name. And I have set real name as page title. But there is machine name being displayed if the first name and last name fields are empty. I want to set user name to the first name field until the profile fields are filled. is there anyone who knows the solution?

use form alter for alter profile2 fields name, then put pass uid load user using userload function get username put this value as default value for the first name field in your profile 2 form ..


How to get the administrator role id to assign new permissions? In my module I'm creating new permissions that I want by default also assigned to the Drupal admin user.

I know how to assign new permissions to a role, but I don't know how to get the Drupal administrator role id. In the database the rid for administrator is 3, but can I rely on that being always the case? I'm using Drupal 7.

unless you install Drupal in your custom installation profile and modify the administrator role there, the rid or administrator will be always 3.
Or you could just do a db_query() on role table to return the rid of administrator as:

$result = db_query("SELECT rid FROM {role} where name like :id",array(':id' => 'administrator'));
$admin_rid = $result->fetchField(0);


how to add cache tag in custom rss feed how to add cache tag in custom RSS feed in Drupal 8
I have tried like this

    use Symfony\Component\HttpFoundation\Response;
    $response = new Response();
    $xml_content = '<?xml version="1.0" encoding="UTF-8"?>
     <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
      <channel>
       <title><![CDATA[ Title there ]]></title>
       <link><![CDATA[ siteurl.com ]]></link>
       <description><![CDATA[ description there ]]></description>
      </channel>
     </rss>';
    $cacheTags = ['node:nid', 'node:nid']
    $response->setContent($xml_content);
    $response->setCache(['etag' => $cacheTags]);
    $response->headers->set('Content-Type', 'xml');

but it not working

Add the cache tags to the cacheable metadata of a cacheable response:

use Drupal\Core\Cache\CacheableResponse;

  $response = new CacheableResponse();
  // ...
  $response->getCacheableMetadata()->addCacheTags(['node:nid', 'node:nid']);


How to extract data from DB into fields? How would I go about extracting the data from a DB into fields? I would like to display information on a page using Views, but the information isn't on the website, instead it is in a separate database. Is this possible?

I get that in order to use Views I need to have fields, but how do I extract this?

If you just want the content, you can use Feeds as Patrick said but this will replicate the content of the other database as entities in your Drupal site.

If you really want views connecting to a remote database, this question looks like a duplicate of:

https://drupal.stackexchange.com/questions/3275/how-do-i-display-an-external-database-data

This will help you make Drupal "aware" of the external db:

http://drupal.org/node/18429


Displaying Decimal Field as Percentage I have a decimal field in my node that I need to display it as percentage through views. I thought about adding another field 100 and multiply them by using the computed field module. I was wondering if there is a better way.

You could create a Fieldformatter that takes the input and converts it to percentage.


Change the Mandatory field based on selection in webform I have Webform with a radio button type field named as "preferred contact method", for selecting email or phone.

When user select the email I want to set the email field as mandatory or if user select the phone I want to set phone field as mandatory.

How to handle this in Webform Drupal 7.

That is an interesting thing to have, but i don't think Webform support such a functionality. However they are some other way to achieve the same result.

Using Webform Conditional module. you can have two sets of  hidden questions, and only one set of question could be visible base on user selected choice.

If user click on phone the first set of question will be display to user where the phone is a mandatory and email optional.

If user click on email the second set of question will be display to user where you can have email as mandatory and phone as optional.

You can ready more about alternative ways here .


Making a file downloading system with valid input in a custom drupal 8 form I am trying to create a custom drupal 8 form, that is going to allow user to enter his/her firstname, lastname and email address, and if the user enters these credentials, will be able to download the file that I will upload to cms. This is how my form looks like right now:

namespace Drupal\whitepaper\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

class WhitePaperForm extends FormBase {

/**
 * {@inheritdoc}.
 */
public function getFormId() {
  return 'whitepaper_form';
}

/**
 * {@inheritdoc}.
 */
   public function buildForm(array $form, FormStateInterface $form_state) {
  $form['iam'] = array(
   '#type' => 'select',
   '#title'=>t('I am:'),
   '#options' => array(
    'dentist' => t('Dentist'),
    'broker' => t('Broker'),
    'engineer' => t('Engineer'),
   ),
   '#required' => TRUE,
  );
  $form['fname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('First Name:'),
   '#required' => TRUE,
  );
  $form['lname'] = array(
   '#type' => 'textfield',
   '#title' => $this->t('Last Name:'),
   '#required' => TRUE,
  );
  $form['email'] = array(
   '#type' => 'email',
   '#title' => $this->t('Your .com email address.'),
   '#required' => TRUE,
  );
  $form['show'] = array(
   '#type' => 'submit',
   '#value' => $this->t('Download Whitepaper'),
  );

  return $form;
}

/**
 * {@inheritdoc}
 */
public function validateForm(array &$form, FormStateInterface $form_state) {

  if (strpos($form_state['values']['email'], '.com') === FALSE ) {
    $this->setFormError('email', $form_state, $this->t('This is not a .com email address.'));
  }
 }

 /**
  * {@inheritdoc}
  */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  drupal_set_message($this->t('Your email address is @email', array('@email' => $form_state['values']['email'])));
 }
}

Can anyone help with a block of code that if the inputs are valid, when the user click download paper button, will be able to download? I got really stuck and i guess my point of view is not helpful to solve this problem.Thank you advanced.

you can do this with the $form_state->response($response)

  $response = new BinaryFileResponse($file->getFileUri();
  $form_state->setResponse($response);


Facet API pretty paths in combination with solr search form I'm building a website with the panopoly distribution in Drupal 7. One of the client requests is a faceted search page combined with a search box to search on specific keywords and the possibility to sort on date and name.

To build this I used the following modules:

apachesolr
apachesolr_sorts
apachesolr_panels

After configuring everything I got this search page working (without clean url's)

http://i.imgur.com/mxDzhi4.png

To enable clean url's I used the following module:

facetapi_pretty_paths

Now the search box always uses the first argument in the url, after I enable the pretty paths module the first argument in the url is the active filter (taxonomy field name in combination with the taxonomy term name).

http://i.imgur.com/5x7Xyoa.png

What would be the best approach to use the search box in combination with the facets and pretty paths (and the sorting option)?

There are two ways to avoid this issue which depend on module what you use.

1) If Search API module is used. (It was taken from https://www.drupal.org/node/2625298)

function hook_search_api_query_alter(SearchApiQueryInterface $query) {
    $original_keys = $query->getOriginalKeys();
    if ($original_keys == 'field_facet_filter')) {
        $query->keys(NULL);
    }
}

2) If Apache Solr Search module is use

function hook_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {
  if ($query->getParam('q') == 'field_facet_filter') {
    $query->removeParam('q');
  }
}


user permission and roles I'm very beginning to the Drupal. I created on role from my admin part, I need to access the roles with some permissions like i listed below.

My concept is ticket raising system in various categories. As an admin I assign some ticket to some roles(user), now how to give permissions to assign roles(user)?

Also, the assigned user have to do action what they have to do, but they don't have permission to access admin part. How to give permission to the user to do the reply?

You can set permissions to users under permissions tab of people module in admin  .Please check below screenshot.Hope it helps


Different Site name and slogan for Organic Groups based multisite architechture I am using OG based multisite in Drupal. I need to override sitename and slogan of default values so that each organic group has its own set of system values like Sitename and slogan etc.Also I am using Variable and OG Variable modules which seem to be for this purpose, but changing variable Realms in Organic groups variables doesn't save the values, the admin form for changing variable values doesnt save values. What am i missing?any help?

Open Atrium (6.x) uses spaces to save different configuration for each og, this may be helpful.

  Spaces is an API module intended to make configuration options
  generally avaliable only at the sitewide level to be configurable and
  overridden by individual "spaces" on a Drupal site. It has been
  described as:

  A way to make one Drupal site act like several sites A way to provide
  much more configurable, full-feature Organic Groups or user homepages
  A generalized API for contextual configuration


Taxonomy manage fields wrong field edit url I have updated my project to the latest updates available using drush and suddenly found no field names and wrong field form url in

 admin/structure/taxonomy/%taxonomy_name/fields

As in the picture, have that issue happened before and how to fix

Edit: I coudn't also be able to add new fields and fatal error occurs

FieldException: Attempt to update an instance of a nonexistent field . in field_update_instance() (line 557 of /modules/field/field.crud.inc

despite being able to add/edit/delete terms

manage display return error

Fatal error: Unsupported operand types in /modules/field_ui/field_ui.admin.inc on line 1025

The issue is reported in issue nr 1275900.

It only happened with taxonomy and other entities work fine.

The problem solved by simply patching the field module file-> field.module function named  field_extract_bundle

function field_extract_bundle($entity_type, $bundle) {
  if (is_string($bundle)) {
    return $bundle;
  }

$info = entity_get_info($entity_type);
if (is_object($bundle) && isset($info['bundle keys']['bundle']) &&     isset($bundle->{$info['bundle keys']['bundle']})) {
return $bundle->{$info['bundle keys']['bundle']};
}
//ADDED THAT ELSE
else{
  return $bundle->machine_name;
 }
}

the function tries to return the machine name of the entity as appeared above.

By doing some debugging I realized that the the object sent in the calling function field_ui_field_overview_form file->field_ui.admin.inc is n't the same as sent in drupal script before our continuous development in that project.

We added many other modules and edit configuration but the most related that I think caused that issue is features exporting the taxonomy vocabulary as the bundle object is the same exported in features so it may be some missing or conflict happened when deploying vocabularies with features

Please contribute your ideas!


Advanced conditions in Database Abstraction Layer? I have a module with a custom schema in it. On my cron job, I want to delete records older than 90 days. There is a date field in the table that holds a unix timestamp.

The query I want to run is DELETE FROM table WHERE UNIX_TIMESTAMP() - date > 778000, where 7780000 is the number of seconds in 90 days.

To test my query, I tried to make a select query with the same conditions:

$results = db_select('table')
->fields('table', array('field'))
->condition('UNIX_TIMESTAMP() - date', 7780000, '>')
->execute()->fetchAssoc();

However, the database AL doesn't parse the conditional the way I want it to:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UNIX_TIMESTAMPdate' in 'where clause': SELECT ...

How do I write this conditional properly in the database AL?

You need to use the 'where' method for complex conditionals:

db_delete('table')
  ->where('UNIX_TIMESTAMP() - date > :date', array(':date' => 7780000))
  ->execute();


How to notify a user who's mentioned in a comment? I'm using the Message module to notify users when someone commented on one of their nodes. I'd like to extend this mechanism and also let users know when they're mentioned (e.g. @user) in a comment.

I tried setting up the following Rule:

Event: After saving a new comment.
Condition: Text comparison: comment contains @.
Action: Create a new entity: message.

I should now determine whether the text after @ is a user and, if so, store it to use it in the action. The problem is that I don't know how to do that. Another tricky constatation is that the username can contain spaces. After asking How to prevent users from being registered when their username contains a space?, I've made sure that usernames never contain spaces.

Is it possible to solve my problem by working on with Rules or is there another solution (coding, I suppose)?

You can do it this way:

Copy the function function mentions_get_mentions($text) from mention module repo, It's defined on line 359.
Unfortunately I can't say if the regex from mention module actually works for user's with space in their name, and the function doc comment is not helpful either. So you could use your own regex

What kind of regex?

#\s?@([a-zA-Z0-9 ])+(?|[^a-zA-Z0-9 ]|$)#

How did I do it?

#                  : Identifies beginning of the RegEx pattern.
(?|^|[^a-zA-Z0-9]) : match any non-username chars or beginning of subject string.
@  : A plain @ char is needed.
([a-zA-Z0-9 ])+    : match any username char after a "@" including whitespace.
(?|$|[^a-zA-Z0-9]) : match any non-username chars or ending of subject string.
#                  : Identifies ending of the RegEx pattern.

Now all you have to do is to write a custom rule, pass it a text variable, and get list of user entities (or uid's) back. You could make sure users who matched through regex actually exists in database too.

A few more notes

A ? in regex causes the group NOT to appear in matched groups. Useful when you need to define a group but don't need it in the array of matched strings.
^|[^a-zA-Z0-9] means beginning of subject string or (the | is or) any char which is NOT (said by ^ in []) in ranges a-z, A-Z and 0-9.

Does this regex have bugs? yes

The returned user name(s) from regex can have an space at the end of their name, you could trim each name. It will be easier than to fix it in the regex pattern IMO.
It displays a funny character in my shell when matching an string with unicode characters in them. preg_match supports such multi-byte characters though, and the u flag dis not work.

But again first check the function from mentions.

References:

Mentions module
PHP preg_match doc
Writing custom rules for drupal, Rules DEV doc
Writing custom rules, A blog tutorial

one more thing I couldn't find in google right now: there is a module for rules which provides text tools, I think it had regex matching and you wont need a custom module.

What is this "Regex" you're talking about all the time anyway?

RegEx stands for Regular Expression. It's a search pattern and is extremely very powerfull. While itself can be complicated (sometimes), many task which usually take a lot of time and effort to be done, such as parsing a text, can be done using regex in one line!In this case we are looking for usernames in a paragraph in order to turn them into links. First we describe what a username looks like (the text patterns of username): any part of text which begins with letter, followed by a sequence of more letters and numbers.
Then we write it as a RegEx (What I've done here) and later extract usernames by passing both text and RegEx pattern to preg_match function and taking usernames array back (the function is preg_match).
If I want to talk about all the benefits it wont fit in here, so I suggest you a little search on duckduckgo. It's a handy tool to have, a powerful one try to learn it :)


How to show "incoming search terms" a lot of blogs have a feature to show the "incoming search terms" - it's great for SEO.
I looked up and down drupal.org but couldn't find a module.

Any recommendations on how to tackle this (I'm new to D7 and haven't built a module yet).

It looks like the Google Analytics Reports module is very close to what you need, except it's currently only for Drupal 6. There is an issue open about porting it to Drupal 7, but it doesn't look very active.


Drupal 6: CCK Images broken (because of path) on multisite after copying/moving site I've just encountered an issue I haven't seen seen before: after copying the dB/files to a new location on the server, none of the CCK images are working, regardless of if ImageCache is used or not. In other words, even when editing a node, the image preview is missing because the path is obviously wrong.

For one example, the path should be /sites/dev-[site-name]/files/homebanners/[image-name].

Instead it is /sites/dev-[site-name]/files/sites/[original-site]/files/homebanners/[image-name].

What I can't figure out is why.

Here's the steps taken:

Copy the dB
Copy the files. I forget why but the new sites/[site-name] mapping changes to sites/dev-[site-name] for the dev site (where the images are broken).
Adjusted .htaccess RewriteBase & Rewrite Rules, and the base_url for each
settings.php file
Set the new files location at admin/settings/file-system
Cleared the cache For the imagecache files, and used Drush to flush and re-build the images

For all but one site, the files use the Public setting, but the problem persists regardless of if the files are set to public or private.

Any help would be most appreciated.

Thanks,

Dan

Changing site URL with a multi-site setup in Drupal 6 is problematic as the paths in the file table will be incorrect.  (See Migration failed)

In Drupal 7, you set up multi-site aliasing via the sites.php file (copy and edit the existing examples.sites.php),  which should be stored in the /sites directory.

For Drupal 6 you can try applying the multi-site aliasing patch.

As a last ditch effort (not best practice) you can also try editing the database (e.g. system and files tables) to change the file paths to reflect the new path.


How do I migrate from a site using a core version to another one using the same version? I like to change the web-hosting provider. I want to remove un-necassary and useless stuff (e.g. modules, content types that aren't used from the site).

I have no idea how to do this. Is there a module for migrating only stuff which is in use? The migration modules I found only consider migration from previous versions to Drupal 8, not from Drupal 8 to Drupal 8.

Why don't you just uninstall those modules and remove the configuration you no longer need?

Migration is a complicated task that requires a lot of work.

And to switch the webhost, you just need to copy the files and database, no need to mix those two things together. Clean up your site first and then switch the host. Otherwise you'll never be sure if a problem is caused by the host change or changed configuration


How can I display a custom form in a popup? I have created a form in my custom module, and I want to show it in a popup. I used the Modal Forms module, but it has some issues.

How can I display a custom form in a popup?

You can do it with the Lightbox module, for example using the following.

Don't forget to add rel='lightframe'. See this page at the bottom, and click on "Mortage calculator."

The other option is the Popup Filter module which allows builders to popup tooltip-like text, nodes, blocks, menus, forms, views and PHP-generated content. Even you can mention the block to appear in popup window. And it has the option to popup the login form, register form etc.

Also look at the Popups API (Ajax Dialogs) module.

  API for building modal ajax dialogs. Its focus is on putting forms inside of ajax popup dialogs.
  Current example can present pages as popups (of the lightbox type). This is amazingly useful for things like confirmation pages. And the best part is it can be applied retroactively to a page without needing to modify the generating module, and (of course) it degrades gracefully.


Page template suggestions are not working I've created a theme and have my template files in this structure

/templates/page/page.tpl.php
/templates/page/page--node-type.tpl.php

I've created a custom page template but for some reason it's not being picked up by Drupal.   I've cleared my cache and also tried adding this preprocessor function in the theme template.php file but it's still not working.

if (isset($vars['node']))
  {
    // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $vars['node']->type);
  }

Any help would be appreciated.

As reported in Drupal 7 Template Suggestions, the template suggestion used by default from Drupal 7 for pages is page--[front|internal/path].tpl.php.

For a page visible at http://www.example.com/node/1/edit, Drupal would look for the following template files:

page--node--edit.tpl.php
page--node--1.tpl.php
page--node.tpl.php
page.tpl.php

To add extra suggestions, your theme should implement template_preprocess_page() and add new suggestions in $variables['theme_hook_suggestions'] ($variables is the variable passed by reference to the function).

If you did that, then the only reason the suggested template file is not being used is because the file is not correctly named: in the case the page shows a book page, for example, the template file should be page--book.tpl.php. You could change the code for your theme, and let it use the page--node-type.tpl.php template, if it doesn't find a template like page--book.tpl.php.

To notice also that, in theme_get_suggestions() (which is the function called by template_preprocess_page()) hyphens are replaced by _, and not vice versa.
The reason that is done is explained in a comment reported in the function code.

// When we discover templates in drupal_find_theme_templates(),
// hyphens (-) are converted to underscores (_) before the theme hook
// is registered. We do this because the hyphens used for delimiters
// in hook suggestions cannot be used in the function names of the
// associated preprocess functions. Any page templates designed to be used
// on paths that contain a hyphen are also registered with these hyphens
// converted to underscores so here we must convert any hyphens in path
// arguments to underscores here before fetching theme hook suggestions
// to ensure the templates are appropriately recognized.
$arg = str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $arg);


How to apply an image style to an image field within a node template I have a view where I can't use fields (the reason is complicated but I have to list the content as full content). I'm trying to figure out how to use differnt image styles from withing the node template. For instance, I have two image styles one that is 120 x 120 and one that is 360 x 360. I want to make the node template behave so that the first row displays the 360 x 360 and the subsequent rows display 120 x 120, but I can't figure out how to apply the image style to the field within the node template.

I found this code somewhere as well and it seems to work within the template file.

 print theme('image_style', array( 'path' =>  $field_my_image[0]['uri'], 'style_name' => 'square_550'));

where the field_my_image is the name of your field  ....  I suppose it does the same as the above code.


How can I unset / remove a paragraph component from within template_preprocess_node? In Drupal 7, I need to be able to selectively remove paragraph components from a given node. Which parts of the $variables array need to be unset?

Pretty easily it seems. Something like the following does the job for removing the first component, for example:

function THEME_preprocess_node(&$variables) {
    unset($variables['content']['field_landing_page_components'][0]);
  }


Is there a way to make a view's content shown right-to-left without manually changing CSS styles? In a site where some of the pages are written using the Hebrew alphabet, I created a view displaying linked headings of nodes. The view's title is shown on the right (as it's commonly done for right-to-left scripts), but the linked headings are on the left.
Is there a way to make a view's content shown right-to-left without manually changing CSS styles?

An alternative way so you don't have to change css all the time.

You can probably setup a generic RTL css rule in your theme (one time)

.rtl {
    direction: rtl;
}

and use this rule in each of your views under advanced > css class as you see fit.

Alternatively as Leymannx points out you can add global text area in the header of your view and add the following css

<style>.view {direction: rtl;}</style>

using Full HTML format as shown in the screenshots below

NOTE: view class is included in all views so this solution could potential affect all views on the page


Autocomplete field not using Entity Reference list settings I'm using an Entity Reference field set to Views: Filter by an entity reference view. That works. I can choose my view: maps_by_project_season – Entity Reference.

I've chosen 3 fields in the view, and added them all to Format: Entity Reference list via settings, and I see all 3, separated by -, in the preview.

But not in the autocomplete field. That only shows the title. What am I missing?

This is a known bug in Drupal 8, see: View output is not used for autocomplete display you could try the patch in #76

There was also another disccusion about the same thing here Views Filter by an entity reference view not working as expected, before it was closed as duplicate.


Adding a CCK field with Rules I'm trying to use Rules to populate a CCK field - a user reference when they flag a node.  It basically works, but if there's already a user reference it overwrites it instead of adding another.  That's not exactly what I want.  I want the rule to add another user reference field to whichever ones are already there, then populate it with the user reference.

Do you have any idea?

Edit - What I eventually came up with, without Rules -

function bamfmodule_flag($action, $flag, $content_id, $account) {
  if($action == 'flag') {
    if ($flag->name == 'event_bookmark') {
        $node = node_load($content_id);
        array_push($node->field_trainer, $account->uid);
        node_save($node);
    }
  }
}

Does it need to be a user reference?

Assuming that you are not using a global flag (then you wouldn't have an issue with multiple users), that information should already be stored in the flag tables. You should be able to show that information with a view (which you can attach to the node with http://drupal.org/project/views_attach). Or if that doesn't work, do a custom query in a hook_node_view() implementation in a custom module.

And if it has to be a user reference for some reason, an unlimited multi-value user reference should be easier to handle with Rules than a unlimited number of user reference fields. CCK (nor Fields, for that matter) is just not designed for that. And you can only add fields to content types, not single nodes.