jQM Theme does not work properly on front page I've started to use Drupal recently, and installed the jQuery Mobile module and the jQM Theme in order to make a Mobile site / Web app.

I'm having some troubles getting it to work properly.

The thing is, that when I go to my sites front page, I get this view:

However, if I click on, let's say 'Store Locator', I get this view:

So my problem is, that it seems like the jQuery Mobile stuff (js or css) does not load correctly on the front page.

If I inspect the page, it seems to be the right template, but somehow the js og css isn't loaded correctly.

Has anyone had the same problem?

Are you including the CSS/JS via your themes .info file? If so, the CSS/JS should be included in the order specified there. The only other thing you should check is that if you have a page override for the homepage (page-front.tpl.php) and verify you have the correct JS/CSS in place in there as well.
Good luck


Menu highlight vs. taxonomy My site (running D7) is divided into four sections to organise its content. This is implemented via a taxonomy vocabulary, and my main menu lists each term in this vocabulary. So when a user clicks a main menu item, it is highlighted and all articles in that section (nodes with that term) are shown. Brilliant.

But, when a user then clicks one of these articles to view the whole thing, the main menu item is no longer highlighted. Although the article does display the taxonomy term, I would very much like to keep the main menu item highlighted so it's obvious to the user which section she's browsing.

How can I achieve this?

Edit: Clarified that I'm using Drupal v7. Also, managing the menu itself is not a goal (that's easy enough), the goal is only keeping the menu highlighted when viewing an article node as opposed to the term node.

I'm sure there is a better way to do it but the context module will allow this.

You can set up a condition for each term which sets the menu item as the reaction.


'Most popular' view since last X days I'm using Drupal 6 and I need to display a block with the most viewed nodes from the last 7 days. I've tried using views + statistics but I can only get the total count of views. How can I get a count of node views from the last X days?

You may want to take a look at the Radioactivity module and see if it works for you.  It defines a "hotness" for a node, and a "halflife" that the "hotness" wears off at.  This attempts to account for popularity over time, instead of raw page views.

For example, a popular blog post from a few days ago will be more "hot" than a wildly popular blog post from last year that had more page views.

Time-decay is configurable, and it integrates with Views.


Expose the user form into a page I've been thinking for a user-friendly navigation into my website.

I wanted to exposed the user form into a page where they can just easily update their information. I've installed the module profile 2 and added 3 types of profile (Personal Data, Withdrawal Form and Drawing Records), these 3 types of form I want to expose in one page.

Can it be just embedded into a views or do I need to use hook_form_alter? Please help... Thank you...

Not exactly sure what you want here. But i think i understood that you have 3 profile types defined in profile2 and want to expose these to anonymous users, so that they can sign up?

If this is indeed the case, then i would reccomend you to take a look at the profile2 registration path module

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

This module allows you to setup a direct menu path to a user registration form that shows the profile types you select


drupal_mail() is formatting my body drupal_mail() is formatting my email body.
Before: http://pastebin.com/LbBy04BZ (note 1 line)
After: http://pastebin.com/nEx7AFwU (note multiple lines)

It should not, because Line 23 in /modules/system/system.mail.inc is the following one:

$message['body'] = implode("\n\n", $message['body']);

How can I prevent the reformatting of my mail content?

Have a look at the API documentation for drupal_mail_system(), there you'll have code to override the default MailSystemInterface.

For an exemple of how to override it, have a look at the Postmark module.
You can then redefine the format() function:

class YourModuleMailSystem implements MailSystemInterface {

public function format(array $message) {
  //remove this formatting.
  //$message['body'] = implode("\n\n", $message['body']);
  return $message;
}

//...
}


Hide content types in administration for certain user I created a user role who can only create and edit a certain content type, this works as it should.

When they log in however, they can click the content box in the admin bar to see all content. I want them to be able to click there and get all the content that they have the permission to create, but other content types should not appear.

I can't find any setting for this is the user role and permissions setting, but perhaps I'm mistaking? How can I fix this?

You should use Content Access module

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.


drupal 8 modifying the menu items path I work on an drupal 8 application that use the group module with the restriction of only one group per user. i want to be able to modify the menu items so that the id of the user's group is always in the url. this way i can use views with a group id in the url.

I search and i always go to the same pages with the same example that doesn't work for me.

this will not work because the menu are build during the cache clearing, thus the url cannot be dynamic.

i instead use an EventSubscriber on Kernel::REQUEST and redirect the user if need be.


List of parent and child taxonomies and related content I would like to show in the front page a list of dishes. Like a real restaurant menu, I would like see:
Wines

 -Whites

  --Product 1

  --Product 2

 -Reds

  --Product 3

  --Product 4

Beers

 -Blondes

  --Product 5

 -Reds

  --Product 6

and so on.
To do so, I created a taxonomy vocabulary named category and then a list of terms and sub-terms like this:

Then in my custom type Product I created a relation field to the taxonomy category.
But when I tried to create a custom view to list all the products by taxonomy terms and sub-terms, I only view the child one.
How can I create the view to display the complete hierarchy list?
Thanks

There is more than one way of solving this.
If you start from your existing case of Content Views and listing your Products, you can add the Taxonomy ER Field. This field will show the Term that the node is directly linked to, the "child" in your Taxonomy hierarchy.
To get the "parent" Taxonomy term you have to add the Relationship for the ER field in question. Once you add that you will be able to access the Parent Field from the "Taxonomy term" Category.
You can then set Grouping under Format Settings. Set the first grouping to the "Parent" Field, and the second one to the "child" regular taxonomy field.
You can hide the taxonomy fields with Exclude from display since they'll appear in the grouping output.
Alternatively, you can add a second Relationship on top of the first one, for the Parent of the term, but that approach isn't necessary unless you have 3 levels of taxonomy hierarchy, and it can add to the performance strain.

You can also start from the Taxonomy term type Views, show hierachy with Depth, and use a Relationship to add the nodes/content into the View.


Drupal 6 failing to login user in IE7 but forwarding to user account page We have just updated a Drupal 6 website to Drupal 6.22 for a client. However, the client is now no longer able to login to their account when using IE7. After clicking "Log in" the client is correctly being forwarded to their user account page, but is getting a "You are not authorized to access this page" message and remain unauthenticated. The client has now choice but to use IE7 at work, so switching browser is not an option.

We have tried testing this in various browsers in our office (Chrome, Firefox, IE8 - we don't have access to IE7) and can successfully sign-in to the site every time.

We have tried repairing the sessions table (in case that was corrupted) and still no luck. Our cookie domain is being set in settings.php as: $cookie_domain = $_SERVER["HTTP_HOST"];

Any suggestions?

I would try the following in order:

Ask the user to clear their browser cache.
Rebuild permissions - admin/content/node-settings/rebuild
Create a test account with the same roles.
Manually verify the roles and permissions haven't changed.


How to sort view by a field that is part of a field collection? I had searched solution for my problem, but I didn’t found anything good.

I have custom a node type Client with Field Collection Product.

My field collection has two fields:

name of the product
date value

In the view I can see Client fields name & surname and field collection Product & date value.

How can I sort by date value?

Duplicate of Sort view items by field collection's field value (But it's answer is not accepted yet)

You can use field_collection_views module which it creates a default View of field collection type. Its address is /admin/structure/views/view/field_collection_view and I recommend you clone this View and configure the rest of the options. The Fields section contains a few items that are very helpful, like Host Entity ID, Host Entity Type and ... .


Print custom HTML between Exposed Filter Area and Results in Views I set up a view in drupal 7 that displays all my content.  I exposed filter criteria's Title and Taxonomy, so now there's a title and taxonomy search field that appears above the result set.  How do I print custom text like "Search Results:" between the filters and the results?

This can easily be achieved using themeing.

In the edit view for your view click on advanced
At the bottom of the section is "theme information"
Look for the line "Display output" and from left to right the themeing becomes more specific
Decide how specific you want the themeing to be (hint if unsure go to the right)
Copy the theme file name (which should be something like views-view--example--page.tpl.php) and create a new file in your theme folder with that name
Click on the display options link and copy the contents of the file from the <?php through to the bottom of the fixed width text and paste that into the new file
Add your text after the code block that looks like this:

  <?php if ($exposed): ?>

  <div class="view-filters">

  <?php print $exposed; ?>

  </div>

  <?php endif; ?>

Save the file
Click the "Back to theming information" link
Click the rescan template files link
Save your view
Visit the page your view is on


How to specify radio buttons in baseFieldDefinitions? In the baseFieldDefinitions method of my custom entity, I see I can provide a checkbox list with code like...

$fields['my_field'] = BaseFieldDefinition::create("list_string")
      ->setSetting('allowed_values', $$my_options)
      ->setLabel('My Field')
      ->setRequired(FALSE)
      ->setCardinality(-1)
      ->setDisplayOptions('form', array(
        'type' => 'options_buttons',
        'weight' => 5
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

But how would I specify radio buttons so the user can make only one selection from the list?

The radios/checkboxes are displayed based on the field's cardinality:

If the field can store more than one (e.g., unlimited: ->setCardinality(-1), or 2,3,etc. ->setCardinality(2), ->setCardinality(3), etc.), it will be displayed as checkboxes.
If the field can store only one (i.e. ->setCardinality(1)), it will be displayed as radio buttons.


How can I remove the asterisk for required fields programatically? How can I remove the asterisk Drupal inserts for required fields programatically (not hiding with CSS)?

In Drupal 7, there was theme_form_required_marker(), but that's gone from Drupal 8.

This can be removed from the theme.  I'm using a Bootstrap subtheme, so in my case I copied form-element-label-html.twig from the bootstrap templates directory into my subtheme's templates directory, then changed the following line:

  {%- if required -%}
    *
  {%- endif -%}

To:

  {%- if required -%}
    {# * #}
  {%- endif -%}

Clear caches and it's done.


Clear cache on view at a set date from a node field value? What would be the best approach to clear the drupal cache on the exact date and time that a node Date field is set to? It's easy enough to do it on node save, but if the node is to be included in views at the specific time that a date field is set to, then I would need someway to set the cache to be cleared at specific times corresponding to date field values on nodes?

If the node is scheduled to be published in the future then presumably the node will also be saved at that time, to update its status. So the cache can be cleared on node save at that point.


Submenu item linked to anchor in parent's content I would like to have a multi-level menu where some of the menus are links not to a content node, but just for inline anchors specified in the parent node's content source.

Is there an already existing solution for this feature? If not, what method should I choose for not to spend too much time on this issue?

Try:

Special menu items

Menu Firstchild


error: Fatal error: Class 'Drupal\syslog\Logger\SysLog' not found in /lib/Drupal/Component/DependencyInjection/Container.php on line 272 I just activated the module syslog in an almost fresh D8 install and now it has crashed. =( How do I deactivate a core module like this manually or fix the issue?

If this is a local install, you could install Drush, and then: drush dis module. Or you can go here for more sophisticated solutions.


Deoes any email is send when i open drupal webpage first time? I heve a not nice "error/message" from time to time on the bottom of the page... It is sth like this:

SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "220 poczta1.www.www.pl ESMTP Postfix "
SMTP -> get_lines(): $data is "220 poczta1.www.www.pl ESMTP Postfix "
SMTP -> FROM SERVER:220 poczta1.www.www.pl ESMTP Postfix
SMTP -> get_lines(): $data was ""
SMTP -> get_lines(): $str is "250-poczta1.www.www.pl "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl "
SMTP -> get_lines(): $str is "250-PIPELINING "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING "
SMTP -> get_lines(): $str is "250-SIZE 262144000 "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 "
SMTP -> get_lines(): $str is "250-VRFY "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY "
SMTP -> get_lines(): $str is "250-ETRN "
SMTP -> get_lines(): $data is "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY 250-ETRN "
SMTP -> get_lines(): $data was "250-poczta1.www.www.pl 250-PIPELINING 250-SIZE 262144000 250-VRFY 250-ETRN "

The strange thing is that this happens only from time to time and is displayed on the main page at the bottom (usser is not logged in). When user visit the page again (F5), information disappear, does that mean that the web template  have hidden code to send an email about web template usage?

You have the SMTP module set up for debug mode, so it prints the protocol exchange details for every email sent. In addition, poormanscron (which is default in Drupal 7) is being triggered by the page request.

If you turn off the debug option for SMTP those lines will no longer appear. Also you may want to set up an automated cron job so cron runs in the background rather than when users are making requests.


Australian payment gateway adapter for Pay API Is anyone aware of a working code for the Pay (7.x) module that will process payments over eWay or NAB Transact?

I am considering writing adapters for these gateways, but though I would put out a call for any existing code to start from.

There are a few modules floating around for commerce, CiviCRM and Ubercart that use eWay, they would be good basis.


Search Taxonomy Term pages containing entity referenced nodes So, I've got myself into a bit of a pickle here and was hoping that could point out a way through.

Drupal 7
Views
Display Suite
Entity Reference
Inline Entity Reference
Search API
Database Search

I have been building a sort of hybrid traditional multi-page and single-page site within the Bootstrap framework. In order to meet these requirements I have used an inline entity reference field to group multiple different nodes (each representing a Display Suite layout, such as 50%-50%, 33%-33%-33% etc) into a content type called 'Subject'. These 'Subjects' are to form each distinct row in a single-page style layout.

This has worked well, and I now need to compile these 'Subjects' into pages.

Because I want to avoid too much complexity in the workflow I decided against nesting these 'Subjects' into yet another content type called 'Page' using more entity references. Instead I went for a taxonomy vocabulary called 'Sitemap' with a term for each page, which could be selected from a term reference field in the 'Subject' content type. I then use a view to spit out all of the referenced 'Subject' nodes associated with that term as rendered entities.

TL;DR - I have a series of taxonomy term pages full of referenced rendered entity nodes.

When looking at implementing search I just can't get my head around how to index and display results. I obviously need the contents of these term pages to be indexed, but I also need to ensure that results will only point to term pages (preferably deep linked) and not any of the original nodes referenced on the term page. Granted, I'm not very familiar with it, but looking at Search API I can't see how I could achieve that.

Is this just a really silly way to achieve this kind of structure?

I stumbled upon a module called Search by Page Paths which swerves the above issue by indexing the front end of the site. This approach means that regardless of the source of my data and where it is placed, it will see anything rendered out onto a page as part of that page.

The main caveat is that one must specify paths to index, but in terms of my particular build this isn't a bad thing and means I have complete control over where a user ends up after searching.


How to consistently style the titles of Views in my Panels sidebar? My Panels website has a sidebar and I put several Views in there as Panes. Every View has a title and I would like to wrap this title in a h3 header. Until now, I manually overrode the Pane's title with %title and chose the h3 tag in the Pane's settings. This works fine, but sometimes I forget to make the adjustments and then things look ugly for a while. It is also possible that one day I prefer to use h2 instead and then I will be facing dozens of Panes to adapt.

Therefore, I would like to know whether there is an easier and more efficient way to achieve what I want. After reading Drupal 7 Views: Use one views.tpl.php file for multiple views, I thought about using a View template, but I cannot just tag the Views that will turn up in the sidebar, because some Views have multiple blocks and only one of them will be put in the sidebar.

Do you have any suggestions that might make life easier for me (or at least the website developing side)?

You just need to target it with css.

.pane-region-class .pane-title h2,
.pane-region-class .pane-title h3 {
  font-size: 16px;
  etc.
}

I think you can add classes to panel regions. And do the above without h2 / h3 to style the general title.


What ways to attach a library to a form? I created a custom form and I use a js library on it. I attached my JS in my template file but in a first time, I tried to attach it directly on my form with

$form['#attached']['library'][] = "mymodule/mylibrary"

like in D7 but it doesn't work.

I found none references to attach library directly to a form and no references to the "#attached" property so I suppose it has been remove.

My library works fine in the twig template file.

But in the case I don't used a custom template or I use various templates for various cases, can I attach my library directly to my form without pass by a hook function or must I pass necessary by the template file, a hook_preprocess or a hook_page_attachment?

Like explain by Clive, add libraries directly in the form via '#attached' parameter works. The mistake in my case was to don't send my form properly to my template file. See  Send a form to twig template


How to list page translations next to the original in the same row? D8's multilingual features are way above average compared to other major competing solutions, but I'm still missing one feature, or I don't know about it being implemented in D8.

When I create transations of the same page, I see them on individual rows, one row per translation like this:

If you have more languages, let's say 5, it's not good for clarity to have it like this. It would be much more clear if it would be possible to display the page (original) in one row and to list all the available translations of the given page on the same row, like this:

Being able to do this in D8 would be a great benefit. Is this possible in D8?

Have a look at the Translation Management Tool, considered as the successor of the  Translation Overview module, and "the" module to move forward with in D8 also. From its project page:

... provides a tool set for translating content from different sources. The translation can be done by people or translation services of all kinds. It builds on and uses existing language tools and data structures in Drupal and can be used in automated workflow scenarios.
This module does not make i18n or any other language module for Drupal obsolete. It does only facilitate the translation process.

One of its community pages also contains some related screenprints, such as this one:

Plan B
Another possible approach that might be worth experimenting with, is to try to tune the View itself, by using "rewrite results" for each of the values in the columns with "Czech", "English", etc. And use these values to rewrite them to shown an image (like "Czech.jpg", "English.jpg", etc) with an "Edit" link below it. For the "Add"-equivalent you'd have to check what value you get for a 3rd language if you don't have a translation yet: if you do get something for that also, you could using a similar rewrite result, but then with an "Add" link.


How to translate a node without creating a new node? I have translation enabled for the node type page, settings " Require language (Do not allow Language Neutral)." and " Normal - All enabled languages will be allowed".

However, when I'm creating and translating a node, it creates a new node instead of translating just the fields and storing the content in $node->body["en_US"][0]. How do I fix that?

That is the way in which the Internationalization module works, when you go to translate a node the module create a copy in another language, if you want one node with the fields transalted you must look at the Entity Translation module.

You can read more in this in Node translation vs. Entity (field) translation


How to set reading permission for each separate page? How to set reading permission for each separate page?
Do already have existing drupal setting for us to use? or I need to coding it?
Thanks.

The Content Access module allows you to configure permissions by content type or, with some additional configuration, by node (per page).  It works on D6 and D7.


#ajax['path'] vs #ajax['callback']? ajax['path']
Description: This is the Drupal menu path for a callback function
which will generate HTML and return the string of HTML to Drupal. The
result will replace the div specified in #ajax['wrapper']. This
property is infrequently used in Drupal 7 and higher, because it is
set automatically if using the #ajax['callback'] property.

However, I can't still why #ajax['path'] function offers more than #ajax['callback'].
When should I use which one?

It depends on your need.

From Form API Reference,

  #ajax['callback'] and #ajax['path'] are mutually exclusive. 'callback' is easier to use and requires less code setup, but may not provide the
  capabilities required for some functions. When you can, use
  'callback'.

In simple words the function specified in #ajax['callback'] generates the content and #ajax['path'] controls the execution of that callback.

#ajax['path'] is defaults to system/ajax which fetches the respective form from the cache and process it then calls the specified callback for fetching the new content.

However if you want alter this flow, instead of system/ajax give your custom callback(But you will end-up with writing another AJAX system).

For example Views module uses its own path(
views/ajax) instead of system/ajax. The reason is that Views doesn't want the cached form so its re-builds it again(However there is a issue going on with regards to this approach).

So just set the #ajax['callback'] alone to have AJAX Form.


theme_key does not switch theme when URL user//edit is called Hello fellows and Gurus,

I am having a problem with a mobile theme of our standard website (running Drupal 7)

We therefore have two URLs:

mywebsite.com
m.mywebsite.com

We use the ThemeKey module to redirect to the correct theme/templates. We also tried Mobile Tools, but it does not work any better, so it is currently disabled.

For most pages, the url detection works and successfully redirects to the mobile theme when m.mywebsite.com/<somepage> is called.

However, when user wants to edit his own profile (m.mywebsite.com/user/<uid>/edit), the standard page is shown instead.

Same happens with the "cancel account page" (m.mywebsite.com/user/<uid>/cancel).

However the registration page (m.mywebsite.com/user/register), and the forgot your password page (m.mywebsite.com/user/password) works OK. Even when the user is connected for the latter.

Any ideas of what could be wrong in our configuration/code ?

Here is the answer : http://drupal.org/node/1130158
To quote:

user/%/edit is an admin path. See function user_admin_paths for details.
So if you enabled an "Administration theme" at "/admin/appearance", this theme will be applied instead of any theme configured using ThemeKey.

Also: Don't forget to specify "system" in your settings for theme_key.


Drupal node add form is empty: why? Just transferred my brand new Drupal webshop to shared to host and guess what: it doesn't work.

I can't figure out that why node add page is lacking form? Everything else is in place. And to be more spefic it is just for one content type, other work fine.

I've tried drush rr, drush cc all etc. I've checked permissions etc. I'm using Display Suite forms as template for node add form.

This all of the rendered form markup that has a empty div container:

<form class="node-form node-content_type-form" enctype="multipart/form-data" action="/content_type" method="post" id="content-type-node-form" accept-charset="UTF-8" novalidate="novalidate">

</form>

And this is for anonymous users. For admins it work normally but it also has another theme.

When I tranferred the site I took a archive dump with drush and imported it into shared host.

UPDATE

Like always this Drupal like problem seemed very odd. So I decided just to change the theme and see if it has any effect.

Using the base theme of my custom the form is rendered normally.

However, custom theme works just fine on my localhost so I can't tell what is the problem. Seems like a theme issue but on the other hand not.

UPDATE 2

Base theme showed some "new" errors on second load. These errors refer to a oooold theme and shows that Drupal is trying to use that tpl file. I assume that this is the core problem which causes different results depending on theme.

'/home/user/public_html/sites/all/themes/custom_boot/node-content_type-form.tpl.php

UPDATE 3

I found the old code that registered this "theme" or template and which is still somehow required/requested on page load:

function custom_boot_theme($existing, $type, $theme, $path){

    return array('node__content_type__form'=>
            array(
                'render element' => 'form',
                //'path' => drupal_get_path('theme', 'custom_boot') . '/templates',
                'template'=> 'content-type-node-form',
            'user_register_form'=>
            array(
                'render element' => 'form',
                //'path' => drupal_get_path('theme', 'custom_boot') . '/templates',
                'template'=> 'content-type-node-form',
            ),
        );
}

How could I undo this?

UPDATE 4

If I remove this old theme and run drush rr, it will give following error every time:

    The following theme is missing from the file system: custom_boot. For information about how to fix this, see the documentation page. bootstrap.inc:1128

Even though custom_boot is removed from system table by drush rr, it will still try to find some files related to this removed theme.

UPDATE 5 - FINDINGS AND POSSIBLE SOLUTIONS

First of all it seems that the problem is somehow in the current theme.
What is it? I don't know.

Secondly, why does this site work perfectly on localhost but not on this live server? Could I make some changes to PHP ini settings that would "look through"/disregard the small hickup of missing theme? I don't understand that why localhost won't die on this missing theme problem...

UPDATE 6

Well, since I couldn't get a rid of I had to stick with it. I've just enabled this old theme but which I'm not using. Now the form shows but it is rendered with this old themes custom form template file described above.

BUT, as soon as I visit /admin/structure/types/manage/content-types/fields the form starts failing again. So Display Suite and old theme have some issues.

AND TO ADD, it is all the same if the content-type-node-form.tpl.php file has content or not: the form is rendered and I can put any code in there and it won't change or break anything.

Well, now I feel stupid. Eventually it seemed to be a file permissions related issue.

I took this https://www.drupal.org/node/244924 script and modified it per server spec.

After few trials it worked...It certainly didn't seem like a permissions related but maybe they cause various situations.


Views display labels with empty fields I've created this view that displays content an author creates in a table. Trouble is, this view only appears once the author creates at least one piece of content, is there a way to show the labels by default? ie. even when there is no content in the fields?

I tried playing about with no result behaviour, but that just overrides the whole thing. I know there is a lot of info out there on how to hide fields if there is no result but i'm looking for the opposite.

Here's the table:

Here's the view:

Cheers,
Rumman

Yes, under Advacned Options for the View there is a No Results option. You can set a global text result as an example and say "sorry no values found." Then under the Table format Settings there is a checkbox to show No Results text in Table. That will replace the empty row with your message -- while still showing the table headers.


How to get field collection values from user object? I added a field collection to the user 'manage field' page, the field machine name is 'houses'. The user may add as many home he want.

This field collection regroup :

a sample text plain field (the name of the house), the machine name
"house_name"
a sample integer field (the size of the house), the
machine name "house_size"

In a custom module, I want load the current user and get values of all values of all his houses (in an array ?), how can I do that ?

I tried this :

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$user_houses = $user->get('field_houses')->getValue();
ksm($user_houses);

But I get :

It's ok, I set 8 houses in "user edit" page, so I get an array of 8 entries. But, I would like get all data in an array like this :

house 1 : name1 : size1
house 2 : name2 : size2
...
house 8 : name8 : size8

Thank you :)

I find =)

With :

use Drupal\field_collection\Entity\FieldCollectionItem;
...
$test = FieldCollectionItem::load(3);

Where "3" is, by example, a value returned by $user->get('field_houses')->getValue();


Changing a form value or input field value during the submit handler I am trying to change the value of a text area field at the end of my submit handler. I have tried using form_set_value and $form['form_id']['#value'] = 'something'; to accomplish this but after clicking the submit button the field never changes. Also the submit button that I am trying to change the field with comes from the file managed form. I also included $form_state['rebuild'] = true; after I set the field's value. Here is my code

function my_module_my_form_submit($form,&$form_state) {

//do something with then file code
...

then

$form_set_value($form['value_to_change'], 'update the value, $form_state);

//I also tried

$form['value_to_change']['#value'] = 'update the value';

$form_state['rebuild'] =TRUE
}

In the form my code is

$form['value_to_change'] = array(
'#type' = 'text area',
'#value' => 'this will change',
);

Just stumbled upon this and it's pretty dead so here's the answer in case OP still cares... turns out @Mołot is right.

The correct way to programatically change a form's submitted value is actually during validation and not during submission.

If you go back and re-read the documentation for form_set_value(), you'll notice that it explicitly says:

  Changes submitted form values during form validation.


style doesn't reflect what's in css On my page http://www.athleticedgefitness.com/, I added a drop down menu under Contact. The hover color is yellow but for some reason, I cannot find that color style in my colors.css. What I found is that the devtools show that the background color change is caused
by a rule starting at line 44 in
http://www.athleticedgefitness.com/sites/default/files/color/corporateclean-659c1a2d/colors.css?mp37st
The rule is:

#header-menu ul.menu li ul.menu li a:hover,
#header-menu ul.menu li.expanded ul.menu li.expanded a:hover,
#header-menu ul.menu li.expanded ul.menu li.leaf a:hover,
#navigation .block-superfish ul.sf-menu li li:hover,
#navigation .block-superfish ul.sf-menu li li a:focus, #navigation
.block-superfish ul.sf-menu li li a:hover, #navigation .block-superfish
ul.sf-menu li li a:active  { background-color:#fbff24; }

But If I check in my colors.css, my rule actually looks like this:

#header-menu ul.menu li ul.menu li a:hover,
#header-menu ul.menu li.expanded ul.menu li.expanded a:hover,
#header-menu ul.menu li.expanded ul.menu li.leaf a:hover,
#navigation .block-superfish ul.sf-menu li li:hover,
#navigation .block-superfish ul.sf-menu li li a:focus, #navigation .block-superfish ul.sf-menu li li a:hover, #navigation .block-superfish ul.sf-menu li li a:active  { background-color:#1b1b1b; }

I have tried to clear the caches and everything but that didn't help either, any recommendations? This is in Drupal 7.x with the Corporateclean theme.

Thank you!

Have you checked the css file route (Chrome will show that in the dev tool) that the website is reading? I use superfish as well, there are some css files for the menu bar in '.../sites/all/superfish/css/', but I also have my overriding style in my custom theme folder. Are you sure the browser is linking to the css file that you think it is linking to?

And, that happened to me once, probably is not your case, but I once forgot to save my css after editing it :P

Good luck.


How to run jquery function on every page load I have a Views grid that contain images in DIV containers. I want these containers to have one of two possible heights 60px or 104px, depending on the images height. So I came up with this function (contained in a $(document).ready function())  that I have added in my theme's JS file.

  $('div.givarbild img').each( function() {
    var container = $(this).closest('div.givarbild');
    var pic = new Image();
    pic.src = $(this).attr("src");
    var picHeight = pic.height;
    console.log(picHeight);
    if(picHeight < 60){
        container.height(60);
    }else if(picHeight > 60){
        container.height(104);
    }

  });

Now, my problem is that this only works once, after clearing the caches in Config -> Performance. If I simply reload the page after clearing all caches in Drupal all DIVs are 60 px high and the container.height value is zero in the js console (Firebug).

How can I force this little function to run after every page load?

EDITED:
Hmmm, I am obviously doing something wrong here :-)... but with this code:

(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                var pic = new Image();
                pic.src = $(this).attr("src");
                var picHeight = pic.height;
                console.log(picHeight);
                if(picHeight < 60){
                    container.height(60);
                }else if(picHeight > 60){
                    container.height(104);
                }
            });
        }
    }
})(jQuery);

... I get the exact same result. It works immediately after clearing all caches in Drupal 7 but not when I reload the page after that. Is there something fishy with my custom script itself?

EDITIED AGAIN: I post this change to my js code in case anyone else is having the same issue. This code does the same thing as the previous one, except that it works every time, and not just the first time after clearing all caches in D7. The only thing I changed was the method for getting the natural image height. It would be interesting to know why this latter code works though and not the first one... it actually works every time even without the added Drupal.behaviors rows.

(function($) {
    Drupal.behaviors.related_content = {
        attach: function (context) {
            $('div.givarbild img').each( function() {
                var container = $(this).closest('div.givarbild');
                $("<img>").attr("src", $(this).attr("src")).load(function(){
                    var picHeight = this.height;
                    console.log(picHeight);
                    if(picHeight < 60){
                        container.height(60);
                    }else{
                        container.height(104);
                    }
                });
            });
        }
    }
})(jQuery);

(function ($) {
  Drupal.behaviors.custom_scripts = {
    attach: function (context) {

      //write your custom code

    }
  }
})(jQuery);

Along with this for the first time you have to clear cache, and this will work in all pages and all the times.


How to manage tickets event? I have to handle tickets request. Let me explain (sorry for my english):

On the site, each authenticated user create a club (Master Club) and members (Master Members). Master Club and Master Members are two content types.

Each club administrator (authenticated user) must be able to send a request for tickets event and indicate the tickets number by listing the name, address and other data of the shareholders chooses from its list.

The structure is similar TICKET module: Site administrator create a content type EVENT. For each EVENT specify the sector( SECTOR_A, SECTOR_B,.....) and for each SECTOR how many tickets want.

scenario: Let's say you require 3 tickets for SECTOR_A and 2 tickets for SECTOR_B:

This request must be sent to the site administrator which can confirm this request or notify club administrator that instead of 5 tickets they can take only 2 tickets for SECTOR_A and 1 tickets for SECTOR_B..

The club administrator receives this notification and can accept the site administrator's request indicating the members(from its membership list) who want to assign these 3 tickets or refuse.

How set it ?

The Ticket module is a good point to start.

  Ticket is a module that provides ticketing and registration for events
  (and more abstractly, entities). Events may have multiple ticket
  types, each with a unique set of requirements and registration fields.


Can I store a computed field as a field of a Content Type? In content type = Person, I have these fields:
- First Name  [node:field_person_first_name]
- Middle Name  [node:field_person_middle_name]
- Last Name  [node:field_person_last_name]
- Suffix  [node:field_person_suffix]

In views, I have successfully concatenated the full name by adding Global: Custom text and using Replacement Patterns to build the fields. However, this is time consuming.

These fields will always be put together in both of these two ways:
- full name, last first
- full name, first first

Is there a way that I can create two computed fields for these which I could store in the content type? If so, how do I do this? Note: I don't want to modify the original data.

Update:
I have Entity Token and Token already. I loaded Token Filter. I found, but have not yet loaded Token Field.

Token Field suggests that it might be nice if one could define a field "without needing to know any PHP" but the samples on this page indicate otherwise. My HTML knowledge is slight and PHP is non-existent.

I did follow a training video which gave me access to some tokens when creating a new field in Person, but these did not include tokens for fields within the Person content type.

Will this be possible (without PHP) if I install Token Field?

Update 2:
The site simplytest.me is excellent. Token Field loaded. Unfortunately in a real test, I'm getting "Cath [node:field_person_middle_name] Staincliffe [node:field_person_suffix]" because author Cath Staincliffe doesn't have a middle name or suffix. Do you know how to instruct the module to only use a name if one exists?

The Concat Field module looks like it can do what you want. From the README:

  This module provides a new field type that allows you to select other
  fields from that content type (or any bundle), and it will concatenate
  their display values into a single field on save.

  The example use case is then using the field as an exposed filter in a
  View.

Or you can write some code to do it via a custom module that calls the hook_node_presave function. In your content type definition, create the fields you want, and set their display type to Hidden. Then, in your function, set the values. See the answer to this question for more info:

How to use hook_node_presave to change field's value

Edit:

While it looks useful at first glance, the Concat Field module is very limited. You can't change the order of the fields, and it requires patches in order to generate any kind of output.

Another option would be to use the Token Field module. With this module, you can create a field into which you can enter tokens. This will give you a lot more flexibility - you can place the fields in whatever order you want, and specify punctuation or other characters around them.

2nd edit to answer updated question

  Token Field suggests that it might be nice if one could define a field
  "without needing to know any PHP" but the samples on this page
  indicate otherwise.

My interpretation of the Token Field page is you only need to know PHP if you want to use conditional tokens, and that's what the sample code illustrates.

  Will this be possible (without PHP) if I install Token Field?

In theory, yes, but the only way to know for sure is to try it. If you're worried about compromising your site or database, install Token Field on simplytest.me and set up your content type there.


How can I fix the pages pager returns? I have a number of "product nodes" that I'd like to return and display in a paged table.

The original query is generated as follows:

    $productNodeQuery = db_select('node', 'n')
    ->fields('n', array('nid'))
    ->condition('type', 'product', '=')
    ->extend('TableSort')
    ->extend('PagerDefault')
    ->limit($page_limit);

    $productNodes = $productNodeQuery->execute();

This returns all the products I want, however the pages are all messed up. Some pages have 3 items, some pages have 10, others have the full $page_limit (50) items per page.

I have a loop

foreach($productNodes as $productNode) {
....
}

to iterate over the results and add each product to the $rows[] array with this:

 $rows[] = array(
            'data' => array(
            'autoupdate' => $part['autoupdate'] == "1" ? 'ENABLED' : 'DISABLED',       // Display Checkbox?
            'part_number' => $part['part_number'],
            'title' => l($this_node->title, url($base_url . '/node/' . $this_node->nid)),
            'category' => l($this_category_name, url($base_url . '/catalog/' . str_replace(' ', '-', $this_category_name ))) . "
(Markup: " . $this_markup_percent['suggested_markup']*100 . "%)",
            'supplier_price' => $supplier_prices_string != "" ? $supplier_prices_string : "N/A",
            'suggested_price' => isset($suggested_prices_string) ? $suggested_prices_string : "N/A",
            'sell_price' => '$' . number_format($this_node->sell_price, 2),
            'competitors_price' => isset($competitor_prices_string) ? $competitor_prices_string : "N/A",
           'edit_node' => l('Edit Node', $edit_node_link, array('attributes' => array('target' => '_blank'))),
           'message' => "" . $row_message . "",
                ),
           'class' => array($row_class),
  );

Finally, after the $rows array has been defined with all the data I need I am building the table with this:

$form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => 'There are no product nodes found',
);
$form['pager'] = array(
    '#markup' => theme('pager')
);

Does anyone have an ideas as to where I'm going wrong with the pager?

(Full Form Code is available here: http://pastebin.com/bna1g1iV)

Thanks,

I would add this as a comment if I could. Looking at your code, it looks like you're only adding rows to $rows is $part['wtcr_sku'] is an empty string (line 258). It's possible you could be filtering out rows because of that.


How to add the value of a drupal field to the class of a wrapper div Working on a clients drupal 7 site, I have a content type that is promoted to the front page. The content type has a list field, I want to use the value of that field to add a class to the wrapper div on the node teasers populated to the front page. For example the html output would be something like this:

<div class="field_value">
content
</div>

I'd prefer not to have to use a view or nodequeue to do this as it's easier on the client administering their site to simply promote items to front page.

I've been trying to add the class in the node.tpl.php file but for some reason I just can't get it to work. I've tried creating a preprocess variable in the template.php file but all I get in the output is: div class="Array".

Does anyone have any ideas on why I'm just getting the word "Array" output? or any ideas on how to solve my problem?

Thanks

Something like this should do it:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node'] == 'some_type') {
    $field_items = field_get_items('node', $vars['node'], 'field_name');
    $first_item = array_shift($field_items);

    $value = $first_item['value'];

    // If you want to write <div class="<?php echo $extra_class; ?>">... in your template file:
    $vars['extra_class'] = $value;

    // Or if you want to add this to the classes on the main node <div>:
    $vars['classes_array'][] = $value;
  }
}


How to set relationship when I create a new (custom) content to another (custom) content in Drupal Premise: I'm new in the world of Drupal, so sorry if this is a stupid question.

What I need is to set some relationships for some new content types I created. For example, I created the "Person" content type and the "Group" content type. Using the "Relation" module I have defined the relation "is in", but now if I want to add a field for setting the relation at creation time, there are no edit widget available. The only way I found to set relationships is using the entity collector: too complicated for a user.

Example: a user creates the Person "John", and he want for him to set the relation "is in" with the Group "Drupal fans". So, during the creation of this Person he needs, for example, a select control that lets him to choose from all the groups already registered in the site.

In brief, I need to manage some entities created by me, with CRUD controls, list, etc. and I need to set some relationships from these entities.

What is the best method/ what are the best module/ how I can do this?

I hope I'm understanding your question correctly... you'd like to know what's the best way, in Drupal 7, to add a reference to a node of another content type when creating this content type?  (i.e. to store a reference to a 'Group' when creating a new 'Person')?

If that's what you're trying to do, a good way to do that in Drupal 7 is using the Entity reference module.

Once you download and enable this module, you'll be able to go to the 'Manage fields' tab of your 'Person' content type and select to create a new field of type 'Entity Reference'.  That field option will only appear once you've enabled the module.  Before hitting 'save' after you've selected that field type, make sure you notice that you'll have two options for the field widget: you can select for it to be a 'Select list' in which case, it will just have a drop-down list of all the Groups currently available on your system for you to choose from when creating a person.  Or you could choose 'Autocomplete', which works better if you have a TON of groups and don't want a super long list.  That'll allow the user to start typing the name of a group, and it will just automatically detect and complete it.  :-)

Once you've selected those two options on the first screen, on the second screen you should select 'node' as the 'Target type' and select 'Group' as the type of the referenced node.  Finally, just choose whether you want that field to be required or not and whether you should select only one or multiple values (like any other field).

Let me know if that works for you, and I hope I understood your question correctly!!


Hook Form Alter Specific Node I want to put a hook to a form on one specific form that I created. Based on Node ID.  The code i currently have is .

The $form array contains a #node key which has the nid attribute. Use that to filter like so:

if($form['#node']->nid == 1072) { ... }

However, since you ask for page-node-1072 it sounds like you want to put something in that particular page template, in which case you should use a process or preprocess function to add or alter variables for the template.


How should I read values from multi-field's subfield? I'd like to access values stored in a Multifield programmatically. I use a Computed Field to do some calculations based on these values.

My current solution utilizes field_get_items(... ,'my_multifield') which returns a data structure containing an array of (sub)fields. Of course, I could extract values from that data, but I wonder if there is a better solution.

I took a look at the multifield source code, especially the tests, but I could not figure it out. What is the intended method for reading values from multi-fields?

field_get_items() is the only function provided by core to help with this.

The Entity module provides the EntityMetadataWrapper class, though, which makes these things a bit more palatable. E.g.

$node_wrapper = entity_metadata_wrapper('node', $node);
try {
  foreach ($node->field_my_field as $item) {
    $val = $item->value->value();
  }
}
catch (\EntityMetadataWrapperException $e) {
  // Recover...
}

That's about the simplest example there is, it would be worth reading the docs to find out how else you can use it.


How do I load an entity? How can I load the entities shown in the following screenshot?

Use loadMultiple():

$storage = \Drupal::entityTypeManager()->getStorage('default_entity');
$config_entities = $storage->loadMultiple();
$list = [];
foreach ($config_entities as $id => $entity) {
  $list[$id] = $entity->label();
}


Creation of products completely except the admin I am using Drupal Commerce and I need to let my users to create products without the product display.

I thus adjusted the permissions, but when a user creates a product, 1/ the url is the one of the admin admin/commerce/products/add/1 and 2/ once the created product, the user has a access denied.

My question: how to let the users to create products completely except the admin (modification of the url etc.) ?

One option is to use a custom node bundle along with Rules. Allow the users to create the new node type. Then, when the node is being saved, use Rules (or a custom module) to take the values that were entered into the node form and carry them over to a product and save it.


Problem with Three hierarchical dropdown for country, state city I am new in drupal and I am working on one form where I need to create Country, State and city interdependent,hierarchical ajax dropdowns. So far I could achieve country and state dropdown but while making city dynamic on change of state is not working. It calls same callback and wrapper which I used for country even if I kept them separate. Please check below code

$form['account']['country_id'] = array(
    "#type" => "select",
    "#title" => t("Select your country."),
    "#options" => $countryArray,
    '#ajax' => array(
        'event'=>'change',
        'callback' =>'my_module_ajax_dropdown_state',
        'wrapper' => 'state-wrapper',
    ),
    '#id' => 'country',
    '#required' => true
);

 if (isset($form_state['values']['state_id'])) {
    // Pre-populate options for city dropdown list if province id is set
    $cityOptions = _load_city($form_state['values']['state_id']);
 }

// Options for city dropdown list
$stateOptions = array('- Select state -');
if (isset($form_state['values']['country_id'])) {
    // Pre-populate options for city dropdown list if province id is set
    $stateOptions = _load_state($form_state['values']['country_id']);
}

$form['account']['state_id'] = array(
    "#type" => "select",
    "#title" => t("Select your county/State."),
    '#prefix' => '
',
    '#suffix' => '
',
    "#options" => $stateOptions,
    "#ajax" => array(
        'event'=>'change',
        'callback' =>'my_module_ajax_dropdown_city',
        'wrapper' => 'city-wrapper',
    ),
    '#default_value' => '--Select State--',
    '#id' => 'state',
    '#required' => true
);

$form['account']['city'] = array(
    "#type" => "textfield",
    "#title" => t("Enter your city."),
    '#id' => 'city',
    '#prefix' => '
',
    '#suffix' => '
',
    '#required' => true,
    '#default_value' => $account->city
);

These are my callback functions which are returning form element

function my_module_ajax_dropdown_state($form, $form_state){
  return $form['account']['state_id'];
}

function my_module_ajax_dropdown_city($form, $form_state){
 return $form['account']['city_id'];
}

I am trying to figure it out but no success yet. Please help me.

Thanks

I was facing the similar issue in my drupal site.
The other issue was the performance especially for IE where it took too much time in rendering the new item.

After some experiments, I made the following module that can help in making three hierarchical dropdown for country state and city. Its developed in a generic way that it can be used for n number of dependent dropdowns and can be used for other dependent data as well.

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


Why is drupal resizing my images? In drupal I'm displaying a view in a block. I'm stripping out all the html and rewriting the results as this

[field_button_image]

On the preview it looks okay, but in the block that contains the view it renders the image like this

The image is distorted because of the width and height styling that is added in the tag. Where is this coming from? And is it possible to disable it?

Check your content type. what is default image type in manage field display. set it Original image. hope this help!


How to securise custom modules I'm trying to understand how to securise my custom modules to avoid php insert into custom inputs and SQL injections in my db_query.

For inputs I'm using :

$form['custom'] = array(
      '#type' => 'textfield',
      '#title' => t('Custom),
      '#description' => t('Custom'),
      '#default_value' => '',
)

I tried to insert some PHP in the input and it actually run it whereas in the documentation it saiys that using form API should escape PHP by using check_plain and the safe example given is :

$form['also_safe'] = array(
  '#type' => 'select',
  '#default_value' => 0, // FAPI will pass through check_plain(),
  '#options' => node_get_types('names'),  // FAPI will sanitize the '#options' attribute with check_plain() for select boxes.
);

So what am I doing wrong ?

Concerning my SQL query I can't succeed to use as documented :

$result = db_query('SELECT $ FROM {custom} WHERE uid= :uid", array(':uid' => $value['in_array'])).

When calling a non object value I just get an error, so doing something like that works well but doesn't escape SQL injection :

$to_user_balance = db_query("SELECT * FROM {ubercart_funds_user_funds} WHERE uid=" . $value['in_array']));

I have to precise that I'm actually learning PHP and still didn't get what objects are. Because my aim is result and not capability, if somebody can explain me quickly how to securise my queries and inputs or drive me to a clear documentation.

I already know those documentation page and didn't help :

Handle user input with care
db_query

It's a better idea to use db_select or other DB API functions, rather than trying to use db_query directly. You'd want to try something like:

 $to_user_balance = db_select('ubercart_funds_user_funds', 'ucfuf')
   ->fields('ucfuf')
   ->condition("uid", $value['in_array'], '=')
   ->execute()
   ->fetchAssoc();

For more, see https://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_select/7.x

And for overall DB API docs, see: Drupal.org DB API docs


Organic-Groups multisite architecture I have a task to build a series of websites all related to the same core business.

Initially, I was going to build each one as a separate website.
Later however, I was told the sites have to be able to share content which changed my plans.

Going by the logic that the easiest way to build multiple Drupal websites which share content is to build one site and make it work and appear as many.

So, I decided to build the site in Organic Groups but I have the following functionality challenges.

How can I direct unique URLs to individual Groups on my site. I:E configuring www.mysite.co.uk to visit Group#1 and www.mysite.com to visit Group#2 etc
Is there a way to create content on the Drupal site which can optionally be shared/posted to one or more of my Groups? The idea is to create content on the primary 'website' and the same content displays in the Groups/'sub-sites'.

I would appreciate any suggestions.

Thanks.

Honestly, I think that the module Domain Access would meet your needs more than Organic Groups would. A friend of mine recently created a site matching exactly your criteria.

  Module Package includes:

  Domain Alias 6.x.2 and higher only by bforchhammer. Allows you to
  specify subdomain aliases and domain name patterns for domain entries
  so that multiple hostnames are matched on a single domain entry.

  Domain Configuration -- Allows you to change select system variables
  for each subdomain, such as offline status, footer message and default
  home page.

  Domain Content -- Provides a content administration page for each
  subdomain, so that affiliate editors can administer content for their
  section of the site.

  Domain Navigation -- Supplies a navigation block with three themes.
  Creates menu items for each subdomain, suitable for using as primary
  or secondary links.

  Domain Path -- Enables custom path aliases per domain.

  Domain Prefix -- Provides a user interface for enabling select
  database table prefixing for use with subdomains. The Drupal 5 version
  is not fully functional on pgSQL, but Drupal 6 version is.

  Domain Settings -- Exposes domain-sensitive variable settings to most
  configuration forms. Requires Domain Conf.

  Domain Source -- Allows editors to set a primary source domain when
  links are written to content from other domains.

  Domain Strict -- Forces users to be members of domains in order to
  view content. This is a sample extension module that uses the API.

  Domain Theme -- Allows separate themes, theme settings and colors for
  each subdomain.

  Domain User -- Allows for the automatic creation of subdomains for
  registered users.

  Domain Views by mrichar1 and nonsie -- Provides Views integration for
  Views 5.x.1 and 6.x.2 or higher.


Is there a way to determine what styles can be used for a nice menu? I am attempting to style a 3-level "nice menu" but between the themes and menu styles, I am having a hard time finding the correct styles to change.  I am using firebug, but I cannot get the styles for some menu items, because moving the cursor over them changes them to hover (or focus).  Unselected menu items are not displaying consistently at all levels the way I want and I cannot identify the styles without hovering on them.  I need to find out what the full styling options are so that I can figure out what is affecting them.

On the HTML tab of firebug there is a "break no mutate" button that will stop whatever javascript adds/changes HTML. This can be used to trap something that is a result of a nice menus change. It can be a little tricky as each hover initiates some javascript and then when you continue execution the break on mutate is turned off, but it gets easier with practice :)


Get pure SQL from Drupal::entityQuery Given the following code, how can I print the SQL that is generated?

$bundle='my_bundle_type';
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', $bundle);
$entity_ids = $query->execute();

What I have tried:

__toString() doesn't work
dpq($query) throws an error

With debug tag (devel module is mandatory) we can print the raw sql.

$query = \Drupal::entityQuery('foo')->condition('bar', 'xyz')->addTag('debug');
$ids = $query->execute();


How to run hook_update for the database Suppose we have a simple module with 3 files: test.info, test. install and test.module.
test.install
<?php
function test_schema() {

    $schema['test'] = array(
        //fields
        'fields' => array(
            'id' => array(
                'type' => 'serial',
                'unsigned' => true,
                'not null' => true
                ),
            ),
        //additional properties
        'primary key' => array('id'),
        );

    return $schema;
}

When I install the module via the web interface, the table is created. Then I add hook_update:
function test_update_7100() {
    $spec = array(
        'type' => 'varchar',
        'description' => "New Col",
        'length' => 20,
        'not null' => FALSE,
        );
    db_add_field( 'test', 'name', $spec);
}

Now I need to run the update function to modify the table. But I don't know where I can do it. Module is not present in "Modules" -> "Update".

You can run just drush updb -y on your site folder.


Exclude first node with specific value from a view? We have an Article content type. The content type has a boolean field called "Featured".
We have two views setup:

The featured article view. This is limited to the most recent article with the "Featured" boolean checked (limit 1, sort by date).
The recent articles view. This shows all the recent articles on the site.

The problem is we don't want the most recent "Featured" article to display in the recent articles view. But we also want other "Featured" articles to display if they aren't the most recent.
I can't find an easy way to achieve this as we are only allowed to filter out ALL featured articles or none, and not just the first one.

The easiest and fastest way I can think of is to use an offset in your pager.
If the most recent featured article is to be skipped, ensure that the list does not start with the first, but with the second result. You can do this for any pager, or even with a fixed amount of items to display.

Alternatively, but that is easier with a node and a view, you might be able to use a contextual filter to suppress a Content ID from a views listing. I have used to populate a sidebar view with all recent articles except the viewed one.
In your situation it might be an issue getting the Content ID from one view to another though


How to add Google Analytics per theme? Is there a way to add GA per theme. The reason for it is I am using themekey to switch the theme for mobile users.

I have read that it is possible to add more than one tracking code on a site but would like to split them between Main and Mobile.

To add google analytics to every theme,some manual work is required as:-

In your theme's folder ,
select a theme in which you want to add google analytics
open the theme folder and then create a folder for js files
create a js file and include the code provided to you by google for google analytics.
save the file and this way google analytics is installed in your theme.
follow the same procedure for rest all themes.


Programmatically creating an order in Drupal Commerce for anonymous users redirecting to payment page Ryan has some great code that you can programmatically create an order

<?php
global $user;
$product_id = 1;
// Create the new order in checkout; you might also check first to
// see if your user already has an order to use instead of a new one.
$order = commerce_order_new($user->uid, 'checkout_checkout');

// Save the order to get its ID.
commerce_order_save($order);

// Load whatever product represents the item the customer will be
// paying for and create a line item for it.
$product = commerce_product_load($product_id);
$line_item = commerce_product_line_item_new($product, 1, $order->order_id);

// Save the line item to get its ID.
commerce_line_item_save($line_item);

// Add the line item to the order using fago's rockin' wrapper.
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
$order_wrapper->commerce_line_items[] = $line_item;

// Save the order again to update its line item reference field.
commerce_order_save($order);

// Redirect to the order's checkout form. Obviously, if this were a
// form submit handler, you'd just set $form_state['redirect'].
drupal_goto('checkout/' . $order->order_id);
?>

http://www.drupalcommerce.org/questions/3259/it-possible-drupal-commerce-work-without-cart-module

I have a site where I want to take anonymous donations so I have two problems.

If a user is not logged into the site they get an access denied message
The checkout process asks for name, address etc.

What I want to do is have a page where you confirm the amount then get taken to the payment page. In this case I am using PayPal WPS so redirecting there would be great.

Any advice you could give would be appreciated.

You may try to test a new module called Commerce Drush which has the following syntax:

drush commerce-order-add 1
drush --user=admin commerce-order-add MY_SKU123

Manual solution

For creating an order programatically in Commerce, you can use the following code (it works with drush as well, e.g. drush -vd -u "$1" scr order_code-7.php).
Please note that commerce_payment_example module is required.

<?php

  if (!function_exists('drush_print')) {
    function drush_print ($text) {
      print $text . "\n";
    }
  }

  $is_cli = php_sapi_name() === 'cli';

  global $user;

  // Add the product to the cart
  $product_id = 5;
  $quantity = 1;

  if ($is_cli) {
    drush_print('Creating new order for ' . $quantity . ' item(s) of product ' . $product_id . '...');
  }

  // Create the new order in checkout; you might also check first to
  // see if your user already has an order to use instead of a new one.
  $order = commerce_order_new($user->uid, 'checkout_checkout');

  // Save the order to get its ID.
  commerce_order_save($order);

  if ($is_cli) {
    drush_print('Order created. Commerce order id is now ' . $order->order_id);
    drush_print('Searching product ' . $product_id . ' in a Commerce system...');
  }

  // Load whatever product represents the item the customer will be
  // paying for and create a line item for it.
  $product = commerce_product_load((int)$product_id);

  if((empty($product->product_id)) || (!$product->status)){
    if ($is_cli) {
      drush_print('  Cannot match given product id with a Commerce product id.');
    }

    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }

  if ($is_cli) {
    drush_print('  Found a Commerce product ' . $product->product_id . '.');
  }

  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

  if ($is_cli) {
    drush_print('  Added product to the cart.');
  }

  // Save the line item to get its ID.
  commerce_line_item_save($line_item);

  // Add the line item to the order using fago's rockin' wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  if ($is_cli) {
    drush_print('Saving order...');
  }

  // Save the order again to update its line item reference field.
  commerce_order_save($order);

  // Redirect to the order's checkout form. Obviously, if this were a
  // form submit handler, you'd just set $form_state['redirect'].

  if ($is_cli) {
    drush_print('Checking out the order...');
  }

  commerce_checkout_complete($order);

  if ($is_cli) {
    drush_print('Marking order as fully paid...');
  }

  $payment_method = commerce_payment_method_instance_load('commerce_payment_example|commerce_payment_commerce_payment_example');

  if (!$payment_method) {
    if ($is_cli) {
      drush_print("  No example payment method found, we can't mark order as fully paid. Please enable commerce_payment_example module to use this feature.");
    }
  }
  else {
    if ($is_cli) {
      drush_print("  Creating example transaction...");
    }

    // Creating new transaction via commerce_payment_example module.
    $charge      = $order->commerce_order_total['und'][0];

    $transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
    $transaction->instance_id = $payment_method['instance_id'];
    $transaction->amount = $charge['amount'];
    $transaction->currency_code = $charge['currency_code'];
    $transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
    $transaction->message = 'Name: @name';
    $transaction->message_variables = array('@name' => 'Example payment');

    if ($is_cli) {
      drush_print("  Notifying Commerce about new transaction...");
    }

    commerce_payment_transaction_save($transaction);

    commerce_payment_commerce_payment_transaction_insert($transaction);
  }

  if ($is_cli) {
    drush_print("Marking order as completed...");
  }

  commerce_order_status_update($order, 'completed');

  if ($is_cli) {
    drush_print("\nDone.");
  }

Note: As suggested in the comment, if you got error about payment method is unknown while saving the order, make sure you've specified it, e.g.

$order->data['payment_method'] = 'commerce_payment_example|commerce_payment_commerce_payment_example';
commerce_order_save($order);


How do I customize the html of each field in a view? I have a custom theme and I want to edit the HTML of a view. I am able to create template overrides but I get stuck, it seems like the editable part of a view does not go deep enough.

I have a view displaying all of a content type. The content type has the following fields a name, an image, a link, and a description. I want to edit all of these with custom elements, classes, ids, etc and change the order of them. However the deepest I can get into a view is the $row variable, which already has this content formatted.

I've ran a function called views_get_current_view(). When I run it's return through print_r I see the information I need deep inside of it, but when I try to grab that information Drupal runs out of memory, I do not want to allocate more memory and I don't think that's the best way to solve the problem.

Long story short - I'm trying to get the fields of each node in a view and customize their html, when I get that data from a view it seems to already be already coded.

Thanks

If you are create any content type and select any content type name ex : your created a "news" is content type and many field as a 'id','name' etc.

after you have add a one php file name as a 'node--news.tpl.php'

and clear caches

this file always call a news content data


How to add custom Views filters (for example, date between X & Y, but specified by myself) As per title. I am aware that there is a specific filter for date between X and Y, but if I wanted to programmatically develop it, what ways are there to do this?

EDIT : To be more specific, I am using Views 3 so that I can use apache solr views on Drupal 6.

Date ranges in solr views still being worked on - see http://drupal.org/node/642430 for latest patch from July 11 2011


Custom html output of form I want to theme a form in drupal. I know I can add and remove things to the form using hook_form_alter(), change the text etc. Great!

I also want to add some custom html to the form. For example adding a div with some text between two form elements.

I want to do this on the comment form. The comment form has the ID comment_form. So I need to add it to the theme registry.

function mytheme_theme() {
    $items = array();
    $items['comment_form'] = array('comment_form' => array('arguments' => array('form' => NULL)));
    return $items;
}

So I then need to add a function to be called

<?php
  function mytheme_comment_form($form) {
    // stuff goes here
  }
?>

How do I affect the html in this function and render it on the page?

You can add the html in your form_alter, just use '#type' => 'markup'.


drupal webform Confirmation Message I have got a webform in a iframe and its quite long when a customer fills the details and clicks submit they just see a white screen because the page has been scrolled down due to the form been very long and they have to scroll back up to see the confirmation message.is there anyway when they click submit the scroll resets?

you can use this js code

 $('.page-node-webform #edit-actions #edit-save').click(function() {

                return confirm('Are you sure?');

            });


How to change the author of a node after payment using the rules module? I would like to use the rules module to change the author of a node after payment.

Even though I have limited experience with the rules module, I am sure it is possible to do.

This is what I'm looking for:

Client pays for existing node.
Ownership of the node is transferred to that client.

Any help would be greatly appreciated!

This seems like a variation of the question "Change node author on node save with rules". And the accepted answer there (with the comment added to it) seems the answer to it.

Does this answer your question?


How do I find and alter the Views field markup in Drupal 8? Below is a twig template: core/modules/views/templates/views-view-unformatted.html.twig:

{#
/**
 * @file
 * Default theme implementation to display a view of unformatted rows.
 *
 * Available variables:
 * - title: The title of this group of rows. May be empty.
 * - rows: A list of the view's row items.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's content.
 *
 * @see template_preprocess_views_view_unformatted()
 *
 * @ingroup themeable
 */
#}
{% if title %}

{{ title }}

{% endif %}
{% for row in rows %}

    {{ row.content }}

{% endfor %}

How do I alter the markup (and add some php logic) in row.content? - which outputs markup such as:

Hello world!

Presumably, there is another twig template for this markup? I cannot find it. I have the twig debugger turned on, but there are no notes above the markup that renders each content field.

I've looked at the template preprocess functions in views.theme.inc too - can't see any markup being generated in those things.

Thanks

First, enable twig debugging in sites/default/services.yml.

Then that should print a wrapper around each template that tells you which template it is exactly using for that piece of marking. In this case, it is probably views-field.html.twig or so.

Twig also reports what kind of suggestions you can use (e.g. a node type specific template for node.html.twig), but that doesn't work for views because views uses a different approach for that, and twig debug doesn't understand that yet.


how do i get fields value of webform before entering into database? I want value of a hidden field of webform in custom module so that i could match it with other value from database to validate it

You can use hook_form_alter to achieve this in your custom module.

/**
 * Implementation of hook_form_alter().
 */

function your_custom_module_name_form_alter(&$form, &$form_state, $form_id) {
  // Add validation for a particular Webform node:
  if ($form_id == 'webform_id') {
    // Simply add the additional validate handler.
    $form['#validate'][] = 'mycustom_extra_validate';

    //$first = array_shift($form['#submit']);
    //array_unshift($form['#submit'], $first, 'mycustom_extra_submit');
  }
}

/**
 * Validation handler for Webform .
 */
function mycustom_extra_validate(&$form, &$form_state) {
  //condition to check validation
}


How to remove "FILE NAME SUGGESTION" from rendered HTML I'm using D7.

I want to remove "FILE NAME SUGGESTION"(please refer to the uploaded image) from pages.

Honestly, I have no idea why it is displayed nor when it was enabled...

So, I searched the ways to enable that IN ORDER TO DISABLE NOW.
I found there are three possible ways to enable it (Sorry if those ways are wrong because of my mis-understanding English):

Make $conf['theme_debug'] = TRUE; in settings.php
Implement function like

function mytheme_preprocess_page(&$vars, $hook) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

Use Theme developer module

About 1, I checked settings.php and found $conf['theme_debug'] = TRUE; comment out in that.

About 2, I checked my template.php and found I coded the function mytheme_preprocess_page(&$vars, $hook) {...}. So, I removed it.

About 3, I installed Theme developer module but it made all pages blank white pages. So I manually updated the module's status from 1 to 0 of the module on system table on the database, and uninstalled.

So, now I don't know why it still output "FILE NAME SUGGESTION". Does anybody have any idea why?

I found the reason why "FILE NAME SUGGESTION" was still output.
It is because a following code still remained in template.php in Zen(not sub theme).

$GLOBALS['conf']['theme_debug'] = TRUE;

I didn't coded it by myself. So, I guess the code was added when I install some module(probably Theme developer?).

Anyways, when I comment out it,  "FILE NAME SUGGESTION" disappered.


how can i add a subterm of taxonomy in code $vocabulary = (object) array(
'name' => st('A'),
'description' => st('A'),
'machine_name' => 'user_a',
'help' => 'test for subterm',
);
taxonomy_vocabulary_save($vocabulary);

$user_a=array(st('A'),st('B'));

$user_a_vid=db_select('taxonomy_vocabulary', 'tv')
  ->fields('tv', array('vid'))
  ->condition('machine_name', 'user_a')
  ->execute()
  ->fetchField();

foreach ($user_a as $name) {
    $term = new stdClass;
    $term->name = $name;
    $term->vid = $user_a_vid;
    taxonomy_term_save($term);
 }

i have two vocabulary A and B

and i want to add sub-term of A and B

A have sub-term 1,2
B have sub-term 3,4

how can i do that in code?

Thanks for reading my question~thx~

Yeh~

i found out,this code can fix all the problem

$term->parent = $parent_tid;


How to make a link type of a news automatically? I made a content type what called news, and I have created a list(text) field type to grab the type of news and name it news_type and it's value is Sport, Health, Technology, Economic and others.

I want each of this type comes to a block as a link to all of that type news. Something like below:

and How to make each news type a link?

Some people say you should use View, How to use view for this?
Please describe step by step.

Create a View named "xyz" & select content of type "news"
Select page or block
Add fields what you want to show or if you need filtration then you can filter your content.
& save.


List pages on frontpage with views? So, I'm relatively new to Drupal, and I'd like to make a Drupal site with a front page with a grid of links to other commonly used pages on the site. This site is intended as a sort of community page for a small town, so it would be links like Government, News, Business Directory, History, Forum, etc.

Some of these pages are basic pages on my Drupal site, some are external links, and some are links to views or modules, like the aggregator module. I'd like all of the links to be sortable and generally have the same markup. I'd also like these links to be gathered automatically, i.e. via the 'Promote to Front Page' option or something like that. I ABSOLUTELY DO NOT want to hardcode this to a basic page.

So far my solution has been to create a view with a list of title fields from pages promoted to the front page, and a special content type I named 'Link' which are actually just redirects to external urls. The problem now is that I don't know how to include special pages, like aggregator or view.

Any ideas? Is there a better way to do this? Have I missed something?

you will have to add a new display type in your views "PAGE" and give it a path so you can goto that page directly.


Is there a module that shows when you last updated or modified an installed module? From time to time I update my modules and I would like to see when they were last updated. Is there such a module that adds this information?

AFAIK, no module, but ls -l in your module directory should give you the dates of last updates.

Btw. it is trivial to create a module that does this. Just throw a module wrapper around something like:

$modules = '/www/sites/all/modules/'; // Path to your module directory.
$output = shell_exec('ls -l ' . $modules);
echo "<pre>$output</pre>";


References by title (not nid) while creating nodes via PHP code does anyone know how to create node reference while creating node programmatically? I mean - using TITLE and TYPE, not nid.

I am creating nodes via python script and user is prompted for title of parent node. Nobody's gonna tell you NID in that case. But content type and part of title should be enough.

If there is no way of doing that in Drupal - I am gonna make my own function to fetch all nodes that fits criteria and go further if there's only one or prompt for choosing proper one if there's more than one..

I'll be happy if there's already something that handles my task.. :)

My current code with doing that by NID:

    $n = new stdClass();
    $n->type="project_release";
    node_object_prepare($n);
    $n->title = "Kaboom [".date(YmdHis)."]";
    $n->language = LANGUAGE_NONE;
    $n->uid = 1;
    $n->body[$n->language][0]['value']="12345";
    $n->body[$n->language][0]['summary']="123457890";
    $n->body[$n->language][0]['format']="filtered_html";

    $n->field_release_project[$n->language][0]['nid']=85;
    $n->field_project_release_notes[$n->language][0]['value']='AaAAAAAA...';

    $path = 'remotely_added_at_'.date('YmdHis');
    $n->path = array('alias'=>$path);
    if($n=node_submit($n)) {
        node_save($n);
        echo "</br>Node with nid ".$n->nid." saved\n";
    }

Cheers

I don't think that you need to write your own function, just have a look at node_reference_autocomplete_value(), this functions does exactly what you need (match Node Title to nid)


Get node internal path from path alias in Twig template I want to get the internal path of a node from its path alias. In Drupal 7 we could use drupal_get_normal_path() directly in the PHP template.

With Drupal 8, Is there a function to get the internal path from an alias inside a Twig template?

In my Twig template I have tried to use the url() function without success...

e.g. {% set path = url('myalias') %} ...

You should not be running Drupal functions inside TWIG templates, the best approach is to use a pre-processor as mentioned in the comments. You can do this by setting a variable inside a hook being called either in your theme file or custom module and setting like this:

$vars['your_custom_variable'] = $unaliasedNodePath

And then inside your twig template you can use the variable set in your pre-processor like this:

{{ your_custom_variable }}

More information can be found here:

https://www.drupal.org/docs/8/theming/twig/twig-best-practices-preprocess-functions-and-templates


Module invoke webform redirecting validation On one page I have this code, that loads my Webform:

$block = module_invoke('webform', 'block_view', '660');
print render($block['content']);

But when I click on submit button, validation leads me to another page (webform page). How  can I stay on current page, where webform is loaded?

Go to admin/block and edit your webform block and check "Show all webform pages in block" and all errors display in block not in node.

This should resolved the problem, however you can check more about this problem here: https://www.drupal.org/node/1308806


function to change language object I know this question may get the dafs-adrenalin of some of you viewers going. But I'm just recently getting my head in there with php and drupal and have been searching the api and googled a possible function only to find functions that did all sorts of other stuff.

It's that I have this custom logic where I want to change the language object after I've set a $_COOKIE['lang']. The value of the cookie lang would be a language code like en or fr. And going $language->language -> $_COOKIE['lang']; is pretty rediculous.

So the question maybe then is: I Know the value of $language->language, now I want to use the function that Drupal uses in core to construct the entire language object. This way the language object actually changes after the cookies is set and the locale module can to it's work to load the site in the new language?

The list of language objects is built up by the core function language_list(), which you can use to overwrite the global $language object if you need to:

// Get the list of languages
$languages = language_list();

// Set up the new language code
$new_lang_code = 'fr';

// Make sure the required language object is actually set
if (isset($languages[$new_lang_code])) {
  // Overwrite the global language object
  global $language;
  $language = $languages[$new_lang_code];
}


Adding CSS and JS to form with attachments I need to add some external and local CSS and JavaScript files to a form, but I can't seem to find the right way to do this.  Do I simply add the paths and URLs for the JS and CSS files?

I assume $form['#attached']['css'][] and $form['#attached']['js'][] are the correct places to do this, so they get reloaded on form rebuilds.  I seem to be missing something.

Have you looked at the documentation?

Attach CSS and JS to form

http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached

$form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css';

$form['#attached']['js'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.js';

External files

http://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_process_attached/7

External 'js' and 'css' files can also be loaded. For example:

$build['#attached']['js']['http://code.jquery.com/jquery-1.4.2.min.js'] = array('type' => 'external');


Is there a way to globally redirect taxonomy paths -- on a pattern? I know there is url alias but what I need to happen is the taxonomy path be redirected to a view. The itemization will be from a tag. This tag basically controls a views output. I want to have that terms URL be redirected to that view page.

As i understand - you want to show some view on taxonomy term page. This view will take term as argument (contextual  filter) and display list of nodes related to it.

For this purpose you can use module Taxonomy Views Integrator:

  The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabuarly.


How can I enforce maintenance_mode at all times in a specific environment? In Drupal 7, we could override the $conf variables in settings.php to force a site (e.g. development) in maintenance mode. In Drupal 8, this has changed to $config, but the maintenance mode variable is not part of the configuration anymore. How can I force system.maintenance_mode in a specific environment's configuration?

I think you might want to take a different approach.

The maintenance mode is now a state in Drupal 8, not a configuration. The difference is a state is a ephemeral state that's specific to the current environment (see the state API docs for more info).

As such, you might want to replace the State service with your own service class that uses the StateInterface interface if you're looking to fundamentally alter the way state behavior (which could lead to unforeseen problems).

Another tact might involve some sort one-time toggling of state (e.g. programmatically as shown above, a drush state-set / drupal state:override) based on some event (e.g. deployment of site).


Hide certain nodes in view listing for anonymous users I am trying to restrict node access for anonymous users based on a custom field.
I got it working for accessing the node directly like this:

$country = "GB";
if ($node->hasField('field_country_hide')) {
  $country_code = $node->field_country_hide->value;

  if ($country_code == $country) {
    // this user should not be allowed to see this article
    return AccessResult::forbidden();
  }
} else {
  return AccessResult::neutral();
}

But this doesn't restrict access for the node in a view listing.
What is the best way to go about hiding a node in a view listing?

Drupal doesn't evoke hook_node_access() when executing a view; it's querying the DB directly to get the data. As such, you're not going to be able evoke the same PHP snippet to have Views filter the result.

The "best" way (read: simple) is to have views create a query filter that does the same thing; you can add a  Content: Country Hide filter (or whatever your custom field is named) with the Operator set to Is equal to and the Value set to GB.

That will filter the nodes as you need, but you'll still need to provide the context (i.e. is the user anonymous or not). Here it's unclear. There's no "best" because there's not one way to provide context and it will depend on your needs.

One idea that comes to mind is to add 2 View blocks, one with the GB filter and one without, and set the block to display depending on the user role. But again, this will depend on your requirements. There's always custom Views integration or, if you want to go the site builder route, other modules that provide context like Context, Panels, etc.


In Open Atrium is there a way to assign a user to a case that user is not in? I would like to be able to have an admin be assigned to a case that is in a group that user is not a part of. In Open Atrium. Is this possible?

No, it isn't possible, at least not by using the Atrium web UI out-of-the-box. Cases can only be assigned to users in the current group.


My PECL uploadprogress bar appears, but why doesn't it show any progress? I installed the PECL uploadprogress bar in php and this is working fine but when I start uploading a file it ends up getting stuck and dissapearing when the file is uploaded.

This is what i see when i start the  upload:

The file is big enough so it doesnt open/close really fast.

But it just ends up being stuck at Starting upload... and not moving the blue bar to the right when its uploading. After a while it just dissapears and says done and i can submit the form fine.

This is how i want it to look like while uploading:

Have a look at the (very old) issue # 633862. Even though it's an old issue, it includes quite a few comments that may help you to find "the clue". E.g. that it it doesn't seem to work for the more "exotic" server configurations.

Comment # 41 states this:

  Apparently secure servers also have an issue with it https:// won't work with this.

Comment # 43 in that issue also suggest the (sandbox for now)  upload_progress module, here is what that comment includes:

  I have created a little module that uses client-side JavaScript instead of server-side code to display the progress. This will finally bring upload progress to more "exotic" server configurations.


Adding Comodo TrustLogo code I have a Comodo certificate for my site to serve content using HTTPS.

I would like to add the Comodo TrustLogo (https://trustlogo.com/) so that it appears on every content page. The problem is that the JavaScript comprises of two parts that must be placed in specific locations according to Comodo:

a) One piece must be loaded just before the HTML HEAD closing tag.

The generic code Comodo wants me to include is:

b) The second piece must be included just before the HTML BODY closing tag.

The JavaScript is this - anonymised for site-specific content:

Positive SSL Wildcard

Since Bartik and other themes do not meddle with the HTML page stuff (only with the actual content) I looked into messing with the file

  core/modules/system/templates/html.html.twig

and add some content there, but stuff does not appear - it seems ignored as it doesn't even appear in the HTML source...

Please help!

Thanks,
Michel

First of all, I hope you didn't edit any files in core :)
Secondly, you can of course add the custom scripts in the HTML twig file, but you need to add this template to you active theme and clear theme registry (or all) cache in order for the changes to appear.

Here is a complete html.html.twig file code:

{#
/**
 * @file
 * Default theme implementation for the basic structure of a single Drupal page.
 *
 * Variables:
 * - logged_in: A flag indicating if user is logged in.
 * - root_path: The root path of the current page (e.g., node, admin, user).
 * - node_type: The content type for the current node, if the page is a node.
 * - head_title: List of text elements that make up the head_title variable.
 *   May contain or more of the following:
 *   - title: The title of the page.
 *   - name: The name of the site.
 *   - slogan: The slogan of the site.
 * - page_top: Initial rendered markup. This should be printed before 'page'.
 * - page: The rendered page markup.
 * - page_bottom: Closing rendered markup. This variable should be printed after
 *   'page'.
 * - db_offline: A flag indicating if the database is offline.
 * - placeholder_token: The token for generating head, css, js and js-bottom
 *   placeholders.
 *
 * @see template_preprocess_html()
 *
 * @ingroup themeable
 */
#}
<!DOCTYPE html>

    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">

    {#
      Keyboard navigation/accessibility link to main content section in
      page.html.twig.
    #}

      {{ 'Skip to main content'|t }}

    {{ page_top }}
    {{ page }}
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">

    Positive SSL Wildcard

You can put this file in your active theme /templates folder, clear cache and it'll load the logo on every page.
There are other ways to do so like using custom module to inject the code, but for simplicity, you can use this solution.


Render add node form within module output I have a content type called “osago”. And I have a module that outputs some things.

How can I output the create this content type form within this module?

You will have to use drupal_render() on node_add() result.

module_load_include('inc', 'node', 'node.pages');
$content = node_add('osago');
print drupal_render($content);


I am not able to traverse from the last step to the first step in a multistep form I have created a multistep form with five steps using programatically. Is there any way to traverse to first step form the fifth step?
I have created multistep form as given in example module. In the module, each step gives previous and next link only, and I am not able to go to the first step directly from the fifth step.

The example module uses a value stored in $form_state['storage'] to indicate which step the form is in, when it is being built. You could add a button with a custom submit handler that unsets this value or set it to the value needed for the step you want to show. Also remember to set $form_state['rebuild'] = TRUE;.

On a side note, if you want to make multi step forms, the ctools multi step form wizard API can help you doing a lot of these things for you.