How to convert User points to vote ballots? I want to achieve the following functionality and I'm wondering if this could be possible:

For each purchase, one can gain userpoints (I can handle this using Rules).

Those userpoints will then be used to vote nominees. So if I have 1000 userpoints, i can use 300 for Candidate A, 500 for Candidate B, and and 200 for Candidate C. ( 1 userpoint = 1 ballot)

Can some give a hint/suggestion on how I could implement this. Workflow would be:

I select a candidate.
"Input" a vote amount.
Vote gets recorded.
Vote amount will be deducted from my userpoints.

Use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another.

As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

If you simply adapt the amount of points (-2 and -1) to something like (eg) +300 and -300, you've a prototype to transfer (300) user points from one user to another (eg Candidate A). Just repeat for Candidate B and C.

If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer some predefined (hardcoded) amount of user points of mine to this user). You could take this even a step further: since flags are fieldable, you could add a field to indicate the amount of points to be "moved", so that the user could enter "300" for Candidate A (instead of some hardcoded, fixed amount).

However, the above Rules example may need further refinements, e.g. if you want to ensure that after moving points from User A to User B, the remaining points for User A is not negative. Refer to "How to check whether one's current User Points are negative with the Rules module?" for details about how you can implement such refinement also.

PS: I'm assuming this question is about D7.


Date field with granularity of Month, Year in Exposed filter, how to alter the default value? I have a Date field with granularity of Month, Year in Exposed filter. Everything is working fine, but the month and year default values are shown as "-Month" and "-Year".
Let me know how to alter the form to remove the "-" from Month and Year filter.

One method would be to alter the exposed filter form date_select form element. Add this to a custom module:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
   $form['#after_build'][] = 'views_exposed_form_date_select_alter';
}

/**
 * Alter the label option on Year/Month selector
 */
function views_exposed_form_date_select_alter($form, &$form_state) {
   $form['MY_DATE_FIELD']['year']['#options'][''] = 'Year';
   $form['MY_DATE_FIELD']['month']['#options'][''] = 'Month';
   return $form;
}


D6: Adding HTML to CCK field data? In Drupal 6, I want to customise some CCK field data with some added HTML, but am not sure of the best/easiest way to do this. I couldn't find a CCK module to do this.

For example, I want to enter a URL (which is stored in the field), and then when it is displayed, it is embedded in some HTML. eg.

CCK Field data: filename.jpg

Output HTML:

Picture

Some answers here including:

Theming individual CCK fields with templates and preprocess functions (credit: Stefan Lehmann)
Theming Individual CCK Fields
Theming CCK fields within a content type
Custom Formatters module


data collection & views I have created a website for neighborhood on d7 for a society of 400 apartments. We need to collect data from each user (like is he a tenant or a owner, his profession, his car registration no, members in the family with age, and respective ID cards to verify and arrange facilities membership card, carparking,maid  access etc. I had accomplished this questionre by using webform,and only later I understand that this is more meant for survey one way. I cannot again use this data and give user a option of edit. example if the user changes his car / maid he should be able to change it online. Data collection from the users have not yet been started.  What would be the best way to collect this type of data and later be used in views, this also has conditions /logic based question example if he is a owner he has a different set of questions and if he is a tenant then different set. Around 3-4 logic questions are involved.

I don't know php. But love drupal.

Thanks.

One way would be to give each user an account / profile. Then add the fields you need to the user profile and the people can provide all the information you need by themselfs. And they can update the data whenever something changes. Or even you can update the data if they're not able to do it or forget about changing them on your site.

An other way would be to have a content type if you dont want user profiles. But in this case, you have to maintain and update the data.


Light box that is compatible with Views? I've created a content type, let's call it Person.
I've got a View which generates a grid of thumbnail images, one for each Person.
When the user clicks on one of these thumbnails, I'd like to open that Person node in a lightbox (without all of the header and footer decorations, just the content of the node).

What lightbox modules are compatible with Views? I tried ColorBox, but I'm not seeing a colorbox option in the "Link Image to.." which is where I would expect to see it.

Is colorbox compatible with Views and I'm just looking in the wrong place?

If it's not, what modules are compatible with Views to do something like this?

The Lightbox 2 module integrates with Views.  I use it on my site.  This module is extremely popular (more than 100,000 installs).

Unfortunately, this issue describes why Views and Colorbox are currently not compatible.


50 Variations of a Node with Access Restrictions Based on User Login I'm creating a site where there are 50 variations of a basic page node. The site is not viewable publicly and the user has to login in order to view the site.

I have enable the URL login module, its setup where you can login to the site by going to a url.

Now there are 50 different users and each user has access to view only one of the variations of the node. I setup a taxonomy vocabulary called version with 50 terms in it and assign one of them to the node.

How do I restrict certain users to view only that content that matches the term they are allowed to?

There seems to be good handful of permission access type modules restricting users to a specific node.

I tried taxonomy access and taxonomy access lite and they dont do what I need as they limit access to a taxonomy to roles only and not doable for specific users. A work around would have been create a bunch of roles. But I have 50 different users that need 50 different access rights to certain pages.

I also tried https://www.drupal.org/project/permissions_by_term but that was a bit wonky as this didn't restrict via the access restriction table. So items still showed in the menu even though they didn't have access to it. Upon clicking on the menu, they do indeed not have access to it, but I wanted all node references to this restricted node removed from the page.

I finalized on the Flexi Access module: https://www.drupal.org/project/flexiaccess

This gives the ability to restrict specific users to a certain node page, but does not restrict by taxonomy terms or by role.

It will add a new flexi access tab on your content pages.


Created Date Doesn't Import (D7 to D7) I'm using the Node Export Features module to move over some blogs to another Drupal installation.

Everything seems to transfer but the created date. It resets all nodes to the present date.  How do I preserve the original created date?

In the dashboard, Go to Configuration > Node Export > Reset Values on Import.

...

I love answering my own questions. In fact, every question I've asked here ..well, have been answered by me, and me only. Thanks for all the wonderful help from the (non-existent) Drupal community.


How can I print node author's last login date on page.tpl.php? I could easily find out how to print the current user's last login date but what about the node author's one?

It would be better to put this logic in an preprocess function rather than directly in the template file, but the code would probably be something like this:

if ($node = menu_get_object()) {
  $author = user_load($node->uid);
  $last_login = $author->login;
}


How do I use an absolute URL to set as breadcrumb link? I would like to use absolute URL instead of relative URL as the breadcrumb link on my website. Right now, I am using Drupal 7 and Path Breadcrumb 7.x-3.0 Module. All my breadcrumbs are set by Module.

This is a sample of my breadcrumb right now.

You are here

                Home »
                Category

       &gt;
      Dimmer

How can I make the breadcrumbs like these?

You are here

                Home »
                Category

       &gt;
      Dimmer

EDIT

My breadcrumb code is generated by print $breadcrumb; in the page.tpl.php file. How can I convert the breadcrumb link from Relative to Absolute in this case?

Using PHP code you can build absolute urls with the url function.

Example:

$url = url('/category.html', ['absolute' => TRUE]);


node access restrict ( Drupal 6 ) We have around 150 nodes of type "X". We want to show only 20 nodes out of that for all the users ( including anonymous ) except users having role "Y". For users with role "Y" will be able to see all the 150 nodes. How can I achieve this?.

There are two module to control node access by user type. Node_Access_1 & Node_Access_2. Use which ever suits you. You will have to set the permission by editing each node, as I have implemented one from it in D7. I have never tried for VBO with it, so can't answer about multiple change..


Setup for Taxonomy throwing 404 constantly I'm running a fresh, vanilla install of Drupal 7.27. There are absolutely no non-default modules installed with it. I was playing with the taxonomy settings to familiarize myself with the system. I have no trouble creating vocabularies, terms and hierarchies, or associating content, but editing any of my existing terms takes me out of the overlay mode, and saving the edits throws a 404 Object not Found. Further, setting urls for any of my taxonomy terms breaks the landing page for the term, giving me, for example:

Page not found
The requested page "/drupal-7.27/?q=/nonfiction/cookbooks" could not be found.

in the content area of the page.

Any ideas where I can look for the source of this error? The error log in admin reports simply tells me what I already know.

I'm new to Drupal, just hoping to get my company to migrate away from Magento, so this is all very exciting, but confusing. Thanks in advance.

Unexpected non-reachable pages you know that exist are 99% of the time a problem in the server-config.

mod_rewrite for apache needs to be enabled and you need to make sure AllowOverride All is enabled in your virtual host for your drupaldirectory. more here: http://drupal.org/node/54832

After you have this setup right you can also enable clean-urls and lose the ?q= in your url. Set it up @ admin/config/search/clean-urls.


How do I load multiple nodes by a user reference? I have a content type "property", with an owner field (field_user_ref) which is a user reference.

I want to loop through all of the properties, given a specific user_id.

$user_id = 18273;

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'property')
  ->propertyCondition('field_user_ref', $user_id)
  ->propertyCondition('status', 1);

$result = $query->execute();  // ERROR

if (!empty($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    echo "<br>".$node-title;
  }
}

But this gives an error..

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'node.field_user_ref' in 'where clause': SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type AS entity_type FROM {node} node WHERE (node.field_user_ref = :db_condition_placeholder_0) AND (node.status = :db_condition_placeholder_1) AND (node.type = :db_condition_placeholder_2)

"field_user_ref" is the name of the field..  property.field_user_ref, so not sure what should be the format here..

And like magic, I've found the answer as a result of this answer..

EntityFieldQuery causing column not found PDO exception

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'property')
  ->fieldCondition('field_user_ref', "uid", $user_id)
  ->propertyCondition('status', 1);


Slashes in single route parameter or other ways to handle a menu tail with dynamic number of params According to the Symfony documentation, a route defined as below should trigger the specified controller for both /hello/bob and /hello/bob/bobby:

_hello:
  path:     /hello/{names}
  defaults: { _controller: \Drupal\mymodule\Controller\Main::Controller }
  requirements:
    _access: 'TRUE'
    names: .+

In the case of a request to /hello/bob/bobby the {names} param would be "bob/bobby" (slash intact) and it would be up to the controller to break that down into multiple variables or to leave it as a single string. The trick to that is the altered regex (".+") used to filter that {names} param.

This stackoverflow post also implies that custom regex can be used to allow slashes in a route param (at least in Symfony 2).

If I try this against Drupal 8.0.0-beta15 it does not work and the specified controller is only triggered for a request to /hello/bob. However, I can confirm that this used to work in previous betas (I think up until ~beta13).

Has something changed in the way Drupal integrates with the Symfony routing component that would explain this? Perhaps there is an alternate way to accomplish the passing of slashes in routing params? I know there is a movement toward Symfony 3.0 in core, but I'm not sure if that could explain things.

I also know that route subscribers are available to manage dynamic route structures. However the case I am working on requires an almost infinite combination/number of dynamic parameters at the end of a base path (but which are trivial to parse in my controller). I'm also trying to avoid query strings (e.g. /hello?names[]=bob&names[]=bobby) for this case.

Mainly I'm just confused as to the disconnect with the Symfony documentation, which seems to state that this should be possible.

Additional Notes

After posting this question I discovered this discussion in the D8 core queues: [Discussion] Drop automated passing of extra argument: Y/N. It seems to conclude that "menu tail" support (which is essentially what I am after) will officially be dropped in D8. That discussion ended 3 years ago and so I can only guess that some of the more generalized implementation specifics were not fully realized until recently (~beta13). This may explain why I've only now noticed this change.

I'm guessing that Drupal (not Symfony) is now generating a 404 response based on the raw slash-delimited request before any of the Symfony-specific routing logic further dissects the route (and it's param-specific regex, etc.). If this is the case it could explain why technique above stopped working. I am still wondering however if there are alternative ways to deal with this need that avoid using query params and custom route subscribers.

You can alter the path by adding a class that implements the InboundPathProcessorInterface

namespace Drupal\mymodule\PathProcessor;

use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;

class HelloPathProcessor implements InboundPathProcessorInterface {

  public function processInbound($path, Request $request) {
    if (strpos($path, '/hello/') === 0) {
      $names = preg_replace('|^\/hello\/|', '', $path);
      $names = str_replace('/',':', $names);
      return "/hello/$names";
    }
    return $path;
  }

}

This way the router will interpret the path /hello/bob/bobby as /hello/bob:bobby and you will get the parameters separated by : (or any other character that won't conflict with the parameters) in your controller.

You will also need to register the class as a service in mymodule.services.yml (make sure the priority is set higher than 200)

services:
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\HelloPathProcessor
    tags:
      - { name: path_processor_inbound, priority: 250 }


Varnish + Adaptive Theme Using the Adaptive theme on Acquia platform and seeing an issue with mobile rendered views being cached and served to desktop browsers with block regions hidden for mobile display. The issue seems sporadic for certain pages.

Clearing Varnish and/or Drupal caches fixes the issue. I think I know what's happening but not sure why. I'm considering disabling Drupal's cache.

I'm working in a sys admin / back end capacity so am limited, experience wise, as to where to look for the source of the problem.

Do you perhaps use Context Breakpoint? I had a similar experience using that module. The module states the following on its project page:

  Caching implications

  This module has implications for using the Drupal page cache. Check the README.txt under CACHING for a detailed
  explanation and possible solutions.

  A more detailed explanation is in the README.

I ran into the same situation and it is caused by the way Drupal 7 caches content. It only checks the URL. So if you were to open a page on a mobile phone, which already existed in cache, you will receive the desktop version.

The inverse is also true. If cache is emptied or outdated and the next user to request the page is using a mobile phone, that user will make sure the mobile version is stored in the cache and served to desktop users.

This is certainly true for Drupal's internal caching system, and disabling the Cache pages for anonymous users option solves the problem.
An alternative could be to use Context Mobile Detect. Which does seem to play nice with Drupal's page cache.


Meta description to views Is there a way to add meta description to views in Drupal 8?

Use the "Metatag Views" sub module that comes with Metatag module. Link https://www.drupal.org/project/metatag


Permission rebuild fail My Drupal 7 site is upgraded from Drupal 6. When I install the Domain Access (not installed with Drupal 6) module, I need to rebuild permissions.

I tried rebuilding them from the administrative pages, but it fails; I tried doing it with Drush, but it failed again.

drush php-eval 'node_access_rebuild();'

I can't find any information in watchdog and PHP logs.

Does anyone know why it happens, or how I can fix this?

I was having a similar problem (Rebuild Permissions failing) and tracked it to Organic groups.

Go to Administration > Configuration > Organic groups > OG field settings
Under Bundles select the Group content type
Under Fields select Group visibility
Click Add field


Create "suggest an edit" functionality for anonymous users on nodes I'd like to provide a way for anonymous users to submit nodes, but also provide suggested edits to existing nodes. The core node revision system cannot support this.

How would one implement a revisioning system that allow anonymous users to save updates which moderators approve. I'm assuming Workbench might get me halfway there.

Edit: like you find on Foursquare and Yelp, for community suggestions on editing venues.

I think you may want to check out the Workbench Moderation module. Basically, you'd configure a workflow that allows anonymous users to 'edit' a node, but their edits would trigger the workflow. From an admin experience perspective, you may want to configure it to trigger an email notice whenever updates have been made, or otherwise alert content admins that suggestions have been made.

One potential gotcha is the way that Workbench handles revisions -- it doesn't fork. Meaning that if you publish a node, that becomes revision 1. If someone comes along and edits it, they suggest revision 2. If a third person comes along, they'll see that the node is on revision 1, but when they go to edit the node, they'll see it's on revision 2. Any changes would be saved as revision 3, and so on. You may need to extend the module with your own custom workflow if you're looking for forking behavior (think pull requests on GitHub).


Importing nodes with Node export is creating them in "unpublished" status I'm importing content from one D7 site to another using the Node export module. However, when importing the content in the new site, the nodes are getting created in unpublished state. I have to publish them manually.

How can I have Drupal import the nodes in published state?

At admin/config/content/node_export there is Reset values on import > [your node type] > Published checkbox, which is not checked by default. Checking this will reset the published status, which means nodes will be unpublished (that's how I interpret that anyway). So leaving it unchecked will not change the status. There seems to be no way to force nodes to be published.

If needed, on the new site nodes can be mass published at admin/content.


Prevent caching some selected parts of a html page I've written a small block in php (used drupal) and have enabled caching because the page contains several static images. But I don't want contents of the block to be cached.

Tried to use Cache_Lite but it's not working. So is there a way to restrict some parts of the page prevent being cached?

thanks in advance...

Checkout ESI. In short you need to AJAX load that block if you don't wish for it be be cached for logged out users.


How to create a panel for a argument path How do you create a panel for a url that looks like product/%nid/title.

The Title should be from the node.
The node paths have already been setup with pathauto.

What i have so far in my panel

The panel doesn't get used on the page

I'm not sure what you are after. You just want the URL to look right, then all you need is Pathauto.

What you are asking however, is essentially how to tell Page manager to load content based on the title of the content. That could make sense, if it wasn't because you already load it by the ID, so loading it again would just be redundant.

If that's really what you want though, here goes:

Page manager doesn't know how to load nodes by title, so you will need to explain to it.

This is a called a Context.

See What are Ctools plugin (content type, access, etc), and how does one create them? for the basics of how to implement a ctools plugin. Look at the existing contexts in the ctools examples directory, and creating the context shouldn't be to hard.


OpenLayers module only displays latitude/longitude instead of map So I began experimenting with OpenLayers because I'm creating a content type that requires it.

I followed the Step-by-step instructions from the docs (added geofield to node, create data overlay view, cloned and set up my map and created a page view to display the map)... but what I actually need is to somehow embedded the maps for each post. What is the next step for something like this? Right now in each node I see the node pictures and this: POINT (-0.138513 50.8239).

Go to your display settings for your content type and choose 'OpenLayers', then click the gear icon and Select which OpenLayers map you would like to use. Only maps which have the geofield placeholder layer may be selected. If your preferred map is not here, add the geofield placeholder layer to it first.


Drupal Newbie - Upgrade Questions I am a Drupal newcomer and have been tasked with updating a Drupal site.

The currently installed version is 7.2.1

I have taken a full backup of both SQL and files so I am safe if anything goes wrong.

My question is the upgrade for Drupal a manual one, as in, do I have to download the update and FTP it over?  I am used to Wordpress being a one-click affair!

Also, is there anything I should be aware of?

Yes, the update is manual. (As someone new to Drupal, you may not know about the command line tool drush, which is as close as we get to being a one-click affair. Drush is awesome, and once you get more familiar with Drupal, you should learn it. It makes your work much more efficient.)

Re the previous answer, 'Download these updates' only works for contributed modules and not for core.

The instructions on drupal.org are excellent.  But before you start, here are a couple of pieces of useful information.

Do not get confused by the instructions at the top of the page sending you to upGRADE instructions.  An upGRADE means moving from one version of Drupal to another, e.g., Drupal 6 to Drupal 7, and is a much bigger deal. An upDATE moves you up by minor versions, e.g., Drupal 7.2.1 to 7.28.
Because you are new to Drupal, it would probably be a good idea to make sure the previous developer did not make the classic error of putting contributed modules and themes in with core modules.  When you do the update you will delete all files EXCEPT [drupal root]/sites, which is where contributed modules, and site-specific files live. On your site, go to admin/reports/updates/list. Open another window in whatever file browser you use, and look at the Drupal file structure.  The list of modules in the update list should match up to folders in [drupal root]/sites/all/modules.  If instead you find those folders in [drupal root]/modules, you have bigger problems than can be answered here.  (Same goes for themes.)
If you have a development and/or staging site in addition to the live site, do the updates there first.  If you don't have non-live sites, you should create them.  You can do updates on a live site, but it's much preferable to test them first.

Sorry, long answer.  There's a lot more good stuff on drupal.org, but it can be hard to find.  I usually use Google to search drupal.org.


Add description to each entity reference I'm using Drupal 8 to build a new web app. I am allowing the user to add connections to other content on the site using taxonomy entity references. I'd like them to be able to add a description to each reference - i.e. select 'Node X', and add a description about the relation to 'Node X'.

Is this possible?

Thanks!

If you are looking for a code solution, you can do this in a custom field type, see this answer https://drupal.stackexchange.com/a/231162/47547.

If you want to do this in UI, you can use Field Collection or Paragraphs to bundle the two fields entity reference and description.


How to solve the "The following module is missing from the file system" error? I am getting the following error in a Drupal 8 site.

  The following module is missing from the file system

It looks as if a custom module was installed and deleted without uninstalling it.

How can I fix this error?

If you have Drupal Console then a quick way to fix this is to generate a module with the same machine name, then uninstall it.

$ drupal generate:module

Then type the machine name at the appropriate prompt and accepts defaults for everything else.

$ drush pm-uninstall

Then you can delete the newly generated module from the file system and continue with your day.

(NB you may find need to keep that generated module, else the error will return. In that case, if you need to install a contrib module with the same name, remove the generated module after adding the contrib module. Then clear the cache.)


How to show views calendar by node field_date I have a date field with start,end dates.

But i can't understood how to show it in a views block by contextial filter date -> content from node

Thanks for any help!)

Just configured your Contextual filters like below snapshot.


ubercart role expiration I hope this question is neither a clone nor a stupid one, but I need to fix/understand this very quickly, I did some research though.

Coming to my problem:
I am building a no-profit website and we do require a small fee for the participants.
So I am using Ubercart to allow people to buy the "Participant" role.

I set everything up and also the payment system works properly.
My problem is the expiration. In the product I set the expiration to 1 year, but when a user registers no expiration is set.
When I go to People -> Role expiration, the table is empty saying "No expirations set to occur".

I followed some tutorials on-line and I believe I did everything right, can you guys help me with this?

I also think I properly set the permission, even though I have some doubts about.

Thank you,
guidout

Edit your product.
Go to features.
From the Add a new feature, Add both recurring fee and role assignment for your product.

Hope this helps.


module_load_include not working I've been looking on several sites trying to figure this out, but no dice yet.

I have a module, 'spower'. I need to include several php files inside the polygon folder (spower/polygon/*.php). In the spower.module file, I've included the line:

module_load_include('php', 'spower', 'polygon/polygonBase');

However, when I run the module, I get the error Call to undefined function PolygonBase, so obviously, something's not loading right.

Assuming you want to load

sites/all/modules/custom/spower/polygon/polygonBase.php

then

module_load_include('php', 'spower', 'polygon/polygonBase');

should work fine.

Make sure the file polygonBase.php is readable by the webserver user.
Make sure module_load_include is added for processing prior to using functions in that file.


How to solve “Query failed” error in drush sql-sync output 2? I have the exact same problem as in How to solve "Query failed" error in drush sql-sync output?, exact same output. That user found the answer as the password in settings.php was wrong, but my password is correct and it still doesn't work. Can anyone please help?

drush sql-query --strict=0 --file=/tmp/mob_20191203_224013.sql.gz --file-delete --uri=mob --root=/home/fc/1/de/mob/web -vvv
 [preflight] Config paths: /home/fc/1/de/mob/vendor/drush/drush/drush.yml,/home/fc/1/de/mob/drush/drush.yml
 [preflight] Alias paths: /home/fc/1/de/mob/web/drush/sites,/home/fc/1/de/mob/drush/sites
 [preflight] Commandfile search paths: /home/fc/1/de/mob/vendor/drush/drush/src,/home/fc/1/de/mob/drush
 [bootstrap] Starting bootstrap to max [0.04 sec, 8.57 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalRoot() [0.04 sec, 8.57 MB]
 [bootstrap] Change working directory to /home/fc/1/de/mob/web [0.04 sec, 8.57 MB]
 [bootstrap] Initialized Drupal 8.7.10 root directory at /home/fc/1/de/mob/web [0.04 sec, 8.76 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalSite() [0.04 sec, 9.06 MB]
 [bootstrap] Initialized Drupal site mob at sites/default [0.04 sec, 9.29 MB]
 [bootstrap] Drush bootstrap phase: bootstrapDrupalConfiguration() [0.04 sec, 9.29 MB]
 [debug] Add service modifier [0.04 sec, 9.45 MB]
 [info] Executing: command -v mysql [0.05 sec, 9.91 MB]
 [info] Executing: mysql --defaults-file=/tmp/drush_IsKDek --database=mob --host=localhost --silent -A < /tmp/mob_20191203_224013.sql.gz [0.05 sec, 9.96 MB]

In SqlCommands.php line 199:

  [Exception]
  Query failed.

/tmp/mob_20191203_224013.sql.gz exists, /tmp/drush_IsKDek does not
Drush is 9.7.1, Mint 19.2, alias

loc:
  root: /home/fc/1/de/mob/web
  uri: mob
  options:
    command-specific:
      sql-sync:
        sanitize: true
        structure-tables:
          common:
            - cache_advagg
            - cache_bootstrap
            - cache_config
            - cache_container
            - cache_data
            - cache_default
            - cache_discovery
            - cache_dynamic_page_cache
            - cache_entity
            - cache_menu
            - cache_page
            - cache_render
            - cache_toolbar
            - watchdog
            - history
            - sessions
    os: Linux
  paths:
    dump-dir: /tmp
    files: sites/default/files

At the time of writing this comment, there is a problem in drush 9 with php7.4 as mentioned here: https://github.com/drush-ops/drush/issues/4319#issuecomment-649223069
I solved it in my case (I have multiple PHP versions installed) by switching to php7.2 using this command:
sudo update-alternatives --set php /usr/bin/php7.2
I think it will work also with php7.0 and php7.1


change time field to select list I am using a date field in a content type.
I want to make it work similar to the date/time input in facebook events.
When I use date field as a Pop-up calendar it appears like this:

For date input it is fine as it is – but for the time imput I would prefer to have a drop down field (select list) with the date input as pop-up calender here. When I try this...

$dropdown_time_array = array('12:00 pm','12:15 pm','12:30 pm','12:45 pm', );
if($form_id == $form_id_node){
$form['field_date'] = array(
     '#type' => 'select',
     '#default_value' => '1',
     '#options' => $dropdown_time_array,
  );
}

…it actually overrides the whole field – including the date input.

Any suggestions how I can do this?

You can tell the Pop-up date widget to use wvega-timepicker depending whether you're using a Date field or custom module there are different ways of using it.


Cannot get value of form field of type 'file' in drupal form I have a form field  such as  ,

   $form['fileTransfer_settings']['file_path'] = array(
    '#type' => 'file',
    '#title' => t('Choose file'),
    '#size' => 22,
    '#description'   => t('path for the csv file'),

  );

Now I am looking to save the path of the uploaded file in the submit handler ,

But when I look into the value of the form field in the submit handler I get null,

function transferfile_submit_handler($form, &$form_state) {

     dpm($form_state[values]); //other fields show value
     dpm($form_state['values']['fileTransfer_settings']['file_path']); //null
 }

What  am I doing wrong here?

Submitted values are flattened unless the form element contains the #tree property.

So either use:

$form_state['values']['file_path'];

Or change the wrapper:

$form['fileTransfer_settings'] = array(
  '#tree' => TRUE,
  ...
);

And use your current submission code.


How to add custom input type button in forms? I want to add custom input type button in form.
I tried following code, but it is converting it to submit type button.
How can i add  input type button ?

$form[custom_button] = array('#type' => 'button','#value' => t('Test Button'),);

It's not converting it to a submit button type, they are different

Form items of type "button" will trigger the form submission but won't trigger the hook_form_submits like a form item of type "submit" does. It's eseentially a blank button apart from hook_validate is called but in there you can do whatever special functionality your button is supposed to do


Create an Exposed Filter for Integer Values Using Drop Downs I'm creating a real estate search, and I'm wondering how I might be able to use the Views module to find properties based on their rent per month using a "Min" and "Max" drop downs as opposed to just using text fields.

Essentially, I would like a filter to appear as "Min" drop down box with arbitrary numbers ($100, $200, $300......$10000) and a "Max" drop down with the same values.

Is this possible with any current modules? If not, is it possible through hook_form_alter()? If so, can someone point me in the direction of how to get acquainted with working with forms in greater detail?

Sure. You can do it with form alter hooks. Here is an example. The form id will be:

views_exposed_form_<view_name>_<view_type>


Multiple database group users for one database For a blog post, I have db design of 1 database in D7, the database contains multiple database users:

Anonymous - Only Read privilege on Database
Writer - CRUD privilege on Database
Admin - Has all privilege to Database

How do I achieve this in Drupal 7 ? The settings.php in Drupal has only one database connection section, as I'd need to connect the database from all 3 database users, and change the database user when they log in, like when Admin logs in, he'll also be admin database user, and so on...

Although the question is a little unclear, it sounds like you just need 3 roles in your Drupal install

Administrator
Writer
Anonymous ( built-in )

You can add the roles at /admin/people/permissions/roles and configure access permissions for each role, regarding node creation etc, at /admin/people/permissions


mod_expires enabled and cache flush I my apache I have mod_expires enabled. My htaccess contains:

<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On
  # Cache all files for 2 weeks after access (A).
  ExpiresDefault A1209600

Problem: If I make html change, it is not visible even after flushing all caches in drupal.
Question: Is it possible to setup html expiring to say 1 hour and other things like css/scripts/images to say 1 day?
Thank you.

If you use boost module "flushing all caches" maybe not work. Go admin > configuration and open boost configuration, there a tab named "cache expiration" then undo click "Ignore a cache flush command if cron issued the request." I think this usable for you


Populating the $variables['classes-array'] in preprocess_html function It seems most likely that the following code is not working due to bad php but I just can't understand why. If I var_dump $variables['classes'] it returns that it is an array with the classes listed in it beautifully.

I debugged the $item and returns very nicely what I want as well. Then why don't these things get added to my $variables['classes-array'];?

    <?php

function mytheme_preprocess_html(&$variables) {
    dsm($variables);
    $path = url($_GET['q']);
    dsm(var_dump($variables['classes_array']));
    $path_items = explode('/', $path);
    foreach ($path_items as $item) {
        array_push($variables['classes_array'], $item);
    }
}

also tried array_push($variables['classes_array'][], $item);

The problem was solved by putting the debug code after the change of values have taken place in the code.


Accessing Drupal core functions in object-oriented code: Call to undefined function I'm a Drupal procedural programmer new to OOP and enjoying it, so some of the techniques are new to me.

I'm getting a fatal error when I'm calling a standard drupal function from within code called within an object that creates a custom Rule. It appears that it's looking for the function drupal_json_encode_helper on the Action object rather than from where it's supposed to look. But why? And how to I tell it to search within Drupal-land rather than object-land?

I'm on D7 with xautoload and composer, modifying the fluxdropbox module that uses fluxservices to use PSR-0 for external libraries.

  "Fatal error: Call to undefined function
  Drupal\fluxdropbox\Plugin\Rules\Action\drupal_json_encode_helper()"

Here's the code:

<?php

/**
 * @file
 * Contains MakeNodes.
 */

namespace Drupal\fluxdropbox\Plugin\Rules\Action;

use Drupal\fluxdropbox\Plugin\Service\DropboxAccountInterface;
use Drupal\fluxdropbox\Rules\RulesPluginHandlerBase;

/**
 * Action for posting a status message on a page.
 */
class MakeNodes extends RulesPluginHandlerBase implements \RulesActionHandlerInterface {

  /**
   * Defines the action.
   */
  public static function getInfo() {
    return static::getInfoDefaults() + array(
      'name' => 'fluxdropbox_make_nodes',
      'label' => t('Make Nodes from Text Fiels'),
      'parameter' => array(
        'account' => static::getAccountParameterInfo(),
      ),
    );
  }

  /**
   * Executes the action.
   */
  public function execute(DropboxAccountInterface $account) {
            //here I build a nice array
            file_put_contents(drupal_json_encode_helper($feed_array), $path . '/novel.txt');

  }
}

It happens because drupal_json_encode() is defined in includes/json-encode.inc, which is not a file that is normally included when Drupal boots. To use that function, you should use code similar to the one drupal_json_encode() uses, although you really should use drupal_json_encode().

include_once DRUPAL_ROOT . '/includes/json-encode.inc';
file_put_contents(drupal_json_encode_helper($feed_array), $path . '/novel.txt');

The code I would use is the following one.

file_put_contents(drupal_json_encode($feed_array), $path . '/novel.txt');


How to get node.tpl.php to display different content for different nodes? I currently display some database content through PHP code written directly in the body of several nodes.

I would like to shift this code into node.tpl.php (as I have seen from the Zen examples that code to modify a node should be in node.tpl.php). However, I have multiple nodes, each displaying different kinds of database content.

How should I structure the code in node.tpl.php so that if it is Page A, then I display database content A and if it is Page B, then display database content B?

As an example.

Currently I have the following in one of my node body:

<?php
  $db = mysql_connect('localhost', 'root', '');
  mysql_select_db('sage', $db);
  $query = "show tables";
  $db_query = mysql_query($query, $db);
  echo "
";
  echo "
";
  echo "TABLE NAME	";
  echo "
";
  while($row = mysql_fetch_array($db_query)) {
      $tableName = $row[0];
      echo "
";
      echo "$tableName	";
      echo "
";
  }
  echo "
";
?>

Do I copy and paste this code directly into node.tpl.php?

I don't See any node id in your code. If all you want is to have PHP generated output for an URL, define the path with hook_ menu() and just return the generated HTML from the call back method.


Custom line items to be included in $order->getTotal() I am using Ubercart for our e-commerce on Drupal 8 website. Everything seems to be working fine except for the $order->getTotal() function - it does not somehow pickup the amount from my custom line items (for eg. 'shipping and handling') that I have added to the order.

It only seems to be going over the default 3 line items (subtotal, total, generic) that are provided by the uc_order module.

How can I achieve that? Thank you in advance.

I was able to achieve this by adding type as 'generic' for all my custom line items.
Sample code:

uc_order_line_item_add($order->id(), 'generic', 'Promotion', -100, 6, NULL);


hook_preprocess_page(): how to tell a views page? Im writing a custom module that need to insert some javascript and css files only in a Views page.

Im using hook_preprocess_page, but I can not tell if the current page is from a view:

function mymodule_preprocess_page(&vars)
{
    var_dump($vars); //output: nothings that reference the views!
    if([view page])
    {
        drupal_add_js([...]);
        drupal_add_css([...]);
        // Rebuild scripts
        $scripts = drupal_get_js();
        $vars['scripts'] = $scripts;
        // Same for css
    }
}

I know i could use a template file (page-my_view_page_path.tpl.php), but the js and extra css must be included only if my module is enabled; so I like to keep this things directly inside my module code.

Ideas?

views_get_page_view() finds out what, if any, page view is currently in use. If it returns NULL, then the current page is not a views' page.

But using drupal_add_js() and drupal_add_css() in a hook_preprocess_page() won't work as expected because the variable $script and $style variables have already been set by template_preprocess_page(). Views's template preprocessing (see Jeremy French's answer) is probably a better place to add your CSS and JavaScript.


How to attach a CSV file with the Google Chart API? I have created a Google Chart based View and it is working nicely.
How to give the facility as the user should be able to upload a CSV file and the data comes accordingly?

To my knowledge there is no way using Google Chart API to "* to upload a csv file and the data comes accordingly*" (as in your question).

However, you may want to have a look at the Easychart module as a possible alternative (which already has an official release for both Drupal 7 and Drupal 8).

It is a graphical user interface, using the Highcharts javascript library as its charting engine (which may require a commercial license though). It claims to support every Highcharts chart-type and option.

Some more details about this module:

It defines a new content type (= Chart) used to add charts to your site.
It creates a chart widget that can be used in your own content types.
It integrates with the WYSIWYG module and provides an editor button to add charts to your WYSIWYG content (CKeditor and TinyMCE are supported).
It provides an intuitive interface to configure charts through the Easychart plugin.
It supports pasting of CSV data to create charts from it.
overheid.vlaanderen.be contains some real world examples of a Drupal website with some charts created with Easycharts (ignore the text on that page if you're not familiar with this language, just concentrate on the charts).

Especially the bullet about "It supports pasting of CSV data to create charts from it." seems close to what you're looking for.

Resources:

Module documentation.
Video demonstration.


Changing the field date type from 'datetime' to 'unix timestamp' without losing data I am investigating how could I convert the date format in the 4 database tables: field_data_field_article_publication_date from the actual datetime format:
2013-09-10 12:43:03  to its unix timestamp equivalent: 1378816983
with a minimal negative impact on data integrity of the actual articles on a production environment.

UPDATE

My guess scenario would be:

Update the field type in my feature: MYFEATURE.features.field.inc // changed to timestamp [EASY]
Alter the table field structure from 'datetime' to 'timestamp' in a hook_schema_alter [EASY]. This should be performed using db_change_field().

RISKY AS I CAN LOSE DATA WHEN MOVING CONTENT. I MIGHT TRY TO DUPLICATE COLUMN DATE (INTO DATE2) FIRST.

I NEED HELP HERE: Convert all existing dates for articles found in 'field_data_field_article_publication_date' table to the new format unix stamp. [NOT SURE HOW]

Any further help?

I am interested in minimizing querying time by using MYSQL: UNIX_TIMESTAMP(date) somehow.

My approach on No.3

loop over all 4 tables {

   - create a new column date2 of type: int (or datetime?)
   - copy all dates from date to date2 passing them through strtotime()
   - delete column date
   - rename column date2 to column date

}

That would be a start in MYMODULE.install:

function MYMODULE_schema_alter() {
//...loop over 4 tables
  $schema['TABLENAME1']['fields']['DATE2'] = array(
    'type' => 'int', //or timestamp
    'not null' => TRUE,
    'unsigned' => TRUE,
    'default' => 0,
    'description' => 'Field added by my_module',
  );
//…
}

/**
 * Content types using date fields should be using timestamp instead datetime
 */
function MYMODULE_update_7192() {
//define their names or get them from schema
$tables = array('TABLENAME1', 'TABLENAME2', 'TABLENAME3', 'TABLENAME4');

foreach ($tables as $table) {
       //create a new column date2 of type: int (or datetime?)
       $schema = drupal_get_schema($table);
       db_add_field($table, 'DATE2', $schema['fields']['DATE2']);
       db_update($table)
      ->fields(array(
          'DATE2' => strtotime('DATE'),
         )
         )
       ->execute();
      db_drop_field($table, 'DATE');
}
}

The strtotime() php function will be helpful for converting date to unix timestamp


XHR2 upload using Drupal 7's ajax framework I'm trying to implement XHR level 2 (file API upload) using Drupal 7's JQuery $.ajax implementation. I've got the feeling I'm almost there.

First of all, I got XHR.send() working according to orginal example on HTML5 demos. But now, I want to use Drupal 7's built in ajax framework.

I found some examples how do this with JQuery but I can't get it working for Drupal 7 with a custom ajax responce. I also found a related (D8) discussion about this on drupal.org.

Here's the code, which returns a ajax error "Illegal invocation". Probably because formData is not in a proper format?

    // 'files' below is a correct object with at least one file

    var file = files[0];
    var formData = new FormData();

    formData.append('file', files[0]);

    // element_settings: see ajax.js in drupal
    var element_settings = {};

    element_settings.progress = { 'type': 'none' };
    element_settings.url = '/mymodule/save/ajax';
    element_settings.data = file;
    element_settings.cache = false;
    element_settings.contentType = file.type;
    element_settings.processData = false;
    element_settings.submit = {
      'savedata': formData
    };

    element_settings.xhr = function() {
      myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        myXhr.upload.addEventListener('progress', progressHandlerFunction, false);
      } else {
        console.log("Upload progress is not supported.");
      }
      return myXhr;
    };

    var base = '#myelement';
    ajax = new Drupal.ajax(base, $('#myelement'), element_settings);
    ajax.eventResponse($(ajax.element));

On the server site, I'm using a menu hook with ajax_deliver as delivery callback.
This works, but I can't access $_FILES in the same way which is possible if you use xhr.send().

By, the way, I'm aware this only works in modern browsers. I'm using Chrome.

I think your approach is flawed. You should use as much of Drupal's ajax system as possible, even though is wildly uncomprehensible and weird. Don't create your own Drupal.ajax object. Let Drupal handle that and the events and triggers that come with that.

Then there are only 2 problems left:

Don't create an iframe and a fake form and submit that. Use Ajax.
Don't serialize and preprocess that request. Use only what I'm giving you.

They're combined in jquery.form.js apparently. So all you have to do, is override where ajax.form.ajaxSubmit(ajax.options); is called: Drupal.ajax.prototype.eventResponse.

The result inside my failed-attempt-module.

It's an override of Drupal.ajax.prototype.eventResponse. I've added everything inside if ( 'FormData' in window )

My original plan (as the module name says) was to make all file fields drop containers for HTML5 File drag/drop. My approach was flawed too. I think with this approach, it's not so difficult. Just extend the FormData object at the right time.


Update custom user fields programatically how can I update custom user fields programmatically?

I've tried this but don't know how to get Id because I have to execute this code automatically on page load ..

$existingUser = user_load($uid);
$edit = (array) $existingUser;
$edit['field_company_name']['und'][0]['value'] = 'Ciklum';
user_save($existingUser, $edit);

It should be something like this:

$existingUser = user_load($uid);
$existingUser -> field_company_name['und'][0]['value'] = "Ciklum";
user_save($existingUser);


jquery.cookie.js is loaded only for authenticated users, by jQuery update module jquery.cookie.js is loaded only for authenticated users and i cannot really figure out why.
The page caching is disabled.

Any thoughts?

The jQuery.cookie library is not always included, it depends the user state and the visiting page.

For example, the login form includes this library by attaching (#attached) it to the form.

What you could do is include it yourself in a custom module or in your theme.

// hook_init()
function YOURMODULE_init()
{
     drupal_add_library('system', 'jquery.cookie');
}

// or in theme preprocess
function YOURTHEME_preprocess_page(&$vars)
{
     drupal_add_library('system', 'jquery.cookie');
}


Is Drupal cache as set in the core enough for simple sites? Let's imagine a site which is almost completely static. There are news which are rarely updated and from time to time some new content in the form of more news. If there are only anonymous users apart from the admin... would the cache retrieval be so fast as simple HTML pages? I ask this because I have tested the config above with cache on and it goes very slow in comparison with HTML saved counterparts and I am not sure if it is a misconfiguration.

No it would be unlikely to be as fast as plain HTML, because the default caching is still using the database and some PHP.

However you can improve the speed significantly with a module or two. It is highly dependent on the speed of your servers - if you have a fast database server but a slow filesystem you might be better using the database although that is an unlikely situation. At minimum I recommend installing Advagg - correctly configured that will reduce load times for a lot of sites by around 25%.

Depending on the site, Boost can also vastly improve performance although I have not found it as universally applicable as Advagg. Also depending on your setup an external cache like Varnish may be better although it requires careful configuration and some server admin knowhow.


create a field that display value from an other one? I'll try to give a clearfull explanation of my question... but it's an hard one to explain, and my english is not really good... but let's try and I hope someone could help me. :)

I have a site running with Drupal 7

In this site I have an event calendar (with date)

And the entity registration module.

The point is:

When my user create a multiple event date I get a display like this:

 event 1 - date_of_event_1
 event 2 - date_of_event_2
 event 3 - date_of_event_3

 event description

 registration form:

 name:
 e-mail:

What I want is to be able to have a field in my registration form like that:

Choose your date: date_of_event_1 []  |  date_of_event_2 []
([] = some check boxes)

So I search for a module that allow my form to display a field referencing my dates...

I can easily display my dates values on a view. So I think there is a way to use the same filter on a field?

I've made some researches but I didn't find anything.

Maybe someone heard about something like that?

Thanks for reading!

Just adding some informations:

I have some hopes with the field-reference module...

But here the problem is my registration form is an other type of content and it's display in the related node by using a field "registration" (that came with the module)

So field reference doesn't find my date value in my form because it's not really in the same content. :(

I'm not sure this is suited to your needs but maybe the entity reference module might be able to help you :

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field Four widgets:
  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete
  widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field)
  Two formatters:
  A
  "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.)
  A "Rendered
  entity" formatter, that renders the references entity using a
  configurable view mode Integration with Views (for both forward and
  backward references)
           Integration with Entity Metadata (and as a
  consequence with Search API and the like) Integration with Devel
  generate Integration with Feeds and Migrate (>= 2.3) for painless data
  import This modules depends on Entity API and CTools.


Getting password hashes and salts from Drupal 7 I need to get user accounts' password hashes and salts from a Drupal 7 app, so as to migrate these accounts into Stormpath. Could you please help me to figure out where this data is stored and how to get it from the DB?

The password hashes & salts are stored in the pass column in the users table with the first 4 bytes being settings, the next 8 bytes being the salt, and the remaining the password. See the user_hash_password() &  _password_generate_salt() docs for how salts are generated.


Is there any way to make a menu link *not* a link? I have a hierarchy of links in my menu, but one of the higher level entries needs to simply be a category, and not link to anything.  It is "Related Sites" and has a bunch of related links under it, but should not itself link to anything.

Drupal doesn't let me save it without a URL, and vomits a bunch of errors if I try using '#'.

How can I achieve this with a minimum of hassle?

You can try the Special menu items module.

One of its features is:

  User can create a new menu item and place either <nolink> or <separator> to the Path field


Is there a way to display webform submission based on element values? I create a webform in Drupal 8 with certain elements (first name, last name, email, phone, visible (Yes / No)).
I want to display the results of the webform based on the element (visible = Yes), so that other roles cannot see the results where visible = No.
How can I do that? How can I filter webform submissions based on element values?

You can achieve this with Webform Views Integration. This module allows you to build a view of webform submissions. You then can use Views' filtering on elements values.
Unclear is where you want to display them. But with Webform Views Integration you can of course build a view page with an URL or view block as you need.

Use Webform Views Integration module to expose Webform submissions to Views (Webform is a module for making forms and surveys in Drupal).


How can I save an unpublished node skipping required fields validation? What is the best way to save node without the required field values?
It would be something like "save as unpublished" and the required validation is omitted, but I am not sure in which module I can find this functionality and how to set it up.

I finally solved this using the Require on Publish module. It offers an additional checkbox to require only when publishing the node.

This module allows fields to be required only when the piece of
content is being published or is already published. This can be used
when you have fields such as tags or SEO information on your piece of
content that editors really don't need to fill in until the content is
going live.


How to create a "Link posting" system in Drupal 7 I'm new to drupal. What I want is to share "links" of different sites - users can publish links. Links can be a certain type of "content" -  I've some knowledge of working with custom content types & "Views". I'm assuming Links should be a custom content type, users can add new links from Add Content >> Links

This "Link" content type should have only two fields:

Text to display for the link
URL

In front page, I want a block that will display most recent links: the first field (text to display for the link) -  when clicked, viewer will be navigated to the 2nd field (URL)

Thanks in advance for helping!

Basically, you need a couple of modules to do that. You already mentioned Views to create the list of links.

To set up your content type, you will need the Link module which provides a link field. You can configure it to display two fields, for link title ("My cool site") and link url ("http://www.example.com"). I think that new content types contain a body text field by default, but you can remove that.

I also recommend Automatic Nodetitles in your case. In Drupal, a node is required to have a title, but you probably do not want to expose a title field to the user because the link field already contains a link title. Automatic Nodetitles allows you to hide the title field and populate it with another value, for instance the link title, the link url or even a combination of those two.

I hope that helps - if not, please clarify your question.


Hook fires before current_user service can identify current user I want to make a menu link disappear when a user doesn't have permission to use it.  I tried this code:

function some_module_menu_links_discovered_alter(&$links) {
  $user = \Drupal::currentUser();

  file_put_contents(DRUPAL_ROOT . '/logs/permission.txt', var_export($user->hasPermission('access some module config'), true));
  file_put_contents(DRUPAL_ROOT . '/logs/roles.txt', var_export($user->getRoles(), true));
  file_put_contents(DRUPAL_ROOT . '/logs/id.txt', var_export($user->id(), true));

  if (\Drupal::moduleHandler()->moduleExists('some_module')) {
    if (!$user->hasPermission('access some module config')) {
      $links['some_module.admin']['parent'] = '';
    }
  }
}

And it didn't know that the logged in user existed.  I was logged in as an administrator, and it thought I was anonymous.  I tried the same code in another hook, and it worked.  So, I'm curious:

Why does this hook load before currentUser knows I'm logged in?
And, are there other hooks like this?
Should I try to figure out the current user through another more low-level method?
Or, is there another way to make a menu link disappear when a user doesn't have permission to view it?

EDIT: Providing code to show what I've done.  The menu link is not disappearing when users don't have access to the route it links to.

some_module.settings:
  path: '/admin/config/system/some_path'
  defaults:
    _form: '\Drupal\some_module\Form\SomeModuleForm'
    _title: 'Some title...'
  requirements:
    _permission: 'access some module config'

The users do not have the access some module config permission, yet the menu link is showing up for them.  When they click on it, they get an access denied page.

Question in the title: Hook fires before current_user service can identify current user

The menu discovery process is not that dynamically, only runs when you clear the cache or make changes that need a rebuild. So the current user while rebuilding the menu has nothing to do with the current user of a request when the menu is displayed.

I want to make a menu link disappear when a user doesn't have permission to use it.

About the question behind this, what do you not like about the default behavior? Drupal doesn't show menu items the user has no permission for. If you want to do more adjustments probably the best place is in preprocess.


When I disable the poll module my add content page doesn't work. Why? Im on d7. I no longer want to have a poll on my site. For some reason when I disable the poll module, the add content page becomes blank and says I have not yet created any content types. I have three other content types on my site and they display fine in the admin panel, just not on the node add page. Anyone have any suggestions? Thanks.

Cache can often be a source to weird problems, clearing it could help. The poll module won't effect if other content types are active or not, so the problem shouldn't be related to the poll module directly.


How to programmatically associate a taxonomy term to a field I'm trying to import user profiles data from a JSON file. Several fields are entity reference to vocabularies.
I'm able to create a new taxonomy term entity in the universities vocabulary bundle using the following code:
$term = Term::create([
  'name' => "University of Bologna",
  'vid' => 'universities',
])->save();

Now I have to link this newly created term to a field contained in Profile Type. I'm testing the following code.
    $values = array(
        'type' => 'profile_type',
        'uid' => 3043,
    );
    $profileStorage = \Drupal::entityTypeManager()->getStorage('profile');
    $profileEntity = $profileStorage->create($values);
    $profileEntity->field_entry_university->appendItem($term);
    $profileEntity->save();

However, this approach doesn't work. How can I fix it?

appendItem takes an array.
Try $profileEntity->field_entry_university->appendItem(['target_id' => $term->id());


How to pass along current $form_state for an #upload_validators callback? I have a managed_file #upload_validators callback and when it is called the $form_state does not get passed along with it. My goal is to use another field in the form to rename the uploaded file. I just need access to that during the validation. Maybe I shouldn't be using a validator callback for renaming the file and displaying in the UI immediately but this but it is all I can think of at the moment.

It appears we can use this code to get the $form_state, however, there are no $form_state['values'].

$form_state = form_state_defaults();
// $form_state is passed by reference and will be updated automatically.
form_get_cache($_REQUEST['form_build_id'], $form_state);

I was able to find the value in
$form_state['field']['field_NAME']['und']['entity'][0]->field_NAME['und'][0];

However, this will not pass along the value you set in another field without first setting an #ajax callback on that field, the callback can just return NULL, it is just to update the form.

In our case we disable the file upload field until the other field has first been set.

Hopefully this will help someone or most likely myself in a year from now.

sources: https://twitter.com/eojthebrave/status/743544054030336000 && How do I load the $form_state for a form loaded with drupal_get_form?


How to change the date format for date entity field I created an entity with date field. Currently the date is being output in the format "mm/dd/yyyy":

How can I use the format "dd.mm.yyyy"? I couldn't find any settings, related to it, in the field configuration form.

You can usually only change the output of a date field, as it is easier to convert an existing date to something else.
The input is often standardised to make sure the system understands the input.

In order to change the output, create a new date format admin/config/regional/date-time/formats and enable it on admin/config/regional/date-time.
Then you can use it as a display for the field on the display tab.


Blocks not shown in /user/logout page Users must be logged in to see anything on my site; so it's important the user login block is always shown to anonymous users.

When users log out, they are normally redirected to the front page. A user has reported an issue where this doesn't happen; the user is kept at /user/logout, where the blocks are not shown.

If I manually navigate to that address, the redirection to the front page doesn't always happen to me, and I can also see that no blocks are shown.

If there aren't modules that avoid the redirection happens, the only case the redirection from user/logout to the front page doesn't happen is when the user is already logged out. user/logout is defined as the following, in user_menu().

  $items['user/logout'] = array(
    'title' => 'Log out',
    'access callback' => 'user_is_logged_in',
    'page callback' => 'user_logout',
    'weight' => 10,
    'menu_name' => 'user-menu',
    'file' => 'user.pages.inc',
  );

When a menu is accessed from the users, Drupal first calls the access callback; if the access callback returns TRUE, then Drupal calls the page callback. In this case, the redirection is done from the page callback, which is never called when the user is logged out. (In that case, user_is_logged_in() returns FALSE.)

For a page like user/logout, the login block is not shown. In fact, user_block_view() contains the following code, used to render the login block.

  // For usability's sake, avoid showing two login forms on one page.
  if (!$user->uid && !(arg(0) == 'user' && !is_numeric(arg(1)))) {
    $block['subject'] = t('User login');
    $block['content'] = drupal_get_form('user_login_block');
  }
  return $block;

What you can do is implementing hook_block_view_MODULE_DELTA_alter() to show the login block also on user/logout, in the case the redirection to the front page doesn't happen for any reason.

function mymodule_block_view_user_login_alter(&$data, $block) {
  if (!$GLOBALS['user']->uid && $_GET['q'] == 'user/logout') {
    $data['subject'] = t('User login');
    $data['content'] = drupal_get_form('user_login_block');
  }
}


How to add text to the user registration form? I've been using the String Overrides module to change a few of the text fields in the user/register form. I've found this approach to be simple and effective.

However, I want to insert some text below the "User Account" heading but above the "Email" field. Just some general information about signing up. Unfortunately there is no text there currently so I can't use "String Overrides". Is there a simple way of adding some text? I don't want to create an entire custom registration form and reinvent the wheel, I just want to add some text to the existing form.

You can use hook_form_alter like this.

  function MODULENAME_form_alter(&$form, &$form_state, $form_id){
    switch($form_id) {
      case 'user_register_form': // the value we stole from the rendered form
        $form['cutomtext'] = array(
        '#type' => 'item',
        '#markup' => '<div > Your text goes here... </div>',
        '#weight' => 1, // Adjust so that you can place it whereever
        );
        break;
    }
  }

Form API Reference

Also you could try hook_form_FORM_ID_alter

Usage :

function hook_form_FORM_ID_alter(&$form, &$form_state, $form_id) {
  // Modification for the form with the given form ID goes here. For example, if
  // FORM_ID is "user_register_form" this code would run only on the user
  // registration form.

  // Add a checkbox to registration form about agreeing to terms of use.
  $form['terms_of_use'] = array(
    '#type' => 'checkbox',
    '#title' => t("I agree with the website's terms and conditions."),
    '#required' => TRUE,
  );
}


Is there a module for adding field types for latitude, longitude, compas coordinates, etc? Either my google searching skills are low, or there is no such module for D7. I want to create a content type where a user can add his position on the sea: latitude, longitude, knots, heading (000°) and other coordinates. Do you know any module that does this?

The Geofield module allows you to store such data:

  Latitude and Longitude Supports entering data as both Decimal Degrees
  (122.340932) and Degrees-Minutes-Seconds (-123° 49' 55.2" W). The
  Degrees-Minutes-Seconds input is very tolerant of inconsistent input.

  Bouding Box Four textfields where lat / lon can be entered

  Well Known Text (WKT) A textarea for direct WKT input

  Draw on an OpenLayers Map Allows drawing of Points, Lines, Polygons
  and Bouding Boxes

  HTML5 Geolocation Transparently asks the browser for the user's
  current location. Works great on Chrome and smartphones with GPS.

You can encode data from another field using the Geocoder module as well.


Quickly build a Drupal website from another Drupal website I have an existing website in Drupal, say abc.com, and it's in english. Now I want to quickly build this website for different domains. The layout remains same, but the language and images may change. How can I do this and how quickly can it be done? Should anything be done on the first site so that building the second site becomes easy like profiling or something?

There are several tools available to make this easier. Some benefit greatly from being applied, while some can be added in hindsight without issues.

Drush make, allows you keep a file with the definition of which modules, their versions, any patches etc, you need to build your site. This then makes it easy to quickly pull in all the modules again when you need to set up a new site. It also happens to be very useful whenever you need a workflow that includes patched modules.
Features on the other hand, allows you to take the configuration you make with your modules, such as Views, Panel Pages, Contexts and more, and export it to a module. To some extent, this module requires you to have thought about features from the beginning. Some things, blocks and their settings for example, cannot readily be exported this way, meaning that those will either need to be manually configured after the new site is setup, or be replaced by something. I use Panels content panes in place of blocks, largely for this reason.
An Install profile finally allows you to tie number one and two together.
In the install profile, you first define dependencies on a few core modules, then on all your features, and finally on any other modules you need, that aren't pulled in by features. Then when you run the install, all of your modules will be enabled automatically. This part can easily be done in hindsight, but then you always end up with some amount of custom work that depends entirely on your site, and can't quite be captured in another way, and needs custom code to run during install. This step has proven to require quite a bit of work when colleagues of mine have attempted this after the site is already built.

This approach can readily be, and should IMO be, applied already when building the site initially, but can also be used afterwards to help cloning a website. Realistically, the second will require more work than the first. It is left as an exercise to the reader to discover other cool benefits of this approach, such as how one can automatically generate demo content and more.


Render value of custom content type in html.html.twig is there a way to render a value from a node of custom content type in html.html.twig?

E.g. in my custom content type "book" I have a field called "author_name". I now like to render the node value of "author_name" anywhere in html.html.twig.

Is this somehow possible using just twig? I tried a few things with extends, embed, include etc, but nothing worked so far.

Load the node and get the field value in a preprocess hook:

function mytheme_preprocess_html(&$variables) {
  if ($variables['node_type'] == 'book' && ($node = \Drupal::routeMatch()->getParameter('node'))) {
    $variables['node_field1'] = $node->field_field1->value;
  }
}

This makes sense to check first for the correct content type, because then you know which fields are defined. Otherwise you would have to check if the field is present to prevent an error. But then you have already loaded the node for nothing.

Output the value in twig:

{{ node_field1 }}


deleting comments in bulk how can I delete all comments at once? I have seen how to do it with nodes and bulkdelete module, How to delete all nodes of a given content type?
but am looking at a similar solution for comments.

I am looking for a solution that does not leave any artifacts in the database. Is Views Bulk Operations the best solution?

AFAIK, VBO should be able to do the job, but I haven't tried it myself to delete comments.

Another way is to run some code (in a module or in Devel module's 'execute php' block) that gets a list of all queries from the db, builds an array of the comment IDs and passes that array to the comment_delete_multiple function. Note that this can take a while to complete (depending on server performance and the number of comments), so you may have work your way around that, for instance by using set_time_limit (http://php.net/manual/en/function.set-time-limit.php) or Drupal's batch API.

[update: see Chris Cohen's answer for example code based on this approach.]


Open form module from popup I have a basic module that I made for a survey/email collection form for a site I'm building. I'm very new to drupal and drupal development and I'm trying to figure out how to open this module on the front page after a click on a button inside of a popup of some sort, I was thinking jquery modal or something of the sort. I can't figure out heads or tails from it and don't even know where to put anything. So far I just have the module files survey.info and survey.module. Do I have to modify theme files or what? Sorry for being so green but the development files online aren't very cut and dry.

Welcome to Drupal!

Take a look at https://drupal.org/project/modal_forms - this performs the functionality that you've described and works with https://drupal.org/project/webform which you can use to build the survey.

I also recommend taking a look at https://drupal.org/project/examples to learn more about module building in general; it includes many practical examples.

If you want to use an existing form, check out the tutorial at http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7 that describes how to use CTools Modal with existing forms.


How to change the positioning of Drupal blocks when a theme is enabled? I am developing a Drupal 7 theme. I want to change the position of the blocks when a user set my theme as default.

In my theme the main menu is positioned in left sidebar. Suppose the current theme of the user has main menu in the header block, when a user enables my theme, the main menu should go to the left sidebar.

Basically I want to position the block using code when my theme is set as default.

Any way to implement this?

Only using Drupal core

Investigate the 'current theme of the user', to identify the 'region name' where the 'header block' (which contains the main menu) is positioned. Let's say that region is called "HeaderRegion".

Then in your own theme, make sure to create a region with the exact same name (like "HeaderRegion"), and position that region in the area that corresponds with what you describe as "left sidebar".

With this approach, the "main menu" will be shown in both themes in the block that is positioned in the "HeaderRegion"-region. And the actual theme that is selected will determine if it will be shown in the header (if using the current theme) or in the left sidebar (if using your own theme). Note: a "left sidebar" with a region name like "HeaderRegion" will sound a bit confusing, but that's a way to make it work ... (and maybe that region name in your current theme has a less confusing name, so you might be lucky and not suffer that confusion ...).

Using a contributed module

By using the Themekey module, you can implement content, user, or role -specific themes.

So if you can come up with the appropriate set of theme variations (which would differ by the location of your theme regions in which the blocks are displayed), this could be a solution that could work.


Drupal Content Updates Not Visible to Public Without Login Attempt New to Drupal picking up an existing prototype site design from another newbie.

Installed version = 7.28

Whenever I make any updates to contents or even site name and tagline, as Administrator I see the updates listed as "published".

If I log out and reload the web page, it does not display any of my updates, until I click the user login button on the homepage. (The button was part of the existing Homepage design.) It does not matter whether the login attempt authenticated or not, the web page would refresh and the updated content loads and displays correctly. However, without the login attempt, the site content remains at the revision before the last update, same behavior whether browsing in Firefox or IE.

The permissions for viewing contents is enabled for Administrator, Authenticated User, and Anonymous User. The Drupal site seems to treat an unauthenticated log in attempt to be an Anonymous User. What about when the site URL is entered in the browser, and the public is viewing the site? What is the "role" of the viewer of the site before a login attempt is made?

Where is the site content being pulled from to display in browser when the site URL is first loaded?

Where is the site content being pulled from after a login attempt?

Thanks for any help to point me in the right direction to debug this!

The Drupal site seems to treat an unauthenticated log in attempt to be an Anonymous User

Correct; an anonymous user is unauthenticated.

  What is the "role" of the viewer of the site before a login attempt is made?

"anonymous user"

  Where is the site content being pulled from to display in browser when the site URL is first loaded?

Either the database or your cache store.

  Where is the site content being pulled from after a login attempt?

Ditto - database or cache, depending on your setup, whether caches have been primed for the particular cache id, etc.

It sounds like you simply have page caching enabled for anonymous users. Clear Drupal's caches and see if the problem persists.


How do I use the flood interface? I'm working on a two-factor login form that sends a text message to the user. With a "did not recieve message" button. I would like to limit the number of times a user can request for a new text message.
I know that I can register flood for a certain event like: \Drupal::flood()->register('eventName', 1800, $user->getUuid()). The FloodInterface has a isAllowed($name, $threshold, $window = 3600, $identifier = NULL); method that, I imagine, tests when a user tries to do a certain $name event, it tests if that event has been done more often than the $threshold within the $window. If so then the method returns false and otherwise true.
In my example I can register the event somewhere in the chain of events/functions that send the message and also check there if the event isAllowed?
Something like so:?
public function someFunction() {
  \Drupal::flood()->register('send message', 900, $user->getUuid());
  $token = 12345;
  $this->sendMessage($token);
}

private function sendMessage($token) {
  $is_allowed = \Drupal::flood()->isAllowed('send message', 3, 900, $user->getUuid());
  if ($is_allowed) {
    // Send the message
  }
}

What I don't get is why I also have to indicate the $window in the isAllowed method when I already assign that in the register method?

They are two different parameters that share the same name (and can share the same value by default). Per the docs for FloodInterface:

::register():

int $window: (optional) Number of seconds before this event expires. Defaults to 3600 (1 hour). Typically uses the same value as the isAllowed() $window parameter. Expired events are purged on cron run to prevent the flood table from growing indefinitely.

::isAllowed():

int $window: (optional) Number of seconds in the time window for this event (default is 3600 seconds, or 1 hour).

The register() parameter specifies how long that flood event will be stored (remembered) after the time of registration before ::garbageCollection() clears it out. The isAllowed() parameter specifies the max number of instances that can occur within that window before isAllowed() will return FALSE


Views filter criteria I added a field to content type. The field type is select list.
I created a view. I added a filter criteria using the above field:

Operator > Is one of

Options > Select All is selected.

When I go to front end, I see -Any- selected by default but I dont the content/result. When I click Apply, i get the result. I am not sure why I have to click Apply to get the result. It should give me result as soon I go to views page.

Please help.

I just tested this and got the same problem as you.

I found the solution you need to check mark limit to selected items.

If you don't have the Limit list option, check marking the expose operator also fixes it. You would then have to use css to hide the expose operator if you don't want it.


Attach JavaScript and CSS assets when render entity using Web Sockets Goal:

Attach all the necessary JavaScript and CSS files to the page, when a rendered entity is delivered on a Web Socket event.

Given:

I have a Web Socket with an event when a new entity is created (Via pusher.com but nevermind).
The Web Socket delivers JSON with some meta-data(entity id, created date, title, etc.) and HTML of a single rendered entity.
I catch the event in and render the entity (I do it in JavaScript, client is the same Drupal website).

Problem:

JavaScript and CSS files, needed for rendering, are not attached on the page. (E.g. scripts for display of an image gallery, lazy-loading of images).

My ideas:

I think that I should list all the necessary JavaScript and CSS files (or something like ajax commands, which can attach assets) in the JSON, when I push the event. To achieve this I might need to rendered the entity via some Drupal-AJAX-Renderer.

Afterwards (when I receive the JSON from Web Socket) there should be some way on a Drupal website to attach these files by executing some JavaScript method in Drupal.ajax.

Currently I haven't figured out how to achieve this. Could you give some advice?

It was quite some work to adapt the rendering process. There is a lot of code, I will just summarise the solution. If you want more details, just write a comment.

The solution looks similar to my ideas/hypothesis in the question's description.

I created a custom render which collects all the libraries during rendering in an array. It results in an array:

return [
      'commands' ['An array with ajax commands for settings'],
      'content' => 'Rendered content(HTML)',
      'libraries' => 'all the needed assets grouped into libraries',
    ];

I had to to override the AjaxResponseAttachmentsProcessor and AssetResolver classes.

Also I implemented the hook_js_settings_build() to collect all the libraries on the page, as ajaxPageState does not contain all the dependencies.

At the front-end side it is not possible to attach all the assets by comparing ajaxPageState and the response from a Web Socket.


What causes menu to stop querying for children half way through menu I have a 'primary menu', rendered in one case using the 'bartik' theme (site preview)  and rendered in the other using the 'Bootstrap' theme. (site preview)

With the bootstrap theme, working from left to right the children are presented until 'Publications'. Then there are no children. The same menu presents all the children in Bartik all the way across. Looking through it, the children are not in the php data ($element[#below]) and are not printed out to the HTML.

What is causing this?

this is what i see. There are no children missing. Have you cleared your Browser cache?

Some themes need the parent item set to "expanded". The setting is available (e.g. http://example.com/admin/structure/menu/manage/main-menu)for every menu item but only parents need it.

  Show as expanded. If selected and this menu link has children, the menu
  will always appear expanded.

This is the only wild guess i can take from your informations.


How can I set a webform's field value by query parameter? I have created the query string for the particular fields.

My URL : www.examples.com/path?title=something

How could I pass the "title" query string value to webform field's default values.

This can be done in the webform backend settings: Edit your webform and go to Settings >> Form; then go down to Form Behaviours and select Allow all elements to be populated using query string parameters.

If you go back to the webform element, select the particular field, and enter [current-page:query:full_name] as default value (where full_name is the field name), if the query string contains full_name=John+Smith, the full_name field will be populated with Josh Smith.


Custom sort to preserve order of referenced nodes I have a node type that references other nodes. When viewing node of Content Type A, I have set up a view that displays all references to nodes of Content Type B on a gmap.

This is the code from a template file that overrides the display of view_one; it calls the map in from another view.

<?php
  $view = views_get_view('view_one');
  $view->set_arguments(array($fields['nid']->raw));
  $view->execute();
  $contents = $view->result;

  foreach($contents as $content) {
    $nodes[] = $content->node_field_data_field_B_content_nid;
  }

  if (isset($nodes)) {
    $args = implode(',' , $nodes);
    $view = views_get_view('linked_map');
    $view->set_display('map');
    $view->set_arguments(array($args));
    $view->execute();

    $markup_map = $view->render($args);

  }
  else {
    $markup_map = '';
  }
?>

It displays beautifully. The only problem is I want to use numbered markers, so that the list is in the same order as the referenced nodes in the main view ("view_one"). Is there some way that I can either utilize a "sort" that won't rearrange the list, or write a custom sort that will preserve the existing order?

I am using the Views module version 7.x-3.1.

Draggable Views will let you define your own manual sort, and keep it consistent across different displays.


Show English when there is no translation I have a website for a client, with more than 5 languages (bg, en, ru, ch, de, it ...). The client wants to add a news section but the news should be only in en or ch and if the user selects a language which is different then en or ch, en should be shown.

Is it possible when you add a content with English language, automatically translations for all other languages to be created instead of adding one by one the translations via translate menu entry?

Language fallback module

I haven't tried this module but it seems to do what you're asking for. You can edit bg, de, it etc languages and set English as the fallback.

Drupal 8 also has one extra module for this: Entity Language Fallback

Automate with Rules

You could probably come up with a Rule that automatically saves translation nodes of an English node under certain circumstances, with some custom code.

Quickly fill in translations

If you can't do custom code for what ever reason, you could enable Synchronize translations (which is a submodule of i18n) on your Content types. This way when you go to translate other languages you'd already have the English text filled in, images kept etc so you just Save the node and see English text on an Italian node.


Status message prompted twice I am opening my registration form in ctools modal popup. I have applied custom module to get that popup.

Once user submit any form ajax window will be dismiss using  ctools_modal_command_dismiss().As window will be closed, status message will be printed using ajax_command_append('.ctools-use-modal',theme('status_messages').

But the status message get printed twice. I had tried to unset session messages. but it was not working.

The function drupal_set_message takes 3 parameters, message, type and repeat. Default repeat is TRUE. If you set it to FALSE, it will prevent duplicates.


redirect sub domain in htaccess file I have tried a number of ways to try to redirect a sub url in my htaccess file with very little progress, and I know I am doing it correctly but for some reason it just is not working, and as far as I can tell there is no module that can do this. I am simply trying to direct a sub domain to the main domain.

This is the code I am using.

  RewriteBase /
  RewriteRule ^red.sitename.com$ http://sitename.com/ [R=301,L]

Now I have red somewhere that you have to do it this a certain way when clean urls is enabled and this is suppose to be the correct way but it is not working.

The piece you are missing is RewriteCond.

This should redirect just the subdomain

RewriteBase /
RewriteCond %{HTTP_HOST} ^red\.sitename\.com$ [NC]
RewriteRule ^(.*)$ http://sitename.com/$1 [L,R=301]

Note also that the separator needs to be escaped as \. to prevent it from being used as a single character match in the pattern.  The [NC] also tells Apache to ignore case during the match.


Running cron results in Caches Flushed I am unable to run cron on a Drupal 6.25 web site.

Running cron using both the run cron option from administration menu and the run cron manually link from status report page results in the following message:

Caches flushed.

The warning message next to the cron maintenance tasks entry on the status report persists and cron hasn't run.

I recently upgraded to latest version of Drupal. This issue also affects development copy of web site.

As always, I ran update.php after upgrade - no errors reported.

Tried changing number of items at /admin/settings/search to 10.

Can anyone advise how to fix the problem?

system_cron calls cache_clear_all with $cid == NULL, which should just be clearing out expired entries.

My guess is that something else is wrong with the system, and cron is failing as a result.

When you upgraded, did you make sure you ran update.php?

Do you see cron listed as being run in watchdog (/admin/reports/dblog)?

Are there any php or other errors/warnings in watchdog around the cron run?

What does your search index status say (/admin/settings/search)?  cron will index search each run.  If this takes too long, you may have problems.  Try dropping down the number of items per run.

If you run drush cron from the command line, does it run properly?


Loading a custom library after all other libraries got loaded So i wan't to load a custom .js file at the very end of the page after all other .js files have been loaded.

This is my library file:

my_library:
  js:
    assets/js/custom.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupal.dialog.ajax
    - core/toolbar.escapeAdmin

So the lib is loaded in the page footer with all the rest of the .js files, but it's not last, it's somewhere in the middle. I even tried to add the dependency for toolbar.escapeAdmin as it's javascript file is loaded the very last, as you can see from the picture bellow of the of page:viewsource, but it didn't work.

Any ideas?

That is neither possible (because JS files have no "weight" anymore in Drupal 8), nor does it make sense: Any module can declare a JS file as async or defered, so even if your file would be in last position in HMTL markup, there is absolutely no guarantee that it will be executed in that order.

PS: Module dependencies seem to quite reliably affect ordering of their JS libs in markup, not really certain about it though.


Proper way to handle ajax request I know the way that I'm currently implementing ajax page loads is not the best way to do it. It goes like this:

I have a module (that I created) that has a path to send all ajax request though. based on the urls parameters, it's able to figure what actual page (node) needs to be loaded. It just returns a json_encoded string for processing (rendering is done client side).

The trouble with Drupal is that it wants to decorate EVERYTHING with all the templates. So I get json intermingled with html. I obviously don't want that. I don't want any rendering done at all in fact. So far, the only thing I've come up with on my own is to implement hook_page_alter and just unset as much data as possible until it renders with only the json. That was working for a while.

Then I added the devel_themer module (or whatever it's called). That automatically appends some javascript to the end of every response. That is breaking the json I'm sending via these ajax requests.

This has brought up the issue of my method of processing the ajax.

What is considered best practice for this type of thing? Ultimately, there may be minimal server side rendering, but I want the data to be sent in chunks that I can inject in various parts of the page. I don't want to have to put in all in one spot. To the ajax_response.title would go in the div with id="title" and the ajax_response.body would go in the div with id="body". There may be info between those two that I don't want to replace/re-render between requests.

Mostly my question is this: How can I tell drupal to send exactly the text that I want as a response instead of insisting on decorating the response with templates and allowing modules to add information?

Simply print your json stuff in your page callback instead of returning it, then Drupal isn't going to add anything around it. In fact, there is a helper function for that, called drupal_json_output(), see user_autocomplete() for an example of that.

That's the official way to deal with this currently, Drupal 8 will hopefully add proper handling for different types of content directly into the routing system (which will be heavily reworked and built upon Simfony2 components).


Show a different view mode depending on role Using the Group module, when a user views a group, I want to use a different view mode depending on whether the user is a member of the group or not.
Conceptually, this is almost identical to showing a different view mode of a node depending on the user role.

I'd have thought it was easy, but I'm struggling. What I know:

The route is entity.group.canonical
I can modify the result of that route using alterRoutes() in a route subcriber

protected function alterRoutes(RouteCollection $collection) {
  if ($route = $collection->get('entity.group.canonical')) {
    // Do something.
  }
}

I'm not sure how to modify the route. Swapping in a whole new custom controller seems extreme.

Turns out, there's a hook for that.

function hook_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {

  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}