Logins with port numbers not including ports on redirect/login We recently upgraded our site to use Drupal 7. Previously we were using Drupal 6. In the testing phase, the Drupal 7 instance was available at ports 8000 and 8443 of the main domain, while Drupal 6 was on the defaults, i.e.:

Drupal 6: http://www.example.com
Drupal 6 secure: https://www.example.com (443)
Drupal 7: http://www.example.com:8000
Drupal 7 secure: https://www.example.com:8443

That worked fine for the testing phase; we were able to log in to each site and restrict D7 access to our internal network. Once we went live, we switched the ports, i.e.:

Drupal 6: http://www.example.com:8000
Drupal 6 secure: https://www.example.com:8443
Drupal 7: http://www.example.com
Drupal 7 secure: https://www.example.com (443)

This is working in terms of production traffic, so the new D7 site is working fine. However, when we try to log in on the old D6 site for reference, we're redirected to and logged in on the D7 site. That is, operating to https://www.example.com:8443/user and logging in results in being directed to https://www.example.com/user/foo/bar, successfully logged in. Going back to the D6 site (on 8443) shows that we are not logged in there.

I thought it could be related to the cookie domain we were using (.example.com), which seemed a stretch, but removing that didn't help. I also thought it might be a base URL problem, though we have no base URL configured. The secure pages base URLs are configured with the port numbers.

Does anyone know or have an idea as to why this is happening?

I have a feeling that it's a simple thing I've overlooked in our configuration.

HTTPS is enforced on both sites by the Secure Pages module.

EDIT: we think we narrowed it down to the login form submission. The form appears to be submitted to the main domain, without the port. That's logging us in on the wrong site and preventing us from logging in on the D6 one. Why the form would submit without the port and how to fix it is now the issue.

Check if anything in this list of typical things might help:

Check if you get the same problem using another browser. If with another browser it works, then it might be a cookie problem. To solve that, delete the cookie in the browser where you have the problem.
Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Make sure the value of "base_url" is set correctly in your settings.php (for D7) and settings.php (for D6).


Blanket CCK Field Permissions for Specific Content Type? I am creating a rather large (100s fields) form using CCK. I would like access to edit the fields to be give to anyone who has access to create the content type rather than by role.

For example, I can allow an anonymous user to edit the field_phone using user permissions, but I do not want the anonymous user to have such permission on other content types, only the custom form.

Also, since there are 100s of fields, managing the edit permission individually kinda drags.

thanks, tom

"Editing a field" can mean a lot of things because a field has many properties for input ('widget'), storage and output ('formatter'). That's why I was trying to figure out what you're after.

If you can write PHP, anything is possible, but I think that introducing a way for content creators to edit (a limited set of) field settings, would require a lot of custom code. However I assume that you're looking for a solution that requires no (or a little) custom coding. In order to achieve that, you may need to choose an alternative solution, like a custom compound field, CCK Multigroup or Webform. However I cannot advice you about that because I don't know which problem you're trying to solve.

On a more theoretical level, I think you have to be careful not to get content and configuration mixed up. Drupal stores both configuration (like field settings) and content (the information in a node) in the database. What you're asking sounds as if editing the field settings would in fact become another way to enter information. That may not be a problem now, but it can become a problem later because other modules are not prepared to access field settings as if they are part of the content.


Using a vocabulary term as a panel wildcard I want to create a frontpage Panel Page that shows Views according to a Vocabulary Term Name in the url, like so:

frontpage/persons
frontpage/companies
frontpage/institutions

That way, I've configured my Content Panel Views to show content by that category.

The thing is, when I create my Panel Page, the only terms I can pass are:

Taxonomy term (multiple): ID
Taxonomy term: ID
Taxonomy vocabulary: ID

And I need something like taxonomy term: machine name, but it doesn't appear within my options.

You can set a validation rule to convert your term name into a term id within your view as a contextual filter, and then pass the term name through the page.


How to make a responsive theme in Zen 5? Modules and procedures to keep or to leave from older Zen versions I'm using Zen theme back from 2007, when Drupal 5 comes out (anyone remembers those subtheme directories put into the main zen directory?). Thanks to this theme reliability and awesome community, the small team I work in completed several projects for customers in Drupal 5, 6 and 7. Since the theme base is standard, projects change hands smoothly and common solutions were standardized internally.

Now, customers start to get more demanding about mobile devices and building a separate theme or a simple alternate stylesheet for mobiles is not enough anymore. "Responsive" become a term used by the marketing people too. And here starts our problems as developers.

A video from July 2012 by Palantir is a good starting point, and the Responsive web design handbook is extensive. Maybe, too extensive. The number of new concepts is overwhelming (to me).

Compass, SASS, the use of a Ruby CSS preprocessor (compass) running as a server to generate CSS files from SASS, and not to improve loading times by the client are some of the new design concepts implemented through Zen Grids. Respond.js and HTML5 shim seems to be new retrocompatibility concepts. Zen Grids seems to be able to do most of the work Panels and templates used to do.

Anyone here started from a previous Zen theme and set of tools like view blocks, Panels and Mini panels, field templates, conditional stylesheets and now have successfully changed the working method to adapt to Zen 5 new features? What should I keep and what should I have better to forget after entering in the Zen 5 world? Here some tools that seems to make obsolete some old companions:

Field / view field templates > Fences?
Panels > Zen grids?

How blocks and views will adapt in this new approach, looking for responsiveness? How navigation? I used awfully a lot Menu Block and now I see responsive menus like this popping out. Conditional stylesheets are something I can forget of because of Compass? How can I adapt user-loaded images through IMCE / TinyMCE?

I don't want to use old, unfit tools in a new environment, so what's the best, practical approach while selecting modules and designing the theme from a "old school" Zen enthusiast point of view in your experience? Priorities for my team is to keep low the number of contrib modules and identify a standard process to create quickly complex responsive layout for nodes and for views keeping code as clean and maintainable as possible. Thank you very much.

I would avoid getting confused.  Zen Grids is not the same as the panels module.  The fences module just makes it easier to override the default field html output.  The responsive menu you showed is just css and a media query.

A little zen might help also, take a deep breath and repeat after me, "It is all just css."


Webform submission edit - redirect after edit I have a webform where I expect users to edit their submissions from time to time.  I want to redirect users upon submission of the submission edit to another node - say node/2 - (back to another node which lists their previous submissions in a view).  How can I acheive this redirect?

Note - this is not about redirecting after the initial submission of the webform.  It is about redirecting after editing an already existing submission.

try using rules module, it has a full featured of triggering actions with conditions like content type, user roles, ... etc.

Take a look at the documentation if needed.


SearchApiException while retrieving config files of Solr server solr_server server SearchAPI in Drupal7 with Apache Solr on Jetty was working ok in Windows, however when I moved the installation to Linux, I'm getting this exception in Drupal log:

SearchApiException while retrieving config files of Solr server solr_server server: "0" Status: Request failed: Permission denied in SearchApiSolrConnection->checkResponse() (line 536 of .../search_api_solr/includes/solr_connection.inc).

I can see that Apache Solr is accessible in Linux by the link:
http://localhost:8983/solr/#/~cores/drupal7

But not accessible by Drupal Search API for the Solar service URI:
http://localhost:8983/solr/drupal7

With the same links everything worked well in Windows. I'm not sure what permission is missing in Linux and would appreciate any insight on this.

I found this question when I started with the same problem (in my case a Debian server we manage vs a RedHat we don't) and did not see the answer (due to how short it was). After a lot of digging I realized the problem was SELinux (which is the same given the answer I now see above).

The main reason for the puzzle was that the requests did work from command line ("wget -O - {your SOLR ping URL}" worked just fine). But we learned from a Drupal thread (https://www.drupal.org/node/1473368) that recommended to test if SELinux was running:

sestatus
getsebool -a | grep httpd

The reason for it to fail normally is that "httpd_can_network_connect" is off. You can set it on by doing: setsebool httpd_can_network_connect=1

By the way what point us in the right direction was trying to use the same API call drupal_http_request() on a different module. We enabled/used Aggregator to pull an RSS feed (which worked), but our call to the SOLR ping show result "-13 Permission denied" on the log.

Hope this helps as a shortcut for the next person with this issue!


Change the google marker icon on Geofield module I need to change the default google marker icon on geofield displayed in my view for a custom marker. I tried adding style google map module but it didn't work. Any idea how to do it?

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
Note: Uploading custom markers should be possible also, similar to what you can see in the screenprint in the feature request about Custom markers.


Export watchdog to CSV I would like to export everything in the watchdog table to a CSV file occasionally using hook_cron(). I do not have access to PHPMyAdmin and don't want to waste time with modules like so.

Right now, I have all records for the watchdog table, but I can't figure out how to format messages properly.

$log = db_query("SELECT uid, type, message, variables, severity, location, timestamp FROM {watchdog}")->fetchAll();
dsm($log);
// Output: "message => '%type: !message in %function (line %line of %file).'"
//         "variables => 'a:6:{s:5:"%type";s:6:"Notice";s:8:"!message";s:27:"Undefined index:..."

How the heck am I supposed to replace symbols in $log['message'] with what's in $log['variables']?

I have tried using t($log['message'], $log['variables']) and format_string($log['message'], $log['variables']) but this won't work.

Rather than "waste time" with modules, I'll spend a little time looking at how a module like https://www.drupal.org/project/views_watchdog handles something I want to do.  Turns out it's like so...

function views_watchdog_format_message($message, $variables) {
  return $variables === 'N;' ? $message : t($message, unserialize($variables));
}


Code for group programatically fields on edit form similar to Flexifield I am looking how programmatically to group fields on edit form similar to Flexifield.  The idea is group in the edit form some fields unlimited.  I want to group the fields like as shown in the next link:

http://blog.merge.nl/2009/08/05/multiple-fieldsets-cck-multigroup

I have tried the Flexifield module but has a lot of errors and poor support.

I am working with drupal 6.x.

Thanks very much!!.

Have you tried the first link on that page? To the dev version of CCK? I just had to do this very thing this morning. The dev version of CCK has an additional module included with it called multigroup. You create a new field of the multigroup type, then add all the fields you want to include in it. Set the number of repeats on the multigroup to unlimited, and you (or your users) can then add as many groups as necessary.


Retrieve GET request from Block Plugin I'd like a block plugin to display content dependent on a GET request.
Inside my block plugin I have

class BlogPage extends BlockBase {
    public function build() {
        $query = \Drupal::entityQuery('node')
            ->condition('type', 'blog_post')
            ->sort('created', 'DESC')
            ->range(0, $range);
        return $query;
    }
}

I'd like to make $range retrieve info from a GET request. For example I'd like
127.0.0.1/page?range=5 to make $range = 5.
I've tried

$range = Request::get('range');

But that does not work. Is there a way to return the values in a GET request from inside the block plugin?

You need to get the current request object first:

$request = \Drupal::request();
$range = $request->get('range');

Or

$range = \Drupal::request()->get('range');


How to set the number of front page's promoted nodes? Is it possible to set the number of front page's promoted nodes and thus display a pager?

Configuration -> System -> Site Information

In the Front Page section there is an option for 'Number of posts on the front page'


How to change the view for a rendered product? I'm learning Drupal Commerce with a Commerce Kickstart installation. I understood in part the way products are displayed, with variation types and content types.

Have made some changes like visible/hidden product fields, and change the order product fields are displayed.

I would like to modify the position of the image to be on the left side and title, description and Add to cart button should stay on the right side.

How can I do that?

You have two high level options: 1) create page templates for your product displays in the theme layer that include the markup your CSS needs to position things or 2) use a module like Panels that lets you build page layouts from within the Drupal admin UI itself. (I'm assuming this is Drupal 7, but if you are on Drupal 8, you should give the core Layout Builder module a try vs. Panels.)


Wrapping a field value with I am using  the Drupal 7's Bartik theme.

It wraps with <p> the content-type fields that are set as "long text," but not the fields that are set as "text."

Where do I change this so that it wraps every field with <p>?

node--<content-type>.tpl.php

Check out the discussion for how to active template suggestions at the theme level: Drupal 7 page template suggestions.


Change views exposed filter value only on page reload Is there a clean way to alter a View exposed filter field, but only on page reload and not each time you submit the exposed filters form ?

Example

I have a View with exposed filters. When a user is loading this View, I want to change the value of an exposed filter field, depending on a cookie value.

I've managed to make it work with the hook_form_views_exposed_form_alter function.

function HOOK_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form['#id'] == 'views-exposed-form-MY-VIEW') {
        $cookies = \Drupal::request()->cookies->all();
        if (isset($cookies['MY_COOKIE'])) {
            $form['MY_FIELD']['#value'] = $cookies['MY_COOKIE'];
        }
    }
}

Problem is : if the user manually change the exposed filter and submit the form, the value is getting back to the first one because the hook_form_alter is getting called again.

Here is a video : https://imgur.com/EmVha6e

Poor solution

I've found a solution, but it doesn't looks like a good one. I've found out that when the hook_form_alter is getting called by a submit, there is a new entry ('a' => '') in the UserInput array that you can find by calling $form_state->getUserInput().

First load :

[
    'MY_FIELD' => 'All',
    '...' => '...'
]

After submit :

[
    'MY_FIELD' => 'New value',
    'a' => '',
    '...' => '...'
]

So now I can use the following to change the field value only on the page load :

if (isset($cookies['MY_COOKIE']) && !array_key_exists('a', $form_state->getUserInput())) {
    $form['MY_FIELD']['#value'] = $cookies['MY_COOKIE'];
}

But I'm not even sure it is fully functional, is there a better way to do it ?

Clean solution

Thank's to @NoSssweat, here's a cleaner solution :

function MODULE_views_pre_build(ViewExecutable $view) {
    $request = \Drupal::request();
    $is_ajax = $request->isXmlHttpRequest();
    if (!$is_ajax) {
        $cookies = \Drupal::request()->cookies->all();
        if (isset($cookies['MY_COOKIE'])) {
            $view->setExposedInput(['MY_FIELD' => [$cookies['MY_COOKIE'] => $cookies['MY_COOKIE']]]);
        }
    }
}

Just added a video link to show you : imgur.com/EmVha6e

You just need to add a conditional to check if it's not ajax

   $request = \Drupal::request();
   $is_ajax = $request->isXmlHttpRequest();
   if (!$is_ajax) {
     // code that sets the filter initial value
   }

Credit: How can I detect AJAX request inside Drupal?


How can I switch back and forth between globally installed Drush versions? I installed Drush 8 using cgr (which is a safer replacement for composer global require):
cgr drush/drush:8.x-dev --prefer-source

But now I also want to install Drush 9 for certain sites. Is there a way to switch between Drush 8 and 9 easily?

As you probably know newer Drush versions have to be installed locally. Go ahead with installing Drush 10 (Drush 9 is EOL) for certain sites. The globally installed Drush acts as Drush Launcher and will find local Drush installs.


How to make menu badges count disappear after the page is viewed? With reference to my previous question which was a little confusing or I should say it was mixed up with two different problems. I am posting my question again with clarification.

I have created a view, which shows activity logged by Message module. I then created a menu badge using menu badges module which shows the numbers on the menu item. - In start, when there is no activity, it shows 0, After there is new activity, say 2 new activities, the number changes to 2, which is correct, but when the page is viewed the count remains the same and does not decrease or disappear i.e 2, which is wrong. This is the problem. When the page is viewed, the number must disappear until and unless there is new activity.

Currently I am using Message:Message ID in the field to count. I have 3 different message types and I am showing it in one view. Actually, I am trying to create a notifications system. When, the user you are following does some activity, you will be notified.

Coming back to issue. For example, the menu badges module comes with a default badge for the private messages module (it allows users to send/receive messages to/from each other). It is working perfectly as the badge disappears when the users reads all the private messages and it reduces as well. Private messages module does not provide a view so i cannot see how it is working with the menu badges module.

Extra clarifications:

if the user visited the page containing the view that shows 2 rows corresponding to those 2 new activities, then both of those 2 new activities should no longer be included in the counter for its menu badge.
I wont use a pager. All items will be listed on the same page.
We only want menu badges to show count of new activities which the user haven't seen yet i.e the user haven't visited the page containing the activities-logs/notifications. Simply, when the user visits the page, the menu badges count must disappear.
Visiting the page means user has seen the notifications/new activities and now the count should not be visible as there is no new activity. As it happens on stackexchange websites: when you click the notification, the count disappears.

To make the Menu Badges counter disappear when visiting the page at notifications/new (as in your question), is something you can do by using a special feature of the Rules module, i.e. a technique that is similar to what is described in the answer to "How to execute VBO list of nodes in Rules on After updating an existing user account event?". Read on for more details about the steps to be completed, specific to your question here.

Step 1:

Create a VBO view of your unread messages, similar to what is described in my answer to "How to allow users to manage their own Message Stack messages?".

Step 2:

Create a custom Rules Component that will execute the VBO list of unread Messages, and which looks like so:

{ "rules_mark_all_unread_messages_read" : {
    "LABEL" : "Mark all unread messages read",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "views_bulk_operations" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "user\/\\d+\/messages\/unread",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "views_bulk_operations_action_load_list" : {
          "USING" : { "view" : "messages_by_user|page_3" },
          "PROVIDE" : { "entity_list" : { "unread_msgs_list" : "A list of unread messages" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "unread-msgs-list" ] },
          "ITEM" : { "current_msg" : "Current message" },
          "DO" : [
            { "component_rules_flag_a_message" : { "message_to_flag" : [ "current-msg" ] } },
            { "drupal_message" : { "message" : "The message with ID [current-msg:mid] (created [current-msg:timestamp]) was marked as read." } }
          ]
        }
      }
    ]
  }
}

Some more details about the rule above:

Rules Event: Drupal is initializing
Rules Conditions:

only for authenticated users.
check if the path being visited is user/%/messages/unread (adapt this path if you use another path).

Rules Actions:

Create a list of unflagged messages.
Loop over each of the unflagged messages found, and flag those messages.

This rule also performs an extra "set message" action, so that you can see what it does if you want to try it in your own site (it shows a message (oeps!) for each message being flagged). Remove that message after QA-testing if you want.

That's it, works like a charm!

Note: this solution can also be used in combination with the solution detailed in the related answer. So maybe you want to set a special permission if you want to combine both solutions, so that admins only can mark selected messages as read or unread, if needed.


Replace pages with static HTML pages I have a drupal 7 driven website.
I need to replace a handful of pages on that website using static HTML without impacting the URLs of those pages.

For example I have a page accessible at: example.com/services/
That page is a proper drupal driven page. I want that page to display a proper HTML page I've written from scratch without any input from drupal engine but still retain the same URL so anything that leads to that page (internal & external links) would continue to work.

What's the correct way to set that up.
Thank you!

lets say your url is : example.com/services , and services is 1 content type of drupal , and if you want to replace whole page with static html them create services.html page on root folder of your drupal and add whole html inside it and then run url it will display only html added in that html file.

Note : this html file name must be same as url , if url is example.com/abc then file name should be abc.html

Hope this helps you.


How do I include linked data to a Page in Page manager? Given two pieces of data, for example two entities, two nodes; when viewing one of them, how do I pull in data for the other one into Page manager/Panels?

In the image below, one can see the Context settings for a particular Page variant. Under Contexts, one can also see Relationships.

Relationships are what one uses to tell Page manager to pull in more, related, data, based on the arguments that the page is built around.

With two nodes related to each other with a reference field, and the base node being supplied through the URI on node/%nid, we can add Node from reference as seen in the screenshot below.

Further content types (and other options) will now be available in Panels for display.


How to list nodes and have them grouped by Day / Week / Month? I have an event content type that has a date field (the time the event will take place)

I like to list these events and have them grouped by Day / Week / Month
I dislike the calendar layout, it is too messy

Any ideas are welcome

I attached this mockup of what i'm looking for. The person interested in the event's section should be able to filter the events by day/week/month

Extra question : Would it be possible to have a 'next weekend' filter (relative to the time the person is visiting the website) ?

What you need to do is create a custom PHP field and manually code out the group by conditions as you have set there. I had the same issue I documented on my blog here: http://drupul.com/content/views-multiple-group-recipe-drupal-7

This is the code I used in my PHP field:

<?php
global $prev_month;
global $month;

if($prev_month != date('F Y', strtotime($data->field_field_date_2[0]['raw']['value'])))
{
  $month = '
'. date('F Y', strtotime($data->field_field_date_2[0]['raw']['value'])) .'
';
  $prev_month = date('F Y', strtotime($data->field_field_date_2[0]['raw']['value']));
}
else
{ $month = ''; }

print($month .'
'. date('M d', strtotime($data->field_field_date_2[0]['raw']['value'])) .'
');
?>

You will of course have to modify it to your setup, but its very similar to the setup you need as I needed it to be grouped by month then week and then day.


Coldfusion - MsSQL to Drupal Mysql I would like to receive some input on how you guys would approach the following:

We have an internal Projects Database application that was intially developed in ColdFusion and Microsoft SQL, approx. 5 - 6 years ago.

We now want to rebuild the entire application on the Drupal platform (with entities) and of course a Mysql Database, so far so good.

Now,

I am wondering how we approach the datamigration from one platform to the other.
Basicly we want to migrate all the database records to the new Drupal database structure once the project is finished.

-> Do we need to try and match the database structures when we are developing the platform in Drupal? Or will we have to write a migration script that matches all records one-by-one anyway?

-> Are there tools out there that can assist us in this project?

Developing the new, empty Drupal platform is not a big deal, it's a lot of work (a lot of fields and views basicly), it's the data migration from the old one to the new one that i would like to receive some opinions on.

Thanks for your advice in advance!

Best Regards,

I would definitely start by looking at the Migrate module. It has a plugin for MSSQL. Then, with writing some code to extend the module, you can tailor your migration to fit your needs. You can define data sources and targets, extend the migration classes, hook into the migration function, run batch migrations to test, and many other cool stuff. It is also well documented and has a few examples and case studies. You can read the documentation here on how to use and extend the Migrate module to build and/or enhance your migration process.


How do I manage custom modules? I have planned to use Composer to manage Drupal core and third-party modules instead of pushing everything to Git and I am using drupal-composer/drupal-project to achieve it.

After running composer create-project drupal-composer/drupal-project:7.x-dev d7 --stability dev --no-interaction, a d7 directory is created with some other directories, including the following ones.

vendor
web (It contains the Drupal core files.)

Its composer.json file is enough to install the same dependencies in another server, but if I use composer install in my server, how can I checkout my custom modules?

If I add custom modules and the composer.json file only in my repository, where do the custom modules go when I run during composer install? Do they go in sites/all/custom or the root directory?

Is there any other option available to manage my custom modules with Composer?

The contributed modules are in web/sites/all/modules/contrib/.

So, the suggested directory for the custom modules is web/sites/all/modules/custom/.

The other way to manage custom modules is to separate repository for the custom modules.

You can add your custom repositories to your composer.json in project root directory. Composer will look in all your repositories to find the packages your project requires. See Use PHP composer to clone git repo. Add your repositories under default Drupal.

After you add your repository to composer.json you have to tell Composer to install your custom modules to web/sites/all/modules/custom/. Add this line to installer-paths

"web/sites/all/modules/custom/{$name}/": ["type:drupal-custom-module"],

When you create your custom module, you must set type of your custom module in composer.json  to drupal-custom-module.


How do I show an exposed view filter in a block only on relevant taxonomy term pages? I have two different taxonomy term views for different taxonomy vocabularies: the Blog categories the and Product types. I have an exposed filter in a block that is relevant only for the Product taxonomy term.
How do I show the filter block only on /taxonomy/term/* pages for the Product term, without the need to list them explicitly in the block settings?

How to make a block vocabulary-specific
You can use the Block Visibility Groups module in conjunction with the Vocabulary Condition module (linked on that page).  Using those two modules together will give you a checkbox on the block to pick the vocabulary it should be shown for.
If you want to do it programmatically, the Vocabulary Condition module should be a good code reference.  There's also another Vocabulary Condition module (same name, ugh!) which could also be a good reference.
Alternative idea: Use different view pages for each vocabulary
If you're using the default taxonomy term view provided by core, I'm pretty sure you can customize it so that you have one page for terms with the Product vocabulary and another for the Blog category. Then you can simply expose the filter on the view page for the relevant vocabulary.


Drupal's .htaccess does not deny access to nodes D7, .htaccess woes. I'm trying to deal with referer spam in my Statistics module and block the most notorious referers. I edited my .htaccess file like this:

# Follow symbolic links in this directory.
Options +FollowSymLinks

# ... some options ....

# Various rewrite rules.
<IfModule mod_rewrite.c>
    RewriteEngine on

    # ... some more options ....

    # Block referer spam
    RewriteCond %{HTTP_REFERER} spamhost1\.com [NC,OR]
    RewriteCond %{HTTP_REFERER} spamhost2\.com
    RewriteRule .* - [F]
</IfModule>

When I went on to test this setup, I found out that it works correctly only if I try to access my site's main page. This request results in a correct 403 response:

GET http://www.example.com/ HTTP/1.1
referer: http://spamhost1.com/
Host: www.example.com

But any request to a node page produces 200 OK and loads the page which I'm trying to block:

GET http://www.example.com/node/1 HTTP/1.1
referer: http://spamhost1.com/
Host: www.example.com

Is it a matter of the Apache configuration in my server? How do I deny access to node pages?

In your settings.php file you can add the following lines and upon recognition of an HTTP_REFERER Drupal will not deliver any page data.

if ($_SERVER['HTTP_REFERER'] == 'http://spamhost1.com') {
  exit;
}

You should consider looking into existing modules that block spam though.  Trying to manage this one URL at a time seems like a lot of work.


Language selector Drupal 8 I can't seem to get a Language Selector to appear on my page.html.twig (or in a block). I must be doing something wrong, I can perfectly translate my content by I can't switch language (unless I change the URL myself).

This guide shows how to create a multi-lingual content.

https://www.ostraining.com/blog/drupal/d8-multi-lingual/

If not success please post some code you're trying to do. Remember to clear the cache.


How to add files using rules module? This question follows Override webform module submit

Based on this answer, I used the rules module to create a node after webform submissions.

My webform contains an <input type="file" />

for other <input type="text" /> I used this solution to How to save webform submissions data in fields using rules module

How can I add this file data in the field-image table?

The tricky part of what you're trying to do, seems to be related to correctly specifying the filename of the attached file (= the value to be stored in your field-image field). For this, have a look at what is suggested in Comment # 25 of the support issue (not bug ...) #1431572 and which states that the correct way to do so is something like so:

[node:field-file-attachments:file:path]

Use Rules debugging

This question is pretty tough to answer with the limited info you provided (and without access to "your" site). Therefor, if needed, you might also consider some Rules debugging, by (temporary) enabling the Devel module, so that you can (temporary) add a Rules Action like "Display a value" (in your case of the entire node/webform that's used to submit that attached file). For way more details about such debugging, refer to Rules debugging, as explained in the answer to "How can I display the value of a variable inside a condition?".


Creating a Display Suite Custom Layout I'm using Display Suite for my website and I want to add a couple layouts to Display Suite, to apply to some pages. I have checked out how to add custom layout to Drupal Suite with google, Stack Overflow and Drupal Answers. What I did:

created a folder "ds_layouts" in my custom theme folder;
created a folder for my custom layout "ds-2col-stacked-custom" in "ds_layouts" folder;
created two files "ds-2col-stacked-custom.css" :

>

.ds-2col-stacked > .group-fhl {
  float: left; /* LTR */
      width: 70%;
}

.ds-2col-stacked > .group-fhr {
  float: right; /* LTR */
  width: 30%;
}

 .ds-2col-stacked > .group-left {
  float: left; /* LTR */
  width: 50%;
}

[dir="rtl"] .ds-2col-stacked > .group-left {
  float: right;
}

.ds-2col-stacked > .group-right {
  float: right; /* LTR */
  width: 50%;
}

[dir="rtl"] .ds-2col-stacked > .group-right {
  float: left;
}

.ds-2col-stacked > .group-footer {
  clear: both;
}

and "ds-2col-stacked-custom.html.twig" :

    <{{ outer_wrapper }}{{ attributes.addClass('ds-2col-stacked', 'clearfix') }}>

  {{ title_suffix.contextual_links }}

    <{{ fhl_wrapper }}{{ fhl_attributes.addClass('group-fhl') }}>
    {{ fhl }}
  </{{ fhl_wrapper }}>

  <{{ fhr_wrapper }}{{ fhr_attributes.addClass('group-fhr') }}>
    {{ fhr }}
  </{{ fhr_wrapper }}>

  <{{ header_wrapper }}{{ header_attributes.addClass('group-header') }}>
    {{ header }}
  </{{ header_wrapper }}>

  <{{ left_wrapper }}{{ left_attributes.addClass('group-left') }}>
    {{ left }}
  </{{ left_wrapper }}>

  <{{ right_wrapper }}{{ right_attributes.addClass('group-right') }}>
    {{ right }}
  </{{ right_wrapper }}>

  <{{ footer_wrapper }}{{ footer_attributes.addClass('group-footer') }}>
    {{ footer }}
  </{{ footer_wrapper }}>

</{{ outer_wrapper }}>

in file "Mytheme.layout.yml", I added:

ds_2col_stacked_custom:
  label: Two column stacked layout custom
  category: Display Suite
  class: '\Drupal\ds\Plugin\DsLayout'
  type: partial
  template: ds_layouts/ds-2col-stacked-custom/ds-2col-stacked-custom
  library: ds_2col_stacked_custom
  regions:
    fhl:
      label: fhl
    fhr:
      label: fhr
    header:
      label: Header
    left:
      label: Left
    right:
      label: Right
    footer:
          label: Footer

in file "Mytheme.libraries.yml", I added:

# DS.
ds_2col_stacked_custom:
  version: VERSION
  css:
    theme:
      ds_layouts/ds-2col-stacked-custom/ds-2col-stacked-custom.css: {}

In Manage Display for page I see the option for my custom layout, and when I apply it, it's working (html tags and css classes are added to the page), but it does not apply any of my css for my layout. I think there is something wrong with the way I added css file to my custom layout.

You’re calling a library with dashes but it was defined with underscores. Update it to match the name.

You should be calling it via 'mytheme/library-name', so:

library: mytheme/ds_2col_stacked_custom


Hide a particular radio box item in a set I want to hide a particular item from an entity field that is using a radio box as widget. Can I achieve this using hook_form_alter()?

To remove the entire field on the form, you can definitely do something like this

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

  if ($form_id == "form_id_for_form_you_want_to_modify") {
    if (isset($form["field_you_want_to_remove"])) {
      unset($form["field_you_want_to_remove"]);
    }

  }

  return $form;
}

To change or remove a specific option on the field you can access and alter it with $form['field_your_field']['und']['#options']

(note: If your site is multilingual, you'll need to alter more than just ['und']. In this case ['und'] means undefined language code).

You can also alter the field type with:

$form['field_your_field']['#type'] = 'checkboxes';

It all depends on what you're trying to accomplish.


How to print the timestamp of date in a Views fields? I am using the Views Data Export module to show feeds as XML.
I need to show the created date and updated date in timestamp .

How can I implement it?

There is a way:

Go to Configuration > Regional and language > Date and Time > Formats (Tab)
Then click "add format" to add a new date format and just type "U" in the textfield. The "U" is actually the timestamp.
Go back to "Types" tab and add the new date type you just created and give it some name like "Timestamp".
In your view select your date field and select your custom date type in "Choose how users view dates and times"

Hope this is what you were searching for.

Otherwise: If you just look for the MySQL like timestamp just select "Plain" as the formatter in your views field.


How to manage placement of blog articles in omega regions I want to be able to control which omega region blog entries (individual blog articles) are placed. They appear to be in the content-zone, but I have not seen how to control which actual region they are contained within.

All content ends up in the Content region.  If you need something different, then I think g you have two options.

One, you can try to use a process function to move the content to a different region withing the zone.  The function would be function mytheme_alpha_process_zone (&$variables) and you would place it in "process/process-zone.inc".  I have no idea if this would actually work, but it is worth a shot.

Two, you could use one of the various techniques for changing layout based on content type.  Personally, I am a fan of Panels, but you could also try Delta (which plays nicely with Omega).


Form submit hook not executing In a drupal 6 custom module I built, I have a menu callback which contains this:

function mymodule_register_confirmation() {
  return drupal_get_form('mymodule_newsletter_form');
}

I have the function that returns the form:

function mymodule_newsletter_form(&$form_state) {
  $form = array();

  $form['logo'] = array(
    '#type' => 'markup',
    '#value' => '<div class="logo-header">',
  );

  ...

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

  ...

  return $form;
}

I also built the function for the submit hook of newsletter form:

function mymodule_newsletter_form_submit($form, &$form_state) {
    die('I am in the submit hook!!');
}

The page shows as expected and contains the newsletter form exactly as I want. However, when I click the submit button, it goes to the action of the form (as expected) but the submit hook I built never executes. I even tried adding the following to the function that returns the form:

$form['submit']['#executes_submit_callback'] = TRUE;
$form['#submit'][] = 'mymodule_newsletter_form_submit';

What am I doing wrong?

Thanks in advance.

Ahhhh, found the problem!

I had to specify manually a redirect to the form:

$form['#redirect'] = ''; // Redirects to the home page

This way the validate and submit hooks are called appropriately and then it redirects to the home page.

Thank you all for all your replies. I appreciate it.

Cheers.


Feeds Soap - importing items but can only add 1 item at a time? I'm having problems with using this API to get my details from:

http://api.tradera.com/v3/PublicService.asmx?op=GetSellerItems

It imports almost all fields and create nodes as it should however the "LongDescription" is not beign imported or displayed in their reponse it is only displayed as  without any content

For testing I tried to use this public service to see where is the problem:

http://api.tradera.com/v3/PublicService.asmx?op=GetItem

Using this allows me to import all single item details but it uses the parametr as the Item ID (Auction Number) and allows only 1 item at a time to be imported

But it imports the Long description as it should

So I was trying to:

1) Import all items I want with "GetSellerItems"
2) Map ItemID into Import ID
3) Use Item ID as parametr that would be passed to "GetItem" feed parametr <-- but this part I dont know how to make

If anyone have some suggestion why the "LongDescription" may not be beign displayed in response that would be great

If not then I would need to find a way to use GetItem to import descriptions of 500 items on schedular basis

I managed to solve my question by my self, In order to do that I had to create simple module

<?php
function feedspop_node_presave($node) {
  if($node->type == 'ubrania_a') {
      $numeraukcji = $node->field_import_id['und'][0]['value'];
      $node->feeds['FeedsWSClientFetcher']['operation_arguments']['parameters']['itemId'] = $numeraukcji;
      dpm($node, $name = NULL);
  }
}
?>


Is there a token for the key of a text list? I need to get the key of the key|value pair from a text list field in a token.

Say the field configuration shows the following options:

no|No Way Jose!
yes|Why yes, that'd do nicely!

and the field is named field_doc_textlist

the token [node:field_doc_textlist] is returning a value like 'No Way Jose!' when what I want is 'no'.  Is there a way to get that from tokens.  I'm using this in the filefield paths module if that matters.

I saw other similar answers here, with no real answers, but I've tried [node:field_doc_textlist:key] [node:field-doc-textlist] [node:field_doc_textlist:machine_name] [node:field_doc_textlist:machine-name] all to no avail

Some additional information: All of the above result in an error similar to

  The File path is using the following invalid tokens:
  [node:field-doc-type-book].

A lot of the information I've found suggests using the hyphenated version of the token name instead of the underscore version, but that seems not to work at all.

You could use roborew's sandbox: Entity Token Display

  This simple module was created to handle the formatting of entity
  tokens.

  When using certain field entities the entity token module will provide
  formatting and data sanitisation for display. However, there are times
  when you need the default value of the original field.


How does the new config_exclude_modules setting work exactly? Drupal 8.8 introduced a new setting: https://www.drupal.org/node/3079028

By adding these lines to your settings.local.php I expected the modules and their configuration to be excluded from config export.

$settings['config_exclude_modules'] = ['kint', 'devel'];

However:

kint and devel still appear in my core.extensions.yml
Yaml files related to devel still get generated.
Modules are still removed and installed based on the core.extensions.yml

How does this feature work?

Edit: I upgraded from Drupal 8.7, that seems to keep this function to work properly.

Enable the module and activate the filter by declaring $settings['config_exclude_modules'] in your settings.php file, eg:

$settings['config_exclude_modules'] = ['devel', 'stage_file_proxy'];

Now, when you export configuration (drush config-export), the selected modules should no longer show up in core.extension.yml and their configuration should not be exported.

Make sure first before doing that to remove these module from core.extensions.yml manually for the first time.

Update:
It seems to be related to a drush issues:
drush config:status does not respect excluded modules #4194


Why am I getting redirect to node?destination=node when trying to login? I just moved my site to another server, and when  I try to login drupal redirects to a blank page. I have no idea
what can I do?
Please, help me. thanks for your support.

This link might able to help you.
How to see the error messages when I get the white screen of death?

It might be .htacces problem. Maybe you should ask your hosting provider to help you solve this problem. My hosting provider always help me solve when this problem appear.


is there a way to customize url alias by content type? I have several contentypes, url alias are working fine, by default if there is a space in node title (or another token) is replaced with a dash "-", is it posible to change that beheavior by contentype and only on this special contentype replace spaces with nothing? example: my special contentype node title is= "word1 word2", this is replaced by "word1-word2", and i need to be "word1word2".

EDIT: i have allready pathauto module installed and working, path aliases are working fine, i need to change de default separator settings from a dash to "nothing" in one contentype only. Both answers bellow do not help me.

Yes. You can use the pathauto module.

http://dgo.to/pathauto


Views Slideshow - showing only one slide I've the content type, from which I want to take one field: title and present it as a block somewhere on the page. Sounds rather easy, but maybe my brain has melted already.

I installed Views Slideshow, created new view and it seems to work. To some degree, because it's only showing me one slide (title) and when it's fading, nothing new appears. When I choose the format for example to unformatted list, it shows all the titles it should, but in slideshow format it just doesn't work. What I'm missing here?

This is how it looks right now:

The possible directions you can look into :

You need to install the jQuery cycle plugin. Create a directory in sites/all/libraries called jquery.cycle, and then copy jquery.cycle.all.min.js or jquery.cycle.all.js into it. You can find the plugin at http://malsup.com/jquery/cycle.
In views slide show settings check for the 'Timer delay' in 'View Transition Advanced Options'.

Also, check for the other options in views slide show settings.
In the views settings, you are only showing published contents for a particular type of content. Make sure you have more than one such content. (Based on your screen shot)
Considering you have enabled 'Views Slideshow: Cycle' module

(Answer is based on trial to regenerate the issue in D7, 7.22)

Hope it helps


Is there an existing module to bulk delete user content but not user? I have a user role that is meant for pseudo-anonymous usage and each account of this role-type will be shared in a pool of users. Whenever a user of this role logs out, I'd like to delete all their associated content to prepare for the next possible user using this account. This sounds like a job for hook_logout, but it also seems like there should be a module for this already, right? I searched but maybe I'm not using the right keywords.

I'd suggest to try out Rules module for this, you've got an event: "User has logout", grab the entities from that user, loop them and delete them.

Here's a exported rule that would do it (change the number of entities to suit your needs)

{ "rules_test_logout" : {
"LABEL" : "test_logout",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "user_logout" ],
"DO" : [
  { "entity_query" : {
      "USING" : { "type" : "node", "property" : "author", "value" : [ "account" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "entity-fetched" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [ { "entity_delete" : { "data" : [ "list-item" ] } } ]
    }
  }
]

}
}


Get field value by machine name I developed a custom module in Drupal 7. I asked a similar question here:
Drupal 7 Get field value by machine name and pass to javascript

But the difference in this question is, instead of a taxonomy term, I want to get the field value of a regular text field.

Here is the code that I use to get the field value of a taxonomy term to pass to javascript, which currently resides in my theme's hook_process_page function:

if ($node = menu_get_object('node')) {
  $tid = $node->field_test['und'][0]['tid'];
  $term = taxonomy_term_load($tid);
  drupal_add_js(array('mymodule' => array('test' => $term->name)), 'setting');
}

Some things that I can see might ned to be changed right away are "tid," "taxonomy_term_load."

How can I change this code to instead get the text value of a field instead of a taxonomy term, to pass to mymodule?

EDIT:

Per a suggested change, I've modified the code, though I'm not sure this is what was meant:

if ($node = menu_get_object('node')) {
  $fieldValue = $node->field_test['und'][0]['value'];
  $term = taxonomy_term_load($fieldValue);
  drupal_add_js(array('jsblock' => array('test' => $fieldValue->name)), 'setting');
}

The in response to Drupal.settings.jsblock.test, the console outputs null.

Here is the Drupal notice:

Devel results:

How can I get the field value and pass it to my jsblock module?

For text fields you can use

$value = $node->field_my_field_name['und'][0]['value'];

or, if you want sanitized value, use ['safe_value'].


Set maximum / disable custom block cache for anonymous users I have a little issue regarding my custom block module. The module itself fetches weather data via json-request and the data is shown as a 4-day weather forecast to the user. As the weather should be actualized every day I want to set a "maximum cache time" or even disable caching for the whole block.
Right now I would have to flush the cash manually every day.

After a little bit of research to that topic I found out that using 'max-age' in the build() function would do the trick but it does not affect the caching for anonymous users at all.

Using \Drupal::service('page_cache_kill_switch')->trigger(); would disable the cache for a specific page or content-type but I don't want to disable the caching for a whole page at once.

So how can I trigger the caching for my custom-block? Or is there even a way to disable the caching for a certain part of the code e.g. the json-request in my case?

This is a known issue Bubbling of elements' max-age to the page's headers and the page cache.

The Internal Page Cache is designed for database content, which is handled by cache tags. So a workaround would be to add a custom cache tag to the block

$build['#cache']['tags'][] = 'weather_forecast';

which will bubble up to the page level and so you can invalidate both cached items, block and page, in a cron job:

/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  \Drupal\Core\Cache\Cache::invalidateTags(['weather_forecast']);
}

All credit goes to @Berdir: Cache max-age and varnish ESI


jQuery Toggle not working in Drupal Problem

I'm using jQuery toggle to make one block appear when another is clicked. The code works in jsfiddle but doesn't in Drupal.

Set-Up

I have a node with two blocks on it, applytoggle and tellafriend. Apply toggle:

    //*Other stuff*

Tellafriend:

In my template file I add the following script :

function mytheme_preprocess_page (&$vars) {
  drupal_add_js('sites/all/themes/tefltheme/toggle.js', 'file');

Which looks like this:

(function ($) {
    $('div.applytoggle').click(function() {
        $('.applytoggle_title, .block-tellafriend').toggle();
    });
})(jQuery);

This works great in jsfiddle - http://jsfiddle.net/dr9vG/, but doesn't in my actual page. The script is loaded successfully and I've got other jQuery scripts loaded and running the same way which work (not related, different objects). Why doesn't this work?

Most likely because the JS code you write in JSFiddle is automatically run when the document is ready; the same isn't true in a normal environment, you need to be explicit:

(function ($) {
  $(function() {
    $('div.applytoggle').click(function() {
      $('.applytoggle_title, .block-tellafriend').toggle();
    });
  });
})(jQuery);

But to be properly Drupal you should use behaviors:

(function ($) {
  Drupal.behaviors.myToggle = {
    attach: function(context, settings) {
      $('div.applytoggle', context).click(function() {
        $('.applytoggle_title, .block-tellafriend').toggle();
      });
    }
  };
})(jQuery);


How can users buy nodes they can create? I want users to pay 5$ for each node they want to create.

They should be able choose, on registration, to pay from 1 to 400 nodes and more later if needed. The nodes should unpublish after a year with an option for a user to renew. Another option is to have multiple roles for purchase, each with a predefined number of nodes he can create, and let users choose the role on registration.

Is this possible?

There's already a Commerce subproject called Commerce Node Checkout that does node publish purchasing with the option for expiration.

  Integrate with Commerce in order to allow you to charge users to
  create nodes. It is possible to have multiple different product
  offerings for each node type, so the user can pick the product they
  want to purchase when creating the node. An example use-case would be
  a classifieds site that charges people to post listings.

It's purchase process is on demand, rather than purchasing a credit quota, so you might have to look at something different to base your project on depending on how important the quota functionality is.

An alternative role-based approach would be the Commerce License Roles submodule and something like the Node Limit module to setup your quota-per-role requirement. You'd also have to find a node expiration solution (e.g. Node Expire) as well.


How to send monthly newsletter if the site is complex and has a lot of content types? I want to send monthly newsletter to subscribers via Drupal. The website has lots of content types (news, events, books, courses, blog posts etc.). If the site has only one content type it would be easy to prepare this newsletter with Simplenews module or Mailchimp etc.

Because the site is so complex and needed to create some specific views for each content type I wonder if is it better to prepare custom newsletter manually (without Drupal interface) or is there any solution to send newsletter via Drupal interface, "easily" and automatically?

There are a plethora of newsletter generation modules in various states of support. But if you want a first class newsletter that your audience reads you almost certainly want to take the time to write and layout the newsletter in a tool meant for the job (Mailchimp's interface or a competitor).

Newsletter generators are very appealing and can be effective if you have lots of very targeted segmentation of your list. But most of the time if you are sending one news letter to the entire list they are more overhead than value.

Most of the use cases people look to a generator to support are signs of a poor communications strategies. For example: I want to send a daily newsletter about XYZ and don't have the time to write it carefully every day -- does your audience want get and read that much auto-generated mail? Or Laying out my message is too hard to get it right every time -- use a better email newsletter tool that does the job better.


Do I need to use drupal_mail after the hook_form_contact_site_form_alter? I have added on field in my site wide contact form through this code :

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

    // Add a phone number field to the contact form.
    $form['phone'] = array(
    '#type' => 'textfield',
    '#maxlength' => 20,
    '#title' => t('Your phone'),
    );

    // Define the order of the top level elements on the form (include those from contact_site_form().
    $order = array('name', 'mail', 'phone', 'subject', 'cid', 'message', 'copy', 'actions');

    // Order the elements by changing their #weight property.
    foreach($order as $key => $field) {
    $form[$field]['#weight'] = $key;
    }
    }

Now Do I need to add drupal_mail with phone number into it or Drupal will consider it automatically ? As I am new to drupal I don't know much about it.

You should use hook_mail_alter().

hook_mail_alter() allows you to modify the email cleanly before it is sent. The Contact module passes the entire form state to drupal_mail(), so you have access to it in this alter hook via the params key.

A quick example. I haven't tested it:

function my_module_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    $phone = $message['params']['phone'];

    $message['body'][] = "Phone number: " . check_plain($phone);
  }
}

Let me know if that works.


How to show the ip address in revision listing? When I see all the revisions of a particular node through in my site, say, http://www.mysite.com/node/1/revisions,  I see an html table representing our data having two columns mainly REVISION and OPERATIONS. I have a requirement to add another column called IP Address from where the content originated for tracking purpose. I have already added a field in ip_address in the database, but don't know how to show the ip address in the revision listing? Plz help.

You could do this using rules and views.
First to create the rule:

  Create a text field named ip_address
  Manage display: make the field hidden
  Use Display Suite or a custom hook (or even CSS) to hide the field when filling out the form
  Create a Rule on event "Before saving content"
  Set a condition of content type: your content type
  Set a condition of Data comparison: [node:is-new], Data value: True (check the checkbox)
  Set an action of Set a data value, and set the field to be:
  PHP Code:

<?php
  print ip_address();
?>

Above taken from here: Get IP address of submitter

For your purposes the 6th bullet (your rule condition) can be set-up like this:

And for the final action (7th bullet) if you don't want to use the php you can first add and action

  'Add a variable' -> Value IP Address

and use that as in a second 'set a data value' action...

Now you can create a view that displays in a table format the fields 'Content Title' 'Revision Log' (i'm guessing this is what the operations column is recording?) and 'IP_Address', sorted by 'Node revision ID (desc)', or similar....

As it stands I am aware that this answer might not work for multiple revisions, rather only displays the IP for the latest revision. I imagine that when setting up your initial (hidden) IP_address field if you allow multiple values the rule will simply add values rather than over-write them. Maybe someone else on here has guidance on that...


Troubleshooting a slow query I've taken over a Drupal 7 website, and i'm having trouble with a slow query that is run when an editor visits the /admin/content page. The query in question is the following:

SELECT COUNT(*) AS expression
FROM
(SELECT DISTINCT node.nid AS nid, node.title AS node_title, history.timestamp AS history_timestamp, node.created AS node_created, node.changed AS node_changed, node.type AS node_type, users_node.name AS users_node_name, users_node.uid AS users_node_uid, node.status AS node_status, 1 AS expression
FROM
node node
LEFT JOIN users users_node ON node.uid = users_node.uid
LEFT JOIN taxonomy_index taxonomy_index ON node.nid = taxonomy_index.nid
LEFT JOIN taxonomy_term_data taxonomy_term_data_node ON taxonomy_index.tid = taxonomy_term_data_node.tid
LEFT JOIN history history ON node.nid = history.nid AND history.uid = '1') subquery;

Edit: I've just managed to solve this issue, but there is a more general question:

How can a drupal 7 administrator identify the cause of errant queries to stop them from occurring?

To identify:

Install the Devel module
Visit admin/config/development/devel, enable the "Display query log" option.
At the bottom of every page you'll see a log of the queries run for the page, and what module and function has been responsible for invoking them. Run time of each query is also listed so you can see where the problems are.

As for stopping them, that will depend entirely on the individual query; whether you need it, whether the bottleneck is simply a matter of weight of data, poorly designed tables (contrib or custom, core tables are fine), not enough system resources, bad caching strategy, and so on. You'll need to profile that in the context of your web server for it to make any sense, there's no recipe for it.


How do I deliver a nested JSON array for content reference with export view display? I created a product content type with content reference to article(one product to many articles). Then I added field "Content: ID" "Content: Title" and "(field_article: Content) Content: Title" to a new REST export View. "(field_article: Content) Content: Title" come from the relationship "Content referenced from field_article" I added in advanced.

The output is:

[
    {
        "nid":"3",
        "title":"Product1 title",
        "article_title":"Article1 title"
    },
    {
        "nid":"3",
        "title":"Product1 title",
        "article_title":"Article2 title"
    }
]

What I would like to achieve is something like this:

[
    {
        "nid":"3",
        "title":"Product1 title",
        "articles":
            [
                {
                    "title":"Article1 title"
                },
                {
                    "title":"Article2 title"
                }
            ]
    }
]

How to implement this?

UPDATED:
I also tried aggregation, but in case of REST export View as the format is Serializer, no "group by" option in format setting but hal_json, json and xml options, while "Aggregation settings" appears on each filed. In this case, I don't know how to set "aggregation settings" group by node id. Also I cannot find document about aggregation settings of field in "Fields" section.

I've created a very simple module REST Export Nested to support nested JSON using Views Field Views.

After installing "REST Export Nested":

Install and enable <a
href="https://www.drupal.org/project/views_field_view" rel="nofollow noreferrer">Views Field
Views
Create view display of referenced content (Articles in your case) of type "REST export" or "REST export nested"
Add a relationship to the parent entity and contextual filter of parent entity ID
Create a view display of the parent entity of type "REST export
nested"
Add required fields (e.g. "nid", "title")
Add a field of type "Views field" (e.g. "articles"), configure with
the correct View and display and pass "nid" as the contextual filter

The module doesn't depend on Views Field View and may work with other fields which produce a JSON string.


Why does my do-nothing subtheme break the parent theme? I'm trying to get started with sub theming in Drupal 8. I followed the example from the Drupal documentation and created what I thought was supposed to be an unmodified inherited copy of the Bartik theme, but the main navigation menu is changed per the below screenshots. My code is as follows, identical to the tutorial other than Bartik as the base theme.

What am I missing here? Why am I not starting with an identical layout to the Bartik theme?

info.yml:

name: wilmettewatch
type: theme
description: Wilmette Watch's theme based off Bartik for now
core: 8.x
# Defines the base theme
base theme: bartik
# Defines libraries group in which we can add css/js.
libraries:
  - wilmettewatch/global-styling
# Regions
regions:
  header: Header
  featured: Featured
  content: Content
  sidebar_first: First sidebar
  sidebar_second: Second sidebar
  footer: Footer

libraries.yml:

global-styling:
  css:
    component:
      css/style.css: {}

Bartik Theme:

My Sub Theme:

The sub theme is fine. Sometimes when you activate a sub theme, you may need to recreate some or all of the block layout. In this case, the primary menu got placed in the header, where it gets a different layout.

Just make note of the block layout in the Bartik theme and duplicate it in the sub theme.


Theming link fields, getting URL value From a field template level, how can I get the link field URL value so I can theme this thing? Here is my overridden field template for this field:

{% for item in items %}
    {%
      set classes = [
        'btn',
        (loop.index0 == 0) ? 'btn--primary' : 'btn--inverted'
      ]
    %}

    {{ item.content['#title'] }}
{% endfor %}

It only holds two possible values.

I have tried every possible way to access the field value, but nothing seems to work.

Ok... found my answer.

There are two ways you could do this. One way, is in the themename.theme file:

function mytheme_preprocess_field(&$variables) {
  if ($variables['element']['#bundle'] == 'motivation_card' && $variables['element']['#field_name'] == 'field_link') {
    foreach ($variables['items'] as $index => $item) {
      $variables['items'][$index]['content']['url'] = $item['content']['#url']->toString();
    }
  }
}

Another (preferable) way that I used is to use the render_var twig function.

{{ render_var(item.content['#url']) }}


How do I add COUNT(foo.bar) to a dynamic query? I have a query like the following:

SELECT t.tid, t.name, t.description, COUNT(i.nid)
  FROM taxonomy_term_data t
  LEFT JOIN taxonomy_index AS i ON i.tid = t.tid
  GROUP BY i.nid
  LIMIT 60

I wish to write this as a dynamic query.

This is what I come up with, but it fails on the COUNT() part.

$query = db_select('taxonomy_term_data', 't');
$query->addField('t', 'tid');
$query->addField('t', 'name');
$query->addField('t', 'description');
$query->addField('COUNT(i.nid)', 'count');
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->range(0, 60)->groupBy('i.nid');

The string representation of the query is:

SELECT t.tid AS tid, t.name AS name, t.description AS description, COUNTi.nid.count AS count FROM {taxonomy_term_data} t LEFT OUTER JOIN {taxonomy_index} i ON i.nid = t.nid GROUP BY i.nid LIMIT 60 OFFSET 0

COUNTi.nid.count AS count is obviously wrong.

How do I add COUNT(foo.bar) to a dynamic query?

@MEsch is right about the method to call, but I would rather write the code as the following.

$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));

$alias = $query->leftjoin('taxonomy_index', 'i', '%alias.nid = t.nid');

$query->addExpression("COUNT($alias.nid)", 'count');
$query->range(0, 60)->groupBy("$alias.nid");

SelectQuery::leftJoin() returns the alias effectively used in the query, and the code I wrote is more generic.

As for calling SelectQuery::addExpression() before SelectQuery::leftJoin(), the result doesn't change, if you are not using the alias returned from SelectQuery::leftJoin(). The following queries return both the same result.

$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->addExpression("COUNT(i.nid)", 'count');
$query->range(0, 60)->groupBy("i.nid");

$query = db_select('taxonomy_term_data', 't')
  ->fields('t', array('tid', 'name', 'description'));
$query->addExpression("COUNT(i.nid)", 'count');
$query->leftjoin('taxonomy_index', 'i', 'i.nid = t.nid');
$query->range(0, 60)->groupBy("i.nid");

When you print $query, you get the following, in both the cases.

SELECT t.tid AS tid, t.name AS name, t.description AS description, COUNT(i.nid) AS count
FROM
{taxonomy_term_data} t
LEFT OUTER JOIN {taxonomy_index} i ON i.nid = t.nid
GROUP BY i.nid
LIMIT 60 OFFSET 0


How to use form field only once I'm looking for solution for following scenario in my D7 site.
I have form with 2 empty text fields. If user enters value in field 1 and submits form next time when he opens this form only field 2 will be available for input.

you can achieve it with some code in your custom module

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'your_form_id' ) { // in your custom content type
    if($form["nid"]["#value"]){  //when we are in edit form
      if(isset($form['field_your_field1']['und'][0]['#default_value']['value']) )
          hide($form['field_your_field1']);
     if(isset($form['field_your_field2']['und'][0]['#default_value']['value']) )
          hide($form['field_your_field2']);
    }
}
}


how to retrieve the index size of a field array What I am working with it this. I have a custom content type with an image field (field_img) that accepts multiple images so they are stored in an array. what I need to figure out how to do is one of two things and I need to do them from the node--custom.tpl.php if possible.

1: get the size of the $node->field_img array so I can then loop through and assign appropriate HTML id's for each image in the content type.

OR

2: directly loop through the field_img array using maybe foreach() to set the id of each image in the content type to an appropriately unique value.

what I am able to do here works for one value because I can put in the actual index of the instance I am working with but the arrays are not all the same length some have 10 images some have only 6 so I need something that will loop through the array.

Here is the static code that works for one element

<?php $i = 0 ?>

<img class="album-image<?php print $i ?>" src="<?php print render (file_create_url($node->field_img['und'][$i]['uri'])); ?>">

this is inside node--gallery.tpl.php and it works fine but it only displays 1 image and I need 14 or how ever many there are for the instance of the content type.

You mention foreach(), but did you try it? Seems to me that it should work. foreach($node->field_img[LANGUAGE_NONE] as $key => $value)


Omega theme on Ipad slides across and disappears I'm using the latest Omega 3 theme on my drupal 7.32 site caerleonlodgehillprimary.org. I notice on the ipad2 (also Ipad Mini), if you swipe across to the left, the entire page disappears and you are left with a blank page. Has anyone got any ideas why that is? I was wondering whether its some kind of corruption in the footer, the last thing I added was to add a Contact Us block showing the address and email in the footer (which is a View based on the Contact Us node), I noticed in portrait mode, the email spills over into the next block. any idea?

This is caused by my social icons in the footer, the same problem is referred to in this posting, it occurs when a DIV gets too big for the page, the Ipad cant cope with this and creates a load of space on the right of your page. In my case, I have an text indent -999 in the class of my social button, defined as :-

.social-button{

    width: 30px;
    height: 30px;
    text-indent: -999em;
    display: inline-block;
    background-repeat: no-repeat;
    background-position: center center;
    margin-right: 2px;
    text-decoration: none;
    border: 1px solid #FFFFFF;

}

To resolve I put :-

width:auto;
overflow-x:hidden;

on the css for the social icons Block in the footer and it worked perfectly as suggested in the link above. Sorry this is slightly off topic with a CSS resolution, but I though it would save someone (like me) hours of messing around with their theme to find a problem thats not there . Thanks


Select fields from two tables using db_select() I am using db_select() and I don't understand the syntax of the fields() method. I'm using a join() to join another table. So for tables t and n, I want to do something like

SELECT t.tid, t.field1, t.field2, n.title, n.author
FROM table t INNER JOIN node n ON t.nid = n.nid;

I have

$results = db_select('table', 't')
  ->fields( ... )
  ->join('node', 'n', 'n.nid = t.nid')
  ->execute();

But as you can see, I'm lost at fields(). The examples I've seen only specify fields for one table:

->fields('t', array('tid', 'field1', 'field2'))

What is the syntax that I want to use?

Easy, just call fields() twice.

$query = db_select('table', 't');
$query->join('node', 'n', 'n.nid = t.nid');
$result = $query
  ->fields('t', array('tid', 'field1', 'field2'))
  ->fields('n', array('nid', 'field1', 'field2'))
  ->execute();

foreach ($result as $row) {
  // Do something with $row.
}

You can call most methods multiple times (multiple fields, multiple conditions, multiple sort orders, multiple joins, ...).

Note that, as shown in my example, the call to join() needs to be separate and can not be "chained" (that's the technical term for having multiple method calls in a row) because it does not return the query object but the name for the table alias.


How do I verify that the form input date is valid? Some browsers (e.g. Safari) allow rubbish dates to slip through a form Date field so that  we get a fatal PHP error  (Call to a member function format() on null) when we invoke the DrupalDateTime::format() per the code below which doesn't catch any exception.

The user can type 19-00 into the time part of the date field instead of 19:00:00 and this will cause Drupal 8.0.5 to crash.

What is the correct way to test that a date in a DrupalDateTime object in the form array can be formatted properly? This doesn't work (snippet from an entity_builder for new and changed Meeting Nodes in our Meeting module):

try {
    $formatted_date_of_meeting = $date_of_meeting->format('l, j F Y');
} catch (\Exception $e) {
    $form_state->setError($form, $e->getMessage());
}
$node->setTitle($name_of_meeting.' on '.$formatted_date_of_meeting);

If the date is valid, then the form state will return an object of type Drupal\Core\Datetime\DrupalDateTime, and otherwise it will return an array with the invalid values. Since the invalid date format will be caught elsewhere, the custom code need only check if the value is an instance of DrupalDateTime:

if ($date_of_meeting instanceof DrupalDateTime) {
  $formatted_date_of_meeting = $date_of_meeting->format('l, j F Y');
  $node->setTitle($name_of_meeting.' on '.$formatted_date_of_meeting);
}


Where is the "auto submit" option? I have an exposed filter for one of my views and I added a drop-down select for the users to pick from.

In Views for Drupal 7 there was an Auto-Submit check box, but I can not seem to find it in Drupal 8 at all. Does anyone know where it may be hiding or how I can get the filter to auto-submit.

While tracking the above issue is good for long-term success... if you need this functionality ASAP, here's a tiny bit of a hack to get it working with some custom javascript. Inside your theme's JS, add something like the following:

// Autosubmit 'view-class-here' views exposed form.
$("div.view-class-here").find("form.views-exposed-form").find("select").bind("change", function () {
  $(this).closest("form").trigger("submit");
}).end().find("input[type='submit']").addClass("visually-hidden");

This will do the following:

Look at any select item in a given views exposed form (for a view with a class .view-class-here), and trigger a submit whenever the select list is changed.
Hide the 'Submit'/'Apply' button associated with the exposed form.

If you want to trigger the submit on input fields, change the .bind() to use something like input:checkbox or input for any kind of input (though that might need more tweaking to make sure things don't go crazy!).


zoom and centre gmap output based on results (views+gmap+location modules) I've got several nodes with location information attached. I am using the Gmap output form views to show the results on a map. Drupal is so great sometimes, I'm literally shocked at how little time it took to get that solution up and running!

At the moment the map is using the default centring and zoom no matter what the results are. I'm pretty sure I have just missed an option or setting somewhere, but can someone point me in the right direction to re centre and zoom based on the pins from the results?

I've had a search on here and Google and can't see this question having been asked. Probably because an available option is staring me right in the face!

Thanks

I just noticed someone talking about the macro behaviour for autozoom. I added behavior=+autozoom to my [gmap] macro in the Gmap views settings and the few tests I have done so far suggest it works


How to render a paragraph field in Twig in correct language? I've got nodes with hero images. The hero images are a paragraph field with unlimited cardinality, each with an image and a translatable text. For design reasons I need to print the hero images in page.html.twig (using Twig Tweak for simplicity)

{{ drupal_field('field_banner_slide', 'node', node.id) }}

The hero slider has some options like timer, size,... which are other fields on the same host node, and pulled in during preprocess

function MYTHEME_base_preprocess_field(array &$variables, $hook) {
  $parentEntity = $element['#object'];

  if ($parentEntity && $variables['field_name'] == 'field_banner_slide') {
    // attach JS library
    // add HTML data attributes on this field based on other field values of same host node
    // ...and so on...
  }
}

All worked fine until my site went to the translator. My slider always returned the default lang. Next I tried setting the language in page.html.twig

{{ drupal_field('field_banner_slide', 'node', node.id, 'default', language.getId()) }}

This works for every other field - except Paragraphs. I've also tried the alternative

{{ node.field_banner_slide|view('default', language.getId()) }}

but still the same language problem.

I've already checked the source code from Twig Tweak, it seems to correctly set the language

  public function drupalField($field_name, $entity_type, $id = NULL, $view_mode = 'default', $langcode = NULL, $check_access = TRUE) {
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $id
      ? \Drupal::entityTypeManager()->getStorage($entity_type)->load($id)
      : \Drupal::routeMatch()->getParameter($entity_type);
    if ($entity && (!$check_access || $entity->access('view'))) {
      $entity = \Drupal::service('entity.repository')
        ->getTranslationFromContext($entity, $langcode);
      if (isset($entity->{$field_name})) {
        return $entity->{$field_name}->view($view_mode);
      }
    }
  }

I've been really digging here, but I can't find any single error. How do I get my correctly translated paragraphs?

PS: I don't want to use {{ drupal_entity('paragraph', my_field_banner_slide_target_ids, 'default', my_langcode) }}, because I also need the preprocessing from the host field.

The problem is that FieldItemInterface::view() has no language parameter. Furthermore paragraph fields are not translatable (only the subfields of the paragraph entity are translatable). So when rendering a paragraph field directly, without going through the host entity render stack, the language information is lost.

My solution was to force the translation in a preprocess function:

function MYTHEME_preprocess_field(array &$variables, $hook) {

  // field_banner_slide is a paragraph field which needs
  // translation AND is rendered directly, e.g. by using Twig Tweak's
  // {{ drupal_field('field_banner_slide', 'node', node.id) }} in page.html.twig
  //
  // don't to this for "normal" rendering, e.g. when using
  // {{ content.field_banner_slide }} in node.html.twig

  if ($variables['field_name'] == 'field_banner_slide') {
    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    if(count($variables['items'])) {
      foreach($variables['items'] as $key => $item) {
        if ($item['content']['#paragraph']->hasTranslation($lang)) {
          $variables['items'][$key]['content']['#paragraph'] = $item['content']['#paragraph']->getTranslation($lang);
        }
      }
    }
  }
}

For a better technical explanation see issue #2753201 on d.o


How to use DataDefinition::create('list')? This answer links to a list of all possible types that can be used with DataDefinition::create().

One plugin that can be used is ItemList.

But I can't find any documentation on how to define what items are on the list.

I would have expected something like this:

$status_definition = DataDefinition::create('list')
  ->setLabel(new TranslatableMarkup('Status'))
  ->setRequired(TRUE)
  ->setListItems([
    1 => 'One',
    2 => 'Two',
    3 => 'Three',
  ]);

But the method setListItems (or anything similar) does not exist.

For some more context I'm following this article on how to extend the entity reference field type but instead of adding an integer field I want to add a list field.

ItemList is a generic base class. List is used here in the context of multivalued field items. Because Drupal has no separate class for single value fields (they are multivalued fields restricted to one value), this generic list data type is used in all Drupal fields.

When you look at the list of field types

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Annotation%21FieldType.php/class/annotations/FieldType/8.4.x

you'll find ListStringItem, where List is used in the context you are probably looking for and you can use this as an example for this kind of field types implementing OptionsProviderInterface.


How to make a custom block listen to context module? I've been creating my own module that consist an array of blocks. I plan to print them using context as oppose programatically as I already have the module on use (no need to reinvent the wheel). However, whenever I use context to display a block on a region, it always display it on the highest part of html body tag.
e.g.

<body>
  block content rendered here...

as oppose to my custom region,

<div class="l-info-bar">
  I want my block content rendered here...

I cleared the cache several times. Made sure that the context is set to display the block on info bar region.

Here's my code for reference.

    function custom_module_block_info() {
      $blocks = array();
      $blocks['my_block_top_navigation'] = array(
        'info' => t('Top Bar Navigation Menu'),
        'cache' => DRUPAL_CACHE_GLOBAL,
      );
      $blocks['my_block_avatar'] = array(
        'info' => t('Avatar'),
        'cache' => DRUPAL_CACHE_GLOBAL,
      );

      return $blocks;
    }
    /**
    * Implements hook_block_view().
    */
    function custom_module_block_view($delta = '') {
      $block = array();
      switch ($delta) {
        case 'my_block_top_navigation':
          $block['subject'] = '';
          $block['content'] = _custom_module_block_top_navigation_content();
          break;
        case 'my_block_avatar':
          $block['subject'] = '';
          $block['content'] = _custom_module_block_avatar_content();
          break;
      }
      return $block;
    }

function _custom_module_block_top_navigation_content() {
    lots of code here...
}

function _custom_module_block_avatar_content() {

   lots of code here...
}

I'm guessing you have to prep your block so context can actually place it to certain region?

Update1: I forgot to mentioned that normal blocks works on context and normal block display (only my custom block doesn't work on normal way and context—which is why I though problem lies in my coding—not context module). I also tried printing the block through code and works perfectly but I don't want extra code I don't need because I have context on use.

Update 2: I also replaced the block content with print t('TEST') and still printing above body through normal means and context. Works well printing using code.

Firstly, You can try putting a regular block at a regular region created by drupal core in context. That should work.

Then compare the different results you got for your custom block and custom region. Try putting your custom block at regular region, or putting regular block at your custom region.

Also, You may need to double check the 'custom region' you mentioned at question does exist at page.tpl.php. I.e the code does print the 'custom region' in page template, like

<?php print render($page['your_custom_reagion']); ?>


Saving custom fields for nodes and users I'm trying add a new user to drupal 7, here is my code:

$values = array('name' => $name, 'pass' => $password,  'mail' => $email, 'status'=>1);
$newUser = user_save('', $values);

But i also have the new field field_foobar, if i add it to the values array drupal does nothing with it. What is the correct drupal way of adding these values to my user object so that drupal saves them when i call the user_save function?

I also saw that the fields are stored in the same type of table that stores custom fields of nodes. Also can't get this done, but i guess these 2 problems can have the same solution.

Thanks!

I haven't done this with user_save() before but if it follows convention from the rest of the system (which is likely) it'll be like this:

$values = array(
  'name' => $name,
  'pass' => $password,
  'mail' => $email,
  'status'=>1,
  'field_foobar' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => $field_value
      )
    )
  )
);

$newUser = user_save('', $values);

In fact there are a few examples further down the page in the user_save() docs confirming this method is the right one.


Stop Advanced Forum cutting off the username? Im using the Advanced Forum module. Many of my users have long usernames which are being cut off (in the author information when they post a comment). Is it possible to lengten the limit before the text is cut off?

I cant see any settings for the Forum or Advanced Forum modules. Below is a theme hook that creates the author information (dont know if this is the right track or not).

/**
 * Theme function to show simple author pane when not using Author Pane.
 */
function theme_advanced_forum_simple_author_pane(&$variables) {
  $context = $variables['context'];
  // Sending the context rather than the account makes it work for anon comments.
  $name = theme('username', array('account' => $context));

  $account = user_load($context->uid);
  $picture = theme('user_picture', array('account' => $account));

  return '
' . $name . $picture . '
';
}

It seems Drupal core truncates the username to 25 characters. I have not tried this but this seems to be the solution for Drupal 7 (code added below for reference).

function MYTHEME_preprocess_username(&$vars) {

  // Update the username so it's the full name of the user.
  $account = $vars['account'];

  // Revise the name trimming done in template_preprocess_username.
  $name = $vars['name_raw'] = format_username($account);

  // Trim the altered name as core does, but with a higher character limit.
  if (drupal_strlen($name) > 25) {
    $name = drupal_substr($name, 0, 20) . '...';
  }

  // Assign the altered name to $vars['name'].
  $vars['name'] = check_plain($name);

}

Add this code in your theme's template.php file, and change MYTHEME to the machine name of your theme, and change the number 25 to something that fits your theme.


Help with wrapping character with CSS span using Jquery I have this jfiddle working (http://jsfiddle.net/FJxcG/), but the same code does not work on my Drupal 7 website. I added the JS file to my theme .info file, and the JS is showing up in the source; it's just not displaying the end result on-screen.

The reason I need this is so that I can wrap a span class around all instances of the Trademark special character (™). That character is too large in the font I am using, and I'd like to use that css/jquery function to apply the span so I can give the TM a smaller font size without affecting the rest of the text around it. Some of the TM's are within menu links, so I can't simply hard-code the new span class.

Thanks!

Two things I can think of that could possibly cause the problem:

Your code runs before the document is fully loaded. To fix it try wrapping the function call inside $(document).ready:

$(document).ready(function() {
  $('div').wrapInTag({
    words: ['™'],
    tag: '<span class="trademark">'
  });
});

The CSS style are being overridden. Quickfix would be to add !important at the end.

.trademark {
  font-size: 9px !important;
  vertical-align: top !important;
}


Override module function in my custom module? I am using module Mixpanel in my site. And I want to override function of this module. Here is link where we can see the function or code which I need to alter CODE NEED TO MODIFIED

Below is the code line which suggest that I can override this function :

    // Let other modules alter the defaults.
    drupal_alter('mixpanel_defaults', $properties, $account);

So from above line I am trying to override it with code as below, please let me know what I am doing wrong as it does not make any changes. However if I do same thing in main module it make changes but I don't want to make change in module but want to do in my custom module.

My custom module name: custom

function custom_mixpanel_defaults_alter($properties, $account) {

  $properties['distinct_id'] = $account->name;

}

When i see in system table weight of my custom module is 1000 and weight of Mixpanel is 0.

Please suggest! Thanks

The error is how you define the parameters, which should be defined as custom_mixpanel_defaults_alter(&$properties, $account).
PHP 5 automatically passes by reference any object passed to a function, but not the arrays. Since $properties is an array, you need to make the reference explicit.

Generally speaking, when you see a call to drupal_alter() like drupal_alter('node_view', $build), and you need to implement that alter hook, check the second and third parameter are object or arrays; in the case they are array, you need to explicitly declare the parameter as reference. In this case, hook_node_view_alter() is defined as hook_node_view_alter(&$build).


Trying to create a custom menu link in a menu So I want to have different menu links depending on if a user has received a message or not.

I make a hook_menu() instance, like this:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => t('Messages'),
  );
  return $items;
}

However it only takes me to my user page, and not the messages (which should be a view at the path specified).

Is there a way to make it so that I can directly go from this item link in the menu to the view?

Got it from here:

http://zufelt.ca/blog/embedding-view-menu-hook-drupal

Changed my hook instance to this:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  global $user;
  $items = array();
  $items['user/' . $user->uid . '/messages'] = array(
    'access callback' => 'user_is_logged_in',
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'main-menu',
    'title' => t('Messages'),
    'page callback' => 'views_embed_view',
    'page arguments' => array('message_private', 'page_1'),
    'file path' => drupal_get_path('module', 'views'),
    'file' => 'views.module',
  );
  return $items;
}

This will embed the view into the hook_menu() instance.


How to add CSS and JS files on node pages from theme's template.php I am trying to add JavaScript and CSS files to one node type page from my template.php file but it is not working.  Here is my template.php code:

<?php
// $Id: template.php,v 1.13 2010/12/14 01:04:27 dries Exp $

function mttheme_preprocess_html(&$variables) {
  $node = node_load(arg(1));
  if ($node->type = 'sales_team_page') {
    drupal_add_css('misc/jquery.fancybox-1.3.4.css');
    drupal_add_js('misc/jquery.mousewheel-3.0.4.pack.js',
      array('type' => 'file', 'scope' => 'header')
    );
    drupal_add_js('misc/jquery.fancybox-1.3.4.pack.js',
      array('type' => 'file', 'scope' => 'header')
    );
    drupal_add_js('misc/jquery.fancybox-calls.js',
      array('type' => 'file', 'scope' => 'header')
    );
  }
}

Does anyone know why it is not working?

Since you want your CSS and JavaScript when displaying a node, you can add the files it in the preprocess function for the node template. Also, as stated in their documentation, when adding a file, the first argument for drupal_add_css() and drupal_add_js() is the path the CSS/JavaScript file relative to the base_path(). You can use drupal_get_path('theme', 'THEME') to get the path of your theme relative to the base path.

function THEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full') {
    $node =& $variables['node'];
    if ($node->type == 'sales_team_page') {
      $path = drupal_get_path('theme', 'THEME');
      drupal_add_css($path . '/misc/jquery.fancybox-1.3.4.css');
      drupal_add_js($path . '/misc/jquery.mousewheel-3.0.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-1.3.4.pack.js', array('type' => 'file', 'scope' => 'header'));
      drupal_add_js($path . '/misc/jquery.fancybox-calls.js', array('type' => 'file', 'scope' => 'header'));
    }
  }
}

Also, doing $node = node_load(arg(1)); to load the currently viewed node is unsafe and wrong. If you have a non node page at whatever/42 but have an existing sales_team_page node with nid = 42, you will load this node and add your CSS and JavaScript files even if the user is not viewing the node.


How to structure repetitive data under an entity type bundle? I'd like to use Drupal in one of my projects but I'm wondering what's the best way to organize my content.

I have a list of authors. Each author has 3 properties:

name
bio
list of books

On the list of books each book has 6 properties(5 text fields + image).

I was thinking about creating entity type bundle 'Author' and 'Book', then assigning certain books to certain authors and displaying lists of books on author page.

The downside is that on the content list I'll have a list of many different 'pages' of content type 'Book' that can't be easily filtered by author. Also, creating new content type for each author is not a good solution.

1) Is it the best possible solution for Drupal?

2) Would it be possible to create:

a) hierarhical list of author/book_list posts or

c) content type Author with list of books on it's page(book field with book properties fields)

I'd appreciate your advice :).

You could always make another view to supplement or replace your content list.  If you're using Entity Reference for the relationship between book and author you can create an easily filterable list of books.

Alternatively, 2c is a viable option.  You can create a group of fields on Author called book using field collection and set the group to have unlimited instances.


How do I find the default value or change state of a form element? I'm putting together a fairly complex form with Drupal 8 (currently building on beta 7). In my validation function, I need to be able to detect whether a field, which was populated with default values, has changed.

In Drupal 7, this would have been pretty straightforward. I could dig into the form_state array and find the appropriate default_value entry and compare it to the submitted value.

But now that form_state is an encapsulated object, I don't see an obvious way to get the default value.

I know I can kluge this if I need to, by including hidden fields in the form itself with the default values. But I know that the information is in the form_state object: if I print_r form_state I can see both the old and new values--but not in any way I can figure out how to access using the methods listed in FormStateInterface.

Bottom line: in Drupal 8, how do I test whether the submitted value of a form element is the same as its default value?

public function validateForm(array $form, FormSateInterface $form_state) {
  $element = $form['elementname'];
  $default_value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
  $value = $form_state->getValue($element['#parents']);
  $changed = $default_value == $value;
    if ($changed) {
    // This is stupid, it's just an example.
    $form_state->setError($element, $this->t("The value has changed."));
    }
}