How to notify users when a new comment is posted in the same page as they did? I have a Drupal 7 website and I display comments on a content type.

What I want, is for every user to have a boolean field in their profile, to declare if they want to be notified when a new comment is posted at the content type that they posted.

I tried the Comment Notify module, but it shows its options right before you post your comment, and doesn't have a use with user profile/field.

I have already achieved a similar notification, for the user to be notified when the administrator replies to one of the user's comments.

I managed it using the Rules module, before a comment is posted, with these Rules Conditions:

Entity has field (comment:parent:author) and Data Comparison, to verify a relevant boolean at the user profile.
Data Comparison, for the (comment:author:roles) to be administrator.

Although, I can't seem to achieve the requested rule.

I know I have to do a search for every commenter at the same node, before a comment is posted, if they have the boolean enabled at their profile, but I can't create it with Rules.

To sum up, I have a content type (projects) and I have created about 50 of them. If some user X posts a comment on one of the projects and has the boolean enabled, then if anyone else comments on the same project, user X will be notified by email.

Any help?

Have a look at this rule (in Rules export format), which does what you're asking for:

{ "rules_notify_commentors_about_new_comment" : {
    "LABEL" : "Notify commentors about new comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "comment" ],
    "ON" : { "comment_insert" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "users_that_commented" : "Users that commented" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "comment:node:comments" ] },
          "ITEM" : { "current_comment_item" : "Current comment item" },
          "DO" : [
            { "list_add" : {
                "list" : [ "users-that-commented" ],
                "item" : [ "current-comment-item:author" ],
                "unique" : "1"
              }
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users-that-commented" ] },
          "ITEM" : { "current_comment_author" : "Current comment author" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "data_is" : {
                      "data" : [ "current-comment-author:field-accept-boolean" ],
                      "value" : "1"
                    }
                  },
                  "DO" : [
                    { "mail" : {
                        "to" : [ "current-comment-author:mail" ],
                        "subject" : "New comment to node with id [comment:node:nid]",
                        "message" : "There is a new comment added to the node with id [comment:node:nid]",
                        "language" : [ "" ]
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

The only additional module needed is the Conditional Rules module, while it does use a few of the more advanced techniques available in the Rules module.

If you're familiar with reading/digesting Rules in Rules export format, I'd hope the rule is self explaining. If not here is a summary of the above rule:

Rules Event: obvious ... after saving a new comment.
Rules Conditions: feel free to add whatever fits (eg limit to selected content types only, like "Projects" in this specific question).
Rules Actions:

Add a variable "users_that_commented" (= a list of users).
Loop over all existing comments, and for each comment author, add that author to the list of users (= users_that_commented). Note the "unique" that is turned on (we do not want duplicates in that list of users).
Loop over the list of users (= users_that_commented ... again, which we just created and populated). And for each user in that list, do your thing, in this case "send an eMail", provided the field field_accept_boolean is TRUE (which you can check if you have the Conditional Rules module enabled). The "To" value is crucial here, the body, the from, the title, etc is up to your own imagination.  If you don't want to use the Conditional Rules module, you could also rework the Rules Action withn the last Rules Loop to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

If you want, just import the above rule in your own site (using the Rules UI), after you enabled the Conditional Rules module, and after replacing the field name of field_accept_boolean to fit the machine name of your own field.

That's really all it takes ... a Rules variable, Rules lists and loops, and Conditional Rules.

PS: There is one minor improvement of this rule I can think of (if perfect is not good enough) ... After anybody finds out what that may be, and after the question details are corrected about that also, I'd be happy to update my answer (= change 1 detail in the rule) to also implement that.


In which table is a path alias stored? I need to make a query to get the path alias used for a node.  In which table is it stored?

They're in the aptly named url_alias table, but you shouldn't query it directly. The path alias manager service is preferable:

$alias = \Drupal::service('path.alias_manager')
    ->getAliasByPath("/node/$nid");

As always, inject the service if you can.


translate strings from format_plural How to translate the output of format_plural which returns a new translatable string every time the count increased.

I put the translation with @count but it returns an array like @count[NUMBER]
the NUMBER increased and for every NUMBER we have a string that need translation.

The translation work if I put @count[NUMBER] and didn't work for NUMBER-1 nor NUMBER+1

How to translate all strings with one translation?

The code comes from download_count module

And here is the piece of code

if (isset($file->downloads) && $file->downloads > 0) {
$output .=     format_plural($file->downloads, 'Downloaded 1 time',     'Downloaded @count times');

}

Finally I need to translate plural strings form the translation interface drupal provides and fix the raised number of strings

I have .po files and had changed the plural-forms as that comment then import the file but nothing changed so I need help to fix it.

Thanks in advance

Thanks all

I found the solution as that comment form-plural in po

Edited on of the po files after exporting the last state to keep translation.

Import the file using drush (uploading from the interface always fail)

Installed drush_lang module

Apply that patch langimp relative path in /home/$_USER/.drush/drush_language

Clear cache for drupal and drush (drush cache-clear drush)

use the commands that module provides and every thing will be fine


Use or Extend module functionallity Recently we started a proyect where we need to implement a webpage that should be able to manage google maps markers and locations, with aditional info on them. However the requirement was to do it as a Drupal module in order for the client to embed it on his existing web page powered by Drupal.

I have a strong background developing web pages using java technologies like JSF, and I have had some previous experience using PHP MVC frameworks like cake php, but that's the reason why I think I'm so confused with the module development process used in Drupal (hook methods and conventions...).

First of all I have been looking at the Drupal 7 module development book by Packt, and I just finished the chapter 4 where you're supposed to implement and theme a single blog module. However by using the techniques showed until that point... I find it extremely difficult to implement a google maps powered (Block???) by just theming it as lists or using the render API.

What I found really interesting was the possibility to use theme templates and create the block content based on them; by just passing variables and priting php statemnets..., but it's not explained very well on the book either. So that's why I wanted to ask you where I could find more resources about theme templates, so that I could just put my html markup and js functions on that template, and pass to it the processed variables.

Anyway I think my best bet would be to extend existing module funcionality. In example for the maps I would use the OpenLayers Drupal module that's already done and tested. However, I need to execute my own code logic when a marker is selected, so that's another question..., how Could I insert a callback or intercept the OpenLayers module's functions so that I can extend them and save the data on my own tables or any operation I needed.

Should I rewrite the module files to add more functionality?? or could I implement my own modules and just intercept method calls?.

I'm just starting Drupal, and I think is really simple... but just for showing content, on the other hand interacting with the user, retrieving data from clients, seems to be really really difficult, because I have no idea how to show custom html markup, or add js functions, and then executing php ajax function callbacks on the server.
For all these reasons I'm felling a little bit overwhelmed, and I really really need some guidance, tutorials, resources to focus on..

The other question I had is..., what are the topics that I should focus most in order to start my module fast, what I basically need is the ability to put markers on a map (Using the Javascript V3 API I guess...), and then sending AJAX callbacks to the server in order to update the selected marker info and adding it to my Session?? variables.. (This is really easy using JSF, and a framework like Primefaces.. however in the php world I'm lost) I think I should look at Drupal Entities and Fields next... but also Widgets?? Right???

Thanks a lot.

I'm not sure that you need to dive into any theming. The Google js API uses an empty div and javascript to fill it. Your could create a custom module with a block hook to create your block. It would also load the necessary js to engage the Google API. This assumes that you are going to access the geographic information for the map independently - i.e. via accessing the database or whatever on your own. I think it makes most sense to use something like Openlayers if the data is stored in nodes and you want to use a View to access it.

If you need to theme the block outside of the map, you could use a straightforward theming function, also in your custom module. Creating or using a template makes most sense if somebody else who is more of a html/css person with less php/js experience is going to be doing the theming. If the theming is simple, you could just create the needed id and class tags in your module and then theme it via a css file.


Hide fields from "address_field Module" form I have a site using Profile2 with address_field Module; and I would like to prevent users from filling out the follwing fields:
Address 1
Address 2
ZIP Code
Country

The goal is is only to be able to fill only CITY AND STATE; (e.g. Orlando, FLORIDA)

Thanks.

J.M.

in a hook_form_alter() add:

   hide($form['field_address']['und'][0]['street_block']);

you can use dpm($form['field_address']['und'][0]) to get the name of the city, and country fields.

You could also use CSS to hide the fields but I ran into problems where browsers prefilled those fields. It's better to hide it with a hook.


How to add a pager at both the top and bottom of a View How can I do this for Drupal 8?

I have searched for a solution but I didn't find anything yet, I hope some one here can help me.

I have this "pager.html.twig" (from the clasy theme) template in the path of my own theme, the path is "mytheme/templates/navigation/pager.html.twig" and this is rendered automatly by drupal in the views where the pager is requiered, but I have a requierement in my job that I have to place the pagination at the top and the bottom from my view.

Example:

<[1|2|3|4|5|6|7|8|9|10]> (this is the pager that I want to place on top)

content of my view
content of my view
content of my view
content of my view
content of my view
content of my view
content of my view
content of my view

<[1|2|3|4|5|6|7|8|9|10]> (this is the drupal rendered pager automatly)

Thanks in advace for the help.

Ok, I solved it.

In my theme, I had copied all the content of classy theme because is like a copy of this.

In the theme exist an "templeate" folder, this have another folder called "views" inside this folder exist the file called "views-view.html.twig" in this file exist a few printing variables whit if conditions. All I had to do was copy the:

{% if pager %}
 {{ pager }}
{% endif %}

Condition almost at the end of the "template" and paste it where is above the content and voilà, I have my pager at the top and the bottom of my template.

I hope this be useful for anybody.

Thanks for your comments.


Control access to taxonomy terms In my project I have companies, which are taxonomy terms, which can create invoices. Users and companies are a many-to-many relationship. I'm able to control access to the invoices using tac_lite, but I've searched everywhere and can't find how to control access to the term page (/taxonomy/term/%). I want users to be able to see a list of their companies and a detailed page of each company, while denying access to other users' companies. Can I do that with tac_lite? If not, how can I approach this? Sorry if this is not the right place to ask and if this is an obvious problem, I'm new to Drupal.

Thank you

You can try https://www.drupal.org/docs/8/modules/permissions-by-term, hope this can solve your problem.


Allow users to moderate taxonomy terms Is there a way to allow users to moderate nodes and their comments by taxonomy terms? And also allow other moderators to add users to to that term as well? It seems that the standard roles aren't granular enough. I don't want users assigned to a "moderator" role to be able to moderate ALL nodes and comments, just those within a particular taxonomy term.

Basically allowing each term to be a "discussion board" where a group of users are the moderators of that term. Similar to how Reddit works.

Thanks

Taxonomy Access Control - access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy terms).
Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.


How to Make field required depending on other field? I have 2 fields in my content type "blog"

1)promote to front page(boolen field with yes or no option)

2)Hero Image(image field)

If user selects "yes" option in promote to front page field ,the Hero image field should become required.

How it can be possible?

You can do this with the Conditional Fields module.

It allows you to configure dependencies between fields (visible / required / etc.). It's still a development release, but it should work.


Alternative to Views Suppose we have numerous entities of types Alpha and Bravo. Alpha entities could easily be taxonomy terms and Bravo – content nodes. Bravo entities can reference multiple
Alpha entities each; whereas, Alpha entities (taxonomy terms) are completely agnostic of any other entities.

The exercise is to aggregate all Alpha entities that are referenced together (by the Bravo entities) with a given Alpha entity.

Example: Alpha entity type is a taxonomy vocabulary containing Artists. Bravo is a Project content type. Sometimes Artists collaborate on Projects; therefore, some Projects have multiple Artists. An example of the aggregation in question would be to list all Artists that a given Artist has collaborated with (has been referenced in the same Project with).

I am building the information architecture for my first Drupal project, in which metadata and it's inter connectivity is important. I have achieved this aggregation using Views, but Views seems impractical for my uses. In many cases I want to list just Taxonomy term names like this:

  Nirvana has collaborated with: Biggie Smalls, Lil' Wayne, Lil' Jon.

(Of course, I wouldn't want my Taxonomy system to make jokes)

What aggregation solutions are there? Do you have tips? Have you done something like this?

Why I'm looking for an alternative to Views:

The reason I find Views impractical for this use: my impression is that it's geared more towards heavier listing, like catalogs and is hard to squeeze into "lighter" roles (like the one in my example). If I am fooling myself, do correct me.

If you're looking for a good core alternative to select entities, using custom queries, make sure you familiarize yourself with Entity Field Query (EFQ)

e.g, fetch 10 published article nodes with field_my_field value 'foo':

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'article')
      ->propertyCondition('status', 1)
      ->fieldCondition('field_my_field', 'value', 'foo')
      ->range(0, 10)

$result = $query->execute();

if (isset($result['node'])) {
  // nids are here
  $nids = array_keys($result['node']);
  // nodes can be loaded as such
  $nodes = entity_load('node', $nids);
}

More EFQ info here


Connect to Salesforce using wsdl in Drupal 8 I am trying to connect to Salesforce (SF) with wsdl to pull data.

I can't use SF suite module or Salesforce rest client service.

In the D7 file, I have:

require_once ('soapclient/SforceEnterpriseClient.php');
require_once('soapclient/SforceHeaderOptions.php');
ini_set("soap.wsdl_cache_enabled", "0");

$sfdc = new SforceEnterpriseClient();
$SoapClient = $sfdc->createConnection($curPath.'/enterprise.wsdl');

It create the connections without any problems.

D7 References from here: https://developer.salesforce.com/page/PHP_Toolkit_11.0_Getting_Started and learned to how to use it from here: https://github.com/developerforce/Force.com-Toolkit-for-PHP/blob/master/soapclient/SforceEnterpriseClient.php

In the D8, I am trying to figure out how to connect to SF in the same way:

namespace Drupal\mymodule\Controller\Soapclient;
$sfdc = Soapclient::SforceEnterpriseClient();
$SoapClient = $sfdc->createConnection('../../includes/soapclient/enterprise.wsdl');

But got the SforceEnterpriseClient class not found error.

Stuck on it for a while, any help will be so much appreciated.
Anybody knows how to connect to SF in the same way like this:https://github.com/developerforce/Force.com-Toolkit-for-PHP/blob/master/soapclient/SforceEnterpriseClient.php

It seems the problem you are facing is due to the way you are referring the library; please refer the following question; they have explained how you should be using external libraries in Drupal 8 custom modules.


Drush error on core update "corrupt (wrong md5 checksum)" I'm getting this error when I try to update core with Drush:

File drupal-7.41.tar.gz is corrupt (wrong md5 checksum).  [error]
Updating project drupal failed. Attempting to roll back to previously
installed version.   [error]

I've tried to refresh and clear all the caches I can think of (drush rf, drush cc all, drush cc drush) but the error continues.

Any ideas?

By looking at this drupal issue queue thread, https://www.drupal.org/node/1961304 , if you are using Drush Make and having problems try --no-cache option for your build.

Otherwise assure the downloaded Drupal version, or module, is readable by the Drush user. If drush cannot read the file then the md5 checksum cannot be run and Drush will report a corrupt file:

  @sobi3ch: this appears to be a permissions issue. If i'm reading the
  Drush output correctly,
  "md5_file(/var/www/vhosts/etcc.pl/drupal-7.38.tar.gz): failed to open
  stream: Permission denied" is saying the md5 checksum function is
  unable to open the file to validate the checksum on it, which causes
  drush to think the file has the wrong checksum.


commerce drupal 7 cache module suggestion Any experiences of suggestion about what cache module to use in with a commerce store? I have been researching about it and I cannot find any suggestions or problems that you can face when using Drupal commerce with caching.

Have you tried to use Authcache module with memcache module

http://drupal.org/project/authcache

Also check Entity cache for Drupal Commerce module

http://drupal.org/node/1588814/release


How do I install with PostgreSQL using Docksal? I use Docksal for developing on Drupal. Recently, I decided to install Drupal 9 with PostgreSQL as a database using Docksal.
Firstly, I cloned https://github.com/docksal/boilerplate-drupal9. Then, I modified some files accordingly to https://github.com/docksal/docksal/issues/193#issuecomment-376343111. Lastly, I ran fin init and this error message.

[warning] Failed to drop or create the database. Do it yourself before installing.
ERROR 2002 (HY000): Can't connect to MySQL server on 'db' (115)
[notice] Starting Drupal installation. This takes a while.

Frankly speaking, I can't understand what does MySQL has to do with it?
The database driver should be PostgreSQL and the default database should be also PostgreSQL.
Has anybody encountered this problem?
Is it possible to install Drupal 9 on PostgreSQL via the Docksal service?

It should be noted that you need postgres 10+ when using Drupal 9.
The steps that you are following in are for Drupal 8 and they will install postgres 9.
Recently a services has been added to Docksal that installs a postgres database that matches your Drupal version (8 or 9).
See the Docksal documentation on adding a postgres service.
Add this service and outcomment the default db image in docksal.env:
#DB_IMAGE='docksal/mysql:5.7-1.4'

When this services is added check that it works correctly by checking the docksal status:
~/S/mysite ❯❯❯ fin status
   Name                  Command                 State                         Ports
-------------------------------------------------------------------------------------------------------
d9geo_cli_1   /opt/startup.sh supervisord     Up (healthy)   22/tcp, 3000/tcp, 9000/tcp
d9geo_db_1    docker-entrypoint.sh postgres   Up             0.0.0.0:49174->5432/tcp,:::49174->5432/tcp
d9geo_web_1   httpd-foreground                Up (healthy)   443/tcp, 80/tcp

Your Drupal settings should look as follows (note that the driver should be pgsql)
$databases['default']['default'] = [
    'database' => 'default',
    'username' => 'user',
    'password' => 'user',
    'host' => 'db',
    'driver' => 'pgsql',
];

User, password etc. can be changed using environment variables.
Now you should be able to install the website.


Embedded view doesn't appear in node I have node  golosuizaprognoz_lenta with hidden field argument-lenta, node golosuizaprognoz with field field_argument, view of table with Rating wiget:

The node have title with date, for example 21/06/14 Голосуй за прогноз!!!

I need that in node was view only with date equal date in title.

What I have done:

I add to node golosuizaprognoz_lenta hidden field argument-lenta where I add url of result node, for example 210614-golosuy-za-prognoz.

I make EVA display:

with contextual filter:

when I insert content of field field_argument wich equal of url node  golosuizaprognoz_lenta , for example  all OK, I get what I want, but in node I have no this view (without contectual filters view is shown so I attached it).

How I need to fit contextual filters that in node I will see only views with content wich have field field_argument wich equal of url node  golosuizaprognoz_lenta.

http://myforecast.esy.es/210614-golosuy-za-prognoz/

You should be able to accomplish this by using Auto Node Title . This will generate automatic node titles, and allows PHP to define that title. Using str_replace  you can remove the slashes from a date field and replacing them with nothing, creating the desired effect. Then use a token or static text in the title for the rest of it

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.


Some info missing on Drupal 7 ckeditor accordion instructions Trying go to get this working:

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

But it's not working, step 5 and 6 don't exist or I can't find them in Drupal 7, are these instructions for Drupal 8 only?

 5.Scroll down to the bottom to the input Allowed HTML tags
 6.Find and replace <dl> with <dl class>

Can't find 5 and 6 in the backend

Go to /admin/config/content/formats and click configure on the format that you'll be using.

Scroll all the way down and click on "Limit allowed HTML tags" tab. Now replace <dl> with <dl class>


Adding an img inline with the content only on a specific page I have a certain page on my site that has the following menus at the top:

I would like to add a logo just before the textual menus on the far left of the screen.  This menu is in the main content of the page.  So far I have been able to get the logo to show up just above the content by adding the img to my page.tpl.php file but I really want it to show up on the same line as my menus.

I thought maybe I could do this by adding the img into a region.tpl.php file but that would make the image show up on every page's region and I only want it to show up on this page's region.  Is there a way to the image show up inline using a page.tpl.php file?

Have you tried creating a block with your context, restricting the block to that one page, and then assigning the block to the correct region?

Your regions will depend on your theme.


Content created using field and content created using , and effect on website performance? I am using the field collection module to create my Content. I have 10 text content. For ease of CSS class, I put each content in separate fields and apply the class using the field formatter module, So I have 10 fields and putting 10 text content in each one.
Now same thing I can achieve by just making

 10 times in body of CKEditor (just one field), For example,

Text content 1

Text content 2

Text content 3

.
.
.

Text content 10

Now, in terms of performance  will it affect the speed/loading of webpage of drupal 7 sites, if I go by 10 separate field or with one html code with 10 div? I am preferring 10 separate field method, because it is easy to handle editing and updating if needed.

Kind Note:   To Moderators, please do not categories this question as opinion based, because i do not have experience with in-terms of performance of website, so I need suggestion/Comparison between this two methods from more experience Drupal developers. Thanks

I'd recommend just using one field and changing the "Number of values" in the field settings. This will allow you to add as much as you want and yet only maintain one field.

In case you have different requirements, here's my opinion on the two approaches you are thinking of.

Here are the differences between the two approaches:

10 fields

you have many fields that each go through the preprocess, process, field_alter, and any other hook that might affect a field.
Assuming they are similar fields any maintenance you would do would have to be done on each on individually.
If the fields will eventually have different values then this approach allows you to easily modify them.

1 text area

you only have 1 field that does through the whole hook process. Which makes things go faster.
You only have 1 field to maintain.
It does not make sense to store multiple values in one textarea since it makes curating difficult and prone to typos. Imagine missing a closing div. Boom, layout gone.
Also, if in the future you have a case to migrate your content, you will have to make additional effort to migrate these since there are multiple values in the data.

All this said, the two options do not have a HUGE impact on performance if you're just loading them up for display and not doing massive preprocessing.


Problem with IF command in comment.html.twig I create a "select" field (field_points) in comment section that users rating my content and in "manage display" I set "key" for my field format.

5|Excellent
4|Good
3|No Idea
2|Bad
1|Very Bad

Now I use this code in comment.html.twig:

{% if content.field_points == 5 %}
   *****
{% elseif content.field_points == 4 %}
    ****
{% elseif content.field_points == 3 %}
    ***
{% elseif content.field_points == 2 %}
    **
{% elseif content.field_points == 1 %}
    *
{% endif %}

When I use this code nothing is displayed But when I use {{ content.field_points }} , print for example 5 ( 5 is field key ).

How can I fix this problem in drupal 8?

Use the comment entity to get the raw field value instead:

{% if comment.field_points.value == 5 %}
   *****
{% elseif comment.field_points.value == 4 %}
   ****

...

{% endif %}

This doesn't work with {{ content }}, because it contains a build array to render the fields.


Drupal clean URLs not working from subdirectory I'm not sure if this belongs here or in serverfault, so feel free to flag it if necessary. I have a server with a drupal installation at /drupal. I want the URL www.example.com to point to www.example.com/drupal. I don't want to change my server root, just do an Apache Rewrite.

RewriteRule (.*) /drupal/$1

This works, so when I type www.example.com I go to the drupal site. The issue is no other URLs go to the correct spot. So when I type a URL like www.example.com/about, I see the drupal theme but then the content just says

  The requested page "/about" could not be found.

The page www.example.com/drupal/about does show up fine. I've also changed $base_url to www.example.com. Any idea what could be wrong?

I've also tested that URLs like www.example.com/?q=node/16 work fine, so the problem is just with clean URLs.

Problem in drupal Clean URL, To Enable drupal clean url in subdirectory un comment the following line in .htaccess file.

  # Modify the RewriteBase if you are using Drupal in a subdirectory or in a
  # VirtualDocumentRoot and the rewrite rules are not working properly.
  # For example if your site is at http://example.com/drupal uncomment and
  # modify the following line:
  # RewriteBase /drupal
  #
  # If your site is running in a VirtualDocumentRoot at http://example.com/,
  # uncomment the following line:
  RewriteBase /

for more refer the blog Enable drupal clean url in subdirectory or subdomain


Adding a tab to commons browsing widget with hook_commons_bw_group_widget() I am trying to add a tab to the Commons Browsing Widget so I made a custom module and followed this guide https://drupal.org/node/1782922. I used the first PHP code with hook_commons_bw_group_widget() but it doesn't add the new tab to the widget. What could be wrong?

Don't know if this is your module, but this one accomplishes just that:
https://drupal.org/project/commons_bw_ui

It was posted just 2 weeks after your post above.


Can you display a variable in a Drupal webform component label? I'm trying to create a webform in Drupal 6 where the label of a select webform component is rendered using the contents of a variable.  For example:

client_name = "Starbucks"

and I would like the label of 5 or 5 different webform components to include "Starbucks".  I prefer to code this with a variable, as this webform will be cloned in the future.

Is there a way to do this?  From what I can tell, labels do not accept Drupal tokens and I'm not sure where to define the variable.

any help is appreciated!

You can alter form elements, including labels with hook_form_alter(). Use dpm() (from the Devel module) to inspect the $form array to find the value you want to change.


Boost + Domain Access + flushing cache I have the Boost and Domain Access modules working correctly. But I've found that if the cache is flushed for one domain it doesn't clear for the others. So if content is added to one, it won't show for others until cron has been run.

Any way to fix this at all?

Saw your post on d.o.: https://www.drupal.org/project/domain/issues/1673650
The suggested fix looks good and should still run:
function MODULENAME_domain_cron($domain) {
  global $base_root;
  if (isset($domain['path'])) {
    $base_root = $domain['path'];
  }
  boost_cron();
}

The error you have there seems strange. The argument should be passed to the hook_domain_cron method ?!?
UPDATE: You still can try to make the argument optional:
function MODULENAME_domain_cron($domain=[])

But I would debug that to find out the real reason ..
How does your code look for mymodule_hook_domain_cron?


redirect to custom profile panel page of individual users Ok As @Letharion rightly says, i need to rephrase my question. SO here it is:

I created a basic page and gave it an url alias as "Profile". This page is meant to be my profile page for users on my site. On this page there are 3 quick tabs,"My-Profile", "My-Content", "My-Flagged-Node". The "My-Profile" quicktab has a call back to a custom panel page "user-profile" which has the user name, user picture, and the user activity (created as a view with activity module), and the number of content created by the user. The "My-Content" has the content by the user. The "My-Flagged-Node" quick tab on clicking loads a view showing the flagged nodes by the user. I have created these views and these work properly. Now when a user goes to his relationship and clicks another user's picture then i want that the user is taken to the "Profile" page of this user (the user on which he clicked). I undersatnd this has to be done by passing arguments to views from panels and so on but i am not clear on that. While creating my view in the contextual filters and the relationships i added user id from url as a default value but this takes me to a blank screen or to the same user profile. I hope i am clear now on what i want. Some redirection rules and passing arguments.

Regards

Panels provides a built-in way to override user profiles-- look for the link (disabled by default) in Page Manager called user_view (User Profile Template).  Instead of using your own custom profile page, enable this page override (User Profile Template) and make your changes to that panel.

Then, to link to user profiles, you can just use the standard user profile links, no rewriting needed.


Change the display name of order total the following code to replace the displayed name of the subtotal.

How to change the display name of order total ?

// Rename subtotal.
function seven_subtheme_back_office_commerce_price_component_type_info_alter(&$component_types) {
  $component_types['base_price']['display_title'] = t('Sous-total hors remises');
}

the following code does not work, it must be poorly written :

// Rename subtotal.
function seven_subtheme_back_office_commerce_price_component_type_info_alter(&$component_types) {
  $component_types['base_price']['display_title'] = t('Sous-total hors remises');
  $components['commerce_price_formatted_amount']['title'] = t('ORDERrrrr TOTAL');
}

For changing order total, this line

// Replace ORDER TOTAL text as per your requirement.
$components['commerce_price_formatted_amount']['title'] = t('ORDER TOTAL');

should be added inside your above mentioned function. Check if it works.


Allow users to see restricted nodes via views I have a content type with meta data about a department, and these nodes is restricted using Taxonomy Access Control so that only the department heads can actually view them.  I would like to create a view of some of the information in these nodes that will be visible to people without full view rights to the node, but views filters out nodes that the current user can't see, which means that these nodes are hidden for non-department heads.  Is there a way to override the node access filtering for a specific view?

I've not used Taxonomy Access Control, but I'd look in Views' Advanced Settings / Query Settings and check Disable SQL rewriting. But, as the warning says, "Disabling SQL rewriting means that node access security is disabled. This may allow users to see data they should not be able to see if your view is misconfigured. Please use this option only if you understand and accept this security risk."


Creating content types with fields that are other content types? I have an existing content type in my current Drupal application, person. This contains all of the data you would expect, more or less - name, address, employer, etc.

I'd like to create a project content type. A project will consist of a name, description, and multiple members. Each of these members should be a person node that will already exist. It would be great if I could have the ability to add members by either selecting from available persons as a dropdown, or maybe some sort of autocomplete on name. I already know how to do autocomplete, but the issue then is that the field will be autocompleting just the person's name. I need a project node to actually contain multiple entire person nodes, so that I can get ALL of the info out of them - name, position, etc. etc. Is this sort of functionality natively in Drupal?

Alternatively, I could implement hook_node_load in this module, and add person nodes to any node loaded that happened to be a project node. Would this be a more viable alternative?

In future it would help to know what version of Drupal you are using.

In D6 you can use Node Reference CCK field, which creates a cck select list, auto complete, radio buttons or checkboxes listing the node types you have selected to be referenced.

There you could use your autocomplete form, type the users name and add them to the project.

This module however no longer exists in D7, instead have a look at these modules which could do the same or similar:

http://drupal.org/project/references

http://drupal.org/project/Relation

http://drupal.org/project/entityreference


How to edit every node of a content type on cron run? On cron runs, I want to edit every node of a certain content type. I think this is implemented through hook_cron() but I can't find any documentation about this hook. How can I edit every node of a certain content type on cron runs?

I need this because I update content on nodes based on another website. I want the content to be updated regularly. I need something similar to feeds but the data source is just HTML not xml.

You would need to implement various hooks.

hook_cron: It will get called on every cron run. Here you could load every node in the system using node_load(), edit whatever properties of the node you need to edit, and then save each edited node using node_save().

However, note that both loading and saving a node is an expensive process, and if you have a site with many nodes, your site would become very slow, unstable, or even unusable on every cron run (which can sometimes happen as often as every 15-30 minutes). In other words, I would be very cautious with whatever you are trying to accomplish.


Cache max-age doesn't correctly expire at midnight I've got a node which cache should expire every day at midnight. Additionally I've a block showing the same node in another display mode, that also should expire every day at midnight. I thought this would be pretty easy by calculating max-age

page_cache is already disabled - dynamic_page_cache is enabled

.module file

function wt_lunch_preprocess_node(array &$variables) {
  $node = $variables['node'];
  if ($node->bundle() == 'wt_lunch') {
    $maxAge = strtotime('tomorrow') - strtotime('now');
    $variables['#cache']['max-age'] = $maxAge;
    $today = strtolower(date('l'));
    $variables['max_age'] = $maxAge; // this line is just for debugging
  }
}

src/Plugin/Block/MyBlock.php

...
  public function build() {
    $maxAge = strtotime('tomorrow') - strtotime('now');
    $emptyResult = [
      '#markup' => '',
      '#cache' => ['max-age' => $maxAge]
    ];

    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['type' => 'wt_lunch']);

    if (!$node = reset($node)) {
      return $emptyResult;
    }

    $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'special');
    $build['#cache']['max-age'] = $maxAge;
    $build['#attached']['library'][] = 'wt_lunch/daily';
    $build['#attached']['drupalSettings']['wt']['lunch']['timer'] = $node->get('field_lunch_daily_timer')->value;
    $build['#attached']['drupalSettings']['wt']['lunch']['from'] = $node->get('field_lunch_daily_from')->value;
    $build['#attached']['drupalSettings']['wt']['lunch']['until'] = $node->get('field_lunch_daily_until')->value;
    $build['#attributes']['class'][] = 'lunch--daily';
    return $build;
  }
...

This works almost every day. Almost. Every 10-15 days the cache does not expire properly and keeps rendering the block from yesterday.

Today the block didn't expire correctly again. I've previously added hidden debug comments in my Twig template, showing cache infos in the rendered HTML:

{{ date().timestamp }} ==> 1543194778 (roundabout 1am yesterday)
{{ max_age }} ==>  78422 (see $maxAge in code above, about 23 hours)

So I can verify that $build['#cache']['max-age'] definitly was correctly calculated, yet I did get the outdated block today at 11am.

Can anybody give me a clue why the max-age of the block sometimes does not work?

I believe your flaw is that if there is day where no one views a node of bundle wt_lunch your nodes max age will get out of alignment; thus, your block will also be displaying an outdated node.

For this, don't use preprocess_node, use Job Scheduler or hook_cron instead.

You might also want to utilize the above with Ultimate Cron.


Why does Drupal store the uploaded files for a content node even if the content is not created? In Drupal 7, I try to create a News, which is a custom content type, with an Image file. I upload the file (not by pressing Ajax button, but just selecting the file), and leave all the other fields (some mandatory) empty. I press Send, and I get the red errors. Even if I close the browser, the image will have been uploaded to the folder ( sites/default/files/news/images ). Even after deleting cache and running cron.php, the orphane image will be still there. Isn't it a bug of Drupal, which would have to delete those images with no associated content? The file is not reused in other content types.

I have discovered that the files are physically stored, and also in the database, there is an entry in the table file_managed with the field status with the following indication and value : 0

A field indicating the status of the file. Two status are defined in core:
temporary (0) and permanent (1).
Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be removed during a cron run.

I have manually changed the timestamp of the uplodaded file, run the cron, and the file dissapears. Obviously there must be a confident time, because if not, files in contents still being update could have the risk of being deleted. My fault for not thinking of this last point.


Print view in twig template My page--front.html.twig is working ok. I want to print the block_1 display of the recent_comments view. I tried this but it does not seem to work.

{{ view.comments_recent(block_1) }}

You can preprocess a new variable and use views_embed_view like:

$variables['my_view'] = views_embed_view('view_id', 'display_id');

So in your case:

$variables['my_view'] = views_embed_view('comments_recent', 'block_1');

And then in the twig file:

{{ my_view }}

See views_embed_view. It can also take arguments.


How do I submit a user registration form in code? I have tried to save registration data in a controller.

$values = \Drupal::request()->request->all();

     $formBuilder = \Drupal::service('entity.form_builder');
     $form = $formBuilder->getForm(User::create(array()), 'register', array());
    $formObject = new RegisterForm(\Drupal::entityManager(),
                    \Drupal::languageManager(), \Drupal::service('entity.query'));

     $form_state = (new FormState())->setValues($values);
                //$formObject->form($form,$form_state);
     $entity = $formObject->buildEntity($form,$form_state);
     $formObject->setEntity($entity);
     $formObject->form($form,$form_state);
     $formObject->submitForm($form,$form_state);
     $formObject->save($form,$form_state);

Above code produces this error:

  Fatal error: __clone method called on non-object in /home/vagrant/www/drupal8/drupal-8.0.1/core/lib/Drupal/Core/Entity/EntityForm.php on line

It seems I need to inject an "entity" before buildEntity().

How did Drupal 8 manage to create a new user? Maybe the container injected that entity some where, but I am unable to find it.

if you just want to create new user, it is easy as you create the user object and fill it and save it:

$user = \Drupal\user\Entity\User::create();
$user->setPassword($values->getValue('pass'));
$user->enforceIsNew();
$user->setEmail($values->getValue('mail'));
$user->setUsername($values->getValue('name'));
$user->activate();
$user->save();

but in my case for example I wanted drupal to do other stuff like send welcome email...etc, so what i did, instead of last step ( $user->save() ):

$formObject = new RegisterForm($this->entityManager, $this->languageManager, $this->entityQuery);
$formObject->setEntity($user);
$formObject->save($form,$form_state); // $form and $form_state can be created like you did.
// if you want to get the newly created user
$user = $formObject->getEntity();

on the other hand I have tried to get your code working, and the following was the outcome code:

$formObject = $this->entityManager->getFormObject('user','register');
$formObject->setEntity($user);
$formStateObject = (new FormState())->setFormObject($formObject);
$form = [];
$form = $formObject->buildForm($form,$formStateObject);
$formObject->validateForm($form,$formStateObject);
$formObject->submitForm($form,$formStateObject);
$formObject->save($form,$formStateObject);

Hope that helps.


Is there anyway to cross reference a view? I have View1 where I would like to add a filter which stops any rows appearing if there are rows in View2.

I thought I would have been able to execute some PHP as a filter, but I can't see any options for that.

Is there any way to use another view as a filter?

For this you could use the advance option of the view where you could add the contextual filters and relationships.
This would help you in filtration.

For php filtration you could use the Views PHP module; that would help you in your filtration.

  This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.

For information about how to use the module you could refer to README.txt of the module.


Create path alias programatically when node is created I have a custom content type that is created by a module.  Is there a hook I can use to set the path alias of my custom content type when a node is created?

One of my fields is an alpha-numeric code, and I want to use that in the path. eg.: 'event/myc0d3'

I noticed that this function (path_set_alias) existed in 6, but I can't find the equivalent for 7.  And do not know where I would call it.

Instead of using hook, Pathauto module should be used where you can define specific pattern how aliases are generated per content type (at /admin/config/search/path/patterns). In there you can use replacement patterns or code your own. It's much cleaner approach.

Otherwise you can try hook_node_presave($node) and change the alias directly:

$node->path['pathauto'] = 0; // Required only if Pathauto is enabled.
$node->path['alias'] = "foo/bar";

or use the path_save(&$path) function directly as below:

$path = array('source' => "node/$node->nid", 'alias' => 'foo/bar');
path_save($path);


Need to enter title before I make blog entry I have installed the Organic groups to make a multi-blog site. The problem is that when I try to create a blog entry, I only get a "Title"-field, which I need to save, and then edit the entry to enter the body text.

Any ideas how to fix this so I get the full blog entry fields when I click "Add content".

This is how it looks like now:

Seems like an issue with the OG field permissions Configuration\Organic Groups\OG field permission overview.

Edit the node type and check the 'Edit Body field' and 'View Body field'.


Getting a 403 error in REST & 8.2.3 has no permission set for REST for GET of content Enable modules (including REST UI):

Enable the Content in REST resources:

Give permissions on /admin/people/permissions#module-rest ??:

Request returns 403 Forbidden error:

Reference:
Getting a 403 error in REST

This is a known issue with the REST UI module. REST UI has issues with Drupal 8.2 and up. There is an open issue specifically regarding this, and a much longer discussion to look into. I'd post this as a comment, rather than an answer, but I'm a new user here. Best of luck. I'm having the same problem.

UPDATE:

I think REST UI is just a no-go for 8.2.3. Bear with me. I don't have enough reputation to post links :-/

Here is what I did to get some requests to work:

Setting up the REST configurations

In the place of step 2 above, it seems that you need to edit the yml for the entity type you're trying to change the rest configurations for. For example, the node entity would use rest.resource.entity.node.yml (look here for some help: https://www.drupal.org/docs/8/api/restful-web-services-api/restful-web-services-api-overview#practical). I've been given the impression that RESTUI really just isn't useful with 8.2+, so you gotta do it by hand. Once you've created this file to your liking, you need to import it to your site.

I still can't figure out how to do this "correctly"; I don't know if you need to use the configuration importer (which will throw a UUID error) or include it in a theme or in /default/site or what. I did get it to work. I ended up using the Features Module to create a feature package for  REST Resource Configuration (admin/config/development/features/edit), downloaded, unzipped, and installed the module created by the changes.

I then manually edited the config files in the created module's directory (DRUPAL_ROOT/modules/MODULE_NAME/config/install/rest.resource.entity.node.yml) to have the settings I wanted. Finally, I implemented the changes by updating the feature from the features config page (admin/config/development/features/ click on the "changed" next to the module you created, click on the checkbox next to the changes, and click "Import Changes").

There HAS to be a simpler way to handle the import, but it works for me on 8.2.3.

User Permissions

Once your REST configurations are set up, the entity types should follow the permissions you have set in /admin/people/permissions/. So, if anonymous users can view published nodes, they should be able to GET published nodes as well, etc. (At least, according to [the documentation][1].)

If you're still having problems, you need to make sure to include the token header usually.

The csrfToken

A GET request to the endpoint YOUR_SITE.DOMAIN/rest/session/token will provide you with a token which you can set as the X-CSRF-Token' header on your GET or POST request. A typical and simple example using jQuery to GET the first entry might look like this:

function getFirstNode() {
  jQuery
    .get('YOURSITE/rest/session/token')
    .done(function (data) {
      var csrfToken = data;
      jQuery.ajax({
        url: 'YOURSITE/web/node/1?_format=hal_json',
        method: 'GET',
        headers: {
          'Content-Type': 'application/hal+json',
          'X-CSRF-Token': csrfToken,
        },
        success: function (node) {
          console.log(node);
        }
      });
  });
}

If all else fails

I've also had success setting up GET endpoints using the Views Module. This article does a pretty good job explaining the process: http://redcrackle.com/blog/rest-export-views-drupal-8. It won't work for POST requests, but it should help.

I hope this helps. It's a really sticky problem for what should be a simple request, and the documentation does NOT do a great job of making this accessible. Good luck!


Create a X discount for every Nth product from the same category I know this is pretty complex task, I don't expect a solution, but a guide on where to start.

(Drupal 7 is in question)

I need to apply X% discount for every Nth products that are in the same category. Category, X and N needs to be imputed by user.

So far, I was able to make a rule (with fixed X, N and category) that calculates a needed total discount that needs to be subtracted from total amount.
How can I apply that number (or should I do something different?), and how to get user's input for X, N and category?

Thank you for any help.

Depending on how you've constructed your product data model, the Per-quantity category discount (% off) offer type supplied by the Commerce Discount Extra module should just work. It lets you specify how many products of which product category must be present on an order before the next one is discounted by any percentage (e.g. buy 2, get 1 free - 100% off). It's repeatable, meaning you can apply the discount any number of times on the same order so long as the right quantity is present, and you have some rudimentary sorting options - e.g. discount the cheapest or most expensive first.

If that solves it for ya, mark this answer as accepted. If you need a little more detail, feel free to add a comment and I'll help if I can. : )


How can I create a View to give me a list of nodes that share a nodereference with the User's profile? I have a "Company" node type and a "Content" node type.

In my User profiles I have added a nodereference to the appropriate Company node, and
in the Content nodes, I have also added a nodereference to the Company owning the content.

What I am trying to do is to construct a view that will present the logged-in user a list of all Content nodes owned by (i.e. with references to) the user's company.

Pseudo-sql would be something like this:

SELECT n.title FROM node n,user u WHERE
n.company_reference = u.company_reference AND logged_in_user.uid = u.uid

There ought to be a way to do this via Views, I just have been unable to figure out how, so any suggestions or pointers will be greatly appreciated

did something similar using panels and view panes. Without panels I'm not sure how I would approach it. You can create a view that lists all the content nodes. then create a display of that view that is a "content pane" (requires panels). Go into advanced, and create a "contextual filter" based on the criteria you want (in your case it would be your node reference to the company). Then click "argument input" under pane settings. you should now be able to add this pane to a panel and pass it the correct argument. I know it's a little confusing written out .... but with this setup you could for instance make a panel that shows the user, the users company, and a list of the content nodes owned by that company.

I've posted this a couple times here, only because it really helped me understand contextual filters and how you can build some pretty awesome things just using them with views and panels

http://dev.nodeone.se/en/learn-page-manager-part-5-views-content-panes-basics


List of D7 contrib modules that create and use custom tables with full Views 3 support I'm trying to understand how to properly use Drupal 7 and Views 3 to retrieve data from a completely customized MySQL table.

There are several tutorials for Views 2 and Drupal 6 (Scratching The Itch: MyWeather being a great example) but very little for Drupal 7 and Views 3.

I would like to compile a list of Drupal 7 Contributed modules that:

Define there own, custom tables.
Store data in those tables (no nodes).
Query those table using the Views 3 API.

It would be very useful as a developer new to Drupal 7 and Views 3 to see live examples of modules that implement functions like hook_views_api and hook_views_data.

You should take a look at Data & Feeds or Table Wizard & Importer.


create field group in hook_install() I am using the field_group module and want to programmatically create groups of fields in the hook_install of my module.install file.

It seems that field_group doesn't have much of an api that can be used by other modules. Does anyone know of a way that I can create a field group and assign field types to it programmatically?

The marked answer is correct here, but I can't comment on it. There's a couple "bugs" in it. The following changes were made to make it work with the object/array that gets exported when using field_group_load_field_group()

Specifically, I changed this line:

'format' => array('type' => 'fieldset'),

To:

'format' => array('type' => $group['format_type']),

And:

foreach ($group['fields'] as $field_name) {

To:

foreach ($group['children'] as $field_name) {

The final code:

/**
 * Create a field group.
 *
 * The field_group module does not come with an API that can be used by other
 * modules. This method fakes a Drupal new group form submission to create the
 * new group.
 *
 * @param  array  $group
 */
function _field_group_create_group(array $group) {

  drupal_load('module', 'field_group');
  module_load_include('inc', 'field_group', 'field_group.field_ui');

  $defaults = array(
    'entity_type' => 'node',
    'mode' => 'form',
    'parent' => '',
    // TODO: default to heaviest weight
    'weight' => '',
    'format' => array('type' => $group['format_type']),
    'fields' => array()
  );

  $group = $group + $defaults;

  $form = array(
    '#entity_type' => $group['entity_type'],
    '#bundle' => $group['bundle'],
    '#view_mode' => $group['mode'],
    '#groups' => array()
  );

  $form_state = array(
    'values' =>  array(
      'fields' => array(
        '_add_new_group' => array(
          'group_name' => $group['group_name'],
          'label' => $group['label'],
          'parent' => $group['parent'],
          'parent_wrapper' => array('hidden_name' => '_add_new_group'),
          'weight' => $group['weight'],
          'format' => $group['format'],
        )
      )
    )
  );

  foreach ($group['children'] as $field_name) {
    $form_state['values']['fields'][$field_name] = array(
      'parent' => '_add_new_group',
    );
  }

  field_group_field_overview_submit($form, $form_state);
}


views - how to filter by birthdays dependent on the current date I have the following use-case:

I have a custom content type called profile which has a birthday field (of type Unix timestamp).

I need to be able to filter all profiles that have a birthday in the interval (-3 days from now to +7 days from now). How can I achieve this using views? Do I need to make a custom filter or custom contextual filter or some other custom plugin?

Thanks a lot for your input.

Update:

So I started building a custom filter with the following:

my_module/my_module.module

<?php

/**
 * Implements hook_views_data_alter().
 */
function my_module_views_data_alter(array &$data) {
  $data['node__profile_birthday']['birthday'] = [
    'title' => t('Filter by birthday'),
    'group' => t('Content'),
    'help'  => t('Filter profiles by birthday.'),
    'filter' => [
      'id'    => 'birthday',
      'field' => 'profile_birthday_value'
    ],
  ];
}

my_module/src/Plugin/views/filter/Birthday.php

<?php

namespace Drupal\my_module\Plugin\views\filter;

use Drupal\views\Plugin\views\filter\NumericFilter;

/**
 * Basic filter handler for Birthdays.
 *
 * @ViewsFilter("birthday")
 */
class Birthday extends NumericFilter {
  /**
   * Override the original Views opBetween behavior.
   */
  protected function opBetween($field) {
    // The birthdate is between -3 days and +7 days from the current date
    $expression = "DAYOFYEAR($field) BETWEEN ((DAYOFYEAR(CURRENT_DATE())) - 3) AND ((DAYOFYEAR(CURRENT_DATE())) + 7)";

    $this->query->addWhereExpression($this->options['group'], $expression);

  }

}

I am still having issues with views not properly saving the values of min and max of the between operator. Any help is appreciated.

So it looks like a custom filter is in order. They are relatively simple to make. There are a few tutorials out there. Look up “custom views filter handler” here or elsewhere. I’ve made custom contextual filters and sort handlers several times. “Contextual range filter” and “Views Raw SQL”. You can look at the code for them on Drupal.org. I think this would be a good candidate for something worth releasing as an official module. You could call it “Anniversary Date Filter” or something.


Two Errors Lumped Into One - File Field Deleted - Cannot Be Found/Deleted/Recreated I'm in the process of adding more content types/cleaning up old ones on my site. Except I keep coming across an error that has another part which seems to differ from other questions posted to this site.

I deleted a field because it had become obsolete, named "Site Document Attachment" which was a file field. Now whenever I make any change to the site, this error puts it on hold:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table
'cocempro_portal.field_data_field_site_document_attachment' doesn't exist:
SELECT field_data_field_site_document_attachment0.entity_type AS entity_type,
field_data_field_site_document_attachment0.entity_id AS entity_id,
field_data_field_site_document_attachment0.revision_id AS revision_id,
field_data_field_site_document_attachment0.bundle AS bundle FROM
{field_data_field_site_document_attachment}
field_data_field_site_document_attachment0 WHERE (field_data_field_site_document_attachment0.field_site_document_attachment_fid
= :db_condition_placeholder_0) AND
(field_data_field_site_document_attachment0.deleted =
:db_condition_placeholder_1) ; Array ( [:db_condition_placeholder_0] => 1552
[:db_condition_placeholder_1] => 0 ) in field_sql_storage_field_storage_query()
(line 652 of /home/cocempro/public_html/portal/modules/field/modules
/field_sql_storage/field_sql_storage.module).

And I did double check to make sure there weren't any tables named that in my MySQL database, as that happened to me once before - and the field isn't listed in my field report. And playing the easy way out, I just tried to recreate the field in the exact same way, but that came back stating that the machine name was already in use.

So where to I go from here? I'd appreciate any help anyone might be able to offer in regards to this problem, because I'm not sure where to go at all. Thanks

You should, in theory, be able to just remove the references to that field from the field_config and field_config_instance tables, clear caches, and then be able to recreate the field again as if it never existed.

Please do try that in a development environment first; it's also possible, in theory, that some other non-core module has a reference to that field in some way, which may either be responsible for the problem in the first place, or cause problems when you manually remove the data.


hook_form_alter Save $form['account']['field_first_name'] into $form['profile']['field_first_name'] Hi I'm trying to save a field into another field in the same form when the form is submitted.

I've tried using hook_form_alter and checked for count($form_state['input']) > 0 to save $form['account']['field_first_name'] into $form['profile']['field_first_name']

I know you may say that I can use the profile2 module. I'm already using that. I just need to figure out how to save one field value into another field when a form is submitted.

Any help would be greatly appreciated.

Got it! In my hook_form_alter function I added $form['#submit'][]='my_submit';

Then I created the my_submit() function.

function my_submit($form, &$form_state) {
  if (count($form_state['input']) > 0) {
    form_state_values_clean($form_state);
    $form_state['values']['profile']['field_first_name'] = $form_state['values']['field_first_name'];
    $form_state['values']['profile']['field_last_name'] = $form_state['values']['field_last_name'];
    $form_state['values']['profile']['field_groups'] = $form_state['values']['field_groups'];

    unset($form_state['values']['field_first_name']);
    unset($form_state['values']['field_last_name']);
    unset($form_state['values']['field_groups']);
  }
}

The important parts of the function above to notice are form_state_values_clean($form_state); then I access the values through $form_state['values'] array.

Hope this helps someone else looking to do the same functionality.


Dynamically change views entity reference filter based on current form value Is it possible to change the result of the view depending on the value being selected on the form, node creation form without saving it first?

Last time, my problem was filtering the views depending on the field value of current node and I found the answer using

Filter View by Entity Reference Value From Current Node -

$node=menu_get_object(); return $node->field_venue_for_catering['und'][0]['target_id'];

But when I tried this on an entity reference view, it doesn't show any result unless I save the form.

The case from the link given above is almost the same for this post, the difference is filtering the view dynamically without saving the form first.

Is there anyone that will be able to help?

Thank you very much!!!

Here's my solution:

I used Entity Reference Prepopulate for my "venue" for my case (linked from my question), so whenever I choose a venue it will pass a parameter to the url.

Then I used Views Contextual Filter Query to get the value of the parameter from the URL and automatically filter the view without saving the form.

BTW, Entity Reference Prepopulate doesn't work on edit form, so you need to create a node_load function on your custom module. Check this for code reference

Then I created a code for edit link that has the param of venue and it's target id.

<?php
    $nid = arg(1);
     $node=menu_get_object();

    $l = l( t('EDIT'), 'node/'.$nid.'/edit',   array('query' => array('field_product_venue' => $node->field_product_venue['und'][0]['target_id'] )  ));
    echo $l;

?>

I hope this will of help to somebody!

Thanks!


How to avoid timeouts on real long page loads I have a few custom modules for our systems administrators where they can select a script and it will remotely execute on a remote server, let's say restart WebSphere.

I would like the results to display, however some of these scripts can take 15 minutes or so to run, I've got a busy spinner running so they know something is running in the back ground, however after 15 minutes or so the page times out, if you reload the page the results display.

I display the results via drupal_set_message() in the "submit" hook.

The Drupal Batch API is a great solution for something like this. You can specify or count the number of actions that need to be done, display a progress bar, and prevent timeouts on long processes. Also there are many examples like this one you can utilize to create a good solution for your use-case.


new admin menu doesn't display on page I followed a tutorial to create an admin menu: Adding sub menu to Management menu. However I still cannot see my new menu on my page. Then I download a module named Administration menu. I found my new menu item on the navbar when I use this module. Here is the screenshot:

All the menu in pink circle are old, the only new menu item is called "Product Substitue." But I cannot find on the page.

Does anyone know how to fix this? Or any tutorial? Thank you~

You're looking at the same information rendered in different ways:

The menu along the top is quite simply reading from the database for any link in that menu.

The page is constructing itself based on the hierarchy of the hook_menu implementation. You're going to need to implement hook_menu for your new link to get it to show on the 'page' version of the menu.


How to add javascript to theme_preprocess_user_login I have working code in my theme's template.php file that adds "autofocus" to my modal login form, but Firefox ignores ajax autofocus fields (only applies autofocus on pageload). So I'm trying to add some js to set focus when the modal login form is called. I currently add autofocus via:

function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['rendered'] = drupal_render_children($variables['form']);
}

And I'm trying to add js to set focus as a fallback this way:

function mytheme_preprocess_user_login(&$variables) {
  $variables['form']['name']['#attributes']['autofocus'] = array('autofocus');
  $variables['form']['#attached'][js][] = path_to_theme() . "/js/focus.js";
  $variables['rendered'] = drupal_render_children($variables['form']);
}

but this doesn't seem to add the js as expected. How can I add either inline or external javascript to my modal login form?

A preferred solution I would use for adding/editing forms would be to use a module hook.

function MODULE_form_user_login_alter(&$form, &$form_state, $form_id) {

  $form['#attached']['js'] = array(
    drupal_get_path('theme', 'THEME') . '/js/focus.js',
    '/* inline js here */' => array( 'type' => 'inline')
  );
}


how to convert node_uri (array) to url string I used a function node_uri($node) get an url array. how to change it to a string?

The path string is contained inside the path element of that array, so

$node = node_load(1);
$uri_array = node_uri($node);

$url = url($uri_array['path']);

should get you what you're looking for


How to replace links with images? I am wondering what is the best way to replace each of the internal links, e.g. 'Bookmark this' etc., with images?

Not really a Drupal specific question, but use CSS image replacement. I personally use the Phark revisited method, because you don't need any additional markup and you use only three or four rules to make it work (in some cases you don't need to use width).


Does you know how the CCK Private Fields module works? Any API? Do you know how the CCK Private Fields module works?
What I'm interested in is having a user who can switch all their content profile fields to private.

Is there an API that I can call to switch all the user's content profile fields to private?
Is there any better way to have a user opt-out and become basically an invisible user?
The definition I'm getting for opt-out is to never display the user in any search, browse or page.

Looking at the description page of this module, it seems that user can do what you want:

  Overview:

  This module allows users to mark administrator selected CCK fields as
  Public (visible to everyone), Hidden (visible to node author, hidden
  from everyone else) or Private (visible to node author and "friends";
  see requirements section below).

Regarding the option to "disappear" a user, I'm not really sure as there's a lot of place where a user can appear, however if you give this user a certain role, you can customize your views to exclude users with this role.


How do i search within views results? Consider i have a view which filter some Content Type according to a specific field.

I want to place a search box in the view page so the results of the view can be search able.

Is there a module? Or can i somehow do it with search api any tutorial for this?

Its not called search, it will be called filtering.

Goto your view and add a filter.

And then select the expose option in the filter.


Creating dependencies between fields in content type creation form I have two fields in my content type that I'd like to have depend on each other. The two fields are category (the dependee, a field list) and icon (the dependent field and also a taxonomy term field). They are both select lists. I want the dependent field (icon) to not be available to authors creating records in the admin interface. It should just automatically select the correct term based on the category selection above it.

I looked into 'Conditional Fields' but I'm not certain it does what I'm looking for.

Any suggestions?

If you are looking out to do this through code, you can use hook_form_alter to hide the dependent field and hook_node_presave to set the value for dependent field.


How to add reset button in webform? I tried to use below code to add reset button in webform,but its not working.I think that is not calling to "contact_form_reset" this function.Please help me out..

function cap_academy_contactus_form_alter(&$form, &$form_state, $form_id) {
       if ($form_id == 'webform_client_form_860'){
        $form['actions']['reset'] = array(
          '#type' => 'submit',
          '#value' => t('Reset fields'),
          '#submit' => array('contact_form_reset'),
          '#prefix' => '
',
                '#suffix' => '
'
        );
        return $form;
      }
    }

    function contact_form_reset($form, &$form_state){
      $form_state['rebuild'] = FALSE;
    }

You should use #button_type and #attributes onclick  like this.

$form['reset'] = array(
    '#type' => 'button',
    '#button_type' => 'reset',
    '#value' => t('Reset'),
    //'#weight' => 9,
    //'#access' => FALSE,
    //'#disabled' => TRUE,
    '#validate' => array(),
    '#attributes' => array(
          'onclick' => 'this.form.reset(); return false;',
        ),
    '#prefix' => '',
    '#sufix' => '',
);

Another option is to use Ajax like this.In the callback we can reset all form elements to default.I tried using $form_state['rebuild'] in there but it didn't work in my case.

 $form['reset'] = array(
     '#type' => 'button',
     '#value' => t('Reset all'),
     '#ajax' => array(
         'callback' => 'my_ajax_reset_all',
     ),
     //'#limit_validation_errors' => array(''),       // No validation.
);


Show node body fields for entity reference checkboxes widget? I need to show the body field of the nodes next to their checkboxes in an entity reference field widget (default is just their node titles). Is there a way to do that without writing a new widget?

You may want to try Entity Reference View Widget.

  This module provides an advanced Entity Reference widget that uses a
  view for selecting items. The view can be paginated and have exposed
  filters. It degrades, so it can be used even if Javascript is disabled


How to check condition and print a value using views-view-field--viewname.tpl.php? I'm having a view and I've created a template file for the row style output.
I'm able to access the fields using the below code:

$fields: An array of $field objects. Each one contains:
$field->content: The output of the field.
$field->raw: The raw data for the field, if it exists. This is NOT output safe.

I'm getting output for the below code:

<?php print $fields['field_some_field_name']->content; ?>

But when I'm trying to print the fields nothing is getting returned:

<?php print_r($fields); ?>

I'm also unable to check the condition for the fields:

<?php if($fields['field_some_field_name']->content == 'Test') { } ?>

I'm also unable to check the condition for the fields:

<?php if($fields['field_some_field_name']->content == 'Test') { } ?>

That is probably because in actuality:

$fields['field_some_field_name']->content =
Test

Therefore,
Test
 is not equal to Test

So what you could do is use raw instead, as raw has no html/markup around the value.

<?php if($fields['field_some_field_name']->raw == 'Test') { } ?>

else, you could still use content with the PHP striptags() function

<?php if(striptags($fields['field_some_field_name']->content) == 'Test') { } ?>

Or else, you could still use your original <?php print $fields['field_some_field_name']->content; ?> but as long as you strip all the markup added by views as shown in my answer to "Is there a more performant alternative than overriding template files?".


How to add a new field image? These are the field thats I already created:

And this is how my page currently looks like:

The first image is the background of this page.

I want to add field image on the blue line. But when I add new field of image it doesn't show the second image.

Any suggestions about how to solve this problem?

Add the field to the content type; check your node/page template, and add some code to print the new image field. If there is no custom template for your content type, create one and customize the output to your wishes.
You might also check the display settings for the content type, and make sure your image is displayed.


Fill Date field in a hook form alter with ajax callback I'm trying to populate some fields via Ajax.

Is working good with textfields, but no with date field and select list.

After the rebuild of the form the date field is empty and the select too.

Here my code:

function PORTO_SUB_form_alter(&$form, &$form_state, $form_id)
{ if ($form_id == 'datore_node_form')
{
global $user;
  $form['title']['#type'] = 'hidden';
  $form['title']['#value'] = 'test';

  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

    $form['user_copy'] = array(
      '#type' => 'button',
      '#value' => 'Sono io il datore!',
      '#ajax' => array(
        'event'=>'click',
        'callback' =>'user_copy_ajax_callback',
        'wrapper' => 'datore_node_form_prefix',
    ),
  );
  // field_group_hide_field_groups($form, array('group_azienda'));

  $user = user_load($user->uid);

  dpm($form);

  if (!empty($form_state['values']['field_cognome']))
  {
    unset($form_state['input']['field_cognome']['und'][0]['value']);
    $form['field_cognome']['und'][0]['value']['#value'] = $user->field_cognome['und'][0]['value'];
    $form['field_nome']['und'][0]['value']['#value'] = $user->field_nome['und'][0]['value'];
    $form['field_luogo_di_nascita1']['und'][0]['value']['#value'] = $user->field_luogo_di_nascita1['und'][0]['value'];

    $form['field_data_di_nascita1']['und'][0]['#date_items']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#date_items']['value']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#date_items']['value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#default_value']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#default_value']['value']['#value'] = $user->field_data_di_nascita1['und'][0]['value'];
    $form['field_data_di_nascita1']['und'][0]['#default_value']['value'] = $user->field_data_di_nascita1['und'][0]['value'];
return $form;
}

function user_copy_ajax_callback($form, &$form_state)
{
dpm($form['field_data_di_nascita1']['und'][0]['#default_value']['value']);
return $form;
}

Here the solution finally:

https://www.drupal.org/node/1984838#comment-11736060

I had to fill both $form and $form_state values...

$form_state['input']['your_field_to_change']['und'][0]['value'] = $new_date;
$form['fyour_field_to_change']['und'][0]['#default_value']['value'] = $new_date;


Admin page for every special page I'm creating a web site in Drupal 7, there are home page, and three main taxonomy pages(they are primary links), the client is asking, to tell the truth they are insisting on me to make custom admin pages for every primary pages, sounds like primitive but they want to control every part of the main pages manually. How can I handle this task? I've already created these pages with views. Has anybody faced before with this type of issue?

I'm not sure exactly what you mean by "custom admin pages", but to give complete control over the layout of the content you could use Panels and perhaps also Panelizer.  The Panels in-place editor is probably enough for the client's needs, but you might show them the backend editor instead because it looks (and is) far more powerful/complicated.  It may even have the benefit of scaring them away from having the control themselves and asking you to go back to your original plan.

EDIT:

Here's how I would go about this using Panels, Views, Rules, and Flag.  This may not be the most optimal way, but it uses well-supported modules.

Make a panel for the home page.
Make a flag for each section that needs to appear on the home page.
Make a view (content pane) for each section.  The view should display the most recent node tagged with the flag for that section.  Add each view to the appropriate place on the home page panel.
Add a rule that, when a node is flagged, uses the trim flag action to ensure that only one node is flagged with that flag at any given time.

If you do this, your content editors can simply flag the pages they want and they will be displayed in the appropriate sections automatically.  (I have used all these modules to do a similar thing in the past, though I have not built this exact workflow.)


How to add custom stylesheet to print pdf output? I have a view, displayed as table on single page.

HTML print view looks ok (I want border on every td), but it seems that I can't apply any styles to print pdf, I try to use HTML attributes and it seems, that only this is changing appearance of generated PDF.

Any chance to use CSS files to theme PDF output?

I am using Print module with additional PDF module (https://drupal.org/project/Print)

PDF library: tcpdf

EDIT

I just used old plain table attributes and it works inside PDF

One of the benefits mentioned on the PDF using mPDF project page is "Add custom Style Sheet to PDF". Here are some more quotes about this module (from the module's project page):

  ... used for Conversion of HTML pages to PDF documents using mPDF PHP Library. It allows you to generate a pdf document of any node.

  Features

  PDF creation (www.example.com/node/nid/pdf) where nid is the node id of content to render.
  PDF generation API is provided, the content developers can use this API to generate a PDF document.
  By creating your own CSS file and/or the node.tpl.php template files, it is possible to change the look of the output page to suit your taste.

  Benefits

  Document Properties
  PDF Page settings
  Watermark Image/Text
  HTML Header & Footer
  Password Protected PDF
  Add custom Style Sheet to PDF
  Enable/disable PDF generation for each Content type
  Display/ hide any fields of Content type for PDF


Missing external file In my site, I'm getting a 404 error (http://www.site.com/&mch57a). I'm guessing it's a problem with a module. Is there a way to trace where this call is coming from, other than disabling modules one at a time? I do have the devel module.

Thanks for the help

I think you need to look at URL aliases under configuration/Search and metadata or look it up in the url_alias table in the database.

Worst case scenario, try to search "&mch57a" in the entire database, to see which module is generating it.


Same module with different versions in several places This the directory structure of my drupal 8 installation:

├── composer.json
├── composer.lock
├── drush
├── LICENSE
├── load.environment.php
├── phpunit.xml.dist
├── README.md
├── scripts
├── vendor
└── web
    ├── autoload.php
    ├── core
    ├── index.php
    ├── modules
    │   └── custom
    │       └── xyz (version 1.0)
    ├── profiles
    │   └── custom
    │       └── qwer
    │           └── modules
    │               └── custom
    │                   └── xyz (version 1.1)
    ├── robots.txt
    ├── sites
    │   └── example.com
    │       └── modules
    │           └── custom
    │               └── xyz (version 1.2)
    ├── themes
    ├── update.php
    └── web.config

Which version of xyz module "win" in this structure ? For example:
- A site installed with qwer profile (sites/example.com).
- A site installed without qwer profile  (sites/example.com).
- Another option ?

I would like to know the preference that Drupal has when it have the same module with different versions in several places

If each copy of the module in the directory structure is in fact a different version (the module's .info file must specify a version number), you can inspect the version listing either via Drush or on the modules listing (install) page.

Version Listing from the Modules Listing page

Navigate to /admin/modules
Find module "xyz" and expand the
description section to reveal which version is being
detected/loaded.
Refer to the example screenshot below, where
Activity Tracker has been expanded.

Version Listing via Drush

Run 'drush pm-list --no-core --status Enabled' to show a list of all modules other than those included with Drupal Core.
Scroll through the list to find your custom module and note the version number in the right column.
Refer to example screenshot below.

What if there are no version numbers, or they are all the same version?

Temporarily modify the version number in the info file.
Push the updated code to your server (if not a local copy of the site).
Flush Drupal Cache, rebuild the registry.
Follow the instructions above to detect which one is used.
Reset the version number and push the updated code to your server (if not a local copy of the site).

Drupal Multisite Note:

If you are running Drupal Multisite, each site with the custom module enabled may be referencing it from a different path (depending on where the module was located at the time the site was being built).

In this situation, check the versions on each site using the instructions above.
Find the most updated version being used so that you can consolidate all the other sites to use the same version/instance.

Consolidating duplicate instances of the module

Since this is a custom module, be sure to check that the functionality provided between versions is in fact the same and that there is an upgrade path between them before consolidating. Sometimes, lesser experienced developers will copy a custom module and completely overhaul its functionality for use on a similar or different site without understanding best practices.

Backup your code and databases, just in case you need to rollback.
Remove older versions/unused copies, ideally keeping/moving your one copy of the module in /web/modules/custom/.
Push the updated codebase to your server.
Clear caches and rebuild the registry.
Run update.php or drush updatedb to ensure any update hooks for the module are applied.
Test the functionality the module provides on each site (for some custom modules, you may need to edit/resave the configuration settings for the module to properly function).
If all is working, it's recommended to create a new restore point backup; otherwise troubleshoot until you get it working or rollback.


How to put Inline Entity Form in another form (without widget)? My end goal is to put the Inline Entity Form inside of a custom widget, and have it submittable without submitting the parent form inside of which it has been placed.

I'm not sure how to do this programmatically.  I looked for an example in the tests/ subdirectory of IEF, and found a form like this:

$form['inline_entity_form'] = [
  '#type' => 'inline_entity_form',
  '#entity_type' => 'node',
  '#bundle' => 'ief_test_custom',
  '#form_mode' => $form_mode,
];
$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Save'),
];

But if I take this code and put it inside an existing form via hook_form_alter or a custom widget, it will submit the entire form, when in reality I just want it to save the values for the reference.  I also tried to experiment by putting a rendered form into an iframe, but it wouldn't load the form code inside it.

$form = \Drupal::formBuilder()->getForm(\Drupal\user\Form\UserLoginForm::class);

$ief = [
  '#type' => 'inline_entity_form',
  '#entity_type' => 'node',
  '#bundle' => 'article',
  '#default_value' => \Drupal\node\Entity\Node::load(1),
  '#form_mode' => 'default',
];

$element['inline_entity_form'] = [
  '#type' => 'inline_template',
  '#template' => '',
  '#context' => [   // Tried the above with & without |escape
    'ief' => $form, //<--tried both $form and $ief here.
  ],
];

Is there any example of doing this that I can look for, or any suggestions or which direction to look?

i would do it via ajax submit handler. yes you will recieve the full node but you can just take the necessary values and save it directly yourself.

see this post for how to do ajax in forms: ajax_example_add_more - Drupal 8


Module css not displayed I have created a custom module for Drupal 7 that displays a block, and I would like to add some CSS. The problem is that the CSS is not working.

This is the module code.

/**
 * Implements hook_block_info().
 */
function filter_search_form_block_info() {
  $blocks['filter_search_form'] = array(
    'info' => t('Filter Search Form'),
    // 'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function filter_search_form_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'filter_search_form':
      $block['subject'] = t('block Title');
      $block['content'] = array(
        '#markup' => '

          <form id="filter-search-form-form">

              <input type="text" class="form-control form-text" name="txt_search">
                ' . t('Brigadista') . '
                <input type="checkbox" class="form-control" name="chk_brigadista">
                ' . t('Fuente Documental') . '
                <input type="checkbox" class="form-control" name="chk_fuente">
                ' . t('Encuadramiento Militar') . '
                <input type="checkbox" class="form-control" name="chk_encuadramiento">
                <input type="submit" value="' . t('search') . '">

            </form>

',
          '#attached' => array(
            'css' => array(
              drupal_get_path('module', 'filter_search_form') . '/css'
             ),
             'js' => array(
               drupal_get_path('module', 'filter_search_form') . '/js/'
             ),
           ),
         );
         break;
    }

    return $block;
}

This is the module .info file.

name = Filter Search Form
description = Module that create a Block for Filter Search Form, form with checboxes to filter search.
core = 7.x
package = CUSTOM

scripts[] = 'js/filter_search_form.js'

stylesheets[all][] = css/filter_search_form.css

These are the CSS styles.

#filter-search-form {
    float:left;
    background-color:red;
}

Why aren't the CSS styles applied to the module output? I cleared the cache with drush cc all.

The structure is:

css/

filter_search_form.css

js/

filter_search_form.js

filter_search_form.info
filter_search_form.module

You may need to rename the CSS file.

  The word "style" can not be used in the name, like "myown_style.css".
  It will conflict with the default style.css. Anyhow, myownstyle.css
  will work.

See Adding style sheets from .info files for more details.


Feature with Content Types is not reverted I am stuck watching the Feature state as Overriden. I tried different solutions as:

Disable and re-enable the feature
Restart apache to ensure the APC cache is cleared
Clear All caches from Drupal administration

But I get stcuk with the overriden state.

Doing a Diff within the Diff module, I see the following differences:

But if I check the current feature code the Line 732 doesn't seems to be the same as the Diff module is detecting.

So I don't understand where is the difference.

I do the revert of the feature, clear cache, ... several times, and the Feature is always on Overriden state.

Please, any idea to discover the reason why I can't do the revert and a solution to perform the revert?

Please check whether there are two copies mistakenly placed inside drupal modules. Just recreate the feature with a new name and a version number. Download new feature then disable current feature and remove module completely from source. Then make sure the feature is completely removed and not appearing in the module list. Then add new feature and see.


Trigger custom code on existing Webform Submissions I have created a custom Webform handler which submits the Webform data to an external webservice via SOAP. All is working but now I need to submit (to the same external web service) all the older Webform submissions that were received before I enabled my custom handler.

My current custom handler has my custom SOAP code wrapped in the function

public function preSave(WebformSubmissionInterface $webform_submission)

(I'm using the preSave function as the Webform is a multipage form.)

I was just wondering what function I should use to run the same SOAP code on existing submissions?

As I know the range of submission ID's that are affected, is there code that can loop through the submissions and trigger the code based on the Submission ID?

Or alternatively, as there only about 20 of the older submissions, I could open and save each one to trigger a Handler based on submission update - in which case, what is the function call I need to wrap my SOAP code in the custom handler?

Thanks

F

Just install devel php run your code and then uninstall it.
https://www.drupal.org/project/devel_php  As it is great for quick adhock tasks.

but yep keep back up of your database ect.


How to show users with the same term? I added a term reference field (field_department_term_ref) to user entity (/admin/config/people/accounts/fields), then I need use Views to list all the users with the same term as current logged in user (including current logged in user himself). I referenced this post, But unfortunately there are 2 differences:

Contextual filter "User: field_department_term_ref" can not get the right default value.
If I don't select the "Exclude" checkbox in the MORE section, it will only show current user himself; if not, it will show others users but no current user.

By default it provides a way to pass the term from current node and not from user. But there are two different ways to do this :

By Custom Code : Get the term id using $user variable and pass term id to the views_embed_view function which is used to render the views.
Create two views :

First view : User list with contextual filter term field that is added in account settings.
Second View : User view with contextual filter uid that filters the
current logged in user.

-- In field section add term id field and
exclude it from there.

-- Next field would be the first view  which
prints the list of users by taking the term argument.

-- Pass the token
of tid in argument section of view field.

To add a views as a field you need a module : Views Field View.


Google Analytics custom dimension for anonymous/authenticated users I use Drupal 6 and Google Analytics module. I'd like to have custom dimensions to add segmentation for anonymous/authenticated users. I have added a custom dimension with [user-role-name] token. But I have a lot of roles for authenticated users, and then I get a long list of roles in GA data. I'd like to have only anonymous vs authenticated.

Is there anyway I could filter it with GA module in order to send only this two roles names?
Thanks.

There currently isn't a role token that provides only a anonymous/authenticated role. The only way to do this (without removing all roles) is to create your own custom token to use with GA.


How does Drupal find contributed modules and themes? I have a development site with a peculiar problem  Although the contributed modules and themes are in their proper place under sites/all/modules (& themes) I am getting an error message that says that my custom theme cannot be found.  Also, the modules list does not include any of the contributed modules.

The error message indicates that it does not find my default theme:

  Notice: Undefined index: CR_Stark in drupal_theme_initialize() (line
  100 of /example.com/includes/theme.inc).
  Notice: Trying to get property of non-object in
  _drupal_theme_initialize() (line 145 of /example.com/includes/theme.inc).

While I would assume that the relative locations of these custom directories is hard coded in Drupal core, the fact that it cannot find the modules when they are in the correct place suggests that there may be a missing variable or setting.  I have checked the sites/default/settings.php file and looked through the variables table in the database, but cannot find a reference that would serve this purpose.  Can anyone point me in the right direction?

EDITS:
per suggestions in comments:

Caches have been cleared frequently without change
Changing to a default theme removes the theme error, but it is replaced with an error I believe is tied to not knowing where the custom modules are.

  Warning: opendir(sites/all/modules): failed to open dir: Permission denied in file_scan_directory() (line 2034 of example.com/includes/file.inc).

Line 2034 is in the core function file_scan_directory () and reads if (is_dir($dir) && $handle = opendir($dir)) {; so it looks like Drupal is searching for a custom module (or theme) directory it cannot find or access. The directory access settings are correct.

The directory settings in the systems table are correct and the contributed modules and theme are all included.

This may not be the solution, but it is one resolution, of a sort.

I recreated the site from scratch with a new core install and copied all of the contents of the sites/all/... directories to the new site.  I then imported the entire database from the affected site into the new one and ran update/php.  This new site is seeing everything fine.  These dev sites are being run on a virtual box running Ubuntu.  It may have had something to do with settings on the directories from the OS, but I could not find it.

If anyone else has had a similar problem and found a source for the problem, please post it here.

Based on the error message you are getting, "failed to open dir: Permission denied in file_scan_directory()," I would assume that directory access settings are in fact not correct. The user running your webserver can apparently not open sites/all/modules. The best way to check this is to actually switch to the user running the webserver and try to open the directory. A common example would be a user named "apache" for the apache httpd.

On a Linux/OSX system one would often run the following command to accomplish this, though it could vary if your distribution already has a default shell for the user, or supplies a different one from bash. The example is from ubuntu, assuming you are using a normal user account with sudo privileges.

sudo su apache -s /bin/bash

How to do this in Windows I don't know, though I assume it's possible.