Which Rules Event can I use for automatic login from main site to sub site with same database after clicking on a link? In the home page of main site, I am listing all the products. Buyer has logged into the main site and clicks on any product title or image, then I take the buyer to the corresponding sub domain individual product page. In the redirected page or site I want the buyer to logged in since I am using the same database.

This is what I have done for that to happen:

I am using the Rules module to redirect from one site to another site.
The Rules Event I am using is Content is viewed, but actually it doesn't get called at all.
In Rules I am using page redirect action with value http://[node:author].[site:url-brief]/ajax_callback.php?context=buyer-redirect&username=[account:name]&nid=[node:nid]

In my ajax_callback.php file I have used this code:

case 'buyer-redirect':
        global $user;
        $username = $_REQUEST['username'];
        $user = user_load_by_name($username);
        $login_array = array ('name' => $username);
        user_login_finalize($login_array);
        $nid = $_REQUEST['nid'];
        drupal_goto('node/' . $nid);

But in the sub domain still I am not logged in as buyer.

Above mentioned is a PHP file where I am manipulating the requests, but Rules Event "Content is viewed" is not all getting invoked.

How can I make buyer login info to be send and make the buyer to be automatically logged in which clicking on a link in main site?

Any suggestions?

I'm pretty sure that the "... Content is viewed, but actually it doesn't get called at all ..." part of your question is not correct. And that this Rules Event does get called (if not you've found a major Rules bug ...), but that it is NOT the right Rules Event to use for your scenario. Read on for details (and a possible solution) ...

You should be able to get this to work, using the Rules module, using the "Drupal is initializing" event. That will ensure that the rule gets triggered BEFORE the actual content is shown. Using Rules event " Content is viewed " is typically 'too late'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for more details on that. Adapt your rule to use this event, and (just for temporary unit testing) add a Rules Action (as the very first Rules Action) to "Show a message on a site", e.g to say 'Bingo, let the Rules party begin (we did find a Rules Event to continue building on)'.

Moreover, as per the http://[node:author].[site:url-brief]/ajax_callback.php?context=buyer-redirect&username=[account:name]&nid=[node:nid] URL that you mentioned, you can make the value of the URL arguments (= such as the value of the context argument in this example) available as new variable to Rules, simply by using the Rules URL Argument module. Here is a quote about it (from its project page):

  ... provides two rules conditions based on URL arguments:

  check if a URL argument is present.
  compare the value of an URL argument.

  It also provides an action that makes the value of an URL argument available as new variable to Rules.

The newly provided Rules actions and conditions can be found under the "URL Argument" conditions and actions groups in the rule configuration interface.

For an example of how to use it, refer to Comment # 3 in issue # 1686360 which is about "Pass an amount to the url, ie; site/content/node-title?amount=10 or /node-title?=amount:10". Here is the relevant part of it:

  add a "Check if URL argument exist" condition to your rule and set the "ARGUMENT" value to "amount".
  add "Provide URL argument value" action to the rule and set "URL ARGUMENT NAME" value to "amount" and in the "Provided variables" section "ARGUMENT FROM URL - Variable name" to e.g. "amount_from_url".

  You will now be able to use the amount value as a variable "amount-from-url" for other actions in this rule.


Adding a drop down field to user registration We are using Drupal 8 for one of our new project and we need to add a country dropdown to the user registration form. I see that we can add a select box through Manage fields section, but how do I make it configurable?

I mean I want to show the values in the select box from a configurable list.

It sounds like you've found where you can add user fields (under Administration >> Configuration >> People >> Account settings). Once you've clicked the + Add Field button, you can select List (text), add your Label, and click the Save and Continue button to configure the options you can add to your country select list.

Here is where you add your list of items. The Allowed values list text field is where you can add your selectable items. You can add each country you want, once per line. Once finished, you can click the Save field settings to continue to the final configuration page.

Customize the remaining settings and click the Save setting button to finish adding the country select box for your user account.


How to include Facebook feeds inside my page? I want to include Facebook feeds from my Facebook page to my Drupal site as a block.
How to do that?

Go to the Facebook Developers site and configure the kind of feed you would like to have. Save the generated the HTML somewhere.

Create a new block in your Drupal installation with the Full HTML text format. Paste the generated HTML in your the content part of your block.

If you do not want to use the default Facebook feed, take a look at this drupal module.


Views AJAX Submit is removing my custom classes I have custom jQuery that I've added to views filters to my ajax view. When a user selects certain criteria a slideDown and addClass event is triggered and a new set of filters is shown. You can view it here:

https://www.feedingmatters.org/helpful-books

When I click submit the classes that are added to my elements are removed by Drupal. This causes the elements to display: none and now the users can no longer see their filter trail. How can I either stop Drupal from clearing my addClass? The filters need to remain visible so long as the correct criteria are selected.

Note: I tried views dependent filters but it doesn't work as needed.

I struggled with this recently in this question

The answer is to wrap your jQuery in a Drupal Behaviour so that the classes are not removed on every ajax request. Because your current jQuery is probably only run on the first page load.

(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {

        // Put your jQuery Code Here

  }
};
})(jQuery);


Drupal 7: View filters impact on performance Does having multiple view filters affect the overall performance of the site. for example having a category and search filter on main pages of articles and galleries?

In general having more views will effect the performance of your site. However you can check the view query / render etc at the bottom of the view edit pages which should give you insights into what degree they effect performance. You can also cache views but it means there will be a lag on content updates being shown by the view.

In general you will also find more modules you add to drupal will have a performance impact although it could be slight. Even adding views to pages will add js and css and thus the more page weight so it will take longer to download. Also views run will have more db queries and have a performance impact on the database.

Was there something in particular you were looking for?


Default 404 page not working In a Drupal 8.5.3 installation I have set up the following configuration:

I created a basic page, its node path is /node/42.
Under Administration » Configuration » System » Basic site settings (/admin/config/system/site-information) I have set the Default 404 (not found) page to /node/42.

Now I expect a non-sensical URL to show the contents of /node/42 for the 404 page. However, I still only get the generic 404 page.

The theme we are using does not have a custom 404 template or anything like that. What other reasons could there be, that the default 404 page is not the one set in the config?

It was due to the multi-domain setup. I did not realize that you can/have to assign a different 404 page for each domain.


creating messages that appear after content is created I am trying to create an a message to appear with a link to the content when the new content is created

Thanks for any help on this

This could be done with some code in a custom module:

hook_node_insert($node) {
    if($node->type=='my_content_type') {
        drupal_set_message(t('New content created: :link', array(':link' => l($node->title, 'node/'.$node->nid))));
    }
}


Sub menu item not found by system I'm try to overwrite the menu.html.twig file to support my menu structure.

My menu has some links and sublinks (only one level deep). Now when I write the menu.html.twig file I only to all the root links. No subitems can be found.

Can someone tells me what I'm doing wrong?

My source code of menu.html.twig looks like:

{% import _self as menus %}

{% for item in items %}

{% if item.below | length == 0 %}

    {{link(item.title, item.url)}}

{% else %}

 item.title

      {% for subItem in item.below %}

{{link(subItem.title, subitem.url)}}}

      {% endfor %}

{% endif %}

{% endfor %}

My menu structure in Drupal looks like:

Found a way to display the menu correctly.

{% import _self as menus %}

{% for item in items %}

{% if not item.below %}

    {{link(item.title, item.url)}}

{% else %}

 {{item.title}}

      {% for subItem in item.below %}

{{subItem.title}}

      {% endfor %}

{% endif %}

{% endfor %}


Creating Parent-Child Entities Is there a way to create parent-child entities in Drupal 8?  I'm trying to create a structure where the top entity is for County, and the next level entity is for departments, and next level would be staff.  There will be different counties so the departments created at the second level entity will only be tied to the county it's created for, and same goes for staff which will only be associated to the the 2nd level entity(departments).  So Let's say department 1 on County 1 will have different staff from department 2 of the sane county 1.

Also how will the path for this be programmed?  Where in Drupal or what files should be created or modified so that it will structured like myowndrupalxx.xxx\module\county\1\department\2\staff\1 to display staff information for staff #1 of department 2 of county 1?

Lastly, can the database tables have a key for each table, so let's say for the Staff table being at the 3 level, it will have 3 keys, County, Department, and Staff, vs. the County table will have 1 key County.  This way it does follow the parent-child or relational database structure.

I am not a very skilled programmer in Drupal so please provide your explanations in lay man terms as much as possible.

What about using entity reference (included in D8) ? In your case, Each "department" has "county" and each "staff" has "department" : you may just add field to your department and staff content type (or taxonomy term depend on what you need to do with these).
Your may use pathauto to generate the URL you need for each content type :

county/{county_nid}
county/{county_nid}/department/{department_nid}
county/{county_nid}/department/{department_nid}/staff/{staff_nid}

This can be easylly used with views / content type display mode and could imho fit all your needs.


Trying TDD with PHPUnit I'm trying out the built in test driven development method in Drupal 8 but I'm running in to a problem..

I'm getting the following errors when trying to run ./core/vendor/bin/phpunit --list-groups ./modules/ in my cli:

  PHP Fatal error:  Class 'Drupal\Tests\UnitTestCase' not found in
      /Applications/MAMP/htdocs/drupal/modules/custom_cookie_compliance/
      tests/CustomCookieComplianceTest.php on line 10

  Fatal error: Class 'Drupal\Tests\UnitTestCase' not found in
      /Applications/MAMP/htdocs/drupal/modules/custom_cookie_compliance/tests/
      CustomCookieComplianceTest.php on line 10

I have created a module folder called custom_cookie_compliance in my modules folder. In turn I have a custom_cookie_compliance.info.yml file containing the following.

 name: Custom Cookie Compliance
 description: Displays a cookie compliance information window at the top of the website.
 core: 8.x
 type: module

I also have a tests folder containing a src folder which then contains a CustomCookieComplianceTest.php file with the following code.

<?php
namespace Drupal\custom_cookie_compliance\Tests;

use Drupal\Tests\UnitTestCase;

/**
 * @group cookie
 */

class CustomCookieComplianceTest extends UnitTestCase {
  public function testSetCookies() {
    if (!isset($cookie_set)) {
      $cookie_set = TRUE;
    }

    $this->assertTrue($cookie_set);
  }
}

I have written the code by following this guide.

I understand it can't find the UnitTestCase class, but the guide says that is should work, so why isn't it?

My guess is that you're not including the phpunit.xml.dist file, which sits in the core folder.

Either run tests from there (./vendor/bin/phpunit ../modules/your_module) or specify that file with -c.

You can also provide your own phpunit.xml.dist file (see the Payment module as an example); then you can run PHPUnit from your module folder.


Adding a query string to menu items determined by the current node? I'm pretty new to Drupal 8.  I'm trying to figure out how to programmatically add a query string to a menu item link, the specific query string is determined by the node/page the user is currently on.

For example, I've got a link on my primary menu that goes to http://www.example.com

If I'm on the 'about me' page I want the link to add a query string of '?origin=about'. (http://www.example.com?origin=about)

If I'm on the 'contact me' page I want the link to add '?origin=contact', etc.

Are there any modules where this can be done, or how might I go about doing this myself?

The menu is cached. You could disable caching and add the query string to the options of the url in hook_link_alter, but this is not good for performance. So this would be better solved in javascript. You can prepare the link in php by setting an attribute, so that you can easily find the link later in the client and attach the query string.


Display vocabularies/terms inside content-type view I'm working with D7 and Views 3.  I created a view for my term pages (type=content, to show all my tagged content, which is a products' catalog). So far so good.

But now I would like to display in the same term page the vocabulary to which the selected term corresponds, along with all its siblings-terms, and a list of all the other vocabularies (without their terms), so the user can click on them and change the product category they're viewing.

I have my catalog like this:

Vocabulary A
 - Product A1
 - Product A2
 - Product A3

Vocabulary B
 - Product B1
 - Product B2
 - Product B3

Vocabulary C
 - Product C1
 - Product C2
 - Product C3

And I'm trying to have this in my view (supposing I'm viewing product C2):
 Vocabulary A
 Vocabulary B
 Vocabulary C
 - Product C1
 - Product C2 (selected)
 - Product C3
 Plus the other fields that belong to my product content type.

The idea is that the user can easily move between categories, and have the current category they're viewing with all its terms displayed.

Can I accomplish this with a single view? I tried adding taxonomy:name, term:name, etc as fields to my current view but I just managed to display the current term name and that's it. Can I create a taxonomy view inside my content view? or maybe this can be accomplished with arguments and relationships?

This is my first Drupal site so I'd appreciate any suggestion to know if I'm on the right track.

Thank you!

Create a new view block within your View definition and define it using contextual filters to display the appropriate content.  Then go to admin/structure/blocks and move the block to the regions you wish it to appear in.  One of the options for configuring the block will be to assign what pages it shows up on.  By entering taxonomy/terms/% or whatever other path alias you are using you can limit where these additional blocks will appear.


Views Ticker missing views, what are views and where can I get them I have just installed the module called "views ticker" but I cannot activate it as apparently it requires : views(missing).

Today represents my first experiments in Drupal (I am using V7), so I'm finding some things a little less straightforward than I would expect. For this reason I'm a little lost here, I don't know what "views" are being referred to here much less do I know how to give the module the "views" it requires!

So, any pointers in the right direction would be appreciated.

Many thanks

Modules sometimes have dependencies on other modules.

The Views module is one of the most used modules in all of Drupal that isn't a part of Drupal core.

Generally you can find your missing modules by going to http://drupal.org/project/[name]. This is not always true as some modules is not a single module but multiple modules. Views is one of those modules, that has a core module called Views, and an UI module called Views UI which is used to create the interface for setting up views.


Flag a node n days after its creation Similar to Drupal Answers, I'm creating nodes that are questions. Once I create a question node, I want to have it flagged as 'unanswered' if a user doesn't flag it as 'answered' within 10 days. I have Flags module setup so I can click 'answer/un-answer this question' on the node itself and Views displays the unanswered questions. I'm thinking that the Rules module will be of assistance here, but I do not see a way to start a timer (for lack of better words) in Rules once a node has been created.

Thank you.

You'll need to enable Rules Scheduler, which is a sub-module included as part of the Rules module.

You can watch a screencast on how to use Rules Scheduler from Node One here.


Show more than 10 location using Gmap I am using Gmap + location for show my store locations on my page.

I have added near about 50 locations. However on map it is showing only 10 locations.

I want to show more than 10 locations. Can you please let me know how it is possible.**

Thanks

Simply - edit your pager options in view to fit your needs.


How to override core taxonomy/term/% with a view? I have enabled the taxonomy/term/% view provided by the Views module but taxonomy term views are still handled by the core. Modifications has no effects and hooks such as  hook_views_pre_render() are not invoked.

However, views explicitly specifying a term such as taxonomy/term/5 work.

Do you have any idea on how I can override the core default taxonomy?

The Taxonomy views integrator module can help you; it allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice.


Views load the whole entity even though they only need 3 fields I am using Views to fetch the 3 fields of a specific entity. However, this leads to the view to make a full load of the entity and all the images included in it, even though they are not displayed. This leads to loading 20 images per entity instead of 1!.
How can I hook into the process and modify this. I tried almost all view's and entity's hooks but nothing seems to have an effect. Any ideas?

Are these custom entities or from a module? If they are custom you could try to override the 'query' or 'load' function in the entity controller class (defined in hook_entity_info() ). If it is from a contributed module, there isn't anything you can do without altering the module code.

Also please note that the actual images are only loaded when the browser requests them over http via an  tag, the entity loads the fields over SQL. Agreed, this creates some overhead. But I guess you would hardly notice the difference when a few fields less are loaded.


Tagging a friend in a node Is it possible to create the functionality where, on creating a node, the user can tag friends to associate their friend with the node. Such as in Facebook's tag a friend in a post.

This would require a friends lookup field, which would imply that the users have already approved each other as friends (maybe using User Relationships).

So, the key thing is to provide a lookup field which searches the user's friend list, and also exposes itself to Views.

Ideally, the field would allow you to enter an email address if their friend isn't already on the site (probably asking too much, and could possibly make do with using the Invite module here).

It is definitely possible, and some of the functionality you need already exists.

I would go the route of creating a new field widget for a standard user reference field that tackles limiting the possible list to current friends.

Have a look at user_relationship_views hook_menu implementation for an example of how you would do the user lookup (in this case we're looking up relationship types but you can get the idea). I think the code for doing this with standard user fields in views is pretty straightforward as well if my memory serves me correctly. To find all the relationships with the current user look at the api docs for user_relationships_load().

User relationships already comes with invite module integration (invite user x with y relationship attached to the invitation). The ui isn't that stellar but I'm guessing you could squeeze it into a node form with a little work.


How do I get the fields of a user object I want to know all the fields of the object returned by user_load().

I can analyze it while the site is running with var_dump(), but I want to see the fields without running Drupal, say by opening any (.module) files.

In general, how can I see the object fields of standard objects?

The full answer is: There's no single piece of code which can answer your question. Since PHP has weak and dynamic typing, any piece of code can access the global $user object and can remove/add something to the the object (whether this is always a good idea is an other question).

As a Java (which statically and strong typed) veteran this was the biggest difference to cope with.

BTW: Use dpm which comes with krumo support instead of var_dump this makes the output much more readable. An other aproach is to get familiar with a debugger (Xdebug or Zend).


With Drush, what's the correct procedure to install Commerce Kickstart, Drupal, and the sample store data as a new site? In my opinion, the install documentation is a bit lacking when answering this question.

http://www.drupalcommerce.org/commerce-kickstart-2/install

I want to avoid the browser all together and install commerce_kickstart and configure the sample store all via the command line with Drush.

What's the correct way to do this? Download Drupal; Download commerce_kickstart which creates a profile directory, and then 'drush si commerce_kickstart ... ' ?

Commerce Kickstart differs from the standard core installation profile, by having extra installation steps. These steps are illustrated in the offical Commerce installation docs - they ask questions about store features and whether or not to install the sample store data.

Installation via drush does indeed work, however it does NOT offer these extra-step choices to the user. Instead it assumes you want the sample store.

So installation via drush is straight-forward. Assuming you have downloaded and unpacked the distribution archive file, just cd to the Drupal root, and run drush site-install commerce_kickstart.

Take some time to review the options described by drush help site-install. Most likely you will need to pass in a few more options, such as database credentials. A typical installation command will look something like this:

drush site-install commerce_kickstart --account-pass=admin --account-name=admin --db-url=mysql://root:pass@localhost/db_name --notify

Note that the Commerce Kickstart takes a lot more time than the standard core install profile. It sets up over 100 modules, several content/product types, and imports the sample store data. drush site-install will tell you "This takes a few seconds...", but it took 10 minutes on my machine :-)


Get User IP Address in Twig Template Is there a way to get the user's IP address in a twig template? All the twig examples I find say to do it like this:

{% set ipAddr = app.request.server.get("REMOTE_ADDR") %}

But this variable always returns NULL. These examples aren't specific to Drupal so I'm guessing part of the Drupal implementation blocks/omits this.

Suppose you want to get the ip in the page.html.twig file.

in your

  YOURTHEME.theme

you can try

use Symfony\Component\HttpFoundation;

function YOURTHEME_preprocess_page(&$variables) {
  $variables['page']['ip'] = \Drupal::request()->getClientIp();

}

in your template

  page.html.twig

you can try:

{{ page.ip }}


Contextual filter for taxonomy terms I have a taxonomy terms display that list a taxonomy_list, this taxonomy_list has parents and childs:

Parent
 child
Parent
 child
 child

Is there a contextual filter in views that i can use to pass the parent id and it would return the childs under this parent.

You can use "Taxonomy term: Parent term" as contextual filter in your view.

Most likely you will need to provide a default value for the filter, such as "Taxonomy term ID from URL".

Provide a default value for your filter according to your preferred usage. The options for setting the default value of the filter should be self-explanatory.

Since you didn't specify where this view is supposed to be displayed, I can't give any other insight.


Drush 9 on Windows 7 problem I installed drush 9 and now I'm getting the following error whenever I run a drush command:

/usr/bin/sh: /cygdrive/c/mysite/vendor/drush/drush/drush.launcher: No such file or directory

Details:

I have installed drush 9 on Windows 7 using composer. This was an update to my previous drush 8.
The drush files are installed in my local site's vendor directory.
The drush.launcher file is in the directory indicated in the above error message.
To run a drush command, I go to my site's root directory using MINGW64 and run the command using vendor/bin/drush. for example:

vendor/bin/drush drusn --version

I have C:\mysite\vendor\bin in my path environment variable.
I don't want to use drush.launcher at this time but not sure why it gets invoked and yet not found.

Thank you in advance for your help.

Drush 9 doesn't come with drush.launcher so something is wrong with your Drush installation / update. You should try to fix that by updating or reinstalling Drush. However, in the meantime just delete drush.launcher.

PS! It's recommended to install Drush Launcher in addition to the site-local Drush.


Disable links on Forum Containers Using Drupal 8, is there a way to disable the links of the Forum Containers on the Index Page of the Forum (Forum is activated via the Forum core Module)?

You can do this with jQuery, like this:

$(".link-class").click(function(event){
    event.preventDefault();
});


How to force Feeds to import content? (Feeds too lazy to import every minute) I've setup Feeds to import content every minutes. All settings was fine.
Feed source contains only 1 rss item, and it changed every 1 or 2 minutes.

When I manually click "Import" tab, it will import nicely. But in many times, Feeds too lazy to import it.

By using cron, Is there any way I can force Feeds to import?

Check the minimum refresh period in your feeds setting; feeds will not import anything if the last import is more recent than that setting.


New commerce site checkout broken It turned out there were two issues here: first checkout stopped working, then the server ran out of space. I now have space on the server, but the checkout still isn't working.

It's a commerce site, and checkout worked fine until launch and now the process appears to be broken. I get this message in the Drupal error log.

  Notice: Undefined index: field_extra_instructions in commerce_customer_profile_pane_checkout_form() (line 165 of /home/wholebox.org/www/profiles/commerce_kickstart/modules/contrib/commerce/modules/customer/includes/commerce_customer.checkout_pane.inc).

The site is wholebox.org and if anyone can help find out what's wrong, it would be very handy right now.

Could I have disabled an important module when trying to make it faster?

Checkout problem - there are two possibilities that fixed it, as I re-enabled Extra Panes and Coupon UI at the same time.

I had set an extra field in Customer Shipping Profile. I didn't think it was dependent on Commerce Extra Panes, but when I disabled that module the process broke.

It could also be that the coupon UI module provides the text box on the checkout process, so when I disabled that it broke it.

Thanks for everyone's help in the comments above :)


mobile site question here's my plan to build a site w a mobile site:

1)  develop all my core modules with robust api's.
2)  build a pair of ui modules for each above module.  These ui modules are just ui's for the api's of the above module.  There will be two ui modules for each above module: one for the normal site and one for the mobile site.
3)  use a device detection library and if the client is a mobile device, then use the mobile ui/theme.

example:

I'll build a 'friends' module with an api that allows for adding friends, deleting friends, etc...  This module has no ui.  Then I'll build a normal site ui module and a mobile site ui module that will all for controlled interaction w the ui.

what do you guys think?  Anyone have a better way?

Drupal already has a UI layer in the theme. There are modules which will allow you to switch the theme depending on the device (have a look at mobile_theme), so you can have different themes for different devices. This way your modules should only send data to the theme layer which then acts appropriately for the device viewing.

However with the increasing sophistication of mobile devices it is possible to create a site which has the same markup but adapts to the device using clever css and jquery.


programmically change price of product I want have a product that user can change the price of it to custom ,I want programmically change the price of product when user submit a custom form with entered price.

my require is I want to have product that according to entered value by user ,product price change and then add to his/her cart.
really I dont know how can I achieve it.
appreciate any urgency help

I suppose the existing answer is fine if every customer gets a unique version of the product to purchase. However, it should be obvious that if more than one person uses this it would fail.

You should instead look at what we recommend in this video tutorial:

http://www.drupalcommerce.org/videos/tutorials/donations-custom-line-item-types

The main idea is that you can enrich the line item with custom pricing information and then use the product sell price calculation system to swap in the appropriate custom price.


Show block on nodes and only for node author I am building a simple classifieds style site. Instead of using straight email, I was thinking about creating a simple "make offer" node type. Create a few basic fields (reference to classified listing, message, will buy for X price, would trade, etc...).

Then create a view block and put the nid in to limit those "offer" nodes to only the node being viewed. However, I would like to do two things.

1) Limit the block to only be viewable to administrators and the node author themselves, other users should not be able to see the other offers.

2) Make it so going to /node/{nid} that is an offer content type is hidden from view so users can't just bypass the block and hit the nid of the offer node.

Any help on how to implement this? I am trying to do it with no added modules.

EDIT: The access to the block should be as follows:

Administrators: Should see all "offer" nodes in the block regardless of who they are from.

Listing Author: Should see all "offer" nodes in block.

Offer Author: Should only see "offer" nodes they have submitted to "listing" nodes. They shouldn't see any other "offer" nodes from any other user.

In views, add a relationship on "Content: Author", then add a filter "User: Current" and configure it so it uses the relationship you added and has "Is the logged in user" = "Yes".
Install the Rabbit Hole module and its node sub module and configure it (on the edit page for the offer content type) to give a 404 error for those nodes. Then configure the rabbit hole permissions so that admins can bypass rabbit hole if you need that ability. I would recommend adding this module as opposed to writing some custom code to do this.


Drupal add google analytics event tracking query strings to url I have Drupal 7 site for sending the newsletter. I am using simplenews module for sending newsletter. I want to add google analytics tracking query strings to all links in the newsletter so that it is tracked in my google analytics account. How can I achieve this?.

Create your links here and add them in your newsletter node content and/or mail template.


How does Drupal check write permissions for a folder? How does Drupal check the write permissions on a folder in Linux?

I am using php5-fpm and the web server is working as the user that owns the Drupal directory and I expect that even with a 700 the directories should be readable and writeable by the PHP process and there should be errors only when nginx itself needs access to files or folders.

Does Drupal just test the file permissions for the other user, or does it attempt to read and write as the PHP process itself? It appears to work only when o+rwx is set on the sites/default/files folder but r-x alone should work.

Can anyone point me to the exact routines that make that check?

You're probably looking for the file_prepare_directory() function:

  Checks that the directory exists and is writable.


Can't translate the messages of the flag module I'm using Drupal 7.20 with Commerce. I installed the following modules:
 - internationalization module
 - translation helper
 - flag module

I have customized the text for my flag links to be 'add to my favorites' and 'remove from favorites'. I want to translate them, but they don't appear in the translate interface.

Does anyone have a clue?

See this from the Flag module issue queue

  Each string you enter as an administrator is available in the Translate Interface section, but you first have to switch to a different language, then view a page that contains that message (such as trying to flag/unflag a piece of content). Afterwards, the string will be flagged as needing a translation and you can find it in the Translate Interface section.


How to write a template_preprocess_node hook to get the Image Style for an Image field? I have an image field on Basic Page content type with a View Mode where format = Image and Image Style = Large.

How can I write a template_preprocess_node hook to get the Image style that is based on the View mode?

Here is what I was thinking but got stuck and cannot figure out what to call.

function mymodule_preprocess_node(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $node = $variables['elements']['#node'];
  if($variables['view_mode'] = 'default' && $node->hasField('field_image')){
    $fieldImage = $node->get('field_image');
    /** stuck here as I cannot find method to get the Image Style **/
    //goal
    $image_style = $fieldImage->getImageStyle() // not sure what method this would be
    $image_path = $fieldImage->entity->getFileUri();
    $image_url = ImageStyle::load($image_style)->buildUrl($image_path);
    $variables['content'][0]['image_url'] = $image_url; // this is the goal
  }

}

twig template

It is part of the render array generated by the formatter: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldFormatter%21ImageFormatter.php/function/ImageFormatter%3A%3AviewElements/8.2.x

You can see that it is set on #image_style, so in node preprocess, that should be $variables['content'][field_imge][0]['#image_style'].

Depending on what you want to do, you could also write your own formatter or you could preprocess/alter the image_formatter template.


Meta tag module not visible under individual node I have installed Drupal 8 on my local machine with Metatags module for SEO.

The global settings are available to edit under Configurations → Search and Metadata → Metatag but the Metatag tab is not visible when I edit individual articles.  I want to change the meta title and description for each article.

When the metatag module is installed, you can create a metatag field in drupal just like creating a textfield, and can be reused in other content types.


How to Lazyload any src object in node body Currently using Blazy on Drupal 8. What I am trying to do is figure out how to lazyload any image, iframe, mp4 found in the body.

I think I have found a good solution as seen here:
https://www.drupal.org/project/blazy/issues/2912992

But how do I implement it. I am stuck at step 4.

I think he means to add this to mytheme.theme

/**
 * Implements hook_page_attachments_alter()
 */

function MYTHEME_page_attachments_alter(array &$attachments) {
    $attachments['#attached']['library'][] = 'blazy/load';
}


Strange behavior: Extra css classes are NOT merged with the 'Search Block' form tag classes but with those of BLOCK wrapping the form tag i'm experiencing such 'strange' behavior with Drupal (v8.7.10) when trying to add css classes to the default Search Form form tag using MYTHEME_form_FROM_ID_alter hook, the classes are NOT merged with the form tag classes as expected but with those of the BLOCK wrapping the form tag itself.

this is my code:

function MYTHEME_form_search_block_form_alter(&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#attributes']['class'] = 'form-inline';
}

and this is the rendered output in question

  <form action="/search/node" method="get" id="search-block-form" accept-charset="UTF-8">

      Search
      <input title="Enter the terms you wish to search for." placeholder="Search .." data-drupal-selector="edit-keys" type="search" id="edit-keys" name="keys" value="" size="15" maxlength="128" class="form-search form-control rounded-0">

      <input data-drupal-selector="edit-submit" type="submit" id="edit-submit" value="Search" class="button js-form-submit form-submit btn btn-primary rounded-0">

  </form>

any thoughts ?

It's fairly straight forward PHP mistake $form['#attributes']['class'] is an array of classes

And by doing $form['#attributes']['class'] = 'form-inline'; you're saying forget whatever $form['#attributes']['class'] was before its now a string that contains 'form-inline'. So you're changing the variable from an array to a string.

Long story short you should be adding your class to the existing array with:

 $form['#attributes']['class'][] = 'form-inline';

Note the [] after ['class']

That explains why you have no classes coming out on your form. The issue about the classes on your outer div isn't related to this code and you must have something else going on too. Perhaps a block alter hook


Workflow for redesigning a drupal site I'm relatively new drupal user, that always get nervous when taking a site live.

I need to redesign our current website as well as add some modules and node types etc.

What i plan to do is just grab the drupal files and the database, change them up locally and then replace the files and database on the live site.

Is this the best method for doing this?

Looks like a relatively simple task, but i just don't wanna be spending 3 days of headache again working out how to take a site live.

If you can guarantee that no content will change on the live site while you do the work then that is fine.

This doesn't just include content creation, but also things like users signing up, users commenting or submitting webforms (unless you don't need to keep the webform submissions on your site), users flagging things, or rating things or subscribing to things.

Basically anything an user, admin or not, can do that might change the database in some way.
Or even things that change without user action, like time based events (this is probably less likely).

If you can't be sure of that and you can't afford to lose any data there are other options.
Whether these options are suitable for you also depends on your specific project and what you are actually changing.

You can try keeping a record of any database changes you make and make them again to the live site when deploying your changes.  This method is very error prone and can cause you grief if you are not extremely careful. - Things like views & contexts (and many other things) can be exported and imported, making certain tasks very easy to deploy in this manner. Other things require manually reproducing all the changes. There are other import/export type modules around for things like content types, users, taxonomy, menus etc. that are useful to varying degrees depending on your requirements.
You can try using modules like features or configuration management, for deploying your database config.

In the end, an exact answer cannot be given for a question like this as it depends on your requirements.


Same as shipping checkbox in admin is not showing While creating an order from Drupal admin section, "Same as shipping" checkbox is not showing, but for normal checkout it is showing.

How do I show the checkbox in the administrative page?

I'm guessing this checkbox is meant to copy the address from the billing address to the shipping address?

As Ryan pointed out on the frontend this will require ajax as the shipping and billing profiles could be on different steps, however on the backend they are both on the same page so all that is required is some javascript.

For example...

Add the checkbox and custom javascript to the page in a hook_form_alter:

/**
 * Implements hook_form_FORM_ID_alter() for commerce_order_ui_order_form.
 */
function MY_MODULE_form_commerce_order_ui_order_form_alter(&$form, &$form_state, $form_id) {

  // Add the checkbox
  $form['commerce_customer_billing'][LANGUAGE_NONE]['profiles'][0]['copy_from_shipping'] = [
    '#type' => 'checkbox',
    '#title' => t('Copy address from shipping'),
    '#attributes' => ['class' => ['copy-address-from-shipping']],
  ];

  // Attach our custom js
  $form['#attached']['js'][] = drupal_get_path('MY_MODULE', 'taronga') . '/js/copy-address-from-shipping.js';

}

And then for the javascript:

(function($) {

    /**
     * The Drupal behaviors to copy address from shipping to billing on admin order edit page.
     */
    Drupal.behaviors.copyShippingAddress = {
        attach: function(context) {

            // Only bind our click event handler once
            $('.copy-address-from-shipping').once(function(){

                // Bind the click event
                $('.copy-address-from-shipping').click(function () {

                    var $shipping = $('#edit-commerce-customer-shipping-und-profiles-0');
                    var $billing = $('#edit-commerce-customer-billing-und-profiles-0');

                    if($(this).is(':checked')) { // Copy values from shipping

                        // Loop over inputs & select in shipping fieldset
                        $shipping.find('input, select').each(function () {
                            // Skip any inputs without a name attribute (e.g. chosen)
                            if($(this).is('[name]')) {
                                // Get the name of this field and convert it to the billing name
                                var billing_name = $(this).attr('name').replace('shipping', 'billing');
                                var $billing_field = $billing.find('[name="' + billing_name + '"]');
                                // Make sure the billing field exists
                                if($billing_field.length) {
                                    // Replace the value
                                    $billing_field.val($(this).val());
                                }
                            }
                        });

                    }
                    else { // Clear values

                        $billing.find('input, select').each(function(){
                            $(this).val('');
                        });

                    }
                });

            });

        }
    };

})(jQuery);


Alternate ways to call a function inside a .module file of a module I have installed quickdraw module and it needs some additional functions to be executed using drush commands. For that, I used the following drush commands:

drush php-eval "quickdraw_xx_xx_additionalfunction();"

But it returns an error

Fatal error: Call to undefined function quickdraw_facet_navmenu_materialize() in /usr/local/Cellar/drush/6.3.0/libexec/commands/core/core.drush.inc(1100) : eval()'d code on line 1
Drush command terminated abnormally due to an unrecoverable error.                                                                [error]
Error: Call to undefined function quickdraw_facet_navmenu_materialize() in
/usr/local/Cellar/drush/6.3.0/libexec/commands/core/core.drush.inc(1100) : eval()'d code, line 1

As discussed in this post. I have tried module_load_include(), which returns the same Fatal error.

Also tried drush eval 'quickdraw_xx_xx_cron();' - Didn't work!!!

Is there any alternate ways to execute the function or how can I resolve the issue. Any ideas??

NOTE: The additional function is defined in quickdraw_xx_xx.module file, I assume it is not being recognized.

You should make a drush command. It's not very hard:

function quickdraw_xx_xx_drush_command() {
  $items = array();
  // Name of the drush command.
  $items['quickdraw_xx_xx_additionalfunction'] = array(
    'description' => 'A quickdraw additional function.',
    'callback' => 'quickdraw_xx_xx_additionalfunction',
  );
  return $items;
}

This way, Drupal will bootstrap and everything you need will be there, including dependencies to other files.


Prevent users from including their username in their password I'm aware of the Password Policy module that has a number of features for forcing the user to constrain their passwords to certain criteria, but this module does not contain an option to prevent users from including arbitrary strings in their passwords (such as their own username).

Ex. User bob receives a validation error if they try to change their password to anything that includes the string "bob", such as "889bobisthebest99".

Does anyone know how to code custom functionality to achieve this result for Drupal 7.5 or a module that already does what I'm looking for?

I found that the Password Policy module actually does have an option to prevent the user from including their username in their password. The broader issue about how to restrict arbitrary strings from a user's password still stands though.


How to make a table sortable by CCK field An odd question: I have a custom column added to the default admin/content page that shows the value of a CCK field "field_foo". I'm trying to sort the table by this field. (I can't use Views for this unfortunately). This is what I have for the header:

$header = array(
  'title' => array('data' => t('Title'), 'field' => 'n.title'),
  'foo' => array('data' => t('Foo'), 'field' => 'n.field_foo', 'sort' => 'desc');
)
$query = db_select('node', 'n')
   ->extend('PagerDefault')
   ->extend('TableSort');
node_build_filter_query($query);

I also tried the name of the field as declared in the $rows, ie...

'foo' => array('data' => t('Foo'), 'field' => 'n.foo', 'sort' => 'desc');

This results in a link at the top of the Foo column head, but when I try to click on the link to sort Asc or Desc it doesn't really work and the Foo values aren't ordered in the requested order. If anyone has any suggestions I'd really appreciate it.
Thanks!

Try out Tablesorter moulde and add js function to your js file

$("Table").tablesorter();


How do I allow users to see other users' views based on taxonomy fields I have a bunch of nodes called 'article' with a taxonomy field attached called 'publication'

I have also added the 'publication' field to the user so he/she can choose which publications they want to see - they select these and then there's a view where they can only see their own selection, based on a contextual filter.

Question is, how can I let users select the option to see other users' chosen publication view. Can this be added to their setting page, along with the actual publications - /user/1/edit?destination=admin/people

It is possible with views relationship and contextual filters. You can add a relationship that references users and publications and then add user id to filter the publication based on the result


View mode template for user-profile.tpl.php? I can set up a view mode for the user profile, but I don't know how to create a template targeting it. user-profile.tpl.php is the template used, but I can't figure out how to make a view-mode targeted version of it.

Any suggestion?

You already figured out how to create an additional view mode for the user entity:

/**
 * Implements hook entity info alter
 * Adds additional view mode for user entity
 */
function MYCUSTOMMODULE_entity_info_alter(&$entity_info) {
  $entity_info['user']['view modes']['teaser'] = array(
      'label' => t('Teaser'),
      'custom settings' => TRUE,
  );
}

Now you can define theme suggestions for that view mode using HOOK_preprocess_user_profile:

/**
* Implements HOOK_preprocess_user_profile()
* Adds theme suggestions for the user view mode teaser
*/
function MYCUSTOMMODULE_preprocess_user_profile(&$vars) {
  if ($vars['elements']['#view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'user_profile__teaser';
  }

After clearing the caches Drupal will search in the theme folder for a file called user-profile--teaser.tpl.php, which could look like this example*:

  <?php print render($user_profile['field_last_name'][0]); ?>

<?php print render($user_profile['field_user_picture'][0]); ?>

    <?php print render($user_profile['field_biography']); ?>
    <?php print render($user_profile['field_birthdate']); ?>
    <?php print render($user_profile['field_nationality']); ?>

(* actual code will depend on the fields you defined for the user profile)


Button on user profile page to send email I think this is pretty simple, but I don't know what's the best way to achieve this.

This is what I need:

Add a button on each user profile page. When another user clicks on the button, it opens a form (in a popup window would be great) to write the message. The email should be sent to the user of the profile page we are seeing.

If it's not possible to add a form, I just need a "mailto:useremail" so when i click the button opens the outlook our gmail, wtv.

How can I do this? Is there a simple way?

Thank you!

To get what you want, you need to modify the template user, to do this you need to follow the next steps:

Find the file called user-profile.tpl it is in the module user modules\user (NOT inside sites/all/modules).
Once you found it, open it, and you should see at the end of the file something like this:

  print render($user_profile);

Now copy and paste this line of code inside php tags:

  $usr = user_load(arg(1));

  echo 'mail.'?Subject=textyouwant"
  target="_blank">Send Mail';

That should work !


How to get the path to the translated node? I've set up a multilanguage site in Drupal 7. In a template I need to add a link to a specific content node. This node has translations and path aliases like so:

node/42 = pathalias_de (german version)
node/43 = pathalias_en (english version)

In the template I'd like to call url() to get the link to the aliased version of the content node in the current language.

On the german page it should link to /de/pathalias_de on the english page to /en/pathalias_en

I've tried several variations, like calling the nid, calling the alias, passing the current language object to url().

Is this something url() should be able to do or do I need a different function? Thanks!

After looking at the source of the "Content translation" module I've come up with this solution:

    global $language;
    $translations = translation_path_get_translations("node/42");
    /*
    Returns the paths of all translations of a node, based on its Drupal path:
    array(2) {
        ["de"]=>string(7) "node/42"
        ["en"]=>string(7) "node/43"
    }
    */
    print l(t('Link Title'), $translations[$language->language]); //l() will return the alias to node/42

This will output the link to the correct node alias. Works and isn't overly complicated - still wonder if there's a function that already does this.


VBO hook_entity_update I would like to perform the following mass action via VBO: send a mail to author of a node.
This mail is configured and sent in a hook_entity_update function.
The beginning of the function is the following :
if (is_null($entity)) return;
if (!isset($entity)) return;

$nid = \Drupal::routeMatch()->getRawParameter('node');
if ($nid) {
 $type = $node->bundle();
 if ($type != 'membre') {
   return;
 }
}
else if ($nid == null) {
 return;
}

...

$mailManager->mail($module, $key, $to_trsf, $langcode, $params, NULL, $send);

test 1: If I update manually the node, the mail is sent.
test 2: If I update the node through a VBO, the mail is not sent because the nid is null, so the "return" statement is done.
Is there a possibility to retrieve the nid of a node when the hook is fired throught a VBO action?

Your problem is that you are using routeMatch() to get the node id, which won't be returned when using VBO.
You said you're using hook_entity_update():
function hook_ENTITY_TYPE_update(Drupal\Core\Entity\EntityInterface $entity)

This code assumes that the entity you are running hook_entity_update() for is the node entity.
Since the hook provides the $entity object, you can get the node id like this:
$nid = $entity->id()


Issue with Mac OS and AJAX in Forms I'm working on a custom field type module for a Drupal 7 project and tried to make use of Drupal's AJAX framework in forms.
For some reason not even the simplest AJAX requests work on my machine (MacBook with Mac OS Lion) whereas the same code works fine on the Linux machines of my colleagues. When I click the button that's supposed to trigger the request I also get that little blue spinner and the "Please wait..." message but nothing happens after it disappears. In Firebug I can see that it posts to /system/ajax and also sends a "200 OK" header but an empty response.

The code was something similar to this:

$element['ajax-btn'] = array(
  '#value' => t('AJAX Test'),
  '#type'  => 'button',
  '#ajax'  => array(
    'callback' => 'test_callback',
    'wrapper'  => 'ajax-test',
    'method'   => 'replace',
  )
);

$element['new-ingredients'] = array(
  '#markup' => '
test
',
);

function test_callback($form, $form_state) {
  return array('#markup' => 'response');
}

Any ideas?

I have a colleague with a similar problem on his OS Lion machine, but not a problem on our Snow Leopard machines. I stumbled across a solution that worked for me and may work for you. I can't see this portion of your code, but the URL that you are requesting is most likely an absolute path:

http://yourwebsite.com/someFolder/somePage.html

but what you want is a relative path:

someFolder/somePage.html

AJAX requires that all requests come from the same website. This is a principle of Same Origin Policy and is done for security reasons.

If you are requesting an absolute path to a link on the same website (as you probably are doing), the system should look and see that the request is from the same domain, in which case does not break Same Origin Policy. However, the person in charge of coding Lion's AJAX Same Origin Policy has a problem with their code that does not realize this is the case, causing the browser to think you are trying to run a Cross Domain Script. Hopefully they will realize this soon and fix it in the next update.


Attaching libraries to specific controllers I want to include the google charts js library to a specific (or set of) controller(s).  In my library file, gcharts.libraries.yml, I have the following:

google_charts:
  remote: https://developers.google.com/chart
  version: current
  license:
    name: apache 2.0
    url: http://www.apache.org/licenses/LICENSE-2.0
    gpl-compatible: true
  js:
    https://www.gstatic.com/charts/loader.js: { type: external, minified: true }
  dependencies:
    - core/jquery

Which, unless I copied something incorrectly, should be correct.

Question 1: is the dependencies tag allowed here?  The documentation isn't expressly clear on that.

My controller (GoogleChartsController) correctly instantiates and looks like:

<?php
array(
  '#theme' => 'custom_theme',
  '#attached' =>
    array(
      'library' =>
        array('company/google_charts')
    ),
  // For testing purposes
  '#cache' => array(
    'max_age' => 0,
  )
);
?>

However, when I look through the source I don't see the library that I told my controller has a dependency for.  My library never loads.

Question 2: Do I have have to use the hook_page_attachement or the hook_preprocess_page hooks?  If so, how do I limit it to use just my set of controllers I want (I don't need or want this loading on every page)?  Can I get the path, check to see that it is what I want and then add it conditionally, like so?  Or is there some other way?

My custom-theme.html.twig looks like:

Are we here?

The documentation isn't crystal clear as to when and where to include inline js.  From the google charts api, I'm to include something like:

Now, my intuition is that I can actually abstract each of the charts I want into their own "library" and add the dependency, because of the way I designed things, this will be fairly trivial.  But I'm not certain if this is the best way to do it.  But I've read that you can dump inline js into twig files; but I'm not 100% certain this applies here...

Question 3: Is adding the js into twig best practices or is libraries the way to go?  Assuming libraries, can I include several libraries into one library file and just include the one(s) that I want/need?  So I would have one library for customized_charts.libraries.yml and in there there would be declarations for pie_chart, bar_chart, etc.  And then I would load module/bar_chart when I wanted to display bar charts, etc?

You are not indenting parts of the yml file that you need to indent.

Look at this example from token.libraries.yml at /modules/contrib/token/token.libraries.yml:

jquery.treeTable:
  remote: 'http://plugins.jquery.com/treetable/'
  version: 3.2.0
  license:
    name: MIT
    url: https://github.com/ludo/jquery-treetable/blob/3.2.0/MIT-LICENSE.txt
    gpl-compatible: true
  js:
    js/jquery.treetable.js: {}
  css:
    component:
      css/jquery.treetable.css: {}
      css/token.treetable.theme.css: {}
  dependencies:
    - core/jquery

Also, pay attention to colons, since they are part of YAML syntax.

use:

remote: 'remote: https://developers.google.com/chart'

not

remote: remote: https://developers.google.com/chart


Creating, modifying and removing folders and folder structures in Drupal 7 I know that it is possible to delete files from the File Browser view, but is there a way to create, modify and remove folders in Drupal 7?

If you're using 'file browser' than you probably have the IMCE file manager enabled. What you want to do then is enable the extension module IMCE_mkdir to create directories and subdirectories (within folders your web user has permission to access):

  IMCE Mkdir allows users to create and delete sub-directories under
  directories assigned by IMCE.


Display taxonomy term from id I want to display taxonomy term from it's id. I have the following code that get's me id of this term but I don't how to convert this id into term name to display it.

function menu_custom_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  dpm($items);
  $element = array();
  foreach ($items as $delta => $item) {
    $element[$delta] =  l(check_plain($item['target_id']));
    }
  return array(
    0 => array(
      '#markup' => theme('item_list', array('items' => $item)),
    ),
  );
  return theme('item_list', array());
}

To get the taxonomy term name from ID.

function menu_custom_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  dpm($items);
  $element = array();
  foreach ($items as $delta => $item) {
    $taxonomy = taxonomy_term_load($item['target_id']);
    $element[$delta] = $taxonomy->name;
  }
  return array(
    0 => array(
      '#markup' => theme('item_list', array('items' => $item)),
    ),
  );
  return theme('item_list', array());
}

$taxonomy->name  will give you name of taxonomy term.

I hope this will help.
Thanks


Saving additional node fields programmatically I have the following content type called stars with the following fields:

Title
Body
Distance (this is an added text field)

Here's what I have to save the node, but how do I add the distance field?

$node = new stdClass();
$node->type = "stars";
$node->status = 0;
$node->uid = $user->uid;
$node->title = 'This is the title';
$node->sticky = 0;
$node->language = 'en';

// Let's add standard body field
$node->body['und'][0]['format'] = 'filtered_html';
$node->body['und'][0]['value'] = 'Body info';

$node->revision = 0;

node_save($node);

You'd need to set the value for the Distance field just like you have already for the Body field. Lets assume that the name of your Distance field is field_star_distance. (To find the name of your field, check if you have the Field UI module enabled and head over to the Manage fields page for your content type)

// Your code
$node->{'field_star_distance'}[LANGUAGE_NONE][0]['value'] = 100;
// Your code

The general skeleton for setting the value for a field of an entity is:

$entity->{$field_name}[$language][$delta][$field_property] = $value

To understand the different field properties for a given field (like value in our example here), you need to look up its schema (see hook_field_schema() and see text_field_schema())

To see if $delta can be  > 1, you need to check the cardinality of the field instance.


Can not remove the Devel module While doing an upgrade to the Devel-module something went terrible wrong. Decided to remove the module through the "Uninstall"-tab. The module is however not listed there, while it's marked as active under the "Install"-tab. Removing the module manually (deleting the files) causes errors so I cannot do it this way either.

Ironically I need this module to be able to re-install other modules which are outdated. Anyone got any feedback how to cleanly remove the Devel-module without the Uninstall tab?

I do not have Drush for D8, need another way as I got D6 and D7 instances installed on the same environment aswell.

Can't you use the "normal" upgrade scenario for FTP servers?
(I usume this still works btw. haven't tested it on d8 yet)
 - Download your intended version of devel from d.o.
 - Unpack the download
 - Upload to the server in place of the old devel module (so same paths,permissions,etc)
 - Run the "update.php" script to update the Database.(you need to be admin to do this, or change your settings.php to temp. allow anyone to do it).
 - Devel should be updated now.

according to the docs this should work see d.o. D8 Update a module


User registration question I have built a new form from scratch. I was examining a code example displayed on here earlier, but I am not sure if I fully understand the syntax.

So far I have the following code:

$items['user/register'] = array(
    'title' => 'a large ferrret',
    'page callback' => 'redirect_custom_reg_form',
    'page arguments' => array('user_register_form'),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
);

I looked at a similar example in my book, and it looks like the page callback is used to build the form. I have  used a similar example which uses the page callback.

Could someone please explain this function to me. I understand that this is a menu alter function. this should check to see if the user/register page is set

function redirect_custom_reg_form__menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_user_register_form');
  }
}

function mymodule_user_register_form($form) {
 $fields['legal_agreement'] = array (
    '#type' => 'fieldset',
    '#title' => t('Legal Agreement')
 );

 $fields['legal_agreement']['PL'] = array (
    '#type' => 'checkbox',
    '#title' => t('Legal Agreement')
 );

 $fields['legal_agreement']['decision'] = array(
    '#type' => 'radios',
    '#description' => t('By registering at %site-name, I certify that I am over 18 and have read and accepted the terms and conditions of the pravacy policy', array('%site-name' => variable_get('site_name', 'drupal'))),
    '#default_value' => 0,
    '#options' => array(t('I disagree'), t('I agree'))
 );

 return $fields;
}

I then made the assumption that I need a page callback method and this callback builds my page. It does not seem to be rebuilding anything.

In Drupal 6, you implement hook_user() to add the extra fields to the registration form implemented by Drupal.

function mymodule_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'register' && $category == 'account') {
    $form['legal_agreement'] = array (
      '#type' => 'fieldset',
      '#title' => t('Legal Agreement')
    );

    $form['legal_agreement']['decision'] = array(
      '#type' => 'radios',
      '#description' => t('By registering at %site-name, I certify that I am over 18, and I have read and accepted the terms and conditions of the privacy policy.', array('%site-name' => variable_get('site_name', 'drupal'))),
      '#default_value' => 0,
      '#options' => array(t('I disagree'), t('I agree'))
    );

    return $form;
  }

  if ($type == 'validate' && $category == 'account') {
    // If the user needs to always agree with the conditions, this is the place to show an error message.
  }
}

If you want to completely replace the registration form used by Drupal with your own, then you need to implement hook_menu_alter().

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_user_register_form');
  }
}

function mymodule_user_register_form() {
  $form = array();

  // Add the form fields for the registration form.

  return $form;
}

In Drupal 7, as you are just adding form fields to an existing form, you need to implement hook_form_FORM_ID_alter() using code similar to the following one:

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  $form['legal_agreement'] = array (
    '#type' => 'fieldset',
    '#title' => t('Legal Agreement')
  );

  $form['legal_agreement']['decision'] = array(
    '#type' => 'radios',
    '#description' => t('By registering at %site-name, I certify that I am over 18, and I have read and accepted the terms and conditions of the privacy policy.', array('%site-name' => variable_get('site_name', 'drupal'))),
    '#default_value' => 0,
    '#options' => array(t('I disagree'), t('I agree'))
  );
}

The variable that contains the form definition is $form, and the hook doesn't need to return any value, as the form that needs to be modified is passed by reference.

This is very similar to the example code reported in the documentation page for hook_form_FORM_ID_alter(), which uses the following code:

  // 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,
  );

If you want to completely replace the registration form used by Drupal with your own, then you need to implement hook_menu_alter().

function mymodule_menu_alter(&$items) {
  if (isset($items['user/register'])) {
    $items['user/register']['page arguments'] = array('mymodule_user_register_form');
  }
}

function mymodule_user_register_form($form, &$form_state) {
  // Add the form fields for the registration form; the variable containing it is $form.

  return $form;
}

To notice that in the Drupal code, the form builder receives $form as argument. The common error when porting code from Drupal 6 to Drupal 7 is to still have $form = array() at the beginning of the form builder function.
In both the cases, when you implement hook_menu_alter(), your module needs to handle all the registration process.


Can AJAX be enabled for a form element inside a tableselect row? Firstly, a working select element with an AJAX callback:

public function buildForm(array $form, FormStateInterface $form_state) {

  $form['select'] = [
    '#type' => 'select',
    '#options' => [
      0 => 'ZERO',
      1 => 'ONE',
      2 => 'TWO',
    ],
    '#ajax' => [
      'callback' => [$this, 'ajaxSelectChanged'],
      'event' => 'change',
    ],
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Submit'),
  ];

  return $form;
}

public function ajaxSelectChanged(array &$form, FormStateInterface $form_state) {
  $selection = $form_state->getValue('select');
  // Do something with the selection.
}

Now I want to put the select element inside a tableselect element...

This comment shows how form elements may be added inside the rows of a tableselect (which is also a form element).

Here's my attempt:

public function buildForm(array $form, FormStateInterface $form_state) {

  // Build the sortable table header.
  $select_options = [
    0 => 'ZERO',
    1 => 'ONE',
    2 => 'TWO',
  ];

  $form['table'] = [
    '#type' => 'tableselect',
    '#header' => [
      'name' => $this->t('Name'),
      'select' => $this->t('Select'),
    ],
    '#options' => [
      'alice' => [
        'name' => $this->t('Alice'),
        'select' => [
          'data' => [
            '#type' => 'select',
            '#options' => $select_options,
            '#ajax' => [
              'callback' => [$this, 'ajaxSelectChanged'],
              'event' => 'change',
            ],
          ],
        ],
      ],
      'bob' => [
        'name' => $this->t('Bob'),
        'select' => [
          'data' => [
            '#type' => 'select',
            '#options' => $select_options,
            '#ajax' => [
              'callback' => [$this, 'ajaxSelectChanged'],
              'event' => 'change',
            ],
          ],
        ],
      ],
    ],
    '#empty' => $this->t('There is nothing to see here.'),
  ];

  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Submit'),
  ];

  return $form;
}

public function ajaxSelectChanged(array &$form, FormStateInterface $form_state) {
  $selection = $form_state->getValues();
  // Do something with the selection.
}

It works, except for the AJAX callback, which never runs.

Am I doing something wrong?
Is there a way to let form elements inside a table trigger AJAX callbacks when they are changed?

Here is my solution:

Add placeholders (like a simple string, or an empty array) to the table row, where the select lists should go.
Add select lists below the table, and check that they have fully functional AJAX callbacks.
Register a #pre_render function on the form which moves the select lists into the table.

In the buildForm function:

$form['#pre_render'] = [[$this, 'preRender']];

And then in the form class:

public static function preRender(array $form) {
  foreach ($form['table']['#options'] as $delta => &$row) {
    $row['select_lists']['data'] = $form['select_lists'][$delta];
    unset($form['select_lists'][$delta]);
  }
  return $form;
}

I also tried hook_form_alter, but it runs too early, and messes up the AJAX. Apparently, a pre_render function runs after the AJAX stuff has been set up by Drupal, and then we can move the element anywhere on the page without affecting the AJAX functionality.


sharing contents between two sites i setup two sites site 1 and site 2 by using drupal multi site functionality.site1 i consider as the master site and site 2 consider as the slave. some contents in both sites have similar content.when updation made in site 1 its reflect in site 2(only similar contents) for this i try to share the DB. while i try to execute following steps i get following error while i see the site pages

"You are not authorized to access this page. "

i follow this steps:

1.create a db prefix like this $db_prefix = "master_" in site 1 and $db_prefix = "slave_" in site 2.

i set the cookie $cookie_domain = 'site2'; in site 1.
Then i add prefix like way in site 1
$db_prefix = array(
node' => 'master_',
'node_access' => 'master_',
'node_counter' => 'master_',
'node_type' => 'master-',
);

above thing i did site2 also instead of using 'master_' i use 'slave_'
is there any thing missed out in my con fig.any one guide me do this.
thanks......

Multisite isn't really meant for situations where you want to share content.  This is what Domain Access module does.  Essentially, it allows you to have different behaviors for a site with subdomains, but running from the same database.  This is different from multisite, which uses a different database for each site.  I would try starting with that before you go down the road of multisite.


How to find where Drush is installed to include a file in my module? I have installed the module Drush Help to see the module's Drush commands in the module help page. But when I go to see the help page of a module that use in the drush commands drush constants like DRUSH_BOOTSTRAP_DRUPAL_FULL I got a Notice because this constant is only defined in drush, and not for Drupal.

You can see this problem if you install the Drush Help and the Node Revision Delete modules (the Drupal 7 version): Visit admin/help/node_revision_delete and you will see this notice message.

  Notice: Use of undefined constant DRUSH_BOOTSTRAP_DRUPAL_FULL - assumed 'DRUSH_BOOTSTRAP_DRUPAL_FULL' in node_revision_delete_drush_command()

So the problem is that Drupal can't reach the file includes/bootstrap.inc where the constant is defined. I can include the file but the problem is that I need to know where Drush is installed.

How to find where Drush is installed to include a file in my module?

A temporary solution that I found is define the same constants in the drush_help.module file.

/**
 * Constants defined by drush in the includes/bootstrap.inc file.
 *
 * To see why we need to do this please read:
 * https://drupal.stackexchange.com/q/250786/28275
 */
define('DRUSH_BOOTSTRAP_NONE', -1);
define('DRUSH_BOOTSTRAP_MAX', -2);
define('DRUSH_BOOTSTRAP_DRUSH', 0);
define('DRUSH_BOOTSTRAP_DRUPAL_ROOT', 1);
define('DRUSH_BOOTSTRAP_DRUPAL_SITE', 2);
define('DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION', 3);
define('DRUSH_BOOTSTRAP_DRUPAL_DATABASE', 4);
define('DRUSH_BOOTSTRAP_DRUPAL_FULL', 5);
define('DRUSH_BOOTSTRAP_DRUPAL_LOGIN', 6);


Is it possible to use jQuery on filters (B.E.F.) in a view? I am trying to add some special behaviours with jQuery to input type checkboxes in a view (using better exposed filters).
Ideally i need to make inactive all checkboxes when one of them is clicked. I`ve written a script but it did not do anything.
So i added a simple another code via drupal_add_js in template.php just to see whether it would be working:

jQuery('input#myid').click(function(){
alert("clicked");
});

it didn`t work and i am asking is it possible to use jQuery on checkboxes in a view?
Thanks in advance!

The right way to write jQuery in drupal 7:

(function ($) {
  Drupal.behaviors.functionname = {
    attach: function(context, settings) {
      // some code, with $
    }
  };
})(jQuery);


How can I see the clean query of a view? I created a test view. It displays data of a content type 'Anagrafiche (name for internal use: contatti)'. The view has the following fields (sorry for the interface language):

Contenuto: Immagine (Img)    it's an image field
Contenuto: Nome (Name)       it's a text field
Contenuto: Cognome (Surname) it's a text field

I used the proposed code for the following question, to get a 'clean' query: link

But the output was not what was expected:

SELECT
  node.nid AS nid,
  node.created AS node_created,
  node.changed AS node_changed,
  users_node.name AS users_node_name,
  users_node.uid AS users_node_uid,
  'node' AS field_data_field_immagine_node_entity_type,
  'node' AS field_data_field_nome_node_entity_type,
  'node' AS field_data_field_cognome_node_entity_type
FROM  node AS node
LEFT JOIN users AS users_node
  ON node.uid = users_node.uid
LEFT JOIN field_data_field_cognome AS field_data_field_cognome
  ON node.nid = field_data_field_cognome.entity_id
  AND (field_data_field_cognome.entity_type = 'node'
  AND field_data_field_cognome.deleted = 0)
WHERE (( (node.status = 1)
  AND (node.type IN  ('contatti')) ))
ORDER BY
  field_data_field_cognome.field_cognome_value ASC
LIMIT 20 OFFSET 0

I do not have very clear how the correct output should be, but by looking at the query, I gather that this piece is not correct

  'node' AS field_data_field_immagine_node_entity_type,
  'node' AS field_data_field_nome_node_entity_type,
  'node' AS field_data_field_cognome_node_entity_type

I also tried alternatives like the 'Devel' module and different types of hooks, but I never got what I wanted

@mikeytown2 I ran the query inside phpmyadmin
this is the result:

but the last three columns should not be node | node | node,
but something like thatimg | myName | mySurname

I gather that this piece is not correct

It’s absolutely correct - Views is just using the query results to pass through some meta data about the operation.

In this case your view joins three different fields, and the types of entity that the fields are related to are nodes. Views is just keeping track of the that fact for each field, so it can use a generic processor for the results.

If you don’t need to use those fields from the query, you can safely ignore them.


Set the value of a date field I am trying to set the value of a user field which is a date. If i check the database, the date is in this format:

2016-06-30T07:52:51

I have the user ID and a new Unix timestamp value that I want to overwrite the existing value with.

The following shows no error messages but does not change the date

$account = \Drupal\user\Entity\User::load($email_result); // pass your uid
$account->set('field_expiry_date',strval(date('c',($new_expiry))));

//$field = $account->field_expiry_date;
//$field->set(date('c',($new_expiry)));
//$field = $account->get('field_expiry_date');
//$field->setValue(date('c',($new_expiry)));

What is wrong with this code?

The problem is more than likely that the 'c' format includes the timezone, which is not (currently) included in storage.

The storage format for fields that have both date and time is defined by the datetime module as DateTimeItemInterface::DATETIME_STORAGE_FORMAT, which is 'Y-m-d\TH:i:s'.

Something like this will work:

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\user\Entity\User;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

$date = DrupalDateTime::createFromTimestamp($new_expiry, 'UTC');
$account = User::load($email_result);
$account->field_expiry_date->value = $date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, [
  'timezone' => 'UTC',
]);
$account->save();

Just remember that date+time values in storage are implicitly UTC, so if you are setting the value manually, you need to ensure that what you are saving represents what you want, but converted to UTC.


Pop Up login Forms for LoginToBoggan I am using LoginToBoggan Module to unable anonymous user to register using self created password.

Now in some other page I want a popup login form. I have tried using other module like modal forms, but these seems not to work.

Please show me the right way to do this.

Thank you

Try Popup forms or Colorbox modules. These provide this functionality.


Trying to get COUNT(*) from custom content type with EntityFieldQuery How can I retrieve the 'count(*)' from a query in drupal 7?  The query needs to include a custom content type and a custom field.

Notes

Custom Content Type: employees
Custom Field Name: field_employees_email
As a note, I'm looking to add

WHERE field_employees_email = 'example@example.com'

to the query...

So far, I have something like:

$query = new EntityFieldQuery;

$result = $query
     ->entityCondition('entity_type', 'node')
     ->propertyCondition('status', 1) // Getting published nodes only.
     ->propertyCondition('type', 'employees') //Getting 'employees' type only.
     // How do I include custom field as part of query?
     ->execute();

Also, is there an easier way than

$total = count($result);

to return the COUNT(*) from the query?

You can use EntityFieldQuery::count(), as reported in the documentation for EntityFieldQuery::execute().

  [The result is] Either a number if count() was called or an array of associative arrays of stub entities.

The code you should use is similar to the following one:

$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'employees')
  ->propertyCondition('status', 1) // Getting published nodes only.
  ->count()
  ->execute();

To filter the result by the content type, you need to use EntityFieldQuery::entityCondition('bundle', $content_type).
For conditions on fields, you should use EntityFieldQuery::fieldCondition().


How do I create my own tokens? I use the Rules module. I want to add 1 to a CCK integer field on an action. Someone told me to create a custom token doing this addition.

So, I installed the tokenSTARTER module.

Now, how do I access the content profile (I load it in the rules chain) where the needed CCK field is in?

This module is very good for that: Custom Tokens.

  It gives the user the ability to create custom tokens for specific replacements that can improve other modules relying on the Drupal 7 token API or, for Drupal 6, the Token module.


Drupal Commerce causing database deadlocks I'm trying to get to the bottom of a known Drupal Commerce bug to do with row locking.

When a user logs in on my development site, Drupal Commerce starts multiple identical queries that look like this, even when the cart is empty:

SELECT revision.order_number AS order_number, revision.revision_id AS revision_id, revision.revision_uid AS revision_uid, revision.mail AS mail, revision.status AS status, revision.log AS log, revision.revision_timestamp AS revision_timestamp, revision.revision_hostname AS revision_hostname, revision.data AS data, base.order_id AS order_id, base.type AS type, base.uid AS uid, base.created AS created, base.changed AS changed, base.hostname AS hostname
FROM
commerce_order base
INNER JOIN commerce_order_revision revision ON revision.revision_id = base.revision_id
WHERE  (base.order_id IN  (''203''))  FOR UPDATE

They're all started less than a second apart, and they all hang and sit waiting for a transaction lock to be granted. The thread I linked to suggests the problem could be the same user is logged in on different browsers, but there's only one entry in my sessions table, so I'm looking for another cause.

What else could is going on here? The big obvious clue I can see is that I can't seem to run that query without an error - "base.order_id IN (''203''))  FOR UPDATE" throws a syntax error, and as far as I can see that's not normal usage for IN - it's normally two integers seperated by a comma, like a limit query, like ('1','12'). The order itself is an empty cart: opening the blob file just gives me this:

<!DOCTYPE HTML><html lang='en' dir='ltr'><meta charset="utf-8" /><meta name="robots" content="noindex,nofollow" /><meta http-equiv="X-UA-Compatible" content="IE=Edge"><style>html{display: non

But I don't know enough about SQL to know if this is something you can do in a join somehow - what's really going on here? And where else should I be looking to debug it?

UPDATE 11/02: I haven't gotten to the root cause of this, but I've done some more investigating.

Channel Islander is right, there's nothing screwy with that syntax. I must have just changed it somehow between copy and pasting and trying to get the query to run.
I truncated the order and order_revisions table in the dev site, then tried to replicate the bug by adding and removing stuff from my admin user's cart (trying to create a lot of revisions). I couldn't replicate the bug like this, and performance got a lot better from them onwards: page loads when logging in and out sped up by multiple seconds, and I can't even catch this SELECT... FOR UPDATE query in phpMyAdmin's status tab.

This seems to have resolved the issue for now, but truncating both tables is obviously not feasible for a production site. Maybe setting orders at "cart" stage to expire after a certain time would be, though?

Based on your update, you might consider using the Commerce Cart Expiration module.


trigger in rules a beep sound on user side (current user is working) I have a D7 site running with Organic groups, rules, VBO, panels, badges, private-message modules ... and a bootstrap sub-theme (js, jQuery update, ...) working in all browsers, ios & android, i need to alert users with a beep sound when new OG content is created (or any rules reaction) by a custom module named beepsound module.

What I have:

•   Rules event: create new content

•   Rules condition: my contentype with some fields.

•   Rules action: Loop: all OG group members, loop action: see code below

"beepsound module" must have UID variable to target a specific OG member.

I have manage to have my beepsound as an action in rules, it targets UID, it display a personalised message corectly, also, message is displayed 5 times (when tiggered when mycontentype is being viewed), meaning rule is triggered 5 times, here are my-module code files, dot module file exist but is empty (and not displayed here), If i run this rule with current-user, it works (makes a beep), but not in my OG loop, what it is wrong?

beepsound.info MODULE

name = Beep sound by rules module
description = Module to add a beep sound action in rules
package = Custom
version = 7.01
core = 7.x
dependencies[] = rules

beepsound.rules.inc MODULE

/**
* Implement hook_rules_action_info()
* Declare any meta data about actions for Rules
*/

function beepsound_rules_action_info() {
$actions = array(
'beepsound_action_beepsound_user' => array(
    'label' => t('Make a beep sound'),
    'group' => t('sound'),
    'parameter' => array(
        'account' => array(
            'type' => 'user',
            'label' => t('User to beep'),
            ),
    ),
  ),

);

  return $actions;
}

/**
 * The action function for produce sound
 */

function beepsound_action_beepsound_user($account) {
    drupal_set_message(t('Hello @username',
 array('@username' => $account->name)));
    ?><audio autoplay="autoplay">
      <source src="/sites/all/modules/beepsound/A-tone.ogg" type="audio/ogg">
      <source src="/sites/all/modules/beepsound/A-Tone.mp3" type="audio/mp3">
    </audio><?php
}

here is my rule

{ "og_og_new_content_notification_message" : {
"LABEL" : "OG new content notification message",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "OG" ],
"REQUIRES" : [ "og", "rules", "privatemsg_rules", "beepsound" ],
"ON" : { "node_insert" : [] },
"IF" : [ { "og_entity_is_group_content" : { "entity" : [ "node" ] } } ],
"DO" : [
  { "og_get_members" : {
      "USING" : { "group_content" : [ "node" ] },
      "PROVIDE" : { "group_members" : { "group_members" : "List of group members" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "group-members" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "privatemsg_rules_new" : {
            "USING" : {
              "recipient" : [ "list-item" ],
              "author" : [ "node:author" ],
              "subject" : "\u0022[node:title]\u0022 a sido creado. ",
              "body" : "\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E Por favor haz clic aqu\u00ed para ver su contenido\u003C\/a\u003E"
            },
            "PROVIDE" : { "thread_id" : { "thread_id" : "ID of new thread" } }
          }
        },
        { "beepsound_action_beepsound_user" : { "account" : [ "list-item" ] } },
        { "drupal_message" : { "message" : "beep beep, usuario: \u0022[list-item:uid]\u0022" } }
      ]
    }
  },
  { "drupal_message" : { "message" : "Se ha enviado un mensaje a todos los miembros del departamento." } }
]

}
}

In order to send a message to users other than the current user, you will need to do some additional processing. drupal_set_message sets a message in the current user session. It does not set a message in another user's session.

Some possible approaches include a push or pull notification type system.
For example, the server can push updates to the client using something interesting like a Service Worker (advanced). Alternatively, the client can poll the server periodically, via ajax type request to get message updates.


8 - Is there a drush command to reset a module's config back to install defaults? I'm working on a custom module in Drupal 8 and have nested the config a bit, but getting errors and want to just reset the config for that module completely.

I guess it doesn't provide drush integration yet, but have a look at https://www.drupal.org/project/config_update

It provides a UI to compare and revert configuration with the defaults provided by a module.


Is there an hook to react to custom entity updates? I need to react to updates of custom entities wich are using Entity API (Redhen organization in my case).

I tried using hook_entity_update($entity, $type) but it does not seem to be fired when updating said entity.

Thank you for your time.

If it can help other people :

hook_entity_update is working fine as long as it is declared in the .module file.

I putted it int an inc file so it was never fired !


How to modify a core theme and what is the correct way to do this? I modified the core's Bartik theme file, node.tpl.php.  I simply added

echo "Last updated by $name on " . format_date($node->changed);

The problem is that when there is a new core update, my change will be overwritten.  Is there a way to create a module that will easily add this simple line in the node.tpl.php of Bartik's node.tpl.php theme file so that future updates will not overwrite my change?

What you want to do is create a subtheme of Bartik, and make your modifications to node.tpl.php there instead. Themes support the notion of inheritance, so this can be leveraged to tweak core themes without actually hacking core. As a rule, it is best practice not to hack core for the reasons you mentioned and a slew of others, security not the least among them.


How can I install a beta version of a module? Now, a good amount of modules do not yet have a stable version, for example, webform. composer require drupal/webform says:

  Could not find package drupal/webform at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

If I try composer require --minimum-stability=beta drupal/webform, I get:

  The "--minimum-stability" option does not exist.

drush dl gives:

  This codebase is assembled with Composer instead of Drush. Use composer update and composer require instead of drush pm-updatecode and drush pm-download.

Note that due to the special versioning of Drupal this is not a generic composer question but a Drupal specific one. Ie. webform today is 8.x-5.0-beta12, how do I install the latest in the 8.x-5.0 series...? Now, composer doesn't understand or use 8.x-5.0 but uses somethting else, but what and how does that work for betas? This needs documentation somewhere because it currently does not exist. I would be the happiest person if this didn't need an answer, but alas, despite having perfectly fine working tools to build sites, with Drupal 8 we need to use composer and most modules are in beta.

This installs the latest beta-12 for me:

composer require drupal/webform:5.0.*@dev

You need to do a bit of translation from the Drupal version number. From Using Composer to manage Drupal site dependencies:

  Specifying a version you can specify a version from the command line with:

 $ composer require drupal/<modulename>:<version>

  For example:

 $ composer require drupal/ctools:3.0.0-alpha26
 $ composer require drupal/token:1.x-dev

  In these examples, the composer version 3.0.0-alpha26 maps to the drupal.org version 8.x-3.0-alpha26 and 1.x-dev maps to 8.x-1.x branch on drupal.org.

  If you specify a branch, such as 1.x you must add -dev to the end of the version.

Hence for Webform, 8.5 becomes 5.0.x, and that's what you need to use to identify the package correctly.


Include files used by multiple modules I have some include files (.inc) that have classes in them that are used by multiple modules. Where should these be stored so that they are accessible to files[] in a modules .info file? Preferably without having to store copies of the files in each modules directory.

Probably the sanest way to do this would be to create a new module which has little to no functionality, but includes the .inc files; then make your other modules dependent on that module. As you develop the other modules and find other functionality you want to share between them, just implement it in the "parent" module, and away you go.

If adding another module is objectionable for some reason, you could implement it as a "library" and use the Libraries API module - but that's intended for Drupal-external third-party PHP libraries like TinyMCE, not things you've built yourself.


Custom redirects and Drush/updates I usually update Core with Drush, because it's so easy and wonderful, but I have a custom htaccess and it always overwrites it, forcing me to rely on a checklist where I have to go and put my custom one back in. Is there a way I can either tell Drush not to overwrite it when updating or automatically put the custom one back in with a bash script or something? Or should I use a module to do these redirects instead? They are all like this and are a legacy from when our main company website hosted some custom apps:

RedirectMatch 301 ^/blah/ blah blah.cgi http://anotherwebsite.com/cgi-bin/blah.cgi

Short of support directly in Drush, this is what I would recommend.

Keep your site in a structure something like this:

srv
. www
. . mysite.com
. . . .git
. . . custom-htaccess
. . . custom-robots.txt
. . . htdocs
. . . . .htaccess
. . . . robots.txt
. . . . ... other files in the Drupal root

I like to structure my Drupal files as shown above so that I have a place to keep files in the same git repository as my Drupal files without exposing them to the webserver (or worrying about hiding them from the webserver with custom .htaccess rules).

If you keep all of your customizations to .htaccess and robots.txt in separate files like this, it would be an easy thing to concatenate them on the end of the corresponding Drupal core files.  This structure might be a good starting point for a formal Drush feature that does the same thing.

Update: If you are not on shared hosting, you'll do much better to store your .htaccess customization on the Apache vhost conf file, and leave Drupal's .htaccess file unmodified. The syntax of this file is about the same as the .htaccess file. The first step is to find the right file; it's often in /etc/apache2/vhost.d or /etc/httpd/vhost.d, although on Debian distros such as Ubuntu it is in /etc/apache2/sites-available. Apache configuration is not a Drupal-specific topic; there's a lot of info about it available on the Internet.


Remove the resizing of images that are bigger then the max resolution. (reject instead) I'm using a very specific theme on the site where an image need to be exactly 1110x540.
I've set up the min and max resolutions and everything works perfectly, except when I upload an image that's bigger then 540px. Then the image rescales.

Is there a setting that rejects these images instead of resizing them ?
I'm using Drupal 7 btw.

Set min/max on the FIELD ITSELF, under content types. Not on the image style.