When should I use Backdrop CMS rather than Drupal 8? From what I've heard, Backdrop is basically an alternative to Drupal 8.

Is deciding which one to use simply a matter of preference and ideology, or are there specific use cases for each?
If I'm upgrading from 7, how do I decide which way to go?

Backdrop CMS is a good choice if:

You are currently spending a lot of time managing your configuration using Features module. Backdrop includes built-in Configuration Management tools that allow you to deploy configuration across environments using JSON files, which should save a lot of time compared to Features.
Your needs are met by the current selection of Backdrop Contributed modules or you are capable of porting modules to Backdrop (it takes a few hours per module generally speaking). References from: Lullabot, Tag1, and Backdrop documentation.
You are familiar with Drupal 7 code and would like to transfer that knowledge to a newer system that will be supported in the future. Backdrop code is nearly identical in concepts, though there are several new additions to manage configuration. Drupal 8's code base is significantly different in many fundamental concepts.
You have an existing Drupal 7 site that you would like to upgrade. Backdrop includes an upgrade path (via update.php) that can upgrade your existing Drupal 7 site to Backdrop. Drupal 8 does not include an upgrade path from Drupal 7; the plan is to provide migration tools to move from Drupal 7, but at this point, it is not yet working. Backdrop does not yet have a port of the Migrate module, but it probably will in the future (since porting modules from Drupal 7 is fairly trivial).
You want to upgrade/build a site right away. Backdrop 1.0 had been out for about 2 months now and is stable. Drupal 8 may be coming out some time later this year (though we can only estimate the date). Drupal 8 does not yet support upgrades even between beta versions, so if you build a site on it now, you won't be able to upgrade it when the final version comes out.

Other features that Backdrop includes:

Backdrop is slightly faster than Drupal 7 out of box because of it's lighter core. Generally it's about the same speed as D7 but since D8 is slower than D7, Backdrop is faster than D8.
Backdrop has a built-in Panels-like module (Layout) that replaces the old Block system. Blocks are given new powers like contextual information, advanced conditional selection, multiple instances, control over markup, and config-based settings.
Updated libraries (e.g. new jQuery versions).
Responsive, HTML5 elements, and better mobile support out of the box.
All the other features listed on the Backdrop CMS homepage.


How to position elements within views? I have a view which is displaying a content type with text and image (1 column grid). Right now, the image is positioned under the text. Is it possible to position the image to the right?

Is this possible without using custom css? Or if it isn't, which css file should i be looking for? (Haven't done custom css yet)

The best way to accomplish a floating image is to have some custom css: http://css.maxdesign.com.au/floatutorial/

Anyway, the drupal module Media can help you alot. Please follow this complete and well explained article: http://purewebmedia.biz/articles/2013-01-10/how-insert-and-float-inline-images-drupal-7.


Products with 2 different titles Is it possible for a product to have 2 different titles. One would be displayed on full product page and the other shorter one on a grid product catalog.

Yes, a product can have two different titles.

You can add fields to products on the product type admin screen (/admin/commerce/config/product-types) by choosing the appropriate product type and selecting manage fields.  I would add a text (plain) field and call it short name or something like that.

Then, you can configure the display settings for the product type to hide the short name field (disable it), ensuring only the full title is shown on the product page.

Then, in your grid product catalog, configure your view (or whatever you use to make the catalog) to show only the short name, not the title field.


Parsing value of a field from content to a webform field I have a content type named apartments. When i view a content of content type apartments i will give a button for requesting a quote. When clicked on that button it takes to a webform and by default a field value should be filled by that contents title. Please let me know the process of parsing a fields value to a webform field.

Try using the webform node value module

  Fill a Webform field with the value of a node field.


CTools CSS cache error While viewing my Status report, I came across this error under the CTools CSS Cache header:

  The CTools CSS cache directory, ctools/css could not be created due to
  a misconfigured files directory. Please ensure that the files
  directory is correctly configured and that the webserver has
  permission to create directories.

How do I fix this?

That directory must be writable by the usre that runs the web server (apache, for example).

So you have to:

go to admin/config/media/file-system and check the path of public files (may be sites/default/files)
check which user runs web server (on Ubuntu could be "www-data", on centos/fedora/redhat could be "apache")
using a terminal go to the document root of drupal and set the owner of the directory:

  sudo chown -R www-data:www-data sites/default/files (or apache:apache)

if you couldn't use a terminal, use the ftp client or contact your hosting provider

PS: this instruction works on *nix servers


how to retrieve field collection data associated with a node I have an event node which contains a reference to a gallery field collection. If I do a dump of the $variables variable, I can find this

$variables -> field_gallery_image['und'][0]['value']

but I don't know where to use that value to do a table look up to actually find the data in the field collection. I was able to find that id number in the field_collection_item table, and then was able to find that id in the field_data_field_image table (I have an image field), but I'm not sure where to go from here.

I believe you are looking for field_collection_item_load or field_collection_item_load_multiple function both are in field_collection.module


Can I set "$conf["image_allow_insecure_derivatives"] = TRUE" in settings.php file? Hi my multisite site structure is, I have followed sub directory multisite mechanism

So in hosting server the url will be

http://123abc.hostring.com/mysitename1
http://123abc.hostring.com/mysitename2

I have pointed and configured with production url as,

www.mysitename1.com (http://123abc.hostring.com/mysitename1)
www.mysitename2.com (http://123abc.hostring.com/mysitename2)

Everything working fine. But the private (Amazon S3) image styles cannot be created.

private file link
http://www.mysitename1.com/system/files/styles/stylename/s3/myimage.jpg

It shows "Access Denied" error.

When I added below line in settings.php file the images styles has been created perfectly.

$conf["image_allow_insecure_derivatives"] = TRUE;

But I believe there are some security issues in that. Do I need to follow any other configuration instead of this?

Please advice.

It is not a critical security issue perse. But it can expose your site to DDOS attacks. So you can fairly enable this setting and you can disable it if you face any DDOS attacks that targets your site.

You can find more about this issue on https://www.drupal.org/SA-CORE-2013-002

  Drupal core's Image module allows for the on-demand generation of
  image derivatives. This capability can be abused by requesting a large
  number of new derivatives which can fill up the server disk space, and
  which can cause a very high CPU load. Either of these effects may lead
  to the site becoming unavailable or unresponsive.


How to to get the prices centered in the node:teaser with commerce price savings formatter? I am pretty new to drupal and I have a problem with formatting the price in my drupal shop. I am using commerce sale price -module and commerce price savings formatter -module.

In the default view, the price shows ok, in the right position. But in the view (node:teaser) it shows the prices in the wrong position. I have tried everything to get the prices centered (modifying the css), but they are still on right side all the time. I would also like to remove the line above the price if its possible.

Here is the link to my shop: http://www.oladevelopment.fi/mifuko/content/home-shop

Ant ideas on how I can get the prices shown in the way I want?

Add this in your CSS:

table.commerce-price-savings-formatter-prices{
width: 100%;
}

Also, you can add:

.commerce-price-savings-formatter-price .price-amount{
display: block;
padding-top: 5px;
}

Prices looks much better with this.

If width:100% doesn't work try to use width:100% !important; because width is already defined in module's theme.

To remove line above price add this to your CSS:

table.commerce-price-savings-formatter-prices tbody{
border-top:0;
}

Also, if it doesn't work, use border-top:0 !important; instead border-top:0;

To minimize the space between prices add to CSS:

table.commerce-price-savings-formatter-prices-down{
margin: 0 auto;
width: 50%;
}

Important part here is width: 50%;, change this percent to see which space you want to have, the more percent is the more space will be between prices. Again, use !important if doesn't work.

You can also add this to your CSS to make prices look better (to make it equal at the bottom edge):

table.commerce-price-savings-formatter-prices-down tr td{
vertical-align: bottom;
}

Don't forget to clear cache.


Make all Quicktabs closed by default Is there any way to set all of the tabs on Quicktabs to closed or inactive by default?

I would like, that if I visit the page then the first Quicktab isn't open by default. In this inherited site there are images and content underneath this open tab that I would like visible instead of an opened tab.

Would I have to implement something using JavaScript or is there a better option beside Quicktabs?

Quicktabs Version: 7.x-3.8 | Drupal Version: 7.57

I think that you might need to add some jQuery to your theme.

Here is a way to do it.

jQuery(document).ready(function(){
    jQuery("#id-of-my-custom-block h3:first").trigger('click');
});


How to call a view in a twig.template not page I don't find good info on how to call for an existing view
in a particular twig.template (NOT the PAGE.HTML.TWIG!!!!).

The systemname of my view is this: testfeest

So I find sollutions online and tried them:

{{ testfeest }} not working
{{ content.testfeest }} not working
{{ view.testfeest }} also not working

Keep in mind that:

I don't want to create a extra block of region for this
The view will be placed not in the page template but a node template

Hope somebody can help me...
Thanks for reading.
Kristof

One very simple method is to install the Twig Tweak module and use:

{{ drupal_view('testfeest', 'display_id') }}


How do I link an image field to an pdf file I have a challenge in linking my image to a pdf file. I have a content type with 2 fields, image field which will contain the cover picture and an attachment field which is file of type pdf.

In my view am trying to link an image to attachment so that when a user clicks on the image it open a pdf file.

In some instances where am just using description to link to a pdf file, this what I have put in my Global PHP(Description) output code in my view.
nid, 'filename.pdf');
?>
As soon as click on the description my pdf opens. works fine

But I need to do the same thing with my image, to just click on image then should open my pdf file. Any idea???

Hope this will help you,

In Drupal 7 you can use VIEWS Rewrite results to link an IMAGE to a PDF file.

Steps:

In PDF field, exclude it and change the format to "URL of file"

Go to your VIEW -> Image field and under Link image to select NOTHING
And then go to Rewrite results and check Output this field as a
link and give the path of the PDF file.

You can also use TOKENS by using Replacement patterns for PDF file  path name


search block form not accepting special characters in drupal 7 If I search with any special character in drupal default search block form it returns error message like "You must include at least one positive keyword with characters or more.".after i do search with letters or numbers it does not bring results.shows same error.the form has been submitted but value does not change.
Any help appreciated..

The error has nothing to do with special characters (e.g. "$", "@"). It pertains to the length of your keywords. By default, Drupal core search restricts minimum keyword size to 3; any query less than 3 characters will trigger the error (e.g. "$9").

If you really need search to include 2/1 character queries, the search settings in /admin/config/search/settings under the Minimum word length to index option will allow you to do this.

Note: This will expand out the size of your search index (catching common words like "an" & "a"). If you have a large site with thousands of nodes you shouldn't do this.


How do I add images in pager for views nivo slider? I am using Views Nivo Slider for displaying a slideshow of banner images on my site. And i wish to show the pager in the form of images. I tried using Image pager in views slideshow and it worked there. But there are no settings specific to adding an image preset for it. I was able to add numbers instead of bullet. Please suggest a way to add image particularly.

The module(views Nivo slider) does not support using images as pagers by default. If you want such functionality you would have to write a custom module to extend the views nivo slider module. So I would advise you to go back to using the views slideshow module to achieve that. Even the original plugin created by nivo slider itself does not support such functionality. See demo site


How do I sort by taxonomy term parent, and then by post date? I have the following taxonomy structure:

Locations

Group 1

Location 1
Location 2

Group 2

Location 3
Location 4

Group 3

Location 5
Location 6

Pieces of content are being posted to the site, and each piece of content has a location and a post date associated with it.  When the view is displayed, how can the results be grouped by parent term ID (group 1-3), and then grouped by post date within each group?

I've tried using the "taxonomy term: name" sort criterion, but then adding the "content: post-date" criterion seems to have no effect.

I think I found a way to do this--I added the "content: taxonomy terms on node" and "taxonomy term: parent term" relationships to the view.

The key is the "taxonomy term: name" criterion has a checkbox where I selected "parent", which appears only after you add the relationship.  I added the post-date sort criteria after that, and it appears to be working the way I want.


How can I simplify the use of flags with Views Bulk Operations? I have an administrative display (made with views) that lists content that is pending approval.

In the case of my site, approval means flagging with the approval_for_pub flag (which triggers a custom rule).

VBO allows nodes to be flagged/unflagged all at once by clicking a handy button:

However, upon clicking this button, by default it shows all possible flags and the flag/unflag option:

This is a problem on my site because some of the people responsible for approval get confused by the names of the flags and select the wrong option.  So, what I would like to do is create a VBO option that, when the button is pressed, automatically flags all applicable content with the approval_for_pub flag.

How can I approach this?

It seems like a small detail, but this step happens several times a day, so the chance of making a mistake is quite high.

Instead of using the "Flag (or unflag) a node" action directly, create new a rules component and show it in your administrative view.

Navigate to Configuration » Workflow » Rules » Components
Click on Add new component , choose Rule from the components plugin drop-down menu.
Choose a name (e.g. Approve), add a parameter with the type node.
Add a condition, choose Node is flagged from the drop-down menu.
Choose the appropriate flag, select the node-parameter for the node, choose site:current-user for the user on whose behalf the flagging-action will be performed, select negate such that the condition will evaluate to true when the node is not flagged.
Add an action, choose Flag a node from the drop-down menu.
Choose the appropriate flag, select the node-parameter for the node, choose site:current-user for the user on whose behalf the flagging-action will be performed.

Edit your administrative view, configure bulk operations such that the Approve operation is shown instead of the Flag (or unflag) a node


Redirect incoming traffic to homepage How can I set Drupal 7 so that all incoming traffic is redirected to the homepage? I need to ensure all visitors go to the homepage, even if they click a link on some other site that links to example.com/section/node-1

You could do this easier in your .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/$
RewriteRule $ / [R=302,L]

Put this at the bottom of your .htaccess file and you're set.


Multiple node reference on same node In Drupal 6, I have the "Player" content type that has a field reference to the "Team" content type.
I want to make content type for sports match.

It has two referencing field for teams:

field_host_team
field_guest_team

I want to make a relationship for players that played, but I want the users to be able to choose only players that have a reference to the selected (home/guest) team such as:

field_host_players (only players from team selected in field_host_team)
field_guest_players (only players from team selected in field_guest_team)

Do you have any idea on how to do this?

You can have a node reference for players. In node reference you can limit the list of options to a view. You can make a view that has a custom argument that looks up players from the home and away teams already attached to the node.

You might get a better answer for this, but throwing this one out there in the few mins I have.


Theming image.html.twig What name do I have to give to my image.html.twig so the template only being used in content type "project" because I need to add class to an <img> tag.
I already tried

image--node--field-afbeeldingen--project.html.twig
image--node--field-afbeeldingen.html.twig

I'm not sure about overriding the <img> tag itself, but for your approach I would recommend overriding the field template. Assuming your field is named field_afbeeldingen, you can create a template called field--field-afbeeldingen.html.twig.

Within there, you could manually render your <img> tag as needed, with whatever additional classes required.


Get visibility of a block I've found plenty of posts about changing the visibility of a block programatically.

My problem is the opposite. Given a block's ID/delta, how do I find out if it should be displayed at the current path?

I have a field collection that allows you to append a block using the Block Reference module (I preprocess the field collection and use my own template, so the logic has been taken away from the Block Reference module). It works, but I only want it to kick in if the "Show block on specific pages" rule says that block should be displayed.

To test the block style visibility rules, you can use drupal_match_path

For example, in core: block_block_list_alter

  Checks the page, user role, and user-specific visibility settings. Removes the block if the visibility conditions are not met.


How to find correct hook/preprocessor Aside from searching the Drupal api, is there a module or an easy way that will allow you to find out which hook or function you need to use to interact with pages in your site?

For example, I am looking to force certain values in a webform setup, to which I was able to use mymodule_form_webform_configure_form_alter to change the submission limit, status etc. But I was able to do this because I found the starting point for the script, now I am looking to force a default 'email to' value in the setup, but I don't know what function I need to use

What's the best way of finding out the best hook (etc..) for the job

Kind regards

I find the Devel Themer module to be very helpful.

From the description:

  popup display shows which theme function/template outputted the HTML, and what other files could have done so.


Drupal Migrate - Link fields from an XML Source I am using the Migrate (v7.x-2.2) module to migrate records from an XML source into Drupal 7.9.

I've also installed the popular link field module (v7.x-dev).

So far, in my migration class, all built-in fields work well during the migration, but I have not figured out how to migrate link fields from my XML source with their title.

I have two XML source fields (xpaths):

/record/organization/name  <-- I want to migrate this into the link title
/record/organization/url   <-- I want to migrate this into the link url

I am able to get the URL to import using this line in my Migration file (had to use link v7.x-dev module, not 7.x-1.0):

   $this->addFieldMapping('field_organization', 'organization_url')->xpath('/record/organization/url');

...but I have no idea how to inject the /record/organization/name into the title argument:

   $this->addFieldMapping('field_organization', 'organization_url')->xpath('/record/organization/url')->arguments(array('title' => [WHAT GOES HERE?]);

So, the solution is to not use arguments, but instead, fix up the record using the prepare() method:

In the constructor:

//IMPORTANT - DO this source mapping without a destination mapping (NULL)
$this->addFieldMapping(NULL, 'organization_title')->xpath('/record/organization/title');

$this->addFieldMapping('field_organization', 'organization_url')->xpath('/record/organization/url');

Then, create a method named prepare():

function prepare($node, $rec) {
      $node->field_organization[LANGUAGE_NONE][0]['title'] = $rec->organization_title;
}

As of today (Nov 30, 2011), you must have the 7.x-dev version of the link module installed, not the "stable" 1.0 version, in order for link fields to work at all!

Whew!


How to exclude page from Redis cache? I'm using Redis and need one dynamic page to be excluded from being cached. How can I do that?

Not sure how you are generating this dynamic page, but somewhere in the mix, you could put something along the lines of:

drupal_set_header('Cache-Control', 'public, max-age=0');       // set max age to 0
drupal_set_header('Expires', 'Sun, 18 Dec 1983 02:28:00 GMT'); // some date in the distant past

before any other output, eg, at the top/start of your page's menu callback or in right before you select its custom template if it has one.

If this doesn't work, a quick hack would be to do a drupal_set_message('Welcome to my dynamic page'); which would cause drupal's core functions to try not to cache the page :)


Url Path Alias is not working with the "raw value from URL contextual filter" I could really use some help with this one. Long story short, I have a contextual filter which pulls the taxonomy term from the url (2nd position).

For example: if I'm at walldamp/drupal/acoustics, it will pull all the nodes with the tag "acoustics".

Here's the problem: Drupal doesn't read path alias's. The actual address for walldamp/drupal/acoustics, is something like walldamp/node/59. So if I have an article tagged 59, it works.

I do not want to change all my tag's to the node number, because this needs to be really user friendly. How can I get my contextual filter to read the url displayed, or is there another work around?

Thank you.

How have your configured your contextual filter? I have the following configuration and it's working fine for me:

Contextual filters: Has taxonomy term ID
You also need to specify validation criteria for this filter, my setting is:

a) Specify validation criteria = Taxonomy Term
b) Select the correct vocabulary.
c) Set Filter value type to Term name converted to term ID
Create a relationshiop of Content: Taxonomy terms on node

a) Select the correct vocabulary.
b) Set Require this relationship to true

You may also wan't to use Has taxonomy term ID width depth if you have nested terms in your vocabulary.


Same CCK field in one content type I have a content type named "school;" this content type has the "teacher" CCK field, but the number of teachers is not same for any school.
I need a thing like "add new teacher" button, which can be used to a new "teacher" CCK field.
Does anyone know a module to do this?

School needs to have a nodereference field pointing to teacher. Then, as tim.plunkett said, you need to make the number of teachers node reference field to unlimited.
Same as the one detailed here, but the number of values set to unlimited.


How do I create menu link icons? I noticed that when I added a new menu link, an icon is now show like groups, events, etc. How do I add an icon for that menu link item?

You can use menu icons module to generate icon for the menu item.

  This module allows you to upload an image in the menu-item's
  configuration form.

  After uploading the image, the icon data will be added to the menu
  link's options array.

  When a menu link is goes through the theme layer, it will receive an
  extra class which by default is used to attach the images as a
  background image to the corresponding menu item.


Manual about modules confusing me I'm reading in Apress' Definitive guide to Drupal 7 and I'm trying to understand what they're saying. For those who have the book, on page 404 paragraph it says - and I quote - "Every path ultimately matches up to a menu item with a page callback function that has chief responsibility for displaying the page at that path."

But aren't there paths that don't match up to menu items? Or are menu items in this content different things to begin with? And menu items containing functions? How do menu items contain functions?

Maybe The Definitive Guide is a confusing book and there are better resources for understanding how module development works? (I've searched the web for many resources already and they've all been just as confusing as Apress's)

I have the book, but page 404 does not include the quote in mine (the beginning paragraph is "The switch statement does...", so I cannot interpret the exact context of the quote.  In general, every page is assigned a path and drupal determines the display from its 'menu' of path options.  Think of the displayed menus as a subset of the available options in drupal's list.

Drupal stores information about each site in the database and callback functions are associated with the each master menu option.  When  a URL is requested, it queries the database, finds the associated function and executes it.

I found parts of 'The Definitive Guide...' confusing to begin with too, but it is actually pretty good overview and quite useful.  The problem is that Drupal is very large and a complex system to get your head around at first. The learning curve seems enormous at first (I know), but soon parts begin to fall into place and you begin to "GET IT".

This site is a great place to expand your understanding and begin to put it together.  Your question was well written (clear) and there are plenty of people here to answer (although traffic is slow this week with the holidays).


Where are hooks stored/cached? I have a hook_form_alter in a module, and it should be firing, but it appears it's not. I've cleared caches and rebuilt the registry. Is there someplace in the database or somewhere else where I can see if my hook is registed? FWIW here is my hook:

/**
 * Implements hook_form_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
}

The hook implementations ARE cached inside the database.. this is why it's necessary to clear cache in order for a newly implemented hook to fire.

Taking a look, inside the cache_bootstrap table, there is a row with cid value of module_implements, and it's data value is a very large serialized string.  When unserialized, it is an array of the form

  'hook_name' => array('module1', 'module2', 'module3', ...)

The hook names have the hook_ beginning lopped off, so hook_block_info() will appear as block_info. I believe the value is the list of modules which implement that hook, so...

  'block_info' => array('views', 'webform', 'my_module')

Means that the following hooks are registered and should be fired:

views_block_info()
webform_block_info()
my_module_block_info()


Views page list of all content grouped by taxonomy term I have created a view in Drupal 7 that displays all nodes that contain a particular taxonomy vocabulary. The view contains a page in an unformatted list format set to show content | teaser. All I am trying to do is to group the list by the specific taxonomy term. Here is an example of what I'm talking about:

TERM A
Title
Teaser

Title
Teaser

TERM B
Title
Teaser

I've scoured the web and have only found solutions for displaying EITHER taxonomy terms OR content, but not both. Am I missing something? Is this not possible with Views?

Thank you so much to whomever can help, I've been agonizing over this for days.

-Dave

Here's how you would go about doing this:

Include the tag you want to group by in your fields (see map)
Click on your format settings. (see map)
Set grouping field to the tag.
Set exclude from display to true in your tag field.

That should get you to where you want to be.

Here's a map of where 1 and 2 would be located.


How to prevent scan by drupalxray A website called Drupal X-Ray can detect a Drupal site's Drupal version and modules in use. So if I don't want others to find that information, what can I do?

You can look at deploying a site and scrubbing it of files like CHANGELOG.txt/INSTALL.txt automatically. Other things, like removing the meta generator tag in the head also can hide that it is Drupal, but nothing is bulletproof. For example, typing 'Drupal' in the browser devtools window is another way to tell if a site is Drupal or not (in most cases). You could also try banning requests originating from that domain/service at the server level.


drupal_goto overlay page I'm using drupal_goto to redirect users on login.
Administrators and 'other' are redirected to the dashboard. All works fine but I want to redirect to the dashboard in an administrative overlay.
(Path = #overlay=nl/admin/dashboard)
Chrome and Firefox alter the # to %23 so I get a page not found error.

Can this be done?

Here is the function:

/**
 * Implements hook_user_login().
 */
function myModule_user_login(&$edit, $account) {
  $user_roles = array_intersect(array('other', 'administrator'), array_values($account->roles));
  if (!empty($user_roles)) {
    drupal_goto('admin/dashboard');
  } else {
    drupal_goto('');
  }
}

You need to pass a fragment to drupal_goto() as an option like so:

$options = array('fragment' => 'nl/admin/overlay');
drupal_goto('some-url', $options);

Reference for this can be found on the url() docs page (the docs page for drupal_goto() actually refers you to there as well).


Really strange WSOD after submitting a form/add to cart I've read everywhere, but just can't seem to find an answer for my particular problem.

Basically when I click 'add to cart', or 'login'.  I get a white screen of death with absolutely no errors.  Error reporting is on.

For example:

I am on a product page mydomain.com/product
I click add to cart
I am not redirected to the cart page, it just redirects back to mydomain.com/product except the page is completely blank
The form still submits successfully however.  If I navigate to the cart page the item has been successfully added.
After I have viewed the cart page, by manually navigating to it in the browser.  Adding any other item to my cart works as expected.

A similar issue happens when I login to the backend.  At first I get a WSOD, but if I refresh the page it works fine.

Now here is where it gets really damn strange.

I suspected that perhaps it was a cookie issue, so after I logged in I decided to delete the session cookies from my browser.  I was hoping that I could replicate the issue once more.  However, the problem had disappeared, no WSOD even though I had deleted my cookies.

The next day the issue returned.  I logged into the backend and the issue disappeared.  To confirm that the issue had disappeared entirely, not just for me.  I asked a friend on a computer in another building to visit the site and attempt to add an item to cart.  He said it worked fine.

Every morning the issue returns predictably and only when I login to the backend does the issue disappear for everybody for the entire day until the next day.

Has anyone experienced similar issues or have any idea what this could be?  I'm on drupal 6.26 using ubercart

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

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

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

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

To solve this problem:

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


Hook_search_execute(); i am using this hook in my custom module but getting a fatal error

  Fatal error: Cannot use object of type stdClass as array in
  C:\wamp\www\bid\includes\common.inc on line 5901

Anyone can help???

Below is my code, I have two conditions in it. In the second condition I want to search with taxonomy index because I have added a filter contains taxonomy parent term.

/**
 * Implements hook_search_execute
 * Override core node_search_execute here with custom implementation
 * Basically a clone of node_search_execute, but with limit variable available
 * See mymodule_module_implements_alter
 */
   function mymodule_search_execute($keys = NULL, $conditions = NULL) {
 // Add new limit conf variable
   $limit = variable_get('search_result_limit', 10);
 // Build matching conditions
  $prnt = (isset($_REQUEST['prnt'])) ? $_REQUEST['prnt'] : 'none';
  $site = (isset($_REQUEST['chld'])) ? $_REQUEST['chld'] : 'none';

  $query = db_select('search_index', 'i', array('target' => 'slave'))->extend('SearchQuery')->extend('PagerDefault');
    if (($prnt != 'none' && $site!= 'none') || ($prnt = 'none' && $site!= 'none')) {

        $query->leftjoin('node', 'n', 'n.nid = i.sid');
        $query->leftjoin('field_data_field_category', 'fdfc', ' fdfc.entity_id = i.sid ');
        $query->leftjoin('taxonomy_term_data', 'txd', 'txd.tid = fdfc.field_category_tid');
        $query->condition('txd.name', $site, '=');
    }

    if ($prnt != 'none' && $site = 'none') {

        $query= db_select('taxonomy_index', 'ti');
        $query->leftjoin('node', 'n', 'n.nid = ti.nid');
        $query->leftjoin('taxonomy_term_data', 'txd', 'txd.tid = ti.tid');
        $query->leftjoin('taxonomy_term_hierarchy', 'tth', 'tth.tid=txd.tid');
        $query->condition('tth.parent', '$prnt', '=');

    }

   $query->join('node', 'n', 'n.nid = i.sid');
   $query
         ->condition('n.status', 1)
         ->addTag('node_access')
         ->searchExpression($keys, 'node');

   // Insert special keywords.
   $query->setOption('type', 'n.type');
   $query->setOption('language', 'n.language');
   if ($query->setOption('term', 'ti.tid')) {
   $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
 }
  // Only continue if the first pass query matches.
 if (!$query->executeFirstPass()) {
  return array();
  }

 // Add the ranking expressions.
  _node_rankings($query);

// Load results, use limit variable
  $find = $query
   ->limit($limit)
   ->execute();
 $results = array();
 foreach ($find as $item) {
  // Render the node.
  $node = node_load($item->sid);
  $build = node_view($node, 'search_result');
  unset($build['#theme']);
  $node->rendered = drupal_render($build);

  // Fetch comments for snippet.
  $node->rendered .= ' ' . module_invoke('comment', 'node_update_index', $node);

  $extra = module_invoke_all('node_search_result', $node);

   $uri = entity_uri('node', $node);
   $results[] = array(
  'link' => url($uri['path'], array_merge($uri['options'], array('absolute' => TRUE))),
  'type' => check_plain(node_type_get_name($node)),
  'title' => $node->title,
  'user' => theme('username', array('account' => $node)),
  'date' => $node->changed,
  'node' => $node,
  'extra' => $extra,
  'score' => $item->calculated_score,
  'snippet' => search_excerpt($keys, $node->rendered),
  'language' => entity_language('node', $node),
 );
}
  return $results;
}

I don't question that the suggested answer (from NishantP) might answer the question. But the "Goto ... & open taxonomy.module ..." looks like hacking this module. If you just do that, then be prepared for the issue potentially coming back in the next module upgrade (because such upgrade might wipe out your edit).

As an alternative, how about filing an issue for this module (if such issue doesn't exist already), and attach a patch to it corresponding to the suggested edit (hack). It might (and probably will) get accepted to be committed to the module in the next reease of it). From then on no more issue with future upgrades of that module. And if it doesn't get accepted, you can still use that same patch to re-apply in further module upgrades (assuming you don't have to re-roll them then).

Edit: looks like NishantP's answer is no longer there (deleted?). Not sure (yet) if that implies that I should now also delete "my" answer. Since I'm sure there was something in it like that "Goto ... & open taxonomy.module ...", I'll leave my answer here for now, just in case anybody else ever has similar hacking-suggestions ...


Changing a filter in a view without modifying the filter clone? I duplicated a block from view using clone display, but when I change the language on the block cloned filter, the filter is changed in the master view also. How to avoid this? I need 3 blocks, the block to master the English language and the other 2 blocks to English and Spanish.

Thank you

When you're changing a filter, before you apply there's a dropdown box. It's probably set to "All displays (except overridden)" by default. Before you hit Save, change that All Displays to "This display only"


View test result of BrowserTestBase based test? How can I setup my Drupal config to be able to view the results of failed tests using the new BrowserTestBase class in 8.2.x?

I don't see any files generated and the phpunit.xml config does not seem to be getting respected:

<!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/var/www/testing" />

The command I am using is:

vendor/bin/phpunit -c core/phpunit.xml --group tvi

I have some failing tests but I can't see what the test sees.

Figured it out. Before calling parent::setUp(), I set:

$this->htmlOutputEnabled = true;


How to prevent entering a time-slot that is already taken when using the Calendar module? I have installed and enabled the Calendar module. I have noticed that this allows multiple events for the same time slots. It means if event 1 is on Aug 12th from 11-12, I can still enter the same time slot for event 2.

In this case, how can I apply a logic so it complains that if the time-slots already taken?

I'm not aware of any way to use the Calendar module for this. However, you may want to look at this set of modules (with an official D7 release) that may help to implement the logic you are trying to implement:

Availability Calendars (Reported installs: 2.061 sites).

  ... allows you to add an availability calendar to entities. Example use cases are tourist accommodation, e.g. bed and breakfast, holiday homes or self catered apartments, and car or motor bike rental.

  An availability calendar shows your customers at what dates your accommodation is still available and at what dates it is already booked.

Rooms (Reported installs: 1.575 sites).

  ... is a booking and room management solution for hotels, vacation rentals and B&Bs.

Its module page also mentions some related modules you may want to look at, such as:

Rooms Package: Define special offers for bookings.
Rooms Availability Constraints - Allows admins to define availability constraints such as the minimum period of a booking.
Rooms Views- Provides a "Rooms availability" filter and a "Booking form" field to improve the Views integration for Rooms.

MERCI (Reported installs: 441 sites).

  ... can extend any content type into a list of unique reservable items (like studios) or buckets of interchangeable items (like DV cameras). We followed the approach used by Organic Groups, Feed API, and Scheduler and added MERCI's configuration to the Edit tab of those content types.

Resource Conflict (Reported installs: 329 sites).

  ... allows for users to book resources for use during events. For example, a student can book a microscope for use within their lab.

Simple Reservation (Reported installs: 202 sites).

  ... provides a simple and easy way to reserve items which can be created by the administrator. Examples for it's usage can be hotel rooms, boats, cars, airplanes, basically anything you can think of which can be reserved by one individual.

  The module provides the possibility to create reservations for other users (dependent on the permissions), and provides also restrictions in the maximum number of reservations a user can make and a maximum time a reservation can be made in advance.

  There is NO support for payment, booking and what ever one could imagine beyond the pure and simple reservation, and it is also NOT intended to create more than this simple functionality.

Room Reservations (Reported installs: 156 sites).

  ... for use by academic libraries to manage access to and use of their study rooms.

  All academic libraries have rooms set aside for student study and collaboration. These rooms are often available on a first come, first serve basis. Many libraries would like to have a room reservation system that would allow students to better plan their use of these often scarce resources, but setting up and administering such a system without computer support is a very difficult and time consuming undertaking.

  The Room Reservation module was created to meet this need. It allows any library to very quickly put together a reservation system customized to its own particular requirements. And once the system has been set up, it performs all the functions necessary to manage the use of group study rooms with practically no involvement from the library staff.

  Although this application was written specifically for use by academic libraries, it could also be useful to any facility that provides rooms that can be reserved and used on a short term basis.

Booking Systems Comparison

Refer to Comparison of Booking System modules for a comparison of various modules related to bookings / reservations.

This comparison contains some other modules (not mentioned in my answer here) that might be worth considering also, e.g. in case of requirements that are slightly different (as compared to those in the question here).

How to pick the module that fits best

I've ordered my recommended shortlist above by number of reported installs. Though that is often a good first indicator, it should not be used as the only criterium to pick a module.

So do your homework to pick the right one for you. E.g. by using criteria such as those I often use for selecting module, as mentioned in the community documentation about Maintenance Scorecards. Here is the intro about it (from that page):

  ... contains a list of 23 criteria (=28-5) that might help to evaluate
  the maintenance and support of contributed modules. Below is an
  attempt to apply those criteria to each of the native charting modules
  ...

Obvious, these scorecards are related to "charting modules", but the same criteria are applicable, IMHO, wheneven you need to decide between multiple modules.

Disclosure:
I'm the author of that community documentation page (partially inspired by the 28 criteria in the issue linked near the beginning of the scorecards paragraph).


How do I make a block appear in a panels display based on the state of a field I have a field that is a single on/off checkbox. Whenever it has been selected it outputs a key of 1 into the panel display, if it hasn't it outputs a 0. I want it to output custom html for a link to another page if it's a 1 and I want it to become disabled/hidden if it's 0. The resulting block/field/html needs to be inputted into a panels display, just like the key currently does.

As of right now, I'm using jquery to do this for me, but it seems like there HAS to be a way to do this with drupal. I've looked into  conditional_fields and field_conditional_state but they seemed to be more focused on entering conditional information and not on only making conditional outputs. I'm currently looking into minipanels, panel pages, and context right now to figure this out, but haven't found an easy way of doing it and it feels like I'm overthinking it.

I know that there's a States API that handles this kind of thing, but there's surprisingly little information that I've been able to find on how to apply it to displays. Any help here would be greatly appreciated.

Thanks,
Cole

If I understand your case you could :
 - have a Static field, containing your link
 - use Conditional Fields Module and set up a condition with :

"dependee"  = your checkbox
"dependent" = your static field (containing your link to another page)
condition = dependent is visible if dependee has value 1


how can I show the node create date I have used the format_date() in my template files to try and output the date created.

I followed this tutorial http://webwash.net/tutorials/handling-date-and-time-drupal-7

I created a date format 'd, j M y' and date type 'article' and called it through the code:

<?php print format_date($node->changed, 'article') ?>

however the date that it shows is the date it was updated not the date it was created.

How do I show the creation date of the node ?

There is a property on the node object called "created". This is what you are after and can be used in the exact same way you have used "changed".

<?php print format_date($node->created, 'article'); ?>


How can I modify the result of the core Path listing filter? The core Path module defines the page admin/config/search/path which gives a listing of all path aliases.

The menu hook in the module calls the path_admin_overview function in path.admin.inc which makes the query to retrieve a list of URL aliases:

$query->condition('alias', '%' . preg_replace('!\*+!', '%', $keys) . '%', 'LIKE');

What I would like to do is somehow intercept this query and modify the condition in a custom module (to avoid hacking core, of course). To be more precise, I want to make it possible to extend the condition to search the source column as well as the alias column as indicated above.

My first thought was to intercept the Path admin listing form: path_admin_filter_form which I have done using hook_form_alter. I was then hoping that somehow I could override the existing submit handler or attach an second one which would call path_admin_overview, but of course I cannot directly modify that core function.

So it seems like I would have to make my own custom copy of path_admin_overview and modify the code inside, then have that called instead. Of course this doesn't feel right either - since if the Path module changes, the module will fall behind.

Is there some kind of hook or pattern I can employ here to modify the query in path_admin_overview or otherwise achieve the goal indicated in bold in a standalone module?

EDIT: It looks like it could be possible if the query in path_admin_overview was tagged (it isn't currently), see here: https://www.drupal.org/node/310077#hook_query_alter

You can override admin/config/search/path path using hook_menu_alter
and use a custom function as menu callback.

function oyurmodule_menu_alter(&$items) {
  $items['admin/config/search/path']['page callback'] = 'mymodule_custom_path_admin_overview';
}

Then your mymodule_custom_path_admin_overview shoud be a copy of path_admin_overview with your needed alterations.

This is not optimal as you should keep your function code in sync with original code, so any patches applied to path_admin_overviewfunction should applied to your altered function, but is the only way you can alter the functionality without hacking core.


Is there a way to load the current entity object? Is there a way, from anywhere in drupal, to get the current entity object? I'm using the hook hook_filter_FILTER_process() and I'd like to replace things in the $text with data from the entity, but it doesn't look like there is a way to access the entity without doing something like

if (!empty(arg(0)) && is_numeric(arg(1)) {
    $entity = entity_load(arg(0), array(arg(1)));
}

This works most of the time, but sometimes (like taxonomy terms) it doesn't. On top of that, this is really messy as it makes another call to the database.

Is there a better way to do this?

I think menu_get_object() might be helpful:

  menu_get_object() provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling menu_get_object() will return that. Normally, it is necessary to specify the type of object referenced, however node is the default. The following example tests to see whether the node being displayed is of the "story" content type:

<?php
$node = menu_get_object();
$story = $node->type == 'story';
?>

You can use this with any router-loaded object so it stands to reason that on entity pages (including taxonomy term pages) that this would get you the correct object:

$entity = menu_get_object($entity_type);

UPDATE

On further inspection you still have to pass the position of the ID in the URL as a parameter to menu_get_object() so it's pretty much the same as using arg(), but it's arguably a bit cleaner. For taxonomy terms the path is taxonomy/term/% so you would call:

$term = menu_get_object('taxonomy_term', 2);

It's worth bearing in mind that entity_load will only incur a database call if the entity hasn't previously been loaded in the current page request. If it's already been loaded, it will be served from the static cache.

UPDATE 2

Just to add an example of the static pattern to avoid reloading the entity over and over again if you're getting memory errors:

$loaded_entity = &drupal_static(__FUNCTION__, NULL);
if (!$loaded_entity) {
  $loaded_entity = menu_get_object();
}
return $loaded_entity;


Google Store Locator I have installed this module on a clean Drupal 7 installation. But I can't activate the Google API. I have added the API key in the GEOCODE field. But I still get the error.

Also I got a blanc screen when I add location via the content type Store Location. Maybe because the API key isn't working?

My API key:

Got it from Google API:

After clearing the cache, I still get the error:

And no Google Maps:

Thanks.

Actually you need to different keys one for the browser (client side) and one for the server . You already have configured your server key but you need to get a new key from google developer dashboard for the browser side .
then go to google_store_locator.module line 441 and change it to :

'js' => array('//maps.googleapis.com/maps/api/js?sensor=false&libraries=places&key=' . variable_get('geocoder_apikey_google_client') => array('type' => 'external')),


How to use the path suffix in the Metatag page title? My articles currently have a Metatag page title [node:title]. Sometimes this results in duplicate page titles (articles can have the same title), which isn't desirable from a SEO point of view. Therefore, I would like to add a number after [node:title] when there already exists an article with the same title.

I use the Pathauto module, which adds a suffix to duplicate paths, so this suffix would be perfect. Can I use the path suffix in the Metatag page title? Or is there another possible solution?

The only token Pathauto provides is [node:url:args:join-path], the generated alias for the node. The suffix originates from, pathauto_alias_uniquify(&$alias, $source, $langcode), which Pathauto doesn't expose in any way; it's generated as needed to ensure the output alias is unique.

Theoretically, you could provide your a custom token that tries to find the value, but it would be error prone; pathauto isn't storing the suffix independently so there's no guarantee that a matched value is actually the suffix generated from Pathauto.

This is more of an editorial problem then a technical one. So a better solution would be to enforce unique titles at an authoring level.

For example, utilizing the Unique Content Title module to verify that each node title is unique upon submission.


How to create a tabbed view in a panel without a menu entry? What is my goal?

I'd like to create a view for my users' profile page, similar to the 'Questions' block one finds on the user pages on this website. Instead of the user's questions, I'd like to display the articles he/she created. The users should be able to reorder/filter the articles in the view by clicking on "filter links"/tabs similar to the ones I marked in the underneath picture.

I don't know the exact term for this, but I suppose one calls this a tabbed view.

What is my problem?

I can't find any suitable solutions for this functionality on the internet, but I've read a lot of similar requests. The main problem is that the view doesn't have its own page. That means: it should just be part of the user profile page, which has been overridden with "user_view" (see: How to create a profile page?) into a panels page. (This is exactly why the tabs in @Jhilke Dai's solution don't show up.)

It's also important that the path still contains the user's ID when one clicks on the tabs, because - of course - the Articles view needs this information, namely via the Contextual filter: (author) User uid > Provide default value: User ID from URL.

What did I try so far?

I've already created a view called Articles that displays all the articles that were added by the user. As any view would, it's displayed perfectly in the panel on my user profile pages. My next step was to add the tabs to the view. I followed @Jhilke Dai's answer to the letter, but as I mentioned before, the tabs don't show up when I don't give the Master display a normal menu entry (that's not what I want).

You don't need 3 views, just create one view with 3 pages Votes, Activity and Newest. define your fields and filters. In Page Settings -> Menu Option, Use the Menu tab.

Edit: Exmaple

If Page Path for main view is mylist

Add Pages in View with Paths mylist/votes, mylist/activity,
mylist/newest for all the 3 pages respectively
Select Menu Tab and Provide the Menu for Votes, Activity and Newest respectively

Above was the previous reply, here is answer with some graphics.

For the demo of your use case:

I created a taxonomy vocabulary called DSE with 3 terms Vote, Activity and Newest
I created a new content type called Drupal Stack Exchange, with Title, Questions and Tags field, where Tags field is Term Reference to DSE

In Views, I created a Master Display with Just Title field for demonstration, and I gave the Page path as questions like in this picture

For the Menu for Master display I selected Normal menu entry and selected Main Menu as its menu type:

Then I added the new Page for Activity, and in Path I gave questions/activity

In Menu for Activity, I selected Menu Tab and gave a title called Activity

In Filter for Activity I selected DSE Tag and chosed it to be one of Activity Tag like in the picture below. (Note: While adding filter select only this display)

I repeated the same process for Votes and Newest, as you can see Path settings for Newest is also the Menu Tab like:

Save the view and you'll see the New Menu called Questions in Main Menu, and clicking the Menu will give you 3 tabbed menu inside like:

Note: To make tabbed menu it is required the path to be on the same Path like in above case questions/vote for Vote tab, questions/activity for Activity tab.

Finally the Sneak peak of the View page


Drupal 8 reset session each request I have create a EventSubscriber like this:

<?php

namespace Drupal\custom_session\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\KernelEvents;

/**
 * Class SessionInitial.
 */
class SessionInitial implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['setSession'];

    return $events;
  }

  /**
   * This method is called whenever the kernel.request event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function setSession(Event $event) {
    // Start request.
    kint($_SESSION['page']);
    $route_name = \Drupal::routeMatch()->getRouteName();
    if ($route_name == 'view.frontpage.page_1') {
      $_SESSION['page'] = 'Home page';
    }
    else {
      $_SESSION['page'] = 'Other page';
    }
    // End logic.
    kint($_SESSION['page']);
  }

}

Every request I'll check prev $_SESSION['page'] and process logic.

But each request $_SESSION['page'] all has same value Other page.

Test step by step:

1, Go to home page (router name is **view.frontpage.page_1)**

2. Refesh browser with url home page but debug result is the same:

Also last request was set $_SESSION['page'] to Home Page.
I don't know why. Someone can help me. Thanks!

With @4k4's suggestion, I found the problem. After each request has a ajax request. The request has route name is quickedit.attachments and method post. So I edited code like that:

public function setSession(Event $event) {
    $route_name = \Drupal::routeMatch()->getRouteName();
    if (!$event->getRequest()->isXmlHttpRequest()) {
      if ($route_name == 'view.frontpage.page_1') {
        $_SESSION['page'] = 'Home page';
      }
      else {
        $_SESSION['page'] = 'Other page';
      }
    }
  }

Now it's working good. Thanks!


How do I show the form for adding a node as block? I have a content type with the title and name fields. How can I the form for adding a node as block, in the front page?

I am using Drupal 7.

function mail_block_info() {
  $blocks = array();
  $blocks['mail_block'] = array(
    'info' => t('backend info left block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function mail_block_view($block_name = '') {
  if ($block_name == 'mail_block') {
    $match = TRUE;
    $types = array('mailin_list_node_form' => 1);
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(array('nid' => $nid));
      $type = $node->type;
      if (isset($types[$type])) {
        $match = FALSE;
      }
    }

    $contact_node = node_load($node);

    drupal_get_form($node);
    $block = array(
      'subject' => t(''),
      'content' => $content,
    );

    return $block;
  }
}

Try node_add():

$content = node_add($type);

or:

$content = drupal_get_form($type . '_node_form', $node);

Also, please keep in mind that node_load() changed in D7. You should use it like this:

node_load($nid);


"Cannot use a scalar value as an array" error I'm getting a bunch of PHP errors every time the cron runs. I can't seem to track down what is causing them all.

  Cannot use a scalar value as an array in drupal_render() (line 5822 of /var/www/vhosts/tlthost.net/httpdocs/includes/common.inc).

  Cannot use a scalar value as an array in drupal_render() (line 5767 of /var/www/vhosts/tlthost.net/httpdocs/includes/common.inc).

  Invalid argument supplied for foreach() in element_children() (line 6300 of
  /var/www/vhosts/tlthost.net/httpdocs/includes/common.inc).

  Cannot use a scalar value as an array in adaptivetheme_page_alter() (line 235 of
  /var/www/vhosts/tlthost.net/httpdocs/sites/all/themes/at_core/inc/alter.inc

  Cannot use a scalar value as an array in user_relationships_ui_page_alter() (line 247 of
  /var/www/vhosts/tlthost.net/httpdocs/sites/tlt/modules/user_relationships/user_relationships_ui/user_relationships_ui.module).

  Cannot use a scalar value as an array in fbconnect_page_alter() (line 568 of
  /var/www/vhosts/tlthost.net/httpdocs/sites/all/modules/fbconnect/fbconnect.module).

  Cannot use a scalar value as an array in block_page_build() (line 269 of
  /var/www/vhosts/tlthost.net/httpdocs/modules/block/block.module).

I'm hoping you know what's causing this one. it might help me figure out the rest of the errors.

Sometimes these error messages come up on my sites if cron is run while the site is in maintenance mode. I'm guessing the maintenance mode template for our site has something to do with it, but it could be a variety of things.

When cron runs, it is still running through Drupal's theme system, so you probably have something awry in either your theme or one of your custom modules. Does this happen every time cron runs, or just sometimes?

A final troubleshooting step would be to install elysia_cron and run each cron task individually to see which one might be causing all these errors.

See also: Warning: Cannot use a scalar value as an array


"drush up" fails with "pm-updatestatus failed." When I execute drush up, it returns the following error message.

  The command could not be executed successfully (returned: The
  filename, directory name, or volume label syntax is incorrect, code:
  1)   pm-updatestatus failed.

drush pm-updatestatus runs without errors.

Similarly, "C:\\Users\\user1\\AppData\\Roaming\\Composer\\vendor\\drush\\drush\\drush"
    --backend=2 --verbose --debug --root="C:\\website\\drupal7"
    --uri=http://default  pm-updatestatus 2>&1, which I extracted from the debug output of drush -d up (see below) also successfully runs.

What could I try?

The debug output is the following.

  Calling hook drush_pm_updatecode_validate [11.27 sec, 17.04 MB]
  Returned from hook drush_pm_updatecode_validate [11.27 sec, 17.04 MB]
  Calling hook drush_pm_updatecode [11.27 sec, 17.05 MB]
  Cache MISS cid: 8.1.2-alias-path--59067c616e8e4f3b7078e0502d77bf35
  [11.27 sec, 17.06 MB]   Backend invoke:
  "C:\Users\user1\AppData\Roaming\Composer\vendor\drush\drush\drush"
  --backend=2 --verbose --debug --root="C:\website\drupal7" --uri=http://default  pm-updatestatus 2>&1 [11.61 sec, 17.09 MB]   "C:\Users\user1\AppData\Roaming\Composer\vendor\drush\drush\drush"
  --backend=2 --verbose --debug --root="C:\website\drupal7" --uri=http://default  pm-updatestatus 2>&1 [11.61 sec, 17.09 MB]   The command could not be executed successfully (returned: The filename,
  directory name, or volume label syntax is incorrect., code: 1) [11.79
  sec, 17.09 MB]   pm-updatestatus failed. [11.79 sec, 17.08 MB]

I am using Drush 8.1.2, Drupal 7.50 running on Windows 7, PHP 5.6.23, and Apache 2.4.23.

I was able to fix the problem by editing the file /path/to/drush/includes/exec.inc and changing line 331 from

return _drush_escapeshellarg_windows($arg, $raw);

to

return _drush_escapeshellarg_windows($arg, TRUE);

as described by peterromero here https://github.com/drush-ops/drush/issues/2152


"one more" ajax call for multiple node add forms on one page I want a page with an initial node add form (in small size), the title line and body textarea 3x20 size;

And a button "one more" with ajax call to display another form plus another button etc etc.

and of course the submit button always at the bottom.

So the question is ... which module ? :) I hardly cant find the terms for searching!

UPDATE: I want to add , this task seemed to me quite often used and modular, so I thought there would be a module for it; Now as i work through related questions and learn about ajax form api http://randyfay.com/ajax it's okay to code it for me and maybe you can give some starting points.

I worked on similar case. I wanted to add few nodes at one time without reloading page.

Instead I did multi value field in my content type (mysomething), but I needed to have more elements than one field. So I found field collection module, made collection and put it as multi value field of type collection. Now when I do node/add/mysomething I have collection and [Add more] button below.

Creating collection allows You to add all core field types, so in your case I would add text field working as title and body field to collection.

The other thing is, that if someone add 3 collection at once it will be consider as one mysomething node by D7 core - You should make some views to see whats inside. Another approach is to catch node creation action of type mysomething and try to split it into nodes by rules, but I didn't do that so I'm not sure if it is possible. And finally someone probably can write custom module with ajax form, where submit button will save node for each element...

I think it's nice trick with no coding (UI visual puzzle). I can write step by step config for You, if needed, but it's pretty easy.


How to programmatically select a view display in a view based on some node data I have a content type that includes a field to store how that node should be displayed (display_option). display_option has two values (1|2).

I have created a view with two displays. Both are pages. Both use the path /node/% and use the node id as a contextual filter.

Display 1 has an additional filter criteria for requiring that display_option = 1.

Display 2 has the same filter but with the criteria that display_option = 2.

I can supply a node id to each display preview and they both individually produce the content I am looking for.

I was hoping Drupal would simply select the correct display based on the filter criteria but it doesn't. It always uses the display that is first in the view.

So I was looking at adding a pre-process function of some kind to template.php to manually change the view display id based on the node data.

I see quite a few views pre-processing functions and I am not sure which to use or at what point in the page build and view build process.

Any help would be appreciated including another method for accomplishing this.

The simple way to do this is

print $view views_get_view('yourviews_name','yourdisplayname');

for more information you can read documentation here


How can I stop cron from deleting images I need I have an image that is being deleted by the drupal 7 cron.

This is not good for us and I am trying to figure out how to prevent this.

As I am new to drupal I am not sure even where to begin but I am pretty sure we add the image via the core image module if that helps.

Please if anyone could help I would be most appreciative and sorry if this Q is too noob for here :)

The image is the only one in it's containing folder too.

Try using

<?php
$file->status |= FILE_STATUS_PERMANENT;
$file = file_save($file);
?>

While you save the file

References

hook_insert


User role referencing when they might not exist I'm making a Drupal 7 site that has an event content type. There are two user roles: venues and speakers, and both can create events. I need a way for both to be referenced in the node (with auto-complete), but keeping in mind that they won't necessarily have an account on my site.

Example 1: The venue "Big Conference Center" creates a new event called "Cool Conference 2012". Their speaker is John Doe, so they enter his name in a text box, it finds him using user role Speaker auto-complete, and he is referenced. If you go to John's user page now, it lists Cool Conference 2012 as an event he is speaking at.

Example 2: The same venue creates another event. This time the speaker is Jane Anon, who doesn't have an account on the site. The auto-complete returned nothing, so Jane Anon is stored in plain text in that field. When Jane Anon joins the site two weeks later, she is presented with a list of events that match her name, and she can select which ones are hers. Then, the plain text changes to a reference.

Examples 1 and 2 should work the same if it's the speaker who is creating the events and the venue who is referenced.

Lets say there is a module in drupal which just does what you are asking for, how would you like it? :P

I found this module recently. TextNodeReference

What this module does is

It creates a new widget for the references. Once the widget is enabled,
If the referencing node exists then it will store a reference to that node in the table.
If the node doesn't exist already on the system, then it will store it as text. But when the node with the same title is created, it will auto-reference it to the node.

Caveat : When that node doesn't exist, make sure that you are entering that right title(for the author or venue), and then use the same title when creating the actual node for that entry(author or venue).

You can thank me later, but do thank Boobaa who wrote this module.


Using rules to grant new role upon visiting page Using the modules "rules" and "rules linkevent" I am trying to get drupal to automatically assign a new role to the user upon visiting a certain page.

I've written it like this/entered the following values and selected these options:

-

Events Event
levelup2 was accessed

-

Conditions Elements

User has role(s)
Parameter: User: [site:current-user], Roles: authenticated user

-

Actions Elements

Add user role
Parameter: User: [site:current-user], Roles: Level 2

What am I doing wrong or how could I alternatively make the user accessing the page, reading the page or another trigger I can make be granted a new role?

I have tried searching the net but have found no answers.
Can anyone help?

The Rules Path and Rules URL Argument modules trigger events based on the current URL being viewed.

You could also use the Rules Link module to generate a custom link that will trigger your rules. The catch here is that this specific link must be clicked to access the page and the user I believe must be signed in.

If you need fine tuned control over when the Rules event is triggered you could even implement your own Rules Event.


How to ignore opening quote in views sort I use views to display a sorted list of book titles. Titles that begin with a quote are listed first. I want to ignore the quote for sorting purposes. So, instead of:

"Once Upon a Time": Fairy Tales in Reality
Grimm's Fairy Tales
The Best Book of Fairy Tales

I want:

Grimm's Fairy Tales
"Once Upon a Time": Fairy Tales in Reality
The Best Book of Fairy Tales

It appears the Views Natural Sort module will handle this, but it's still in Alpha for Drupal 8. Is there another, relatively straightforward (non-custom-code if possible) means of accomplishing this?

I've read a number of posts addressing more complex situations with fairly complex solutions, but it seems something this simple should have a simple solution.

views_natural_sort is able to do this kind of sorting.

It might be currently in alpha state but it already has more than 250 installation for the alpha 3 release which means that  most major bugs should have already been ironed out.

Upon enabling you are able to choose title to sort with and you are given 2 extra options for natural sorting (sort natually ascending and sort natually descending)

It also has some handy settings at admin/structure/views/settings/views_natural_sort which you will allow you to chose what other characters you want to ignore (and other settings)

Following are the default settings


Commerce Kickstart 2 Need Rule To Apply Sales Tax To Shipping I need a Rule to apply sales tax to shipping on a sales order.

I tried the following code (borrowed from here: https://www.drupal.org/node/2307695) and it doesn't work for me:

{ "rules_apply_sales_tax_to_shipping" : {
"LABEL" : "Apply sales tax to shipping",
"PLUGIN" : "reaction rule",
"WEIGHT" : "5",
"OWNER" : "rules",
"REQUIRES" : [ "commerce_tax", "commerce_shipping" ],
"ON" : { "commerce_shipping_calculate_rate" : [] },
"DO" : [
{ "commerce_tax_calculate_by_type" : {
"commerce_line_item" : [ "commerce_line_item" ],
"tax_type_name" : "sales_tax"
}
}
]
}
}

Maybe there is a typo? There are only two tax_types on our site, sales_tax and VAT so I don't think so.

Do I need to add this as an Action onto our Sales Tax? I don't see how to do this... this does not appear in the drop down list of available Actions.

don't know if you solved this yet (hope so). The trick is to set your tax rate and THEN apply is a calculation rule to shipping. Not the most intuitive way to do it, but it works.


When using drupal_add_js with the 'setting' option, do the set variables apply for all users? I am trying to find out if the following function will just set the JavaScript variable for that specific user, or if it will switch back and forth between usernames.

function my_module_form_submit($form, &$form_state) {
  $username = custom_get_username_function();
  drupal_add_js(array('user' => $username), 'setting');
}

Assuming that custom_get_username_function() returns a different username for each of the logged-in users, then that code will pass to JavaScript a different and a single username for each user. There could be 4 different logged-in user, but each user gets one username, assuming custom_get_username_function() is using the currently logged-in user ID to retrieve the username.

I would rather not add JavaScript code from a form submission handler; if I need to add it, I would add it to the form, or to the page where the users are redirected after they submit the form.


Guidelines For Features as building blocks Any guidelines on how to use features module as building blocks for a consolidated drupal site from a prototypic approach, so that most of the functionality is just a plug and play using feature.

I am afraid my question might be too broad to answer, but looking for initial pointers basically the important things need to be taken into account while building features so there can be least chances of conflicts.

Some of my thoughts coming from my experience:

Features should be logical and separated functionality blocks - each feature should be standalone as much as possible and there should be no overlaps to prevent one feature overriding other.
You can safely put your custom code in features - if you write something into your .module file (or any other that is not filled with features exports), next time you recreate the feature it will be respected and it will stay there - this fact is not so often used but it can be very helpful to achieve the first point.
More smaller features are easier to manage than few big ones - this is just because bigger features are more error prone when creating (e.g. you add something without noticing) and you need to inspect more code when searching for stuff.
It's good practice to put features in separate folder (e.g. sites/all/modules/features)
You can use Features Extra (https://drupal.org/project/features_extra) to export some additional entities, especially blocks.
Use Context (http://drupal.org/project/context) or Panels (https://drupal.org/project/panels) for powerful exportable layouts.
Everything can be exported only once, features UI will not even allow to export duplicities.
Use drush to make your life easier (see drush help, section features)
Use Advanced Options to replace your existing features when recreating (instead of downloading it and copying it manually)
Keep everything clean 1 - install Diff (https://drupal.org/project/diff) to see overrides of your features code and revert when necessary.
Keep everything clean 2 - recreate you features often, to keep your code updated and to avoid unclear situations when you are not sure what should be in code, what actually is in code and what is overriden in database.

I will update my answer when I come up with additional stuff


Import won't import content in CCK image fields I am using the Node Export module to migrate thousands of nodes from a Drupal 5 site to a Drupal 6 site, and it is working really nicely except for one thing: It systematically fails to import my CCK image field and I get the following error message.

  Unknown error occurred attempting to import file: [path to file]

Does anyone know how to resolve this issue?

Are the images already in the directory in the new site?  For most import modules, the images Have to been in the directory before you start importing.


how to send a file to a specific user? I have a content type which has an entity reference pointing to users. I need to have a permission policy that says: only users who are defined in the content (as entity reference) can view it or download the file attached to it. anybody else should be faced with a message which saying: It's not your business!!

help please

You can try this module: https://www.drupal.org/project/nodeaccess_userreference. I use it too and it works very well.

As the module's page says, it "Gives content access permissions to users for content that references the users with User reference or Entity reference."

With this module you can define permissions just for the entire entity, you can't define them to the single fields.


Limited permissions for users logged in with facebook and twitter I would like to know if there's a way to allow people to log in into my Drupal site with limited permissions with their Facebook or Twitter account.

I have created a website which allows authenticated users to upload images. I have added a voting option which can be used by the authenticated users. I want to allow the people logged in with facebook or twitter to be only able to vote and not upload images.

I am using Social Login to allows users to login users with their facebook and twitter. Is there a way to set this limitation?

You could use Rules to automatically assign them specific roles, then limit permissions based on those roles.

A few ideas about how to work with rules and auto-assigning roles.


Where is the 'display post information on' settings? I've seen the discussion of this setting, which I gather used to be under theming.

They discuss it being moved to content type, which makes a lot of sense; going through content types in my install, I don't see any option similar to this. Where is it in Drupal 7?

It's under "Structure > Content Types > your content type  > edit > Display > Settings."


Can I setup the Security Kit module via Drush? Does a Drush command exist which I can use to setup the Security Kit module? Something like this command:

drush seckit --img-src:self,unsafe-inline?

You could update the Security Kit settings via the config-set command:

drush config-set seckit.settings seckit_xss.csp.img-src "'self' 'unsafe-inline'"

You can find the available configuration keys by looking at Security Kit's  default configuration file, config/install/seckit.settings.yml, or you can view your site's current settings through the config export page.


Views, group by first letter as rest export (Alphabet/Glossary listing?) Is there a way to group results by the first letter of their title in a REST export per the screenshot?

My first thought would be perhaps extending Serializer to process the results, at the expense of pagination. In my case, it is only about 100 records, and won't be paginated.

I am not sure if this is the best solution, but I came up with this:

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "serializer_glossary",
 *   title = @Translation("Serializer Glossary"),
 *   help = @Translation("Serializes results and groups them by first letter, for small result lists only."),
 *   display_types = {"data"}
 * )
 */
class SerializerGlossary extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];

    foreach ($this->view->result as $row) {
      $entity = $this->view->rowPlugin->render($row);
      $title = $entity->label();
      $first_letter = Unicode::strtoupper($title[0]);
      $rows[$first_letter][] = $this->view->rowPlugin->render($row);
    }

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }

    return $this->serializer->serialize(['results' => ['items' => $rows, 'totalCount' => count($this->view->result)]], $content_type);
  }
}

I am open to other answers if there is a better way.

The frontend is processing this via ReactJS to do the screenshot in the original question. The reason it is wrapped with 'results' and then 'items' is from a request from the frontend developer to have it structured that way.


Adding new rows on a draggable table via jquery I have a draggable table with preloaded "new items" - sorta like the Power Edit feature of the menu_editor module. Everything works perfect.

However, I want to have a button that adds a new row via jquery. I was able to do this via the following code. However, the new rows added by jquery are not draggable. What can i do to make it work? Is it even possible?

var preloaded_items_count = '.$preloaded_items_count.';
$("#edit-add-new-item").click(function(){
  var append_tr = $("#guide-pages-table tr:last").clone();
  var replace_pattern = new RegExp("new-" + preloaded_items_count, "g");
  var new_item_id = "new-" + (preloaded_items_count + 1);

  //append_tr.find("a.tabledrag-handle").remove();
  append_tr.html(append_tr.html().replace(replace_pattern,new_item_id));
  preloaded_items_count = preloaded_items_count + 1;

  //Drupal.tableDrag.prototype.makeDraggable(append_tr);
  $("#guide-pages-table > tbody:last").append(append_tr);
  return false;
});

As I can not reproduce your case, this answer just is a suggestion:

look at misc/tabledrag.js:

Drupal.tableDrag.prototype.makeDraggable = function (item) {

So you need re-running necessary javascript after adding new row.

Drupal.attachBehaviors($('#guide-pages-table > tbody:last'));


Hook for Field Duplication I have a custom module that is formatting the display of an image field, which can accept multiple values.
I would like to know what hook I should use to duplicate the first value of the field (e.g. "[image1]"), and add it back to the beginning of the array (with array_unshift() I guess) before the rest of my functions format the display/theme of the field.

So what was

[image1]
[image2]
[image3]

becomes

[image1]
[image1]
[image2]
[image3]

I am then going to theme them separately, but I think I already have that part figured out.

I am currently using hook_field_formatter_view(), and have tried to just add it to the beginning of the $items array at the top of the function, but that didn't seem to work. If I immediately dprint_r() the $items array after this it shows, but only 3 items get output; I am assuming that the number of field gets determined elsewhere.

You want hook_field_formatter_prepare_view() instead. Note this hook operate on a group of entities, not on a single one.

Here's a working snippet. Some array-fu is needed to not end up writing an ugly loop of ten lines, since deltas must be preserved linear.

<?php

function MODULE_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  foreach ($entities as $id => $entity) {
    $array = array(0 => $items[$id][0], 1 => $items[$id][0]);
    if (count($items[$id]) > 1) {
      array_splice($array, 2, 0, array_slice($items[$id], 1));
    }
    $items[$id] = $array;
  }
}


New Modules Not Listed at admin/build/modules So I'm trying to install the Backup and Migrate module on an older drupal site (still 6.22) but it, or any other module, wont show up on the list of modules at admin/build/modules.  The current modules (active and not active) show up, but nothing new will.

All files and sub-folders have the same permissions and owner of the new modules, also tried flushing all caches.

What else could cause this?

Check the following:

Are the uploaded modules correctly unpacked? No .tar or .zip endings?
Does the problematic module contain its .info file and are you sure the module is D6 compatible?
Is the module placed into the correct folder where you keep all contributed modules?


Passing Image through hook Background:
Im working in Drupal 8 and I have a paragraph type that contains a title and an image and I am trying to pass it through the preprocessor hook so I can set it inside a html template. For testing purposes all I have on my template is div that calls the image variable. Im more worried about the pre_processor than I am the html
Code:
function theme_preprocess_node(&$variables) {
  if ($variables['node']->getType() == 'landing_page') {
    $paragraphs = $variables['node']->field_section->getValue();
    $section = [];
    foreach ($paragraphs as $key => $paragraph) {
      $p = Paragraph::load($paragraph['target_id']);

      echo "<pre>".print_r($p,TRUE)."</pre>";

      switch ($p->getType()) {
        case 'tabbed_body':
          foreach ($p->field_body_tab_content->getValue() as $tab) {
            $t = Paragraph::load($tab['target_id']);
            $title = $t->field_body_tab_title->getValue();
            $content = $t->field_tab_content->getValue();
            $image = $t->field_body_image->getValue();
            $section[$key]['tabbed_body'][] = [
              'title' => $title[0]['value'],
              'content' => $content[0]['value'],
              'image' => $image[0],
            ];
          }
          break;
      }
    }
    $variables['sections'] = $section;
   }
}

Image Settings:

You can pass only the image uri, and render image using it in the twig.
Try the following suggestion:
In your loop try to get image as the following:

  $image_field_values= $t->field_body_image->getValue();
  /**
   * @TODO: if you have multiple values loop through them i will test just by the first
   */
  $image_target_id = $image_field_values[0]['target_id'];
  $image_file = File::load($image_target_id);
  $section[$key]= [
    'image_uri' => $image_file->getFileUri()
  ];

In your twig will be something like:

<img src="{{ file_url(section[0]['image_uri'])}}" >

Don't forget use Drupal\file\Entity\File;.


Adding group manager email to "membership pending" text When a user tries to join a private group in Drupal Commons she will see the following text:

  Your membership request is pending review by a group organizer.

We'd like to give the user the ability to email (or otherwise contact via form) the group manager. Is it possible to update this text to add an email (to authenticated users only of course)?

Update: It appears I may be able to accomplish this by hook_preprocess_field

function hook_preprocess_field(&$variables) {

  if ($variables['element']['#field_name'] == 'group_group') {
        $variables['element'][0]['#markup'] .= "Group Mgr Email Placeholder";
  }
}

Though after a drush cc all && drush cron, the page content remains the same. Am I using the wrong function?

Update 2: Well I now have a placeholder for email by using item instead of element. Next I'll move onto extracting the group managers and their emails to show to pending users.

$variables['items'][0]['#markup'] .= " [[ place holder for emails]]";


Redirect "edit" tab on single node view I created custom node edit pages and I want the edit tab to redirect from

node/2545/edit

to

topic/2545/edit

or

node/2549/edit

to

arts/2545/edit

depending on the content type

This is not an alias this is a custom edit page/view I created, it is NOT the node edit page or an alias of it. it is a completely separate page and I simply want to redirect to this page when I click edit. In other words "I want to redirect to a completely random page when I click "edit"

http://screencast.com/t/zHcFsr8I

(Disclaimer: This is not tested, it's been a while since I did a D6 site...)

First, I would implement hook_menu_alter and clone the node/%node/edit item into topic/%node/edit and arts/%node/edit. (If you want to use custom page callbacks for the forms, that's fine. You can make all changes you need to the menu items.) At least, you must change the access callback property and set it to the function name of your custom access callback (see below). Now you have three similar menu items with three different URL's. All of these should be visible as tabs on all nodes, so we're not done yet.

Second, I would create a custom access callback to hide the tabs with the incorrect URL's. This is described in HowTo: Add / Remove a menu_local_task for specific node types. In your case, the access callback should check the type of node on the current page and use it to decide if the tab must be shown or not. Don't forget to also call node_access(), because if the user is not allowed to edit that node, the tab must be hidden too.

Sorry I don't have actual code to share, I hope this helps.


How do I redirect users to a predetermined url after login? I have a view in Drupal 7 that lists PDF files. I want to keep track of the users that open that file; so I want that, if they are not logged in when they click, they are sent to the login/sign up page. I have already accomplished this using two views with different permissions, but the problem is that, after they sign up, they are redirected to the user profile page, as opposed to the PDF file.

How can I accomplish this?

All forms in Drupal support a internal destination parameter.

When you link to the user or user/register form, you can add ?destination=[url]

user/register?destination=node/1

Since you display the files-list with Views, you will need to re-write the files link to include the destination parameter.
If you output the link with l(), you can add the extra url data in l's third parameter like

l('Sign in to View', 'user', 'destination=node/1');


Form display: How to move fields into the advanced group? How can I move a field in a node edit form from the main region into the advanced/secondary group region in the right-hand column?

This question asks how to move elements out of the secondary group into the main group, but this is the inverse.

I tried setting a group for my field in a similar way to the above answer:

$form['field_article_language_filter']['#group'] = 'advanced';

This did move it, but I'd like it to be in a group with a summary arrow button to toggle it closed or open.

In a custom module or your theme, create a group and place your field in there:

/*
* Implements hook_form_alter()
* @param     Array $form, Object $form_state, Array $form_id
* @return    Array $form
*/
function MY_MODULE_form_node_form_alter(&$form, FormStateInterface $form_state,  $form_id) {

  // Create a languages group in the right-hand column
  $form['languages'] = [
    '#type' => 'details',
    '#title' => t('Languages'),
    '#group' => 'advanced',
    '#attributes' => [
      'class' => ['node-form-options']
    ],
    '#attached' => [
      'library' => ['node/drupal.node'],
    ],
    '#weight' => 100,
    '#optional' => TRUE,
    '#open' => TRUE,
  ];

  // Move the languages settings to the right-hand column
  $form['field_article_language_filter']['#group'] = 'languages';

  return $form;
}

This is based on this gist, thanks to Dan Braghis.


How can I filter/sort a Drupal view in this way? I have created a content type called PDF Publication with two fields - a pdf file upload field that allows one file to be uploaded and a term reference field where the user selects an area e.g. area1 area2 or area3

I now need to create a view block that shows just the latest pdf uploaded for each area. so the block will show three pdfs - one for each area

I have followed instruction from here and other forums on the Internet but am struggling to do this.

I would be really greatful for some help, thank you so much for reading.

The easiest way I can think of you doing it since you have just three areas, is creating One block display with two attachments.

The block contains one area with the most recent pdf, and the two attachment, would contain one area each with the most recent attachment, and link the attachments to the block display.

See Image of how to add an attachment

UPDATE

When you are using more than one diaplay and are adding a display you want to make sure at the top of the popup dialog you choose for this display, rather than all display. See image below


How can I sum up the totals of groupings in views? I am trying to sum up my sales in my Commerce store by month.

I have created a view of completed payment transactions that is grouped by payment year (first grouping) and then payment month (second grouping).  The config looks like this:

This gives output look like this:

Now what I'd like to do is sum up each month (the second grouping) to show the total sales for that month.  I think I can use aggregation for this but I'm not sure how to set it up.

Most of the links I found for this kind of thing point towards Views Aggregator Plus.  Apparently it allows you to "aggregate and group by column" (source).


node/add page shows 2 of every type. How do I fix this? My node/add page (Add Content) shows two of every content type!

Here is a screenshot:

I am 99% sure this is is a database problem, but my database node_type table looks OK and only has one of each type.

I have disabled every module I could, updated everything, and have no errors in the log.

When I point my installation at a fresh database I do not have the problem.  When I point a fresh Drupal installation at my current database I do have the problem.  It seems like database to me.

Using Drupal 7.15.

Any idea on how to fix this?

I've fixed it.

The problem was that the table menu_links had duplicates in it for the content types.  How they got there, I have no idea.

The fix is to find the menu_links table using phpMyAdmin and search for the links there were duplicates of (title link_field using LIKE %...% operator). Then simply, drop them from the table.  The reason is because the node/add page is just a page (or Overlay) view of the items in the "Add content" menu.


PHP in database: bad practice but Lots of times here I've been told that using views custom php fields, filters or others is a bad practice, because putting php in the sql is dangerous.

My question is, if you only call to a function, that you defined in a module, is it still as bad?

Sometimes, especially for Views, making a custom handler, or, other example, a custom token, can be really heavy.
What are the risks if I make a custom field that only calls a function? Is it as dangerous and "forbidden"?

Here's my take on it:

The PHP docs says about eval:

  Its use thus is discouraged

It is always, let me emphasize that again, always, bad to use the PHP module (technically eval, but the PHP module makes a dangerous language feature much worse).

Details discussed in this question: What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?

The link provided by Clive claims

  Sometimes eval is the only/the right solution.

It is possible that this is true, some times, but during quite a few years of professional development, I have never stumbled across a real need for it, in PHP or other languages.

Personally, I've taken it to the level that my servers disable the functionality on the php level itself, with disable_functions = eval.

With that said, on a small personal website, it's likely of less consequence than on a large enterprise one, and there are cases where it's at least not completely horrible to use it.


Dropdown menu expanded on page load I have a hierarchical dropdown menu created using Drupal Megamenu module. It works good for my needs, but there is a small issue: when the page loads the whole menu tree looks expanded, and covers the entire page for a while.
It gives a hard look. I would greatly appreciate if you have any suggestions or workarounds to fix this.

Problems like this occur when you rely on JavaScript to hide things. It can take some hundred ms before it happens making the items appear upon page load.

A way to solve this, would be to use CSS to hide the expanded menu when the page is loading and once the JavaScript has been run, remove the effect of the CSS.

The easiest way to do that is by adding a class on the HTML produced, that is required in the CSS rule, and remove the class with JavaScript on page load. You could add a class to the body in the preprocess_page hook and remove it again in one of your theme's JS files.


How to set theme setting i need to set theme setting programmatically. I use mothership theme.
So for example:

$type = theme_get_setting('mothership_classes_view');
dpm($type);
//dpm displays 1 - so this setting is checked
//i need to uncheck it, set it to 0

i can't find a function to do this, what is the best way to set it?

As you can see in the code of theme_get_settings(), if data is not in cache, it's obtained from variables:

// Get the saved global settings from the database.
$cache[$theme] = array_merge($cache[$theme], variable_get('theme_settings', array()));

if ($theme) {
  // Get the saved theme-specific settings from the database.
  $cache[$theme] = array_merge($cache[$theme], variable_get('theme_' . $theme . '_settings', array()));

So usually when you need to change them from code, you will need to use good old variable_set(). And don't forget to clear the cache.