Cookie not being created (not a schoolboy error, I hope) I'm building a deeplink system into a very complex website which needs cookies and other context set-up before the deeplink will work (otherwise the page gets redirected back to the home page - not much use).

So I've added a module which provides the deeplink entry point through hook_menu:

deeplink/<deeplink-parameters>

The callback builds the context, adds the cookies and then redirects to the actual required page.

So much for the theory. It doesn't work and I can't figure out why not.

In order to replicate a completely "virgin" request I've been using incognito windows, restarting the server and clearing caches before each test. In the test version I'm not redirecting to a new page, just outputting a line of text to display the page.

But even attempting to generate a simple test cookie with a long life (REQUEST_TIME + 999999) fails. No cookie created. The setcookie() function is returning TRUE (cookie created), which implies there is no problem.

The only cookies I can see are the ones created by JavaScript on the page itself, and a couple created by the Zeus wrapper (there are no Zeus rules to delete cookies on standard Drupal pages).

Just in case the cookie isn't visible on the first page I am also then moving to another page but still no cookie. Seems like it just isn't being created despite what the function says.

Additional data: There is also no PHP Session ID cookie.

Any thoughts as to why the cookies are not appearing?

EDIT: Looking at this further, I moved the setcookie() function into index.php (before the Drupal bootstrap), and it still wasn't creating the cookie.

So rather than issuing the deeplink command as above I simply went to the home page. And it's still not creating the cookie (as an anonymous user, with everything cleared before we start).

Only when I moved away and into the more complex part of the site did the test cookie appear. At the same time that the PHP Session ID cookie appeared. Is this a hidden dependency? No cookies can be created through PHP unless there's a PHP session ID?

The world has not turned upside-down.

It turned out that Zeus was indeed eating cookies of anonymous accesses, I had to go through every Zeus rule (we have a lot) until I found it.

Testing with Zeus bypassed demonstrated the cookies were created correctly.

Bloody Greek Gods, wandering in uninvited and eating all the cookies...


How to relate two profile2's profile in one single form? I'm developing a portal, using Drupal 7, to manage the entrance of people on my building. I'm using Profile2 module and I created two profiles: "Dweller" and "Visitor".

Now my idea is to create a content type "visit" where I could register the visits that a dweller receive but how can I add two fields, one "dweller" and another "visitor" that will list the entities (persons) of each kind of profile?

Any one have a better approach for this requirements? Or any idea how to resolve it?

Tks!

If you're trying to display 2 profile on the same registration path you can use Profile2 Registration Path and enter the same URL path in the settings. The 2 profile will be added to each other. You can also set the weight to choose which one come first.


Is it possible to change the Taxonomy Parent Term's select list to be a Hierarchical select list? The Taxonomy relations > Parent terms select list is lengthy to look through so ideally we'd like a Hierarchical select list. We already use the Client-side hierarchical select module for other fields, but it doesn't appear to be designed for this particular field. Is there a way for me to programmatically apply the module to this field by altering the form in hook_form_alter()?

We've considered using the Chosen module but an autocomplete isn't exactly the functionality we're hoping for. I also understand there's the Simple hierarchical select module, but since we already use CSHS, I wasn't sure if it was advisable to have both CSHS and SHS. For the time being we've changed ['#multiple'] = false; to turn it into a basic drop-down.

Chosen's autocomplete is just a bonus. You can have your normal hierarchy using chosen and it is much more accessible than other options you have. I would at least give it a go.
Now considering SHS and CSHS.. they are quite similar and I would not recommend using them side by side.
The main reason for that is that they tackle the same issue with a different approach and -best case scenario- one's functionallity would overwrite the other's.
Now as far as I know they do indeed have compatibility issues as stated in CSHS's module page (at the time this was posted)

It is possible to use the CSHS widget as an exposed filter for taxonomy term reference fields. Please note that this feature might break if SHS module is enabled on your site.

While I think I find CSHS's approach more usable, I would stick with SHS and chosen in your case since you mentioned that your vocabularies are large and CSHS, being client side and all, is more susceptible to performance issues, since it

[...], but in contrast to those modules the whole taxonomy tree is already present at page-load and the whole processing is done "client-side".

Now, to give the devil it's due, both  modules have performance issues with very large trees and it is only natural and understandable, but SHS seems like a more stable choice.
Lastly, to achieve what you described, I would prefer a more "Drupal 8" way and would create a new Field Formatter plugin for the entity reference field you are using and attach this to the form in the form display tab of you entity.
To summarize, I  would but not use SHS in conjunction with CSHS, and although you have to try it our yourself, the combination of SHS and Chosen seems to me like the obvious choise for your case. Try overriding the entity reference field's field formatter to add
the taxonomy parent name to your options if you prefer a more custom approach.


Is there a module that allows me to add files via ajax to a body field? I am using Drupal 7. I am looking for a module that allows users to drag and drop files (images/video/audio) inline into a body field with something like jQuery UI sortable. I would ideally like the user to be able to make a "media bank" in the node creation where they can upload their media and then drag and drop it where they want it in their post. Also, and I know that I am already asking a lot, it would be awesome if when the user added an image, they could resize it to the best fit for its position and placement in the body.

Do you have any suggestion, or anything close that I may be able to customize for my needs?

It is probably not exactly what you are looking for, but I'll mention them anyway, as it might give you further search directions:

plup module
Insert module
Image Resize Filter module

I like the plup module a lot, very easy to use, but based on image fields, not inline. Perhaps, in combination with the Insert module, you can get them inline. I don't like the resulting UI, as people won't understand why something so easy (putting an image inline, optionally with fixed dimensions) needs to be presented so complex.

The Media module is still thinking how to handle inline images; see the issue #1283844.


How do I get Drupal to load a node instead of looking for the index.php outside of drupal in a subfolder I inherited a site that has a lot of manually created html/php files in subfolders outside of Drupal. In other words, not as nodes, but static html/php fiels (leading of from the site root). I would like to move many of them inside Drupal as nodes because they are just some basic html/php. However, when I create a node using the same alias, it continues to load the old static html/php page. (I have flushed cache, both local and in drupal). Thoughts?

You'll need to remove the original file, or make it unreadable by your webserver. Drupal is basically a big 404-handler; if the file exists it will get loaded before the webserver looks for the default index.php which then bootstraps Drupal.

That, or check to make sure you don't have APC or similar opcode cache installed.


How can I create a new user—with Profile 2 fields—programmatically? I am writing a module where I need to create a new user and save his profile fields using Profile 2.

This is the code I'm using, but it's not working:

$edit = array(
  'name' => $submission->data[1]['value'][0],
  'pass' => user_password(),
  'mail' => $email,
  'init' => $email,
  'status' => 1,
  'roles' => $role_id,
  'profile_first_name' => $submission->data[1]['value'][0],
  'profile_surname' => 'ag',
  'profile_email' => $email,
  'access' => REQUEST_TIME,
);

$new_user = user_save(drupal_anonymous_user(), $edit/*,'customer_profile'*/);

What am I doing wrong?

I load the profile object:

$profile = profile2_by_uid_load($user->uid, '<role type here>');

Then I edit the $profile object.

I have a Rules component that saves the profile object. I forget why I have the rule but I remember that it requires quite a bit of code and database queries to get it right.

I set the Rules component to take the $profile object as an argument / parameter and invoke it like this.

    rules_invoke_component('rules_machine_name_this_is_the_component_url_too', $profile);


Cannot get just the text of an option from submitted data I'm using Webform 8.x-5.8.
I've got a select box referencing some content. Of course, the numeric option value is passed. But when I reference submitted data with tokens, I just want to handle the plain text appearing with the options, but a concatenation of the text and the sequence " (NID)" is displayed instead, where NID is the content ID. An example with dummy code, names and values - just to roughly show what I suppose is happening behind - is following.
<select name="my_parameter">
<option value="80" selected>Some text</option>
...
...
...
</select>

By selecting Some text, "80" is passed.
My aim is displaying "Some text" picking it up from the submitted values.
Tried with [webform_submission:values:my_parameter] and [webform_submission:values:my_parameter:value].
Anyway I get Some text (80).
What am I supposed to do in order to get rid of that final NID in brackets?
Thanks in advance!
Andrea

I scanned Webform's code base for [webform_submission:values: and eventually found the webform.token.inc file to list a number of Webform tokens from submission values. One of them being entity:*. And another being delta.
'
element_key:entity:*
' .
'
element_key:delta:entity:*
'

The 'entity:*' applies to the referenced entity
The 'delta' is the numeric index for specific value

And when I scan Drupal core's code base for :entity:title] there's [comment:entity:title]. When I scan for just :title] there's [node:title] among the first hits. Okay, with all that I'd assume it must work with either:
[webform_submission:values:ELEMENT_KEY:entity:title]

Or if it's a multi-value field try it with a :delta of 0 to ensure you only get the first referenced node's title.
[webform_submission:values:ELEMENT_KEY:0:entity:title]

Just found out for taxonomy terms it's :name at the end:
[webform_submission:values:ELEMENT_KEY:entity:name]


Change download directory when installing new modules using "Install from a URL" I like using the "Install from a URL" method of installing modules as it's really easy. The problem is that it, by default, downloads the module to "/sites/all/modules", but I like to have my directory structure like "/sites/all/modules/contrib" and "/sites/all/modules/custom", therefore I would like automatically downloaded contrib modules to be downloaded into the "/sites/all/modules/contrib" folder. Is there a way to tweak this setting somewhere or do I need to hack core?

Unfortunately I believe there is no way to change this in settings because there is no setting in the update module to change the installation path. If you check the update module configuration (admin/reports/updates/settings) there are fields regarding updating, but nothing regardig the installation path.

Even if you read the documentation (https://drupal.org/documentation/install/modules-themes/modules-7#using-drupal-interface) its never mentioned there. You would simply have to hack the core.

On the other hand, I recommend using drush (https://github.com/drush-ops/drush) with simple command (drush dl [module_name]) which does respect your contrib directory out of the box.


Is safe adding uid=0 in users table just to use $_SESSION? I read many articles about adding it, but I'm not encouraged to use it yet. People says that Drupal doesn't add this user because MySQL Auto-increment starts at 1. So, about adding uid=0, is it a good practice? Is it widely used? What possible problems could I have with it? Thanks. :)

Drupal does come with a row with uid=0 by default.

Some backup tools (notoriously some versions of PHPMyAdmin) are unable to deal with that, so you will lose this row when restoring from backup.

The easiest way to get back the missing row is to issue this query (for example in PHPMyAdmin):

UPDATE users SET uid = uid - uid WHERE name = ''


How do I get the base path? I want to use the base path in a Drupal 8 template file. I tried the following, but I don't get the correct result.

{{ app.request.baseUrl  }}

{{base_path}}

What I need is the absolute path to the node {{ app.request.baseUrl  }}/{{ url }}.

One solution I found is putting  this code in a preprocess hook, and pass it to the theme.

 $host = \Drupal::request()->getHost();
$response = \Drupal::httpClient()

I am looking for a better solution. What could should I use instead of the one I am using?

You can use url() to generate a base url to any route in Drupal. You can supply the <front> route which, in effect, will be your base URL.

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

But, render it first if you're concatenating it:

{{ url('<front>')|render ~ file_url('public://image.jpg') }}

For example:

{{ url('<front>') ~ file_url('public://image.jpg') }}
# Outputs: "Array/sites/all/default/files/image.jpg"

{{ url('<front>')|render ~ file_url('public://image.jpg') }}
# Outputs: "http://example.com/sites/all/default/files/image.jpg"


How do I create a link in the node template? I have a news content type, and the node--news.html.twig template.

I have some fields, but I can not create links to node for text-field from teaser-view. How can I achieve this?

Node templates have url variable which you can use in your template in the following way:

{{ label }}

(See node.html.twig for an example.)

In general, you can use link function in twig template:

{{ link(item.title, item.url, { 'class':['foo', 'bar', 'baz']} ) }}

(See Functions - In Twig Templates for a short list of twig functions provided by Drupal. Also take a look at TwigExtension for their source.)


Responsive Views-Slideshow Json Cycle working good in Chrome not in IE or mozilla In drupal I AT themes, views with slideshow of json2 and cycle plugin. I set the options for the plugin like this :
Make views slideshow responsive - remove inline styles

height auto  ,  width auto   , containerResize 0  ,  slideResize 0    ,  fit 0

Result:
- In chrome works perfect
- IE and firefox not responsive

Probably something to do with the html but how to find out where en how. Can it be sold with some CSS?
Any suggestions?

I use this code

     $(window).resize(function () {
          $('.views_slideshow_cycle_main').each(function(){
                var cycleMain = $(this);
                var img_width = 0,
                    img_height = 0;
                var clearCSS = {width: "auto", height: "auto"};
                var cycle = cycleMain.children('.views-slideshow-cycle-main-frame');
                cycleElements = cycle.data("cycle.opts");
                cycle.css(clearCSS);
                cycleMain.find('.views-slideshow-cycle-main-frame-row').each(function(i){
                  $(this).css(clearCSS);
                  var tmp_img_width = $(this).width();
                  var tmp_img_height = $(this).height();
                  if(tmp_img_width > img_width)
                    img_width = tmp_img_width;
                  if(tmp_img_height > img_height)
                    img_height = tmp_img_height;
                  cycleElements.elements[i].cycleW = tmp_img_width;
                  cycleElements.elements[i].cycleH = tmp_img_height;
                  $(this).css({width: tmp_img_width, height: tmp_img_height});
                });
                cycleMain.height(img_height);
                cycle.css({width: img_width, height: img_height});
                cycle.data("cycle.opts.elements", cycleElements);
              });

        });

and it works perfectly. you can also add some css to avoid too much high height like:

@media screen and (min-width: 980px){
 .al-slideshow img{
       height: 650px !important;
   }
}

The following css code is also needed

.views_slideshow_cycle_main { width: 100% !important; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row { width: 100% !important; height: auto; }
.views_slideshow_cycle_main .field-content { max-width: 100%; width: 100%; }
.views_slideshow_cycle_main .field-content img { max-width: 100%; width: 100%; height: auto; margin: 0; padding: 0; }


Drush cc all doesn't flush and rebuild templates? I am trying to clear the cache using Drush cc all because I deleted a function in the module/theme files and the site won't render...

I always have to login in as admin, performance > Clear all caches

This works...what is the equivalent Drush command?

I did not try to reproduce your exact situation, but some operations called by cache_clear_all write / remove files from the filesystem. If your filesystem permissions are not correct, then drush cc all will do all of the database clearing just fine, but will leave the other operations undone.

There are two potential solutions to this:

sudo -u www-data drush cc all

Some folks don't like to use 'sudo' with 'drush', but if you run Drush as the webserver user, the cache-clear should work.

set the permissions of your webserver files so that the user that you run Drush as can read/write to the filesystem.

I usually make my webserver files owned by a 'www-admin' user in production, and I make them owned by the user I log in as on my development system.  I set the group of all files to www-data, and make those that the webserver needs to write to group-writable.  This works pretty well for Drush + Drupal access on Drupal 7.


How do I connect to Adsense Account? I have to add a script section to the head section on the website.  I am modifying the html.html.twig file like this:

<!DOCTYPE html>
<html {{ html_attributes }}>
  <head>
    <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
    <script>
        (adsbygoogle = window.adsbygoogle || []).push({
            google_ad_client: "ca-pub-6243578269823283",
            enable_page_level_ads: true
        });
    </script>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">--
  </head>
  <body{{ attributes.addClass(body_classes) }}>
    <a href="#main-content" class="visually-hidden focusable skip-link">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>`

This seems to not work. Google responded and said I still have to connect my site to Adsense for verification. How do I do this? I have the Adsense module installed but I can't use it until I have an account. This script is for verification so that I can have an account with my website.

Did you already look into dedicated modules for this? There is

Google AdSense integration and Simple AdSense. The first one is more advanced, the second is simpler, but less flexible.

For both, you just have to copy over some values, and the module will take carte of the rest.


How to filter content by date in Views? There is one date field = "Display-date" and my content is displaying as:

2016 | abc

2016 | def

2015 | pqr

2014 | wer

I'm applying a filter in view:

content:display-date

and set its value = 2016 so that only 2016 year content will get visible. (as shown in below screenshot) I chose time zone = UTC.

This is giving me NULL results.

How can I get only 2016 year result to get rendered?

You need to use CCYY-MM-DD format

So use is between 2016-01-01 and 2017-01-01 which will print all 2016 nodes, don't worry, it will not print any 1st day of 2017 nodes. (tested it)

Use a group filter so you can change the name, if you expose the filter that is.


Find item position in the pager I was wondering how I am able to find the position of an item in a views pager?

I have nodes listed using views (with pager, 20 every page), and I'd like to find out for example where in the pager one node is?

EDIT (2015-04-05): Updated the snippet to work with newer version of Views.

Us too had to find the page number of a views result on which a certain node appears, so we can redirect visitors to this page.

By loading a view for a specific display and executing it's query manually, we retrieve an array with all node ids which we can search for a specific node id. When we have got the position of the node id, we divide it by the amount of items per page to get the page number the node is on.

I understand that loading all node ids at once in an array probably should not be done on large amounts of records, but for this exercise it's okay.

/**
 * Custom function to get the page number of a views result a node appears on.
 * Based on Drupal's views_get_view_result().
 */
function yourmodulename_views_get_item_page_nr($nid, $name, $display_id = NULL) {
  $args = func_get_args();
  array_shift($args); // remove $nid
  array_shift($args); // remove $name

  if (count($args)) {
    array_shift($args); // remove $display_id
  }

  $view = views_get_view($name);
  if (is_object($view)) {
    if (is_array($args)) {
      $view->set_arguments($args);
    }

    if (is_string($display_id)) {
      $view->set_display($display_id);
    }
    else {
      $view->init_display();
    }

    // Set the limit to 0 to retrieve all node ID's.
    $view->set_items_per_page(0);

    $view->pre_execute();
    $view->build();

    // Get the views query.
    $query = $view->build_info['query'];

    // Get the return assoc array with return objects, keyed by nids.
    $nids = $query->execute()->fetchAllAssoc('nid');

    // Get position of nid in nids array.
    $index = array_search($nid, array_keys($nids));

    // Get amount of items per page.
    $items_per_page = $view->display[$view->current_display]->handler->get_option('items_per_page'); // As seen at http://api.drupal.org/api/views/includes%21view.inc/function/view%3A%3Aexecute/7.

    // Calculate page number.
    $page_nr = $index === null ? 0 : intval($index / $items_per_page);

    return $page_nr;
  }
  else {
    return 0;
  }
}


How can I reduce the initial load of page? I've been monitoring the speed of my site load on Drupal 7 and I would like to increase its initial loading speed. Currently it takes 6 seconds just to get data from the server. What is the first page called? In total it takes about 10 seconds for my site to load.

What methods are there to reducing this initial startup load time? I've tried boost, but I can't use it as it renders all my webforms useless. I've already used the lazyloader module for images and enabled gzip aswell.

There isn't much you can do with the browser debugging tools in this case. You need to debug this on the server:

https://docs.acquia.com/articles/using-xhprof-evaluate-code-performance


How to resave content so that teaser thumbnails are generated I imported a load of content from wordpress, and I am using the teaser thumbnail module. I need to effectively click 'edit' and 'save' on all my content so that any images create thumbnails on save automatically. Is there any way to do this.

The image style files won't be generated when you save the node, only when the style URLs are requested for the first time.

You can generate the styles manually but I think it'll take some custom code. Without knowing more about your setup it's tricky but the following should get you started:

// Get the ids of nodes you want to generate styles for.
$nids = db_query('SELECT nid FROM {node} WHERE type = :type', array(':type' => 'my_type'))->fetchCol();

// Load the node objects
$nodes = node_load_multiple($nids);

// Setup a list of fields to generate styles for
$fields = array('field_image', 'field_image2');

// Setup a list of styles to generate
$styles = array('thumbnail', 'small');

foreach ($nodes as $node) {
  foreach ($fields as $field_name) {
    // Extract the fields items to get at the file ids.
    $image_items = field_get_items('node', $node, $field_name);

    foreach ($image_items as $image_item) {
      // Load the file
      $file = file_load($image_item['fid']);

      foreach ($styles as $style_name) {
        // Get a URI for the image style.
        $derivative_uri = image_style_path($style_name, $file->uri);

        // Create the derivative
        image_style_create_derivative($style_name, $file->uri, $derivative_uri);
      }
    }
  }
}


How to tell what module is running from a function call? I wrote a piece of shared code, and I am trying to figure out which module is actually calling the specific function. I am looking to have a mode to turn on debug inside of the shared module if it is being called from a particular module. Also this is in Drupal 7.

To call the shared module, I am using the following to call the function, made generic:

module_load_include('inc','rest_api','rest_api');
_rest_api_do_request();

You could get the calling function from calling debug_backtrace(). Another way would be to pass it in:

_rest_api_do_request(__FUNCTION__);

However, either seems like a bad pattern. It's fine for debugging, but a function shouldn't require knowledge of what it is calling it. That's an unnecessary dependency.


How do I change a theme based on the URL? I have a Drupal instance running on example.org. Which has a theme X installed and activated. Now for a limited period an event is supposed to be held on the site for which a special section has been "carved out." All the things related to that event will go to example.org/event2011.

I want to have a different theme to be shown whenever a page under this section is viewed (e.g. http://example.org/event2011/about, http://example.org/event2011/node/123). How do I do that?

I have gone through many modules, but none of them is supporting Drupal 7. Preferably, I would like it to be done using modules and don't want to change anything my self at the code level.

Considering that the change is for a limited period of time, and that implementing such code is not difficulT, I would suggest to implement a custom module that changes the theme being used for specific pages.

It is enough to implement hook_custom_theme() as follows:

function mymodule_custom_theme() {
  if (arg(0) == 'event2011') {
    return 'the theme to use for that page';
  }
}

If you would need to change the theme only for http://example.com/event2011, but not for http://example.com/event2011/node/123, then the code should be changed to

function mymodule_custom_theme() {
  if (arg(0) == 'event2011' && !arg(1)) {
    return 'the theme to use for that page';
  }
}

As for using the theme callbacks in the definition of a menu callback, the documentation says:

  As a general rule, the use of theme callback functions should be limited to pages whose functionality is very closely tied to a particular theme, since they can only be overridden by modules which specifically target those pages in hook_menu_alter(). Modules implementing more generic theme switching functionality (for example, a module which allows the theme to be set dynamically based on the current user's role) should use hook_custom_theme() instead.


Error message when deleting folders/files on Maintenance mode I turn the site in maintenance mode for update Drupal Core from 7.30 to 7.32. I follow the step on Drupal docmentation to delete all folders and files, beside "site" folder(on step 5). However, I got the error message and warning about missing files. I dont think that how maintenace mode should be. What am i missing?

PS:
1. the site does show in maintenance mode before I delete all the folders and files(beside site folder)
2. Site back to normal after copying v7.32 folders and files(beside site folder)

Rather than the two step deleting the folders and then uploading the new ones, I would recommend just copying over the old ones with new ones. You'll probably have to tell your FTP program to overwrite but when I upgrade in this fashion, I select all the files and directories except for sites folder and push them to the server.

When possible, I use the Drush tool via a terminal window as it is a much quicker and easier solution.


Join User Profile fields with custom View type In Drupal 6, I've created a custom View type that allows me to query data in my custom table. One of my fields, uid, relates to drupal users.  In the Views I create for my custom type, I can display user info for each record by using a simple join in hook_views_data():

$data['users']['table']['join']['awesome_user_submissions'] = array(
  'left_field' => 'uid',
  'field' => 'uid',
);

Now, I'd also like to display Profile fields in my view (eg: profile_first_name). Unfortunately, it doesn't appear that this will be a simple table join. How can I do this?

Solution: (thanks @googletorp)

Don't use the join I originally used (above).  Instead replace it with the following in hook_views_data(), then I can use fields from the 'users' table, as well as from the 'profile_' tables.

$data['awesome_user_submissions']['uid'] = array(
    'title' => t('User'),
    'help' => t('Relate an awesome submission to the user who entered it.'),
    'relationship' => array(
      'handler' => 'views_handler_relationship',
      'base' => 'users',
      'base field' => 'uid',
      'label' => t('user'),
    ),
  );

Views itself makes a join to the uid, so if you add the Users uid as a relationship, you should be able to get the profile fields as well.

Alternatively you could join the profile field table yourself.

For reference this is how Views makes the profile -> user join:

$data['profile_values']['table']['group']  = t('Profile');

$data['profile_values']['table']['join'] = array(
  // The node table
  'node' => array(
    'left_table' => 'profile_values',
    'left_field' => 'uid',
    'field' => 'uid',
  ),
  // The users table
  'users' => array(
    'left_table' => 'profile_values',
    'left_field' => 'uid',
    'field' => 'uid',
  ),
);


http://example.com/node/111 also accessible through http://example.com/node/111.000 An acunetix scan has complained about the following:

http://example.com/node/111.000 or http://example.com/node/111.0 or http://example.com/node/111.000000 (any number of zeros) serves the node http://example.com/node/111

For the regular url, the pathalias is then used, for the url with .0 added, it is displayed as is.

Two questions: is it possible to disable this behavior, and if not, is there a standard reference to justify this to our security team?

Automated scans sometimes report issues that are non-issues, and the results of an automated scan do need to be combined with an understanding of the issues at hand (and, if they require fixing, the risks of introducing new code to mitigate supposed vulnerabilities).

As R. Leurquin says, in Drupal there are multiple URLs that may work to access the same node or path directly. While this might not be ideal for SEO (if people link to multiple URLs), it likely isn't an actual security concern.

This can likely be solved using approaches like the Global Redirect module in Drupal 7, and the Redirect module in Drupal 8 (and in D7 if patched from #905914: Merge global redirect functions into Redirect module).

You'll get the SEO improvements, and if the security team really need convincing, hopefully it's an easy item to knock off the list!

If those don't cut it, you could do something similar to what Global Redirect or Redirect do, eg implement hook_url_inbound_alter() or hook_init(), check for those zeroes, and redirect them. In that case, be careful that the "fix" for this "problem" is not riskier than the existing situation.

You could also handle this with redirects at the webserver layer.


How do I restrict view/edit access to a custom content type node to only the user it belongs to? There is a content type; let's call it Contract. I have an user role; let's call it Consultant.

I added a Consultant field to the Contract content type with Entity Reference.

How can I restrict access to view/edit that specific node to only the user it belongs to?

You can use the Node access user reference module.

  Gives content access permissions to users for content that references the users with User reference or Entity reference.


Is it possible to populate a field entity reference with query parameters? I created an entity reference field for a node filtered by a view type "entity reference", but I need to pass an argument in the contextual filter of this view, to filter entities on my field.

I tried passing my argument on the URL in a query parameter (e.g. node/add/page_interieur?dossier=2), but I never get results in my field autocomplete.

Is it possible to do that with this method or another one?

Settings for the contextual filter with the Query parameter option

Settings for the Entity reference field

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

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

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

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

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

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

My contextual filter configuration in views :


Load published nodes of certain content type I have to load nodes of certain content type that are published.

Any built in function already available for this purpose?

To load a bunch of nodes based on custom parameters, you have to use EntityFieldQuery. It replaces the $conditions array noad_load_multiple used.


Subdomain drupal sites cannot read domain cookies I have set a cookie from domain (.example.co) and its .NET platform & reading those cookie from drupal site(test.example.co).

While retrieving it shows empty, I have used $_COOKIE.

This link suggests it is possible, also we are setting domain name while creating cookies? Is it possible to use while retrieving cookies?

Also i have found this link, is that interrelated?

You need to provide an appropriate value for $cookie_domain in settings.php.

e.g.

$cookie_domain = 'example.co';

That will allow you to set/retrieve cookies from example.co on foo.example.co, and vice versa.


Commerce - how do I set a discount to a specific user's next order only? I'm making an e-commerce site for a friend.

The point of his shop is to sell honey in jars. When people return the jars, they get a 2 euro discount on their next order.

I've tried several things so far but if I give the user a discount, it continues to give the discount. I only want it the discount for the next order. Same goes for other ways I've tried it. I'm not quite sure how to set these specific conditions.

Generic solution

I think you need to write some custom code to get a solution that will work automatically. This could be handled by a custom Rules condition - meaning hook_rules_condition_info() implementation. After you add the code below, make sure to add this condition through Rules interface as well. Here's example code that would go in YOUR_MODULE.rules.inc:

function YOUR_MODULE_rules_condition_info() {
  return array(
    'YOUR_MODULE_rules_condition_check_next_order_discount' => array(
      'label' => t('Sample condition'),
      'parameter' => array(
        'order' => array(
          'label' => t('Order')
          'type' => 'commerce_order',
        ),
      ),
      'group' => t('Custom'),
    ),
  );
}

function YOUR_MODULE_rules_condition_check_next_order_discount($order) {
  // Perform any checks you want here, load the owner, see previous orders, etc.
  $customer = user_load($order->uid);
  if ($whatever) {
    return TRUE;
  }

  // I recommend doing this the other way around: by default visitors shouldn't be
  // able to have the rights for this discount, but they can get it IF they fulfill
  // your rules above.
  return FALSE;
}

Note: the YOUR_MODULE.rules.inc file would be loaded automatically, and you don't have to include it in the .info file of your module.

One-off solution

In case I misunderstood your question, here's how to configure the discount to have this work only once:

"Apply to" fieldset, add "User" and there select the target user.
Set the value of "Maximum usage per customer" field to 1.

Hope this helps.


Determine if an entity is a certain content type I'm using drupal 8.

Lets assume the following. I have created a content type called Foo. Using the presave hook(hook_entity_presave), I'm modifying some fields in that content type.

Firstly I want to determine if the entity I'm modifying is a Foo content type.

I've tried using Drupal\Core\Entity\EntityInterface $entity->getEntityType() however the return is object(Drupal\Core\Entity\ContentEntityType). So basically an object.

Since my knowledge of drupal 8 is not that great(yet) I assumed initially that it would return something more quantifiable like a string or something of the sort. Obviously I was wrong.

Secondly I want to NOT modify some fields if the fields already have a value. Again, I assume a simple isset or empty will do the trick. I could be wrong. If there are some other ways to do that, more drupal-like way, I'd be more than happy to understand it better.

You should be able to check the entity type and content type like this:
use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $entity) {
  if($entity->getEntityTypeId() == 'my_entity_type' && $entity->bundle() == 'my_content_type') {
    // Do your stuff here
  }
}

Where my_entity_type is the entity type and my_content_type is the content type.
Adding Clive's answer, since the entity type you want to work with is already known to be a node, you can use hook_node_presave() instead of hook_entity_presave:
use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $node) {
  if($node->bundle() == 'my_content_type') {
    // Do your stuff here
  }
}


The login form isn'r rendered I am newbie to drupal. Recently I changed blocks of my theme and set main page content block to none.I logged out of my site. I tried to access admin panel by appending /user at URL. It redirected to login page but it login form is not appearing as displayed in image below. I am unable to enter my username and password.

Any helps are welcomed.

You are going to need to open phpmyadmin from your hosting, and look in the "block" table.

Look for the "main" block, and edit the status to "1" and the region to "content" (or whatever your main region is defined as in your themes .info file).
It seems strange that disabling the main content block would hide the login form though, I thought they were separate.


Why does node_add_body_field() lock down 'body' field instances to the 'node' entity type? For a current project our taxonomy terms need a text field with a summary; naturally as there's already a body field available on nodes, I thought I'd just use that.

Confusingly, 'body' doesn't appear in the list of existing fields when managing fields for the taxonomy term. No problem thought I, I'll just use field_create_instance() and add it manually. Drupal objected:

  Attempt to create an instance of field body on forbidden entity type taxonomy_term.

So I thought I'd get clever. I loaded up the field config, added taxonomy_term to the array of entity_types, and tried to update with field_update_field(). Nope:

  Cannot change an existing field's entity_types property.

It turns out node_add_body_field() does this unconditionally:

$field = array(
  'field_name' => 'body',
  'type' => 'text_with_summary',
  'entity_types' => array('node'),
);
$field = field_create_field($field);

I (perhaps naively, not sure yet) disagreed with Drupal's various assessments, so I went into the database and manually added taxonomy_term to the list of allowed entity types for the body field. Works great, I haven't noticed any ill-effects so far, and the body field is where I expect it to be.

So I guess my question is two-fold:

What reason could there be for the node module locking down this field to a single entity type?
Can I expect to see any bad effects from this further down the line?

I would expect it is for historical reasons and is a place to migrate data from the old Drupal 6 body field.

Since the old Drupal 6 body field was just for nodes it seems in some ways logical that they would then also restrict this to just nodes so it is as it was in Drupal 6.

A couple of quick (not so thorough) greps didn't turn up any code that looks like it would cause you trouble using it for other entities but I could have missed something.

I would not think that this would cause you much trouble in future but I'm not sure of that.

A possible downside though is that it is in some ways like hacking core.
If someone else inherits your site they may find it unusual that your site behaves differently than usual.

Personally sometimes I remove the drupal core body field and add my own field_body and use that throughout the site.


Check if user has access to a certain page How can I determine whether a user has permission to access to a certain page?

If you want to verify if the currently logged-in user has access to a page, you can use the following code:

if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    // The user has access to the page in $path.
  }
}

$path is the path of the page you want to check (e.g. node/1, admin/user/user).

The code works in Drupal 6 and higher versions, and it is the one used from menu_execute_active_handler().

The reason I am not suggesting to directly call the access callback is because the arguments that need to be passed to that function.

The code used by _menu_check_access() is the following one (Drupal 7):

$arguments = menu_unserialize($item['access_arguments'], $map);
// As call_user_func_array is quite slow and user_access is a very common
// callback, it is worth making a special case for it.
if ($callback == 'user_access') {
  $item['access'] = (count($arguments) == 1) ? user_access($arguments[0]) : user_access($arguments[0], $arguments[1]);
}
elseif (function_exists($callback)) {
  $item['access'] = call_user_func_array($callback, $arguments);
}

The code, which needs to be as much generic as possible, doesn't directly handle a user object. This means that is not possible to replace the user object for the currently logged-in user with another user object.
The code must be generic enough to handle menu definitions such as the following ones:

$items['node/add/' . $type_url_str] = array(
  'title' => $type->name,
  'title callback' => 'check_plain',
  'page callback' => 'node_add',
  'page arguments' => array($type->type),
  'access callback' => 'node_access',
  'access arguments' => array('create', $type->type),
  'description' => $type->description,
  'file' => 'node.pages.inc',
);

$items['node/%node'] = array(
  'title callback' => 'node_page_title',
  'title arguments' => array(1),
  // The page callback also invokes drupal_set_title() in case
  // the menu router's title is overridden by a menu link.
  'page callback' => 'node_page_view',
  'page arguments' => array(1),
  'access callback' => 'node_access',
  'access arguments' => array('view', 1),
);

In both the definitions, the access arguments don't include a user object, and node_access() in this case uses the user object for the currently logged in user. In the second case one of the argument is the node object that is obtained from the URL; for example, if the URL is example.com/node/1, then the second argument passed to the access callback is the node object for the node with node ID equal to 1.
Writing code that handles these cases too would mean to duplicate code already existing in Drupal. Even if you duplicated that code, there would be still the problem of the access callbacks that are checking the access against the currently logged-in user.

If you want to check if a user that is not the currently logged-in user can access a menu is to first change the value of the global variable $user, use the code I reported at the beginning of my answer, and then restore the value of $user. For how to change the value of the global $user, you can see Programmatically impersonating another user without causing the currently logged-in user to log out. The difference is that, instead of using the value returned from drupal_anonymous_user(), you use the value returned from user_load().


Structure for a list of links What I’m looking to do:

Content type has an field (addable; unlimited entries to this field)
In that field you select from a list of (mostly external) links.
Each link is a sentence - has a title and pre/post text.

So a piece of content displays a number of formatted links, and these links can be pulled into a view elsewhere.

How could I build that list of links? (content type, field group, taxonomy with link as the name, haven't been able to figure out something that works)

One working solution:

Create a vocabulary where each term has 3 additional fields - a text field, a Link field, and another text field. Add the Term Reference to the content type. Use something like Chosen for selecting ease in needed.
Use hook_field_formatter_info() in a custom module to define a display of the 3 fields as desired. Unfortunately, displaying term fields on the content/node page doesn't have a quick & easy configurable solution.


Drupal 7:: create a page with views to show all the contents not authored by current user I am creating two page with views module. First page will show all the contents authored by current user. Second page will show all the contents that current user can view but not created by him.

I am trying it with contextual filter but no luck yet.

For your first problem, Create a content view with a relation Content: Author, than you will get User: Current in side the add filter, Add this filter to your view

Use No for Second problem.


Drupal 7 Custom Search Result Page I am trying to create a custom page that display my resuslts which I receive after I search for a post.

I am having no luck, I am a total begginer in drupal 7, I googled and looked around here but I did not quite understood what I have to do.

What I tried:

function **themename**_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  if (!empty($variables['module'])) {
    $variables['module'] = check_plain($variables['module']);
  }
  foreach ($variables['results'] as $result) {
    $variables['search_results'] .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
  }
  $variables['pager'] = theme('pager', array('tags' => NULL));
  $variables['theme_hook_suggestions'][] = 'search_results__' . $variables['module'];
}

Creating a search-results.tpl.php ( did not work )
The only module I have installed for search is the default search module.

Nothing seems to work. Thanks in advance

You are just processing the search results in your function but haven;t handled the output. Change the tpl.php to display the variables from your function rather than from the default search function.


Nginx Drupal rules for Views pager I just realised many guide on the internet not works for Drupal 7 Views pager

This is generally Nginx and Views pager issue. I've tried in Apache2 and the pager works without problem.

For example, I'm installing Commerce Kickstart. After submitting contents (SKU), I try to browse admin/commerce/products. But sadly, when clicking next page, it not showing any change

The first page URL is

http://www.website.com/admin/commerce/products

while second page, third page, and so on is:

http://www.website.com/admin/commerce/products?sku=&page=1
http://www.website.com/admin/commerce/products?sku=&page=2
http://www.website.com/admin/commerce/products?sku=&page=3

Currently, below is my nginx config:

server {
    server_name *.com *.net *.org *.in *.cc;
    root   /var/www/html/$host;
    index  index.php index.html;
    set $boost "";
    set $boost_query "_";
    if ( $request_method = GET ) {
      set $boost G;
    }
    if ($http_cookie !~ "DRUPAL_UID") {
      set $boost "${boost}D";
    }
    if ($query_string = "") {
      set $boost "${boost}Q";
    }
    if ( -f $document_root/cache/normal/$host$uri$boost_query.html ) {
      set $boost "${boost}F";
    }
    if ($boost = GDQF){
      rewrite ^.*$ /cache/normal/$host/$uri$boost_query.html break;
    }
    try_files $uri $uri/ /index.php;
    location ~ \.php$ {
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass    127.0.0.1:9000;
    }
    location ~ (.*)/x-progress-id:(\w*) {
        rewrite ^(.*)/x-progress-id:(\w*)  $1?X-Progress-ID=$2;
    }
    location ^~ /progress {
        report_uploads uploads;
    }
    location ^~ /files/private/ {
        internal;
    }
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        track_uploads uploads 60s;
    }
}

change the line:

try_files $uri $uri/ /index.php;

to:

try_files $uri $uri/ /index.php?q=$uri&$query_string;

to pass the query_string to drupal.

(see HttpCoreModule for more informations about nginx variables)


Is there an Image field that let's users select a file from the server? I am currently using file field sources to allow users to select images on our server in the Content Type. However, these are rendering as a download link. Is there something that will let a user either upload or select locally and render as an image in both the full and teaser view?

It sounds like you already have the solution for selecting the image, you just need to control the output of how it is displayed. Are you using the file field instead of the image field? The file field will output by default as a link to the file, rather than as an IMG tag which is what you want.

If you want to keep the field the same but output it as an image, you have two options: you can use an integrated wysiwyg editor or file browser (IMCE is probably the closest to what you're looking for) to assist the user in displaying the file as an image.

Or - you can theme your node template to take the url of the file field resource and output it as an image. This is a little more involved but you can start here with template suggestions and ask more questions if you get stuck.


How can a field definiton be imported, either via the admin or in code? In my admin one of the modules I have installed (I am not sure which) has the ability to export a field definition in code, but I can't see any place where I can import the field. I thought that the field creation dialog has abilty to import a field definition from the export code just as the bundle creation tool give the ability to import a bundle.

There is no such thing in the menu and I wonder if I am missing something in the interface or I have to resort to code.

Is there something missing in the admin interface, or do I have to import it in code?

There is nothing in the interface but what you can do is make a temporary content type which uses the field(s) you wish to import, then export/import that content type to the target site.

Your new field(s) will then be available at the target site, make sure you attach them to other content types before you delete the temporary one or the field(s) will disappear.


Users can post new node but ONLY Unpublished status As the title says, users are able to create new node (type QUESTION), but they can not publish it. The node is saved when the user hits save, but the status is set to unpublished under Admin > Content.
I have checked a few permissions the authenticated user which has:

Question: Create new content
Question: Edit own content
View published content
View own unpublished content

This content is NOT using workflow moderation.

The obvious thing is that the "published" option is unticked on the content type. So if you go to "structure > content types > question" (/admin/structure/types/manage/question) and then click "Publishing option" is the published ticked? That controls the default status

If its not that then you must have some other module/code doing it. Without knowing your sites setup I dont think people can help much further


Move drag and drop handle to other side I want to move the drag and drop handle to the other side of a form, to the same location as the row weight selections.  I am talking about the tabledrag handles, as shown below:

I am using Corolla if it makes a difference.

two changes i made

form .field-multiple-table td.field-multiple-drag { width: 30px; padding-right: 0; position: absolute; left:0px; /*LTR*/ } form .field-multiple-table td.field-multiple-drag a.tabledrag-handle { padding-right: 0em; position: absolute; left: 520px; /*LTR*/


login to magento 1.7 from drupal 7 function custom_user_login($edit, $account) {

  require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
  global $user;

  umask(0);
  Mage::App('default');
  $session = Mage::getSingleton('customer/session', array('name' => 'frontend'));
  try {
    $session->login('alvaro@test.com', 'cec123');

    $session->setCustomerAsLoggedIn($session->getCustomer());
  } catch (Exception $e) {
    print_r($e);
    exit;
  }

i am using this set of code from my D7 installation to log-in to magento.But it is not loggin into either D7 or magento.

But when i run this code from a seperate simple php file outside it logs in to magento successfully. what could be the problem.

The function signature is not right, which may be the reason for the code not executing.
See the docs for hook_user_login function.

The parameter $edit is passed by reference and not directly by value. So, the correct definition your function should be,

function custom_user_login(&$edit, $account) {

  // rest of the code goes here (not duplicating).

}

Also make sure, your modules name is custom and it has files custom.info and custom.module in the module directory. And offcourse, enable the module ;-)

Also, to suggest you to look into the session and cookie info (based on your comment), you can put an echo '<pre>';print_r($_COOKIE); echo </pre> inside your theme's template.php file.
Or simply install the Devel module, and enter dpm($_COOKIE); inside your template.php, to see a nicely formatted result. You'll need to clear the cache to again load the fresh template files.
Similarly, you can print the $_SESSION superglobal to see the session information.


I want to redirect the user to profile page after they log in I want to redirect the user to profile page after they log in. i tried with some modules but those could not help. i am using D7 version of drupal and tried with login modules

Hope this will help  you,

In Drupal 7 you can use RULES instead of using any modules only if you looking for redirection.

Go to admin/config/workflow/rules/reaction/add to add new rule

Now enter the RULE name and select the event on which you want to trigger this RULE

Now its time to give some condition(if required) and to trigger the action.

In Action select Page redirect

Give the redirect URL and and check Force redirect

If the rule is not working means, there may be a other same event with higher weight. Therefore you need to increase you rules weight.


Add taxonomy to Views page I am attempting to get a views page into a taxonomy term page using this solution to no avail.

My taxonomy page is at [URL]/menu-tags/resource, so I made the Views page URL [URL]menu-tags/resource/resource-hub. The page doesn't show up despite having the settings set up in the pathauto config and the taxonomy checks out. I'm not sure where to go from here.

There are a number of different ways to build your own taxonomy term lists via views-driven output. One of these methods, which appears to be the one that you are working on, is to override the core taxonomy/term/% path with a view display. This "routing-level" override just ensures that all requests to a taxonomy/term/[id] page are handled by your view instead of the core term list callback. In order for this to work however, your view needs to use the exact same path as the core taxonomy term path (i.e. taxonomy/term/%), and implement a contextual filter for the term id. This path is independent of any path alias patterns you may have setup for your taxonomy terms. So if one of your term vocabularies is aliased with a pattern menu-tags/resource/[term-name], the actual Drupal path that views needs to respond to, and override, is still taxonomy/term/[id].

It's also worth pointing out that this technique has some drawbacks. Most notably you don't have the ability to define different view displays for different taxonomy vocabularies (as all vocabularies use taxonomy/term/% as their raw path by default). Because of this you may want to consider an alternative approach of using the taxonomy display module. Instead of overriding just the term path, this module overrides the actual rendering of the term page itself, and therefore has a bit more flexibility. It's also fairly easy to setup, just check out the documentation.


Get the titles of the nodes whose node IDs are contained in a field $attr = explode(",", $node->field_xlnum[0]['value']);

$node->field_xlnum[0]['value'] contains 20,4,56,987,68,96, where each value is a node ID.
I want to get all the titles, and output them in an HTML list. How do I do it?

I tried the following code, but it doesn't work.

$attr = explode(",", $node->field_xlnum[0]['value']);
$result = db_query("SELECT nid, title FROM {node} WHERE nid IN ($attr) AND type = %s order by created DESC", test);
while(($items = db_fetch_object($result)) {
  $output = theme_item_list($items, array('class'=>'tabs primary'));
}

echo $output;

A few remarks:

You said that $node->field_xlnum[0]['value'] contains a list of nid separated by comas so you don't need to explode it in order to use them in a IN clause. If you do so, $attr will be an Array().
You put test as an argument in your query, isn't this a variable $test or a string 'test'
You should better use db_placeholders for putting multiples values inside a IN.

$attr = explode(",", $node->field_xlnum[0]['value']);
db_query("SELECT n.nid, n.title
  FROM {node} n
  WHERE n.nid IN (" . db_placeholders($attr, 'int') . ")
  AND type = %s
  ORDER BY n.created DESC", $data, 'test'
);


Where is the location of developer/globals.php It's documented on the drupal website here but this path does not exist in the drupal installation.

That is because there is no such file in the codebase. It is documented separately. When the API site is built, it combines documentation from code comments in Drupal core and the documentation project.


Move views global text field into code (attached fields and fields via relationships) I have recently done away with using views php as it is unsafe. I have read a comment by @letharion whereby he mentions that adding a php directive disable_functions = eval is a good practice to tighten up security.

I have a problem with the views global text field:

One cannot run php functions on fields
It is a bit messy to have a lot of the html markup in the database
It runs the markup through filter_xss (which is good) without giving
one the flexibility of expanding on the allowed tags.

I have read this question: Move php in views to module and would like to broaden it a bit.

I have implemented the accepted answer and it works with a slight modification:

custom.module:

function custom_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'custom') . '/views',
  );
}

function custom_print_my_link($nid, $type){
  return $nid . '-' . $type;
}

custom.views.inc:

function custom_views_data() {
  $data['node']['custom_stuff'] = array(
    'field' => array(
      'title' => t('Custom link'),
      'help' => t('Provide a custom content link.'),
      'handler' => 'views_handler_field_node_custom_stuff',
    ),
  );
  return $data;
}

views_handler_field_node_link_custom_stuff:

class views_handler_field_node_custom_stuff extends views_handler_field_node {
  function construct() {
    parent::construct();
    $this->additional_fields['type'] = 'type';
    $this->additional_fields['nid'] = 'nid'; // this had to be added !!!
  }
  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }
  function render($values) {
    $type = $this->get_value($values, 'type');
    $nid = $this->get_value($values, 'nid');
    return custom_print_my_link($nid, $type);
  }
};

I have set up the view with two hidden fields (nid and type) that appear before this custom field.

This works perfectly for fields attached to the node table.

My question is: How do I implement it for attached fields, and access the fields across relationships as well?

So I figured out how to accomplish a small part of what I need done.

To add an attached field (a simple text field called 'test') I did this:

class views_handler_my_custom_field extends views_handler_field {
  function construct() {
    parent::construct();

    $this->additional_fields['test'] = array(
      'table' => 'field_data_field_test',
      'field' => 'field_test_value',
    );
  }

  /**
   * {@inheritdoc}
   *
   * Perform any database or cache data retrieval here. In this example there is
   * none.
   */
  function query() {
    $this->ensure_my_table();
    $this->add_additional_fields();
  }

  /**
   * Render callback handler.
   *
   * Return the markup that will appear in the rendered field.
   */
  function render($values) {
    $test = $this->get_value($values, 'test');
    return $test;
  }
}


How to group fields and place in seperate tabs/local tasks? I want to group fields and create different tabs/local tasks for them with their own dedicated pages. How can I do that?

I found one module that looked promising, but also that one has bug on installation: https://www.drupal.org/project/entity_ui

What other options do I have?

I tried ask the question before but it was mistakenly marked as duplicated so open a new question to allow for answers:
How to group fields and place in seperate tabs?

You can create local tasks for this in yml. Local tasks are what appear as tabs when viewing an Entity. You can code the tabs yourself. There's not much to it: https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-local-tasks

Answer from Kevin here:
How to group fields and place in seperate tabs?


How do I see the value of one field of a multi-item field in views formatter I have a custom views formatter.

function template_preprocess_views_view_flot_views_time(&$variables) {
  $view = $variables['view'];
  $field_name = 'foo_bar';
  foreach ($view->result as $row) {
    $field_value = $view->field[$field_name]->getValue($row);
  }
}

This works when the field is a single-value field. However, I have a couple multi-value fields. The result of the above expression is always "1" for these fields. These fields can be identified because

 $view->field[$field_name]->multiple == TRUE

I can use

kint($view->field[$field_name]->getItems($row));

to see that this is an array with a render array and raw data.
The value as a string can be found at:

$view->field[$field_name]->getItems($row)[0]['rendered'][#markup']

If the multi-value field is named foo, and has three parts, 'bar', 'baz', and 'qux', is there a better way to get the value of foo_bar or foo_baz?

I've been looking at the documentation for core/modules/views/src/Plugin/views/field/Field.php but it's not helping.

You don't need to search for another method, Field::getValue() returns the array you are looking for:

if ($view->field[$field_name]->multiple) {
  $field_array = $view->field[$field_name]->getValue($row);
}

I don't know if there is a documentation, but you can see this in code:

https://api.drupal.org/api/drupal/core!modules!views!src!Plugin!views!field!Field.php/function/Field%3A%3AgetValue/8.2.x

Difference between field values from view result and entity

If you have a standard multivalue field like text or number in a view and don't change any options, getValue($row) returns a one-dimensional array with the values from the main property of the field. If not you have somehow configured the view so that it shows a different result.

You can although get the original entity field data, which is independent from the configuration of the view. For this the field needs to be in the row entity:

$field_array = $row->_entity->{$field_name}->getValue();

This is then a two-dimensional array with multiple values and multiple properties.


How can I have drupal commerce create a sku and adjust prices on the fly? This is something I've done in the past outside of Drupal but I can't seem to figure out how to do this with Drupal Commerce.

I need the ability to do the following:

Allow the user to create parts via category (this could be a taxonomy term with fields like name, image, sku component, description, price markup...)
Allow the user to create a new product and select which parts can be placed on this product.
When the end user is looking at the product page, they will select which parts they want for this product.
When they select their parts the PHP script, on submission, will create a line item with sku comprised of the parts selected and a price made up of the base price of the product + any additional cost per part.

So, for instance, part category A has 5 parts. Standard and 4 upgrades. If the user selects an upgrade from Category A, it will modify the SKU on submission AND update the price based on the markup price of the part's price field.

Anybody following me here? How do I do this? I'll code it myself if I have to, I just need to know where to begin.

Try this rule, it will alter the line item's label based on tokens specified when a product type "Product" is added to cart. This is how you can keep it specific to a certain product type. A line item's label is defaulted to the product's SKU.

All of your term-reference attributes will be exposed as tokens. For formatting ideas, check out Commerce AutoSKU which generates product SKUs at product creation (not line item.)

{ "rules_alter_line_item_sku" : {
"LABEL" : "Alter line item label",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"ON" : { "commerce_cart_product_add" : [] },
"IF" : [
  { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
  { "data_is" : { "data" : [ "commerce-product:type" ], "value" : "product" } }
],
"DO" : [
  { "data_set" : {
      "data" : [ "commerce-line-item:line-item-label" ],
      "value" : "[commerce-product:type]-[commerce-order:uid]"
    }
  }
]
  }
}


How to get changes in database done by someone else? We are working on features in team. My team-mate have done some changes & synced the cloud database.

I also have some database changes locally, now I want those changes in database which he synced.

I can't use drush sql-sync becauses it asks to drop all the tables. So my local changes will gone.

what should I do?

Unlike code Database changes cannot be synced easily.

Try using Features Module This module exports your database settings to code so that they can be added to Version Control took like Git.

Tip : Create one feature for every independent functionality, so that it will be easy to manage. There are other supporting module for Features, which can reduce your efforts.


Which module allows for tracking recently viewed content per user? I am searching for a module that will enable me to track recently viewed content per user. I found the Recently read module but it does not appear to enable me to configure it per content type. For example, I want to show all recently viewed content by this given user for content type a and content type b. Is anyone aware of a module that would allow this?

The Recently Read module does not allow you out of the box to be configure per content type, but it seems to me that the views you create to show the content can easily be filtered by content type. See comments #3 and #5 of this thread.

Also a quick scan of the modules source code tells me, that there is still support for relationships in views. So you should be able to follow the configuration guidelines in the linked comments to achieve what you want.


do i need to check expiration cache in drupal from cache_get? I'm using drupal 6 and I've build table that is similar to cache (hook_schema) for using it with function cache_get/cache_set.
I just want to be sure how things should work in drupal.

To clean the table I'll need to use hook hook_flush_caches() where I'll decide if i want to clear expire data or whole cache? hook_flush_caches is called on cron?
In case I'll need to check data expiration by second, I'll need to do manually after cache_get function ?

This is kinda confusing...

It is actually pretty simple.

For your implementation of hook_flush_caches, all you need to do is return an array containing the names of your cache tables, eg

function mymodule_flush_caches ()
{
  return array("cache_mymodule");
}

drupal_flush_all_caches and cache_clear_all take care of the rest.  drupal_flush_all_caches is called anytime you manually clear the cache (the perforamnce page, admin menu, drush, etc).  system_cron does get called by cron, and also clears the cache tables, but does not do some of the other things that drupal_flush_all_caches does.

When you get something out of the cache with cache_get, expired items will have already been removed from the cache; you don't need to manually check expirations.  They will be handled automatically according to how you put them in the cache with cache_set.

That's it.


Build a grid with time slots in multiple rooms I need to build a grid for one day (Feb. 27) that allows users to reserve time-slots. There are 12 1/2 slots with a limit of 8 bookings for each slot (in 8 different rooms). The users are authenticated...this is not open to the public.

I'm guessing this is possible with Calendar module and Jquery without having to install another module. Any ideas?

Drupal 7

The bat module - https://www.drupal.org/project/bat would work for this use case without any custom code required.


View Revision log message with display suite In drupal 7, Is there any way, with or without Display suite, to show the revision log message at the bottom of a view node page?

You can easily do this with help of views module. Check the screen shot

Update
Position the view block to show on node page, where view will pick the node id and show the related revision log message.


How do you re-direct an alias at a scheduled time? I am using Drupal 7(.40 or .41) and what I am trying to achieve is to completely change a pages content at a specific time & date (00:00:01 01/01/2016 to be specific)

Because the content changing is about 90% of the page, I presumed that I could set a node to unpublished at 23:59:59 with the alias and then publish the new node at 00:00:01 with the same alias. However it throws up an alias is in use error.

There is nothing obvious in my URL Alias config (/admin/config/search/path) that would indicate this is possible so I am probably looking at it the wrong way, short of using a different URL.

Thoughts and methods would be welcome.

I would use the Rules module for this. But you can't "rely" on the Rules Scheduler in this case, if you want the redirect to start happening as of 00:00:01 01/01/2016 (sharp).

Redirect old path to new path

Here is the rule you'd need for it (in Rules export format, just use copy/past to import it in your own setup):

{ "rules_redirect_an_alias_at_a_scheduled_time" : {
    "LABEL" : "Redirect an alias at a scheduled time",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "AND" : [
          { "text_matches" : { "text" : [ "site:current-page:url" ], "match" : "the_old_path" } },
          { "data_is" : {
              "data" : [ "site:current-date" ],
              "op" : "\u003E",
              "value" : 1451602800
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Please note that the old path (= the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= the_new_path)" } },
      { "redirect" : { "url" : "the_new_path" } }
    ]
  }
}

A few more tweaks to make it fit your exact scenario:

change all occurences of the_old_path to the path to be used until 00:00:00 01/01/2016.
change all occurences of the_new_path to the path to be used starting from 00:00:01 01/01/2016.

Whenever such redirect actually happens, the user will also receive an informational message like so:

  Please note that the old path (= /the_old_path) is no longer in use, you will be redirected automatically to its corresponding path (= /the_new_path)

If you don't want such message to appear, then just delete the line containing drupal_message in the exported rule above.

Attention: this exported rule uses UTC times ... if your question is about another timezone, make sure to also tweak the value of 1451602800 to fit your needs.

Redirect new path to old path

If you don't want to have the new path be shown yet BEFORE 00:00:01 01/01/2016, then just create a similar rule like the previous one, in which you swap the the_old_path and the_new_path, and reverse the test on the site:current-date.


Organic groups joining strategy Does anyone know how I can force a user to register before being allowed to join an organic group?

Presently, my users receive a link which takes them to a page with a join button. Once they click on the button they are either added to the group as registered members or presented with an "error" message which states they need to register for anonymous users.

I would like to automate the process for those anonymous users.

Try this go on to Configuration > Organic Groups >OG Global permissions and Uncheck the fields that u wish to hide from  non-members ...


Changing CSS in Zen Theme in Drupal 7 This is another question that I am sure is very simple. I've been working through tutorials on setting up a Drupal site from scratch with the Zen Theme. I have my Sub-Theme working just fine, thanks to https://drupal.org/node/1549668 and http://drupalonlinetraining.com/youtube/linwclark/drupal-7-basic-theming-zen-and-css

Now, I want to edit the CSS. Unfortunately, the documentation that I can find references 25 separate stylesheets (including both of these tutorials and this page.) The version I have, however, has far fewer sheets than that (13 according to the ReadMe).

I did find the ReadMe that describes the new stylesheets, but as this is my first foray into CSS within Drupal, I'm still a little unsure as to where I should start to add styles. Is it in normalize.css? Is this where I would add, for instance, a background image?

Thanks for any help, and/or for pointing me to a tutorial that breaks it down for the latest version of the Zen Theme!

You should just focus on several main Zen css files:

blocks.css : should add the css of blocks that you create from backend or from your modules.
forms.css: should add the css for forms: for example: login form, register form, contact form (from contact module)
pages.css: should add the css for the pages: static page that you create from Drupal backend or views page..
nodes.css: should add the css for just the common structure of node and specific nodes also
tabs.css: should add for the tab style (You can easy see the tab style at user login page with login/register/forgot password).

For Zen theme. I suggest you should understand SASS structure and change the scss files instead of css files and the name of scss files are the same as the list above (like blocks.scss, pages.scss, nodes.scss, tabs.scss). You should check Getting started with Drupal7, Zen, Sass and Compass for doing your current stylesheet.


Two displays with an exposed filter I have a view using one exposed form in a block with a couple exposed filters.  I would like the same result set to be used in two displays that have a slightly different format.

One of my exposed filters is not being "remembered" from one display to the other, even though the other filter fields are.
When I navigate from one display to the other, the problematic exposed filter (a single checkbox) gets rechecked if it was unchecked.
It appears that the query is being re-run when I go from display to display.  I don't really want that to happen since I am using the same result set.  I figured the query only should get run when you hit the SUBMIT button, not change displays.

I have tried to use a number of the hook_views_xxx functions to set and reset my exposed_input array value for the filter field, but I can't seem to get anything to work.  I have also tried using the $_SESSION variable for the field to fix it, but no luck.

If I can understand what is supposed to happen with Views, I can keep trying to solve this myself, but I am really stuck and into this about 10 hours.

Edit your view displays, make sure the common exposed filters have the same Filter identifier.  You can find this when you click the filter, and in the "More" fieldset.


Views different image styles depending on URL I want get very close Views results, but image style should differ.
It should be done by using different URLs or Views arguments.
How I can reach that?

UPD: final solution:

/**
 * Return actual image_style of image depending on URL params.
 */
function _MYMODULE_image_style() {
  $allowed_image_styles = array('image_style_1', 'image_style_2');
  $params = drupal_get_query_parameters();
  if (isset($params['image_style']) && in_array($params['image_style'], $allowed_image_styles)) {
    $image_style = $params['image_style'];
  }
  return isset($image_style) ? $image_style : NULL;
}

/**
 * Implementation of hook_views_pre_execute().
 */
function MYMODULE_views_pre_execute(&$view) {
  if ($view->name == 'view_1' && $view->current_display == 'services_1') {
    $image_style = _mymodule_image_style();
    if ($image_style) {
      $field_name = 'field_vendor_logo';
      $view->display_handler->handlers['field'][$field_name]->options['settings']['image_style'] = $image_style; // <<< THIS IS the main part of solution
    }
  }
}

Create different ImageStyles, If the image field of the content type is field_image then you can use this code:

        $variables['theme_hook_suggestions'][]='THE_THEME_HOOK_SUGGESTION';
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $photo_field = $wrapper->field_image->value();
        $url = arg(1); // you can distinguish the address by arg(0),arg(1), ...
        if ($url == "URL1") {
                $variables['image'] = theme('image_style',
                     array(
                        'style_name' => 'STYLE1',
                        'path' => $photo_field['uri'],
                    )
                );
        } else if ($url == "URL2"){
                $variables['image'] = theme('image_style',
                     array(
                        'style_name' => 'STYLE2',
                        'path' => $photo_field['uri'],
                    )
                );
        }

Make sure to put such code hook_preprocess_node, and also this code is run when the correspondent content type is loaded. then in the THEME_HOOK page of the content type use $image variable to display the image.


How can I place $content in search results instead of $snippet? I'm using the Link module to display a field that links to an external site. $snippet places this link (along with other fields) in a paragraph. The fields have no separation and the link doesn't work. I'd like to place $content in search-result.tpl to remedy this but everything I've tried has given me an error.

Someone mentions $result here which may be what I need.

I tried <?php print $result['field_lipsum']; ?> but it gives me Notice: Undefined index: field_lipsum in include() . . .

How can I place $content in search results instead of $snippet?

Define yourtheme_preprocess_search_result in your theme's template.php file. Do something like this:

function yourtheme_preprocess_search_result(&$variables) {
  //$variables['result']['node'] should contain the entire node object
  $variables['content'] = $variables['result']['node']->body[LANGUAGE_NONE][0]['value'];
}

You should be able to use the variable $content inside search-result.tpl.php now.


Why this callback doesn't show all node form? This question is related to:
Custom module embedding existing node form

After dealing with returning existing node form via custom module (my_singnup module achieved with the big help of Clive) returning form has no custom field groups and custom fields.

function my_signup($node = FALSE) {
   if($node) {
     if($node->type == 'event') {
       module_load_include('inc', 'node', 'node.pages');
       global $user;
       $new_node = new stdClass;
       $new_node->type = 'signup_node_form';
       $new_node->language = LANGUAGE_NONE;
       $new_node->user = $user->uid;
       $new_node->name = (isset($user->name) ? $user->name : '');
       $form = drupal_get_form('signup_node_form', $new_node);
       return $form;
     }
   }
   return drupal_not_found();
}

signup_node_form was build via field UI (create new content type) and looks great when core node/add/signup. It has vertical tabs, validation etc.

I was expecting to get the same with mentioned code. Unfortunately it's not working. I'm getting just Drupal stuff vertical tab (Menu, Book, Version, Adress, Comments...) without my custom groups and fields.

The following line in your code is wrong.

$new_node->type = 'signup_node_form'

What you are setting as node type is really the form ID, not the content type ID. If you look at the code of node_add(), you will notice the executed code is the following one.

  $types = node_type_get_types();
  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE,
  );
  drupal_set_title(t('Create @name', array('@name' => $types[$type]->name)), PASS_THROUGH);
  $output = drupal_get_form($type . '_node_form', $node);

$type is the parameter the function gets.
If you look at the content type IDs used in Drupal, none of them contains the string "_node_form"; differently, node_add() would call drupal_get_form() passing something similar to "story_node_form_node_form" as form ID. As the modules that add fields to the node edit form check the content type of the node, it is probable they don't add fields for a content type they don't know. That is plausible, as differently it would mean that a taxonomy term field, for example, would be added to nodes for which it was not supposed to be added.


Why does 'Search Question' of the Answers module not show any results? The "Search Questions" view page which is provided by the Answers module does not show any results. I am pasting the typed question as it is yet it just shows "No questions match".

What could be the issue?

Edit: I did get the solution just now, I was trying other related modules Best Answer and Answers Userpoints and after enabling them the Search feature started working. Probably some other module which is mutual between them gets enabled and start working, But I could not figured it out, as the Answers module list was showing all dependency modules enabled prior to all this. Any way it start working.

Have a look at Comment #1 in issue 1619676, which states:

One hypothesis: have you run cron?
The way content gets indexed is during cron runs ... not immediately when new content is created.

It could well be that "in the meantime" cron was run, which would explain why "... the Search feature started working..." (as in your comment).
Disclosure; I'm a co-maintainer of the Answers module.


Why isn't there any output? $results = db_query("select nid from {taxonomy_index} where tid = :tid", array(':tid' => arg(2)));
foreach ($results as $result) {
  $node = node_load($result->nid);
  echo $node->title;
}

I put the code in page--taxonomy.tpl.php, but there is no result. Why?

The output of print_r($results) is the following one.

DatabaseStatementBase Object
(
    [dbh] => DatabaseConnection_mysql Object
        (
            [shutdownRegistered:protected] =>
            [target:protected] => default
            [key:protected] => default
            [logger:protected] =>
            [transactionLayers:protected] => Array
                (
                )

            [driverClasses:protected] => Array
                (
                    [SelectQuery] => SelectQuery
                )

            [statementClass:protected] => DatabaseStatementBase
            [transactionSupport:protected] => 1
            [transactionalDDLSupport:protected] =>
            [temporaryNameIndex:protected] => 0
            [connectionOptions:protected] => Array
                (
                    [database] =>
                    [username] =>
                    [password] =>
                    [host] =>
                    [port] =>
                    [driver] =>
                    [prefix] => Array
                        (
                            [default] =>
                        )

                )

            [schema:protected] =>
            [prefixes:protected] => Array
                (
                    [default] =>
                )

            [prefixSearch:protected] => Array
                (
                    [0] => {
                    [1] => }
                )

            [prefixReplace:protected] => Array
                (
                    [0] =>
                    [1] =>
                )

        )

    [queryString] => select nid from taxonomy_index where tid = :tid

Please confirm you got any value from arg(2) which is equivalent to term id(tid) .

Try this code

$result = db_select('taxonomy_index', 't')
  ->fields('t')
  ->condition('tid', arg(2), '=')
  ->execute()
  ->fetchAssoc();

$node = node_load($result->nid);

print_r($node);


Adding Facebook Like-button to the User menu in the top-right corner Do you think there is a way to make a Facebook Like-button appear in the User menu of Drupal 7, right besides the My Profile and Logout links?

UPDATE: I'd like to add the button for my site and the User menu seems to be the best place.

As an alternative to adding the like-button in the actual link items, maybe you should consider add it via a block or similar above/below your menu.

Checkout the Facebook social plugins integration module.


What are my pages called for adding blocks? I've searched for an answer, but cant find one. On my site I'm building I have 6 or seven main links/pages called things like Home, About us, Contacts, local issues, etc.

I want to add blocks to these pages individually, and I'm told when adding blocks that:

"Specify pages by using their paths. Enter one path per line. The '' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog. (front) is the front page."*

OK, so I can use 'front' (in tags) for my home page, and that worked - but what are the other pages called? What do i put in the box other than 'front' (in tags) to get a block on say my 'Contacts' page.

I am a real newbie, and still rather overwhelmed with Drupal, so please don't asume I understand much!

Thanks

Assuming that you want to show your block on your 'Contact' page.Now, have a look at your 'Contact' page URL, for example it can be http://example.com/?q=node/2 without pathauto module.
Now, lets create a block under that choose Only the listed pages then write node/2 in the field!

Now, save block and it should work.


Migrate nodes with special characters in title Given a source's title like

This "cool" & "neat" article's title has HTML entities

, is creating a title of

This &quot;cool&quot; &amp; &quot;neat&quot; article&#39;s title has
HTML entities

Must I create a process plugin to handle this?
My migration yml looks somewhat like this:

...
source:
...
    -
      name: title
      label: 'Title'
      selector: title
...
process:
  title: title
...

It looks like you will have to define a custom process plugin to do this - I can't find any plugin for it on this or this page.

There is a PHP function called htmlspecialchars_decode, which decodes all HTML special character entities, which you can probably use. It takes in a string and returns the decoded string. We also need to pass it the ENT_QUOTES flag for it to convert both double and single quotes.

So you could probably do something like:

namespace Drupal\YOUR_MODULE\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Decode HTML entities.
 *
 * @MigrateProcessPlugin(
 *   id = "decode_html_entities"
 * )
 */
class DecodeHtmlEntityString extends ProcessPluginBase {

  public function transform(string $value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    return htmlspecialchars_decode($value, ENT_QUOTES);
  }

}


D7 in sub directory - Not able to log in I have a Drupal site I need to show for portfolio reasons so I have installed it in a sub directory.

I have changed the rewritebase to /subdir

Initially without that change I was served the homepage just fine but no interior pages. With that change I was able to get deeper into this site but when I went to login the backend it loaded forever and spit out this error:

  Additional uncaught exception thrown while handling exception.

  Original

  PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT source FROM {url_alias} WHERE alias = :alias AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC; Array ( [:alias] => user [:language] => en [:language_none] => und ) in drupal_lookup_path() (line 176 of /home/content/k/c/l/name/html/fsubdir/includes/path.inc).

  Additional

  PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: 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); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => php [:db_insert_placeholder_2] => %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] => a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:284:"SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT source FROM {url_alias} WHERE alias = :alias AND language IN (:language, :language_none) ORDER BY language ASC, pid DESC; Array ( [:alias] =&gt; user [:language] =&gt; en [:language_none] =&gt; und ) ";s:9:"%function";s:20:"drupal_lookup_path()";s:5:"%file";s:61:"/home/content/k/c/l/name/html/subdir/includes/path.inc";s:5:"%line";i:176;s:14:"severity_level";i:3;} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://mydomain.com/subdir/?q=user [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 173.10.171.18 [:db_insert_placeholder_9] => 1354293470 ) in dblog_watchdog() (line 157 of /home/content/k/c/l/name/html/subdir/modules/dblog/dblog.module).

Can anyone point me in the right direction to get this resolved?

The server gone away error is an error that happens when the client cannot connect to the  database server, and it can happen because:

The client doesn't have the necessary privileges to access the database
There has been a timeout on the TCP/IP connection
The client is running on Windows, and the server dropped the connection, probably because a timeout

When I got that error on my sites was always because the credentials I used in the settings.php file were wrong.
The other reason to get that error is that the value of max_allowed_packet is too small.


Show/Hide regions in Omega subtheme I am using Drupal 7 and I am creating an Omega subtheme.

In my case I want a page without left and right sidebars. But when I inspect the page.tpl.php from alpha theme it contains only code for printing attributes, content and footer regions

Here is my page.tpl.php

print $attributes;
  if (isset($page['header']))

   print render($page['header']);

  endif;

 if (isset($page['content']))

    print render($page['content']);

 endif;

  if (isset($page['footer']))

     print render($page['footer'])

  endif;

In the above snipped I don't find any option to show/hide sidebars as we used to do like in Garland theme.

You can create multiple page layouts using delta modules and use the same for required page.


Turn numerical filter into ON/OFF I'm using uc_best_sellers to count the number of times a product has been sold.

The module provides a numeric views filter like this:

I'd like to have a view like this:

A product would be a best seller if it was sold more than 50 times (in my case).

What would I need to achieve this filtering style?

Instead of using exposed filters for this, I think it will be easier to make separate views displays with overridden filters. Then either use quicktabs to display the different filter options, or make each one a page display with a path and output the links to the filter displays in the headers.


Multistep/wizard forms I'm trying to create a multistep/wizard form for Drupal 8.

User fills in a first name, last name fields
Clicks on the next button
Fills out more information
Clicks on the submit button

There are currently many resources devoted to multistep or wizard forms for Drupal 7 like this one and this.

On the other hand, I've had some trouble figuring out which is "Drupal" way of creating Drupal 8 multistep/wizard forms.

I did some research and figured there are several approaches:

Store values with the new configuration system
Use the wizard form interface (not in core yet)
Store values with drupal session object (not sure if that exists or not)

Are those valid approaches for Drupal 8?

The easiest way to do this is to use $form_state. In your formBuild() method, you have an if/else or switch based on something like $form_state['step'] and display different form elements. Then you either have the same in your submit callback or have multiple submit callbacks, that do something to an object in $form_state that you're building, change the step and set the $form_state['rebuild'] flag to TRUE.

There are a few downsides to that approach, which is why (among other reasons) the ctools form wizard was created. It can get complicated if you have multiple steps and have to define all of that in a single form function/class and everything happens in POST requests.

What the ctools form wizard does is group multiple, separate forms together and control the navigation from one to the other. You also use the ctools object cache to store your object instead of $form_state, because that is no longer shared across your forms.

While that system doesn't exist yet, the ctools object cache has been ported to 8.x and is now called user tempstore, available as a service: \Drupal::service('user.private_tempstore') (before 8.0-beta8 called user.tempstore). This is a layer on top of the expirable key value store that introduces ownership of stored data in there. So this is what powers the well known message in views that a different user is currently editing that view and it's locked for that reason. Another advantage over using $_SESSION for that is that your data only has to be loaded when needed, when you are editing 3 views, then using $_SESSION would mean that you have to load and carry them around on every single page request.

If you don't need that, then you could rely on the session or also directly put it in an expirable key value store ($form_state is stored there now as well, not a pseudo-cache as it was in 7.x).

The configuration system however isn't a good match. That is not meant for per-user content (or content at all) as it doesn't really scale to store thousands or tens of thousands of records and might make some assumptions to pre-load everything it might need on a given page request (not yet, but there is an issue to make that happen)


Using Infinite Scroll module with Views paging: Detrimental to Google SEO? I love using the Infinite Scroll module with Views. But does Google limit indexing to to only those first bunch of nodes which appear in the view?

I'm guessing that when using a regular pager, Google will dig deeper and index all subsequent pages in the view. But what does it do when ajax is used to move forward to the next batch of nodes as is the case with Infinite Scroll?

No it's not detrimental (well, not in the way you're thinking at least) - the standard pager links are hidden with infinite scroll, but still in the markup, so there's no problem from that perspective. Google will find and visit the subsequent pages as with a normal views pager.

The only question is whether Google apply some sort of penalty to the pages linked to from those hidden links. But that's something you'd need to get out of Google :)