Menu links not being translated I have installed Drupal 7 and also the internationalization modules. I am able to add a basic site and translate it. I can even opt to add localized url aliases which work fine when switching language. The one thing not working is the menu translation. When translating an article I can choose a different menu name for each language - but only the english version is shown in the menu for all languages.

Anybody has a clue why this could be?

Here is what I understand with the current Drupal 7.32.  The behaviour of the i18n in Drupal heavily depends on the settings, so I mention the way I am fairly familiar with.  If your settings are different, the behaviour can be different.

First, i18n_menu must be enabled, as well as i18n_node (I understand some people prefer Entity translation, whose behaviour must be different, but I don't know about it).

Second, give "URL" with "Path-prefix" the top priority at /admin/config/regional/language/configure.  Also, personally I much prefer to explicitly set the path prefix for the default language (usually English, "en") at /admin/config/regional/language/edit/en.  In default it is Null and that is I found quite confusing due to its inherently asymetric nature.  Having said that, it is up to each developer, obviously!

Third, "Translation mode" at /admin/structure/menu/manage/main-menu/edit is the key.  In default, it is "No multilingual options for menu items".  Obviously that is no good for translatable menus.  Choose either of the following two options, that is, (1) "Translate and Localize." and (2) "Fixed Language."

I think the second option (2) suits the most sites, unless the menu stractures for all the supported languages in the website are identical.  If you choose (2), simply create another menu, say, "Main French Menu", tick the "Fixed Language" as French, and place it in the area you like in the block configuration /admin/structure/block

If you choose the first one (1) "Translate and Localize", you then will see "TRANSLATE" tab (near the top) in /admin/structure/menu/manage/main-menu/edit (for the main menu, for example) and can now translate each link from the "translate" column (right-most?) at /admin/structure/menu/manage/main-menu.

Now, there are more than one option, entirely depending what you want to achieve on the menu.  For example, suppose there are a node "Hello" and its French translation node of "Bonjour" (they are two different nodes, say, nodes 1 and 2, respectively).  Would you like to provide the two links for both "Hello" and "Bonjour" in the menu (when viewed in either language)?  Or, would you like to provide the link for "Hello" for the English mode/readers, and that for "Bonjour" for the French mode?  (Such is the complexity of multilingual sites...)

Suppose you prefer the second option.  As an example, prepare a single menu link for "Hello/Bonjour" in the main menu; that is, the plan is, "Hello"-menu linked to "Hello"-node(=1) appears if viewed in English, and "Bonjour"-menu linked to "Bonjour"-node(=2) appears if viewed in French.

First you create the "Hello" menu link, linked to node 1.  Second, via the above-mentioned "TRANSLATE" tab in /admin/structure/menu/manage/main-menu/edit, you input the translated title as "Bonjour", and don't forget to change the link to Node=2 to make "Bonjour"-menu correctly point to the French "Bonjour" article.

Now if you view a different French node ("Au revoir" for example) in French (the path-prefix must be /fr/), you will see the menu of "Bonjour", which is linked to the French "Bonjour" node.  If you see its English translation ("Good Bye") in English mode (the path-prefix must not be /fr/), the menu above is "Hello", which is linked to the English "Hello" node.  Job's done.

The thing is, I think it is simpler to set the path-aliases for each content (a single path alias for a set of nodes for all the translations), and basically to give up using the form of node-type links like /node/2 entirely.  In the above-mentioned example, say, suppose you set the path-alias of artilce/hello for the node 1 (English; don't set a different path alias for the node 2, French, as it would add a confusion).  Now by accessing /fr/artilce/hello, you can see the node of "Bonjour" with the French menu.  However, if you access /fr/node/1, what you will see is the English "Hello"-node(=1), while the menu above is French one "Bonjour".  It is because the node=1 is written in English, while you are viewing the content in the French environment, which forces the menu to be in French (if you have enabled localising, other parts like user-menu become also French, but not the main content).

For some people, that may be what they want.  For example, a French shopping site may offer an English interface for shopping-basket etc, while they can't be bothered to translate the description of each item to sell.  I am guessing that is why the i18n in Drupal is designed like this.

Finally, you may want to "Flush all caches" frequently, while you modify the settings, to make sure any change you have made is reflected to what you see.


A module or solution to build first time user walkthrough? Is there a module or existing solution out there that can be used to create first time user walkthroughs of a site? For example, a user logs in for the first time and gets redirected to a certain page and then can follow steps to learn the site etc etc. I have done some googling on the matter but as you can imagine the results are hold to filter when searching for terms like "guide", "walkthrough", "module", "new user" and so on...

The jQuery Joyride module would certainly be an option

  This module provides Drupal integration with Zurb's Joyride Jquery plugin in order to provide a tour of different html elements on your Drupal site. Drupal integration is done via the Context module, which provides a way to control conditional calling of the joyride plugin and copy-and-paste method for adding specific tour code.

It wraps around the excellent jQuery Joyride plugin


How do i use hook_menu to add a menu item into an exisiting menu as the title says i'm trying to add a menu item to the user-menu. I'm using the following code:

function sawqr_menu() {
    $items['user/%user/qr'] = array(
            'title' => t('QR Code Management'),
            'page callback' => 'sawqr_view_embed',
            'page arguments' => array('qr_codes', 'page'),
            'access callback' => 'user_access',
            'access arguments' => array('Administer SAWQR'),
            'menu_name' => 'user-menu',
            'type' => MENU_SUGGESTED_ITEM,
            'weight' => 0
    );

    return $items; /// forgot to add this from my module
}

If this is your real code, then you're missing the return $items; line at the end, looks good otherwise :)

Edit: You are using 'type' => MENU_SUGGESTED_ITEM which means that the menu item needs to be enabled manually in the administration. And when you do, it will show as a sub menu item of /user/%user, which basically means it is invisible because there the default secondary menu position only displays top-level menu items. Try MENU_LOCAL_TASK instead to have it show up as a local task.

P.S.: permission strings are usually all lowercase (they are a technical identifier, not a user facing label or so).


Date math in View table Sorry for any incorrect terminology; I'm new to Drupal so it's possible that I'll mess up the Drupal-specific vocabulary.

I'm putting together a View->Page with a Table Format.

I've got a field in my data set called "registrationdate", and I can display that just fine.  However, what I need to display is registrationdate plus 14 days.  I haven't been able to figure out how to add a number of days to the value so I can display the adjusted value.

I know how to do this in SQL, but since Drupal acts as an abstraction layer between me and the database, I can't do so in this case.

Thanks in advance for your help.

You can change the value using a field template.

Add the date field to your view
Look in Advanced -> OTHER -> Theme: Information for a suitable file name for a field template that will only affect the field in this specific view.  They are listed in order from least specific to most specific so the final one in the list for that field is probably the best one to use.  The link on the filename will show you the default contents for such a file.
Create a file in your theme where you keep template files with that filename
Start with the default contents in that file and refresh your cache
Install devel module and use dpm($output) in your new template file to see the structure of the output
Use PHP to edit the appropriate portion of the output, you may need strtotime() and date_add() to achieve this.

Clear your cache often.  If you haven't already got drush installed, do it, it is a very useful tool.


Drupal 8 Menu Tree issue in my contrib theme possibly because of "Convert menu tree building to a service." Previously, in my Drupal 8 contrib theme, I was rendering the full menu tree as:

function gratis_preprocess_page(&$vars, $hook) {

// Build the main menu links tree.
  $vars['primary_nav'] = FALSE;
  if (!empty($vars['main_menu'])) {
  // Build links.
    $config = Drupal::config('menu.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu');
    // When menu module is not enabled, we need a hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    $vars['main_menu'] = menu_tree($main_links_source);
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
  }
}

However, in testing the theme with the latest Drupal 8 dev, I am getting a WSOD with this specific error:

PHP Fatal error:  Call to undefined function menu_tree() in /themes/gratis/gratis.theme on line 93

Line 93 from the above is:

$vars['main_menu'] = menu_tree($main_links_source);

I did a little searching and discovered this core change: Convert menu tree building to a service. and its corresponding change notice.

I tried adjusting my code to:

$vars['main_menu']= \Drupal::service($main_links_source);

... but now I am getting this error:

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "main". Did you mean one of these: "maintenance_mode_subscriber", "user_maintenance_mode_subscriber"? in Symfony\Component\DependencyInjection\Container->get() (line 303 of core/vendor/symfony/dependency-injection/Symfony/Component/DependencyInjection/Container.php).

So I am at a loss of how to fix this. You can see the repo for my .theme file here.

Cross referencing Render full menu tree in Drupal 8 version.

Update: [working code]

Here is the code in its fixed and working version thanks once again to @Clive

// Build the main menu links tree.
  if (!empty($vars['main_menu'])) {
  // Build links.
    $config = Drupal::config('menu.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu');
    // When menu module is not enabled, we need a hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    $vars['main_menu'] = \Drupal::service('menu_link.tree')->renderMenu($main_links_source);
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
  }

and then we render the wrapper set above with menu_tree__primary

/**
 * Theme wrapper function for the primary menu links.
 */
function gratis_menu_tree__primary(&$vars) {
  return '
' . $vars['tree'] . '
';
}

Does https://drupal.org/node/2226481 help you?

This should be something like

\Drupal::service('menu_link.tree')->renderMenu($main_link_source);


How to show all nodes and comments by a user in a single view? I am using Drupal 8 in combination with the Forum module, and I'd like to show all comments and nodes by a user on his profile page, in a single view.

I can't find a way to get this to work, because they are different entity types.

I've tried using two relationships, but that only gives me rows with each comment linked to each node.

Is this at all possible?

EDIT: This is an example of the result that I'm trying to achieve:

Comment 5
Comment 4
Node 2
Comment 3
Node 1
Comment 2
Comment 1

This is an example of my setup, just switch out article or content type for your content type or forum posts.

node--article--teaser.html.twig:

    {# other fields #}

    {{ content.field_comments }}

or:

    {{ content }}

As long as the comment field is set to display in your teaser view mode, and printed via your template, the comments will show in the view results.

View Config:

The contextual filter is the important part.

This setup uses content format teaser, the alternative would be using fields. Both will work, with fields you may need a relationship to comments depending on what fields you need available in your view.


How to pass multiple objects to hook_view()? I want my hook_view($node) to display not only the $node, but other fancy stuff too - like a table on the bottom using a while-statement. How can I do this?

I am only able to pass one object to hook_view() so I am limited to one object for output? For example:

function Mymodule_load($node) {
  $sql = "SELECT colors FROM ctable,node WHERE ctable.nid=node.nid";
  //returns lots of color (e.g. blue, red, green, pink)
  $result = db_query($sql);
  //here's where I am stuck!
  while($row = db_fetch_object($result)) {
    return $row;  //oh noes! $row keeps getting overwritten
                  //and all my colors aren't being passed to hook_view
  }
}

function Mymodule_view($node,$teaser=false,$page=false) {
  node_prepare($node,$teaser);
  $node->content['colors'] = array(
    // only can display ONE color.
    '#value' => $node->colors
  )
  return $node;
}

The above code returns only ONE color whereas I want ALL my colors to be passed to hook_view().

THE SOLUTION:

while($row = db_fetch_object($result)) {
  $colors[] = $row->colors;
}
$node->colors = $colors;
return $node;

hook_load() gives you the node that was just loaded. The reason it gives you the node is so that you can modify it. So you'd do something like $node->myModule['colors'] = array ( some colors here... ); Read up on the API documentation.

See also the API docs for hook_view().

If you move on to Drupal 7, you can do all this stuff as fields. :-)


User select the filter criteria current_salary_range is 20000. I will show the results also salary range below 20000 I have created the content type named candidate_profile, included fields like Current_Salary_Range.

I have created a view and also I am using better exposed filter for current_salary_range field.

My  question is: When the user selects the filter criteria current_salary_range of 20000, I want to show the results who is having current_salary_range 20000 and also who is having current salary range below 20000.

how to proceed with this...?

In your Content type Manage Fields, what you need to do is make the Current_Salary_Range FIELD TYPE be a (number) Integer field and not a text field.

  Note: You will have to delete and create a new field, as you cannot change field type after the field has been created

Then when you add it as a filter in your view, you should get the option of less than or equal to

Note: picture is from Drupal 8, but should be the same in Drupal 7.


What is the meaning of $form['cid']['#value']? /**
     * @Implement of hook_form_alter()
     */
    function mycaptcha_form_alter(&$form, &$form_state, $form_id) {
     if ($form_id == 'comment_form' && !$form['cid']['#value']) {
。。。。。

Someone has written the above code, but I don't know what $form['cid']['#value'] is for, and what I should use in Drupal 7.

cid is the comment id. And this comment checks if it is empty or not. When it is not empty, it means that we are editing an existing comment as opposed to creating a new one and this code doesn't need to run.


Add CSS class to body for admin-end There are classes in the body like .front and .no-front that are good for styling front page separately and etc.

I am using same theme for front end and back end and would be nice if there was some .admin-end class in the body each time when editing content or just being in admin zone when logged in.

Depending on your theme, you should be able to do something like this:

function YOURTHEME_preprocess_html(&$variables) {
  global $user;

  if ($user->uid) {

    if (arg(0)=='admin') {
      $variables['classes_array'][] = 'admin-page';
    }
    if (arg(0)=='node' && arg(2)=='edit') {
      $variables['classes_array'][] = 'node-edit-page';
    }

  }

}


drupal 8.1 blocks config choices different from D8 I did a migration in Nov/2015 of my D6 to D8 and the blocks look like this.

Then I repeated the migration of my D6 to D8 on May/2016 and my blocks
look like this.

They are different.

Where is the documentation for the configuration of the block visibility

Thanks,

This is not a difference between 8.0 and 8.1, it happens in both versions.

It is a core bug, triggered by ctools. See https://www.drupal.org/node/2632434


Changing width in Bartik theme How do I change the width in the Bartik theme (or better yet, allow it to adjust for different browser sizes)?

I've been trying to link to my drupal site via a Facebook page, and the default width is too large.

I've also downloaded the Bartik-Facebook subtheme, which made the width small enough for facebook, but also removed scrollbars, so that large pages were cut off and could not be scrolled down to.

I'd like the width to be smaller, but still allow scrollbars if the page has too much content.

I haven't yet done any coding regarding modules/themes, so a solution that is simply downloading a module/theme would be preferred, but if developing my own theme/module is the only way, I'm prepared to have a go at that.

If you're not committed to using Bartik, you could try one of the Adaptive Theme subthemes.  These themes are very popular (one of them, Corolla, was intended for inclusion as the default theme in Drupal 7 but lost out to Bartik) and they allow you to change the width of the page easily on the settings page.

They are also responsive, which means that they will automatically adjust the columns on your page to display better on different screen sizes (by default, they provide PC, tablet, and smartphone layouts).  You can also adjust the colors from within the UI just like Bartik.  They are very newbie-friendly (the other major collection of newbie-friendly Drupal themes are the Fusion subthemes).

The base theme is Adaptivetheme, which you must install (though you won't actually use this theme).  Then you can choose from Corolla, Sky, or Pixture Reloaded.


multi-domain recognition at db level I have:

2 domains
single database
Single codebase
single form with a text-editor and submit button.

What I want is the recognition of domain at database level. So, let's say if I hit http://example.com/en it should save in db with table T1 and if I hit http://example.fr/en it should also save in same db but with different table T2.

And now when I will fetch default value from table T1, it should only reflect to http://example.com/en and similarly for T2 it goes here - http://example.fr/en.

But because of same database and code base of both domains it is difficult to know from which domain the request is coming.

I have 1 solution is like create a table in .install file by considering global $base_url; and then check if table name = $base_url.my_table exists, fetch all results.But I'm not sure it's the best approach in Drupal 8 or some other way to achieve this.

Please share best approach for this.

You need to enable multisite.

The documentation inside the settings.php file is also very helpful, read that too by viewing the source of the file here https://api.drupal.org/api/drupal/sites!default!default.settings.php/8.

Briefly, the steps are,

Multi-site requires the existence of the sites/sites.php file in your Drupal 8 installation. You will need to create this file manually.

Example content would be:

<?php
$sites['mysite.com'] = 'site1';
$sites['8000.localhost'] = 'site2';

Create a site directory inside sites/, the path should be sites/site1.
Put a settings.php file in this directory in order for Drupal 8 to recognize it.
Visit the URL of site1, like mysite.com to install it.


Why are my nodes not showing up in a Panel? I am experiencing something strange: the nodes in my Panels are not showing up anymore. When adding content to my Panels, I can select Existing node, pick the right node title (e.g. Test article) and save the Panel without any problem:

But, afterwards, the node is not printed on the according Panel page:

However, everything worked fine in the past and a quick test on a fresh website shows that there is no bug in the Panels module. Also, other entities like Views are displayed just fine. I have already checked some things that might cause the problem:

The node template at Structure/Panels is enabled, but that doesn't matter: disabling it does not change anything.
The node in the Panel does neither have a style, nor any visibility rules.
My custom modules do not interfere with the printing of nodes or panels.
Clearing the caches doesn't change anything.
All users have permission to view published nodes; visiting the node's full page works fine:

Do you have any idea what might be causing the problem?

Since the problem of non-displayed Panes can be caused by quite a lot of things, it can also take quite a lot of time to find a solution (2 days in my case). It turned out that I had overwritten panels-pane--node.php.tpl in my custom theme and that I accidently put an if statement around the whole code, which only returned TRUE for one specific node. Woops...

In order to make the searching process a bit easier for future users who have a similar problem, I will sum up some stuff to try underneath.

Maybe it's a theming thing

If you have a custom theme, your first reflex should probably be to take a look at it. (That being said, my reflexes aren't that good apparently.) First, use a tool like Firebug to inspect your Panel and make sure that the Pane isn't printed. Something like a lost visibility: hidden; can easily be solved in your CSS files. If your Pane just isn't there, maybe there is something wrong with one of your templates. Take a look at the templates that start with panels-pane.

Maybe it's a Panels thing

Take a look at the Pane's settings in your Panel. As CodeNext suggested in the comments above, check that the active style is No Style. In other cases, there can be a problem with (the CSS of) that style. Also, make sure that you didn't set a visibility rule that hides the Pane for you.

Maybe it's a clashing modules thing

P Magunia suggested that the jQuery version can affect the proper working of Panels. If you installed jQuery Update, you can temporarily deactivate this module to see whether something changes. In my case, nothing happened. Also, install the latest versions of all modules on your website. Maybe the Panels module clashes with another outdated module or is outdated itself (see  No Sssweat's comment).

Taking Jimmy Ko's remark into consideration, I reinstalled an old backup of my website, where the problem did not arise, and updated all installed modules. Since the problem was still there, I could convince myself that the hidden Pane was not related to any module. Yet another reason for backing up your website's (WAMP) folder and database.

PS: Maybe it's an alien thing

If none of the above hints worked, no error messages are shown, Google lets you down, and you have been clicking and typing around for days, probably some aliens hacked your website and are making fun of you. Beware, they are potentially dangerous. Never lose your temper...


How to create a page to custom display of particular node type and add it to node context menu? I created custom node type, let's say "My Node".
I created custom node display type (at /admin/structure/display-modes/view), let's say "Specialized Display".
Configured the "Specialized Display" for "My Node" - configured some fields, their order, etc.
How can I create a page on path "node/*/specialized-display" for "My Node" nodes using "Specialized Display"? (I.e. reject "node/123/specialized-display" if "node/123" is not "My Node", but e.g. "story".)
How can I make a tab appear in node context menu (the one which contains "View", "Edit", "Delete" tabs)?
Bonus question: how can I make URL automatic alias(es) "[alias of node/%]/specialized-display"?

What I tried

Created view page, path "node/%/specialized-display", use contextual filter (to reject different node types, use argument for node selection and to alter page title).

Problems:

Couldn't find out how to add it to the node context menu.
It creates redundant node title on the page (one for whole page and one for item in view). Couldn't find out how to remove it, but it's not that big problem, I'll remove is using CSS (although accessibility is going to be damaged).

My system: Drupal version: 8.8.3

First question:
First you are going to want to set your views path to: node/%node/specialized-display. Then, in the contextual filter, under "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED" check off: Specify validation criteria. Finally, select "Content" from the dropdown and select your node type.

Second Question:
This guide explains how to add contextual links, all you are going to need a basic custom module with a routing.yml file. You can set the route to the view. Hint, Drupal console's drupal debug:router is a great way to find the route to your view. https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-contextual-links#s-rendering-contextual-links

Third question:
I've had my best luck with the sub-pathauto module to make the aliased routes. https://www.drupal.org/project/subpathauto

Thoughts...
I am using this setup on two sites so far and this works pretty well. Sub-Pathauto seems to behave fairly well. I do have one tip though, when initially building my views, I disable it, so that I can ensure everything works before I add the extra layer.

Other thoughts...
This could be done through traditional custom views processing. If you have a big site, it may be the way to go. I haven't tested Sub-Pathauto at large scale, this is currently something I am experimenting with.


What would cause certain buttons to not appear on specific fields using the CKEditor? I am using the CKEditor module for Drupal 6 (not the WYSIWYG module). It's successfully showing the editor on a variety of textareas.

However, on a certain content type the editor is behaving differently on the body field than on other CCK textarea fields. Specifically, several buttons are not appearing on the Body field editor that do appear on other textareas in that same form. Additionally, if I change the button order or appearance in the CKEditor Profile, it does update on the other textarea fields but no the Body field. That field keeps the same button set.

I've tried a variety of things:

Deleted and recreated the Global Settings and Profiles for CKEditor
Tried to forcefully show the buttons via CSS
Confirmed there is no config in sites/all/modules/ckeditor/ckeditor.config.js
Confirmed no JavaScript is acting on the CSS class wrapper of one of the buttons being hidden.

I'm stumped. What else could be causing CKEditor to load for the body field differently?

Wow, I am really, really, blind. I missed an errant CSS style that was hiding a child elements of the CKEditor elements in question.


How to get image url in a twig file from a media entity Normally I am able to get an images url by setting the display setting for that field to url and then writing something similar to this in order to print the url

  {{ content.field_image.0['#markup'] }}

However this is not possible in the display settings for a media entity, the only options are -

Rendered entity
Entity ID
Thumbnail
Label

So my question is how to get the url from the image, as I need to use the field as a background image so can't just render it out as normal.

With Twig Tweak module (2.4+) it can be done like this:

{{ node.field_media|file_url }}


CTools CSS Cache Error on Status Page I'm getting this error on the Status report page.

Advice on resolving this?

The "files" directory of your installation (usually located at sites/default/files) must be writable by user the execute the server (Apache, for example).

So, if you have access to a console could try:

sudo chown -R www-data:www-data sites/default/files (for Ubuntu or Debian)
sudo chown -R apache:apache sites/default/files (for Centos or Redhat)


Best Practice: Remove UUID or default_config_hash from Custom Content Type definitions? When I'm exporting the custom content type definitions using the UI, many of the resulting YML files hold a uuid and default_config_hash, like:
uuid: b69d8e54-076c-4a15-a396-19f49369fa68
...
_core:
  default_config_hash: 3aSvUp4PtrivflrkaLdNRL1USkZLsS7NdQroSiRX9mA
...

Now, when I'm using this as a basis for my custom module, is it recommended to remove those lines?

Yes, it is best practice to remove both.
Drupal Console provides these options:
drupal config:export:single \
  --name=config.settings.name \
  --remove-uuid \
  --remove-config-hash

Or export an entire set of YAML files of a content type directly to the modules install folder:
drupal config:export:content:type page \
  --module="demo" \
  --optional-config \
  --remove-uuid \
  --remove-config-hash

See https://drupalconsole.com/docs/en/commands/config-export-content-type


My data content type does not appear as an option on my 'Add content' page I have just created a new content type for my site, and wrote a few rules which act when an instance of that type is created.  I went to create a few test instances of my new content type and noticed that it did not appear on that 'Add content' screen (mysite/node/add.)  'No problem' I thought, 'I'll just go to mysite/node/add/new_type.' However, this failed to work too.  The page loaded as as the url I submitted, but it appeared to be a duplicate of mysite/node/add.  This is a problem because I can not add new content of this type.

I have a few other content type that do not appear on the mysite/node/add, but this was never problematic because I could still create new content of that type by visiting mysite/node/add/some_other_type.

I found that I can create new instances of this content type using Development: Generate Content (and the rules work just fine.)  Still, I have yet to figure out why I cant get to the creation page manually.
What could be causing this?

Edit ===================================

A newly added content type (just called test with no other changes or fields added) does not appear either (even with all permissions set to 'registered user').

It sounds like there is a problem with your menu system.

This is an (educated) guess but rebuilding your menus may help.

Install the devel module and then click on Rebuild menus:


How to remove exposed filter if value is supplied in url? We have a view page (path = /some-path/) that has an exposed filter called category. The detailed view setup is below. How would we hide the exposed filter if it is supplied from the url?

View setup:

Filter criteria:

Settings:

Operator = is one of (list of all tags term values)
Filter type to expose = single filter

Advanced

Require relationships for field_tags
when the filter value is not in the url --> display all results for the specified field
when the filter value is in the url or default is provided

a. specify validation criteria -> validator -> taxonomy term name where vocabulary = tag

b. action to take if filter value does not validate = display contents of no results found

c. case = lower case

d. more -> transform spaces to dashes in url -> enabled

Expected behavior:

when /some-path/ is navigated to, then the exposed filter should show
when /some-path/term-value/ is navigated to, it will filter the results and hide the exposed filter

Current behavior:

navigating to /some-path, shows all results with the exposed filter displaying allowing a visitor to change it.
navigating to /some-path/value2/ filters the results and displays the exposed filter.

Here's a clever way to do it without coding: use two different Views displays and embed one of them as View area into another's No results behavior and configure the contextual accordingly.

Create the Page with the Exposed Filter but without the Contextual filter
Duplicate that Page to create another Page display with the same Path, but make these changes:

override the Filters and remove the Exposed filter
override the Contextual filters and Add your Term name there with these settings:
When the filter value is NOT available
Display contents of "No results found"
When the filter value IS available or a default is provided
Specify validation criteria
[your settings]
Action to take if filter value does not validate
Display contents of "No results found"
Override the No results behavior, add View area and choose the first Page display under View to insert (the one with the Exposed filter). Save the View if you don't see that display as option at first.

This way you get the first page to kick in for /some-path and you see the exposed filter, but if you add a term name to the path and it validates /some-path/value2/ the second Page display kicks in and you don't see the Exposed filter, you see the contextual results.

If the argument doesn't validate, you see the first Page and allow users to choose the term from the Exposed filter. You can change that to something else if it makes more sense. The part that makes this views switching work is the first part of the contextual filter When the filter value is NOT available
Display contents of "No results found" and the embedded View area.


Is there any case where a module needs to implement a class using ServiceProviderInterface? Drupal defines the CoreServiceProvider class which is used to add the twig, twig.loader.filesystem, and module_handler services.

Since the Drupal 8 way to register a service from a module is using the <module name>.services.yaml file, is there any case where a class similar to CoreServiceProvider should be used?

In short, nope. The Twig service registration is written by Fabien Potencier himself and I doubt anyone will have anything as complex as Twig to necessitate this level of complexity in registration. The module handler is just fanciness, we could've written an override for the module handler during install time. Unless you are writing an install profile which uses a service, you won't face this problem.


What kind of content ends up in the "System help" block? How could I answer this question myself? I saw the answer to this question and wanted to enable the "System help" block. When I did, I wondered what other content would be showing on my site besides the "Explanation or submission guidelines" field upon node editing.

Via some grep-ing, I found modules/block/block.module and from what I can tell the block is populated from code there. But it isn't clear to me what would end up in that block. What's the correct "Drupal way" of knowing?

Help content, defined in hook_help is added to the "System help" block for display in

system_block_view

via

menu_get_active_help

which returns the valid help content for the current menu path.

  How could I answer this question myself?

You can answer this question yourself by

Studying the Drupal API
Grepping / searching the codebase for relevant text
Asking on Drupal Answers ;)


How can I remove the space between fields show in a view that are output with a custom template? I have a view that has two fields, A and B.  Both of these fields are modified using a views-view-field--myfield.tpl.php file.

In my output, I want the fields to be displayed as:

  AB (no space in between the values)

However, no matter what I do, it seems that Views puts a space between the two fields.  I am using an Unformatted list and under Settings I have unchecked Add views row classes as well as Add striping (odd/even) rows classes.  This has no effect on the spacing.

Under Settings for Fields, I have unchecked Provide default field wrapper elements.  Again, the spacing remains.

I tried rewriting the results of the fields by inputting [field_fieldA][field_fieldB] under Rewrite the output of this field, but, while this output is shown in the preview in the Views admin interface, it is overwritten by the views-view-field--myfield.tpl.php file for the relevant field.

How can I output two values, both of which are output via template files, without a space between them?

I just created a quick View here that had three fields:

1.  Node title.
2.  Node type.
3.  Global Custom Text Area

I changed the HTML Element and Wrapper HTML Elements to SPANs for the first two fields and also set them both to be excluded from display.

For the Global Custom Text Area, I rewrote its output to be [title][type] and got the titles smashed right up next to the node types without a space.

ADDITION:

You could also copy views-view-field.tpl.php to views-view-fields--smashed.tpl.php (or whatever your Views name is :) and then remove all the whitespace from there, eg, this template looks nice like this:

 <?php something ?>
   <?php something else ?>
   <?php something else again ?>
 <?php yadda yadda ?>

and each of those lines and indents puts in the whitespace that is causing your grief.

If instead this is saved as

 <?php something ?><?php something else ?><?php yadda yadda ?><?php one really big long line of code without any intervening tabs or new lines or spaces ?>

and your view will be created with the <divs> or <spans> smashed right up next to each other in the row.  Then CSS it up the way you want.


In Node References, how to show a custom field, instead of the Title? Is it possible to show in a select list, another field instead of the Title when referencing a node?

As dobeerman says you can use a View as a source, but CCK does some playing with the View behind the scenes (I just found out as a result of this question;). If you look in nodereference.module at the function _nodereference_potential_references_views() you'll find the following code:

// We do need title field, so add it if not present (unlikely, but...)
$fields = $view->get_items('field', $display);
if (!isset($fields['title'])) {
  $view->add_item($display, 'field', 'node', 'title');
}

// If not set, make all fields inline and define a separator.
$options = $view->display_handler->get_option('row_options');
if (empty($options['inline'])) {
  $options['inline'] = drupal_map_assoc(array_keys($view->get_items('field', $display)));
}
if (empty($options['separator'])) {
  $options['separator'] = '-';
}
$view->display_handler->set_option('row_options', $options);

So this means that

if you don't include a title field then it will be included for you;
if you don't make all fields inline and define a separator then it will be done for you.

So if you configure the title field to be hidden, and specify an appropriate separator, you should be able to create just about any effect. If you can't achieve what you want with a view (eg. ordering nodes by their menu position) then you want to use a different approach.

You could create your own CCK widget, or (simpler) you can use a form_alter hook. If you do the latter, you can't edit the form the normal way because CCK hasn't processed the form at this stage - you'll want to use a #after_build function.

I have an example of the second approach used to show nodereferences ordered by the menu if you're interested.

/**
 * Implements hook_form_alter().
 */
function banners_form_alter(&$form, &$form_state, $form_id) {

  // Modify nodereferences for banners so that pages are shown in primary links
  // order.
  if ($form['#id'] === 'node-form' && isset($form['#field_info']['field_pages'])) {

    if (!isset($form['#after_build'])) {
      $form['#after_build'] = array();
    }
    $form['#after_build'][] = 'banners_after_build';
  }
}

/**
 * After_build callback for modifying CCK field select options.
 */
function banners_after_build($form, &$form_state) {
  // Get the menu data
  $new_options = banners_generate_page_options();

  if (isset($form['#field_info']['field_pages'])) {
    $old_options = $form['field_pages']['nid']['nid']['#options'];
    $final_options = banners_process_options($new_options, $old_options);
    $form['field_pages']['nid']['nid']['#options'] = $final_options;
  }

  // Return new form
  return $form;
}

/**
 * Uses the old options to filter out unreferenced nids and add those that
 * weren't detected in a menu structure to the other option group.
 * @param $new_options
 *   The options list created by scanning the menus.
 * @param $old_options
 *   The options list originally passed to the form.
 *
 * @return
 *   The final options list with option groups for each menu and for orphans.
 */
function banners_process_options($new_options, $old_options) {
  // Have to assume that $old_options could get quite large, whereas
  // $new_options is based on menus, and shouldn't get too large.

  // Iterate through $new_options (the menu nids) and remove nids from
  // $old_options that exist in $new_options, and remove nids from $new_options
  // that don't exist in $old_options. After this $old_options has valid nids
  // that aren't under the menu hierarchy.
  foreach ($new_options as $menu_title => $options) {
    foreach ($options as $nid => $title) {
      if (isset($old_options[$nid])) {
        unset($old_options[$nid]);
      }
      else {
        unset($new_options[$menu_title][$nid]);
      }
    }
  }

  $final_options = array();

  // If the field is not marked required, there'll be an option for - None -
  // and it's keyed to the empty string.
  if (isset($old_options[''])) {
    $final_options[''] = $old_options[''];
    unset($old_options['']);
  }

  $final_options += $new_options;

  $final_options['Others'] = $old_options;

  return $final_options;
}

/**
 * Generates FAPI options for the allowed menus' node links.
 *
 * @return
 *   A FAPI options array with all node links on the allowed menus (NB this has
 *   not been filtered in any other way).
 */
function banners_generate_page_options() {

  $menus = array('primary-links', 'menu-top-menu');
  $options = array();

  foreach ($menus as $menu_name) {
    $tree = menu_tree_all_data($menu_name);
    $menu = menu_load($menu_name);
    $options[$menu['title']] = _banners_process_tree($tree);
  }

  return $options;
}

/**
 * Recursive function to generate the options array, keyed by nid.
 */
function _banners_process_tree($tree, $depth = 0) {

  $options = array();

  foreach ($tree as $item) {
    $matches = array();
    if (preg_match('~^node/(\d+)$~', $item['link']['link_path'], $matches)) {
      // Link points to a node
      $nid = $matches[1];
      $options[$nid] = str_repeat('--', $depth) . ' ' . $item['link']['title'];
      if ($item['below']) {
        $options += _banners_process_tree($item['below'], $depth + 1);
      }
    }
  }

  return $options;
}


Data export import module node id different after imported I using Data export import module in my new Drupal 7.

I imported Drupal 6 database into Drupal 7 site.

But unfortunately the node id for the same article is different.

How do I fix this?

You can use UUID module, some quote from module page :

  This module provides an API for adding universally unique identifiers
  (UUID) to Drupal objects, most notably entities. Features in Drupal 7
  version Automatic UUID generation

  UUIDs will be generated for all core entities. An API is provided for
  other modules to enable support for custom entities. UUID API for
  entities, properties and fields

  With this unified API you can load entities with entity_uuid_load() so
  that all supported properties and fields are made with UUID
  references. You can also save entities formatted this way with
  entity_uuid_save() (depends on Entity API). Export entities to use as
  default/demo content

  The integration with Features module provides the ability to export
  UUID enabled entities with intact dependencies and references to other
  entities. This functionality depends on Deploy module 7.x-2.0-alpha1
  (soon to be released) and is probably the most robust way for
  installation profiles and distributions to provide demo content!

The problem is that Drupal uses serial ids for the content (nodes), so if we have the same site installed different places, the id for the same content most likely will be different. (fx in one environment the node id might be 137, while it on another might be 153)
This makes it very hard to track changes on the same content in different environments. The idea with UUIDs is to create a id that is the same on all environments.


How to attach a library to a specific content type? I wonder how to attach a library to a specific content type. .e.g News. I found the following code from a post and applied the "hook" to the "node" but no idea how to filter by content type. Any idea?

function fluffiness_preprocess_node(&$variables) {
  $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
}

ref:
https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

You can check content type and add libraries like this:

function fluffiness_preprocess_node(&$variables) {
  $node = $variables['node'];
  //check content type
  if ($node->getType() == 'article') {
    $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
  }
}


Content profile fields not showing up on user registration page I have created content profile fields that I would like to appear on the user registration form. I am using drupal_render to render these fields on a custom user registration page but they are not appearing. However the other non content profile fields are appearing. Any ideas as to what I could possibly be doing wrong?

I am using Drupal 6.26

Thanks.

Can you see the fields when you create a user as admin (admin/user/user/create)? If so, this means that permissions are not properly assigned to authenticated users to create those fields. So you need to go to permissions page and edit permissions to each new field that you have created on profile node type.


APC caching with Drupal I am confused how APC caching hooks into Drupal system or vice-versa.What I knew so far is APC caches the opcodes for the currently being executing PHP file so next time the various compilation steps can be avoided and then opcodes are served directly from RAM. Since a Drupal page is built with various functional blocks like blocks, node, I am not getting how APC helps it serving fast.I know it does but how?

APC is PHP's op code cache. If you enable it then it works for any PHP code. All of your Joomla/Wordpress or Drupal sites will execute faster provided you have high value of Hit/Miss ratio( or increase APC RAM if it's less).

If you want further optimization then Drupal can use APC for caching( instead of storing in mysql tables) using Drupal's APC module. I'm not sure about this sentence though.

I too was confused in the same way :)


Why is my file upload always NULL in $form_state? I've build a form where the user can upload an image as avatar for his profile. But I have an issue as the selected image is not being recognized at all.

I used the image example from drupal.org, this is my minimal code not working at all:

function my_edit_form($form, $form_state, $entity) {

  $form['picture']['picture_upload'] = array(
    '#type' => 'file',
    '#title' => t("Upload picture"),
    '#description' => t("Your virtual face or picture. Pictures larger than 150x150 pixels will be scaled down."),
    '#upload_location' => 'public://pictures/',
    '#size' => 48,
  );

  return $form;
}

Now, I'm trying to use the file() functions as described in the documentation but it seems my $form_state['values']['picture'] is always NULL.

function my_edit_form_submit($form, &$form_state) {
  dpm($form_state);
}

I have no idea how that's possible and I'm a bit lost here. Any idea what else I could try?

Okay, this is tricky how Drupal handles the file uploads and took me some time to figure out.

$form_state indeed shows NULL or empty strings or empty arrays for my file upload unless I add a proper upload function. The file exists but is not uploaded yet.

It's worth taking a look at user_validate_picture():

function user_validate_picture(&$form, &$form_state) {
  // If required, validate the uploaded picture.
  $validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
  );

  // Save the file as a temporary file.
  $file = file_save_upload('picture_upload', $validators);
  if ($file === FALSE) {
    form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('user_picture_path', 'pictures'))));
  }
  elseif ($file !== NULL) {
    $form_state['values']['picture_upload'] = $file;
  }
}

Calling this function from inside my own validation function will upload the file to temporary://What-is-Sustainability_0.png and it's now visible in $form_state['values']:

This is what I was looking for, now I can simply save the file where I need it and have the fid available to link it to entities.


How do I use rules to iterate over the subscribed users of a organic group to send email notifications? Using the great tutorial at http://webwash.net/tutorials/log-site-activity-message-and-rules I have been able to set up my Site Activity Log. I now want to extend it to be able to use message_subscribe and message_notify to send users, that are following the organic group, an email with the info. In rules I have been able to add an action Send Message with Message notify. However, I can't seem to set "The recipient of the email" to users that flagged (following) the group. Any insight into how to pull this into the rule would be much appreciated.

There is a Flag action called Fetch users who have flagged [entity]. It will generate a list of users that you can then loop through and perform action on (e.g. send an email to). And since OG groups are entities, it should work (although I have not tested this). Also, beware that this might not scale if you have upwards of 1000 subscribers.

Reference: Nodeone's Learn the Rules framework. Checkout part 22 Flag and Rules: overview at the 4:00 minute mark.


How to change the duration of user access? By default Drupal keeps users logged in 2.000000 seconds, i modify in settings.php at the line:

ini_set('session_cookie_lifetime',2000000);

It is right ?

Yes. You are correct. Changing these settings will change the session time for logged in users.


Is it possible to run Drush without root? I run a Linux server that is administered by a friend of mine, and at the moment I work with Filezilla.

I've heard that Drush is a trivial installation: it seems to require no configuration and work out of the box.

However, it looks for configuration in several places:

  Drush installation directory,  the home directory (as .drushrc.php),
  root directory of a Drupal installation, and  site directory of a
  Drupal installation.  Since the configuration files are just PHP
  scripts, they can  contain any PHP code that you would like to have
  executed on startup of Drush.  one could for instance call ini_set()
  to set the value of a PHP configuration option.

and the configuration file /opt/drush/drushrc.php with following content:

# Allow Drush to use 128 MB of memory. Use -1 for no limit. ini_set('memory_limit', '128M');

I see this is necessary because PHP's default is too low, but I'm not sure if I need higher-level privileges because of it.

Do I have to have root-level permissions on the server, or am I able to work with Drush without them?

Update:  As far as i understand this, i only have to ask my admin to get some more privileges (permissions)Note according to BetaRides answer i need to have more than only the access-data that the FileZilla needs - that are provided for the filezilla! Guess so - but i don not need root-permissions.

btw - i have secure-shell-access (ssh2 access) guess that this is enough -With that i can setup a sftp-connection to the server with filezilla just lemme know - if i can use the exactly same data for the shell access (with the command line tool=?!=

You do not need root-level permissions to use Drush: it'll work as long as the user invoking it has direct access to the Drupal installation directory.

Having the the same filesystem permissions as the web user should be enough for most operations: but for things like downloading modules, you'll need write-level access to the Drupal directory as well.


updating database fields of custom entity I have updated my site to drupal 8.4.  Has installFieldStorageDefinition() changed in 8.4? Previously code such as below successfully added an entity reference field to my custom entity database table.

  $storage_definition = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Evaluation'))
    ->setDescription(t('The Evaluation the team evaluates'))
    ->setRevisionable(TRUE)
    ->setSetting('target_type', 'evaluation')
    ->setSetting('handler', 'default')
    ->setDisplayOptions('view', array(
      'label' => 'inline',
      'type' => 'entity_reference_label',
      'weight' => -10,
    ))
    ->setDisplayOptions('form', array(
      'type' => 'options_select',
      'weight' => -10,
    ))
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('eval_id', 'project_team', 'team', $storage_definition);

Is there a change that should be  made?  Thanks.

If you look at this guide, defining field definitions, it all looks right. Do you get any errors, or does it still work?

Remember to clear the cache.


How to map term name via XPath node feed using xpathparser into Term reference field? I have an xml feed to import to and mapped to a content type. However, there are fields that are referenced to taxonomy. The fields that are not referenced seems to be working fine and are getting picked up. But those that are referenced to a taxonomy vocabulary are not.

How can I import data from xml from say:

<properties>
  <item>
    <refid>1234</refid>
    <propertytype>Apartment</propertytype>
    <!-- ... -->
  </item>
</properties>

I want to be able to import propertytype to this content type as 'Apartment' as referenced to a taxonomy vocabulary - Property Types:

Property Types (Taxonomy Vocab)
Apartment
Townhouse
Villa
etc...

I've learned that taxonomy referenced fields stores data to a separate table in the database. Does this mean I have to manually do insert query to these tables separately? Or is has anyone encountered the same predicament?

You create taxonomy vocabulary by name property types and attach this to the content type you are using for feeds import.
Map the fields accordingly.

//properties/item as context
propertytype to the term reference field you have attached to the content-type

But remember just create vocabulary and don't add any terms. Once you do feeds import you can see the terms under property type vocabulary.


Improving performance with Field Collections? I'm using using entity reference, field collection , and field collection table modules on a site that features "courses" and "lessons" as content types. A field collection with unlimited values is embedded in the course content type, and it contains two fields: a text field for "section" and an entity reference field for "lesson". This allows the same lessons to be reused in different courses, while appearing under a different section. (see screen for reference).

This works pretty well, but performance when editing course nodes starts to degrade significantly after about 30 lessons are added to a course. At 100 lessons, it takes about 15 seconds to load a course for editing. With 140 lessons in a course, it takes about 22 seconds to edit a course node. I'm testing locally on a new D7 test site with devel-generated content.

Questions:

(1) Are there any obvious steps I should take to improve performance with field collections?

(2) As an alternative to field collections, would creating a compound field in code likely improve performance significantly?

(3) For testing performance generally, is there a simple profiling tool I can use with Drupal?

Example of a small course with 10 lessons added as field collections:

Update: In the end, I abandoned field collections and created a custom compound field that is attached to the 'course' content type.

This pretty much eliminated the performance problems. Opening a course node with 130 lessons in the field now takes 3-6 seconds, depending on the server.

And because the field is unlimited multivalue, the delta works a sorting mechanism for the lessons in views, etc.

I also added code to add more than one item at a time as seen here:

Slow "Add another item" with unlimited valued fields

When there are a lot of items in the field, adding a new item ends up taking a lot of time.

Good resources:

http://www.phase2technology.com/blog/compound-fields-in-drupal-7/
https://drupal.org/project/examples (field example)
https://api.drupal.org/api/drupal/modules!field!field.api.php/7


Add Attribute to Textfields in Admin Theme I'm often working with Pages in RTL Languages where the default Theme and also the admin theme are using RTL languages.

What often bothers me, is to use LTR texts like Tokens or Paths in Textfields, because the specialchars like / or [ are shifted.

To solve this, i would like to add the dir=auto attribute to all Textfields in admin Theme.

So the textfields should look like this:

< input type="text" id="edit-file-public-path" name="file_public_path" value="sites/default/files" size="60" maxlength="255" class="form-text" dir="auto">

My idea was to create a Subtheme of Seven and use the template_preprocess_field function to add the dir attribute to all fields.

My issue is, that my Preprocess function is never called.

Are the preprocess functions called in admin Theme? And is there an another way to do this?

myseven.info file:

name = My Seven
description = Admin theme based on seven admin Theme
package = Core
version = 1.0
core = 7.x
base theme = seven
stylesheets[all][] = css/myseven.css
settings[shortcut_module_link] = 1
regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[sidebar_first] = First sidebar
regions_hidden[] = sidebar_first

template.php Function

function myseven_preprocess_field(&$variables, $hook){
    dsm($variables);
    watchdog("Hello World!","The preprocess_field Works!"); //if this function is ever called there should be an entry in Reports
    }

template_preprocess_field is for field output themeing not input field themeing, you maybe looking for theme_textfield or hook_field_widget_form_alter


Create a multistep Webform and set to "non-linear" with sidebar showing which steps have been completed? I have several steps in my Webform that require certain values to pass each step.

This is done by Webform Validation and seems to work fine, however how can I turn the Webform into something that's "non-linear" allowing users to jump to any page they want to complete with ease.

Ideally I'd want to move the titles for each multistep page to a sidebar menu which would show the status of whether that page is completed or not.

Is there any modules that do something similar already?

I searched for how to create this functionality, and found this on the drupal site Link for creating multi-step webforms


Can't find cookie for validation in EventSubscriber There's this module Splash Redirect in which src/EventSubscriber/SplashRedirectEventSubscriber.php is supposed to check if the cookie $config_cookie exists or not, if it already exists then the user continues onto the requested node ($config_source), but if it does not exist then the user is sent to $config_destination and it creates the cookie ($config_cookie).

It succeeds in creating the $config_cookie and the redirect to $config_destination but it never seems to acknowledge the existence of the cookie once created and continues to redirect the user to $config_destination.

Any clues? On Drupal 8.6

<?php

namespace Drupal\splash_redirect\EventSubscriber;

use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Routing\TrustedRedirectResponse;

/**
 * Splash redirect Event Subscriber.
 */
class SplashRedirectEventSubscriber implements EventSubscriberInterface {

  /**
   * Triggered when system sends response.
   */
  public function modifyIntercept(GetResponseEvent $event) {
    $config = \Drupal::config('splash_redirect.settings');
    $config_enabled = $config->get('splash_redirect.is_enabled');
    $config_source = $config->get('splash_redirect.source');
    $config_destination = $config->get('splash_redirect.destination');
    $config_cookie = $config->get('splash_redirect.cookie_name');
    $config_duration = $config->get('splash_redirect.duration');

    // If splash config is not enabled then we don't need to do any of this.
    if ($config_enabled == 1) {
      // Current request from client.
      $request = \Drupal::request();
      $current_uri = $request->getRequestUri();
      $http_host = $request->getHost();
      // Current response from system.
      $response = $event->getResponse();
      $route = (\Drupal::routeMatch()->getParameter('node')) ? \Drupal::routeMatch()->getParameter('node')->id() : null;
      $has_cookie = $request->cookies->has($config_cookie);

      // If splash-cookie has not been set, and user requesting 'source' page,
      // set cookie and redirect to splash page.
      if ($config_source == $route) {
        // Kill cache on this route or else cookie might not be read with VCL.
        \Drupal::service('page_cache_kill_switch')->trigger();

        if (!$has_cookie) {
          // Set redirect response with cookie and redirect location.
          $redir = new TrustedRedirectResponse($config_destination, '302');
          $cookie = new Cookie($config_cookie, 'true', strtotime('now + ' . $config_duration . 'days'), '/', '.' . $http_host, false, true);
          $redir->headers->setCookie($cookie);
          $redir->headers->set('Cache-Control', 'public, max-age=0');
          $redir->addCacheableDependency($config_destination);
          $event->setResponse($redir);
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Listen for response event from system and intercept.
    $events[KernelEvents::REQUEST][] = ['modifyIntercept'];
    return $events;
  }

}

Some ideas:

Like for the config you have to add a cache dependency for the cookie, too:

  $response->getCacheableMetadata()->addCacheContexts(['cookies:' . $config_cookie]);

Or use an uncacheable RedirectResponse to simplify things.

And try to set a priority for the event subscriber, for example 31, because your code depends only on routing, which has 32:

  $events[KernelEvents::REQUEST][] = ['modifyIntercept', 31];

You don't need to get a response in an request subscriber, because there isn't one yet. Get the request instead and make sure that you are in a master request. So this would be how the subscriber starts most times:

  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    $request = $event->getRequest();
    ...

Simplifying a bit more and using dummy values for testing:

  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    $route_match = \Drupal::routeMatch();
    if (!$route_match->getRouteName() == 'entity.node.canonical') {
      return;
    }
    $request = $event->getRequest();
    if ($route_match->getRawParameter('node') == '1') {
      \Drupal::service('page_cache_kill_switch')->trigger();
      if (!$request->cookies->has('foo')) {
        $redirect = new RedirectResponse($request->getBasePath() . '/node/2', 302);
        $redirect->headers->setCookie(new Cookie('foo', '123', '+30 seconds'));
        $event->setResponse($redirect);
      }
    }
  }

This is working on my local dev environment.

Complete code (including dependency injection):

/src/EventSubscriber/MymoduleSubscriber.php

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Cookie;

/**
 * mymodule event subscriber.
 */
class MymoduleSubscriber implements EventSubscriberInterface {

  /**
   * The route match.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Constructs event subscriber.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   */
  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  /**
   * Kernel request event handler.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   Response event.
   */
  public function onKernelRequest(GetResponseEvent $event) {
    if (!$event->isMasterRequest()) {
      return;
    }
    if (!$this->routeMatch->getRouteName() == 'entity.node.canonical') {
      return;
    }
    $request = $event->getRequest();
    if ($this->routeMatch->getRawParameter('node') == '1') {
      \Drupal::service('page_cache_kill_switch')->trigger();
      if (!$request->cookies->has('foo')) {
        $redirect = new RedirectResponse($request->getBasePath() .'/node/2', 302);
        $redirect->headers->setCookie(new Cookie('foo', '123', '+30 seconds'));
        $event->setResponse($redirect);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => ['onKernelRequest', 31],
    ];
  }

}

mymodule.services.yml

services:
  mymodule.event_subscriber:
    class: Drupal\mymodule\EventSubscriber\MymoduleSubscriber
    arguments: ['@current_route_match']
    tags:
      - { name: event_subscriber }


How to send e-mail on user account update, but not on password reset? I want to send an e-mail after a user profile is updated but not if they are only resetting their password.

I already have the rule working so that when the user profile is updated it sends the e-mail with all the user details, but rules recognises a password reset as an account update. I don't want an e-mail to be sent if it's only a password reset.

Neither of the below rules work as expected, the first one only fires if both fields are changed, if i change the first field but not the second I get this message in the log file "Unable to evaluate condition data_is." if I only modify the second one then I don't get the e-mail.

{ "rules_account_update_2" : {
    "LABEL" : "Account Update 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-first-name" ],
          "value" : "[account:field-first-name]"
        }
      },
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-last-name" ],
          "value" : [ "account:field-last-name" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "",
          "message" : "",
          "from" : "",
          "language" : [ "" ]
        }
      }
    ]
  }
}

The rule with an OR condition, this just never fires no matter what fields I change.

{ "rules_account_update_2" : {
    "LABEL" : "Account Update 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-first-name" ],
          "value" : "[account:field-first-name]"
        }
      },
      { "OR" : [  ] },
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-last-name" ],
          "value" : [ "account:field-last-name" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "",
          "message" : "",
          "from" : "",
          "language" : [ "" ]
        }
      }
    ]
  }
}

1st rule

About your 1st rule, for which you wrote in your question this:

  Neither of the below rules work as expected, the first one only fires if both fields are changed

Sorry to say, but the Rules module is working as designed ... because within your Rules Conditions, you basically specified that BOTH conditions must be satisfied.

Actually you did not specify an AND or an OR, and therefor the 2 Rules Conditions are combined with the default operator ... which is AND.

2nd rule

About your 2nd rule, for which you wrote in your question this:

  The rule with an OR condition, this just never fires no matter what fields I change.

Sorry to say (again), but the Rules module is working as designed ... because within your Rules Conditions, you basically specified that 3 conditions must ALL be satisfied, i.e.:

Field "first name" must be changed, AND
Some "empty" OR construction must be TRUE (as is shown with the line in your exported rule that looks like { "OR" : [  ] }, ... there is nothing between the [  ] in it), AND
Field "last name" must be changed.

Your crucial error is within that 2nd condition: you started to add on "OR" construction, but you didn't specify the 2 conditions for which that "OR" should be used. You probably thought that Rules Condition 1 and 3 are the 2 conditions to be combined with that "OR", but that is not how the Rules syntax is like (confusing, I know, many users struggle with this ...).

Therefor, try this variation of your rule (and don't forget to complete the Rules Action to actually send that eMail):

{ "rules_account_update_2" : {
    "LABEL" : "Account Update 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "OR" : [
          { "NOT data_is" : {
              "data" : [ "account-unchanged:field-first-name" ],
              "value" : "[account:field-first-name]"
            }
          },
          { "NOT data_is" : {
              "data" : [ "account-unchanged:field-last-name" ],
              "value" : [ "account:field-last-name" ]
            }
          }
        ]
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "",
          "message" : "",
          "from" : "",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Note the difference here: this rule has 1 Rules Condition, which is an "OR"-construct, and 2 (sub) Conditions to be combined with that "OR" are your 2 Rules Conditions about first name and last name.

BTW, when debugging / developing Rules with a Rules Action to send an eMail, I always (temporary) replace such Rules Action with just a "display a message" (like "It works! Just rework the display of this message now to sending an eMail").

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


Search taxonomy terms with node_search_execute() I tried to use node_search_execute() to search nodes. So far, running the function is easy. I noticed that there was a $conditions parameter from the documentation of hook_search_execute().

Is there a way to extend the search function to also search for taxonomy terms?
Simple friendly pointers to guide me to do fast and complete node search are also welcomed.

Actually, the only missing part is the form field that should allow the users to select the taxonomy terms used from the nodes they are looking for. The code used from Drupal 7 (and Drupal 8) is still looking for the corresponding values in $form_state['values'].

If you look at the code used by node_search_validate(), the form validation handler added by node_form_search_form_alter(), you will notice the following lines.

  if (isset($form_state['values']['term']) && is_array($form_state['values']['term']) && count($form_state['values']['term'])) {
    $keys = search_expression_insert($keys, 'term', implode(',', $form_state['values']['term']));
  }

If you then look at the code used by node_search_execute(), you will notice the following lines.

  if ($query->setOption('term', 'ti.tid')) {
    $query->join('taxonomy_index', 'ti', 'n.nid = ti.nid');
  }

Effectively, the functionality of searching those nodes that use specific taxonomy terms has not been removed; it has been hidden to the users who don't have anymore a way to tell the Node module to which taxonomy terms they are interested. This seems rather unintentional; probably the feature was supposed to be completely removed, but the submitted patch removed just the code for the user interface. I cannot find the related issue opened on Drupal.org, and I cannot say if my supposition is correct.

Until the code in node_search_execute() and node_search_validate() is not changed, all you need to do is adding the form fields in the search form, keeping in mind that the Node module is looking for $form_state['values']['term']. (In other words, the form field added for selecting the taxonomy terms should be in $form['term'].)

If, and when, that code is removed, adding that form field would not have anymore any effect.
Drupal doesn't allow a module to alter how a module integrates with the Search module. As a matter of fact, Drupal uses hook_search_info(), but no hook_search_info_alter(); if you would want to extend how searching a node is done (for example, by adding more options), you would need to alter the page callback assigned to search/node and search/node/%menu_trail. See search_menu().


Problem with adding content I allow my administators to add panels, articles, blog posts, forum topics, etc but it only shows the default set that regular users get which is blog posts and forum topics. Ive checked and all the people are set to admin. How do i fix this?

You need to go into People -> Permissions -> Roles.  Find the administrator role and click on 'Edit Permissions'.

Then, go down to the Node section, and check off the appropriate permissions for viewing, creating, editing, deleting, etc.. that particular content type.  The permissions actually look like this:

Article: Create new content [ ]
Article: Edit own content   [ ]
Article: Edit any content   [ ]
Article: Delete own content [ ]
Article: Delete any content [ ]

You'll of course want to check off probably all of those if the role is an administrator, as typically they'll have absolutely power over your application.  That is, if it's what you intend.  The power of Drupal is yours :)


How to merge results from two different views? I need to write an impossible view and I achieve to retrieve the correct list of nodes in two different views and now I need to merge the results in one single table.

How can I merge it?

If the views_1 give me nodes: [2, 52, 68, 41]
and the views_2 give me nodes: [2, 66, 88]
I want ONE table with the nodes: [2, 52, 68, 41, 66, 88]

I can't just merge filter's views because they are based on two relationships so I can't say to require one relationship OR the other one, but only to require one or both relationship.

Output one view as you normally would.

Implement views_pre_render.
Call view::preview on the second view.
Manually merge the results from 2 into 1.


Explanation of pear's include path, and why Drush cr clears it? I got an error message when trying to import Drupal configuration with drush cim, saying the following:

include_once(/var/www/d8site/modules/custom/somemodule/somemodule.module):[warning]
failed to open stream: No such file or directory Extension.php:140
include_once(): Failed opening                                       [warning]
'/var/www/d8site/modules/custom/somemodule/somemodule.module' for
inclusion (include_path='.:/usr/share/php:/usr/share/pear')
Extension.php:140

The somemodule.module file was deleted between versions, but it's still expecting it.  Restarting and/or reloading Apache didn't get rid of this message, but drush cr did.  I don't want to have to clear the entire Drupal cache on production, so how could I update this include list without clearing all cache with drush?  If I didn't have pear installed, would this be any different?

Pear has no connection to this. The error message displays the include path value in brackets for debugging purpose. You can check the value as follows:

drush ev 'print get_include_path();'

In your case the PHP is trying to include the file from this location and emits the error as it fails.
/var/www/d8site/modules/custom/somemodule/somemodule.module

My guess the file still presents in Drupal registry because the module wasn't uninstalled properly. Check out this guide to fix it. https://www.drupal.org/node/2487215


hook form submit being called twice In the following code custom call back function is being printed twice. How to prevent submit call back function being called twice.

function my_module_form_alter(&$form, &$form_state, $form_id){
 if ($form['#id'] == "views-exposed-form-test-page"){
    $form['#submit'][] = 'custom_callback';
  }
}

function custom_callback($form,&$form_state){
    $form_state['redirect'] = false;
    dpm("insert record");
}

hook_form_alter() will fire once for every time there is a form on the current page.

You can try the hook hook_form_FORM_ID_alter(). This will only run once when the form with the specific ID pops up.

Unfortunately I had this issue happen before, the hook_form_alter() ran multiple times. I stopped the code from running multiple times by encapsulating the code inside an IF statement inside the hook_form_alter() example: if($form_id == my_id). So the hook ran multiple times but the code only ran once.


Views Conditional Fields According to Devices Does views allows to render fields according to device. For example is there a possibility to load field a if website is loading on iphone, load field b if device is loading on android.

or

load field 1 if website is loading on smart phones, load field 2 if tab and load field 3 if desktop.

As of now, I don't think views supports this. But you can use the Mobile Detect  module to achieve this. Note: you need to download the mobile detect library as well and place it in the module folder as specified in ReadMe.txt
Then you can use either of the below preprocess functions to detect the device and then return your output to the views template.

template_preprocess_views_view
template_preprocess_views_view_fields

Hope this helps.


Bulk redirect update from CSV: in code or manually? I have a D7 question. My latest site change involves using the Path Redirect Import module and drush path-redirect-import to bulk-create a bunch of URL redirects from a CSV file. It works fine in dev on my Linux box and I need to deploy it to test on Pantheon.

I'm striving to do code-based deployments, so I use Features and a MYSITE.install module with hook_update_n() calls.

1) Is it a best practice or am I misguided in trying to code a hook_update_n() to perform the DB update? Code-based development aims for recording every developer-initiated site change in code, right? Or are there cases where you don't commit something to code?

2) If the answer is "yes, you should do this in code", then I see that the drush_path_redirect_import function simply processes command-line options and executes:

$result = path_redirect_import_read_file($file, $options);

so I should simply do the same in my hook_update_n(), right?

You either use hook_update_n as you described. Or, sync down TEST to DEV in pantheon, perform the task there as needed, and then sync the DB/code back to TEST from DEV.

The workflow that works best for you depends on whether your site is accessed alot by users and can have no downtime or disruptions, or if your sites workflow/content is more static.


Change admin panel template I created a custom template and by mistake i chose my template as a adminpanel template.

that got rid of the dashboard. how change the template to default template.

Go to your-site/admin/appearance page, remove the styles (in Firefox is View/Page Style/No Style) and find the Administration theme form.

Select seven as administration theme and save configuration.


In Views admin, is there a section to insert CSS to style the view? i.e. how to style view without editing theme code or other drupal PHP? In the Views admin (i.e. admin/structure/views ), is there a section in the settings to insert CSS to style the view? i.e. how do I style a view without editing theme code or other drupal PHP?

I am able to find out which class identifiers that I need to style - see question/answer at:
Which html div classes are relevant when styling Views in Drupal 7 (for CSS)?

But I don't know where to put the CSS code to actually style the view.

I assume that it is possible to style a view within the drupal views admin pages, without having to resort to editing/creating themes, PHP and HTML code via FTP (?). Obviously one can do those things too but I'd rather try to find a (non-theme specific) solution within the views admin first.

Actually, the latest views does allow all kinds of CSSing, both from the easiest, such as adding CSS classes to the view Style Settings section, to embedding custom css and fields wrappers in the fields output when you click on their configuration and edit Style Settings there.

But I think the question here is, after you do all that, where do you put the CSS itself.

And that would be in one of your theme's css files, which are defined in your themename.info file (which is located in your theme's toplevel directory) like:

stylesheets[all][] = myfilename.css

So, you could ADD a css file to your theme with your customized CSS without touching anything else in there.


Can I autopopulate between different users' forms with Rules and Webforms or EntityForms? I need to create a form in which some fields auto-populate with the values submitted on other users' forms. Specifically, the manager has to submit a form documenting the progress of projects a, b, and c. However, the manager needs the option to ask another staffer to complete a form for one of the projects. So when the staffer submits the form, their value of textarea field "Project B Status" autopopulates into the field "Project B Status" on the manager's form. The manager can then edit staffer's text if necessary and submit the final report.

I have tried doing this using both WebForms and EntityForms and have tried using Rules to autopopulate. I cannot get it to work right, but before I continue I would like to know if these are the best modules to use or if I am doing something wrong (as I am fairly new to Drupal).

Many of the answers I have seen on this issue involve editing the actual php, which I would prefer not to do at this point (but will if someone can tell me specifically what to do).

If I were to approach the problem, each project would be a node.

First install the Field Collection (documentation) and Field Permission modules.
Create a new Content Type (admin/structure/types/add) and call it Project.
Assign the fields you want filled in (admin/structure/types/manage/project/fields).
Add an additional field called Project Status of type "Field Collection" and choose "Embedded" as the widget type. Click save, leave Hide blank items checked on the next page, then click save again.
Go to the Field Collections page (admin/structure/field-collections). You'll see your new Project Status field listed. Click "Manage fields" and add your subform fields here.
At this point, your manager should be able to create new Project nodes, and the Project Status field will hold the additional information. You'll need to set up the field permissions so that the staffer role can only edit the Project Status field.

Back on your node fields page (admin/structure/types/manage/project/fields) edit each field. Near the bottom of each field's settings, look for the Field visibility and permissions section. Choose the Custom permissions radio button and look at the settings available. For your project, you want to allow your staffer role the ability to edit anyone's value for the Project Status field, but none of the other fields.
Remember to also set permissions to allow the manager role to create Project nodes, and the staffer role to edit Project nodes (admin/people/permissions#module-node).

As an added bonus, you can set the field settings for the Project Status field to allow an unlimited number of values. This would allow for updated status as the project progresses. YMMV of course.


Update module to dev without Drush Is there a simple way to update a module to the dev version without Drush? Ideally, within the admin console, but I could also use ssh to manually loa the files to the correct places. For the purposes of this question, assume Drush sadly doesn't exist.

Drush is a very useful tool and it will take some tasks from your hands, including running update.php after updating a module.

However if you cannot (or do not want to) use Drush, there are plenty of other options to update modules. You can use FTP to delete the module folder and then upload a new version of the folder. You can use SSH to obtain the module zip file by using wget and then delete the module folder and extract the zip file. Basically any possible way to get the contents of the zip file to your destination is a valid updating method.

Keep in mind that you cannot always safely unzip one module directly over another one. Always delete or empty the previous module version first. The reason for this is that several (class) files might have been removed from the module, but would not get removed from the file system this way. Drupal's registry might still load these files but then find another class with the same name in another file, resulting in fatal errors.

And no matter how you update the modules files, always stick to the regular updating instructions. This includes always running update.php.


automatic logoff when leaving a page for a particular user and node/page combination I have a request for 1 user only ($user->name) that after they leave a particular node/page ($node->title) that they be automatically be logged off of drupal.  Leaving this page includes navigating to another page or closing the tab or browser window.
How could the automatic logoff when leaving a page for a particular user and node/page combination be accomplished?

AFAIC you can get current node id from Drupal JS object. Having those id you can send Ajax request to Drupal which performs logout (http://api.drupal.org/api/drupal/modules!user!user.pages.inc/function/user_logout/7)

About JS events for this task you should look on other forurms


Is it safe to clone a EntityMetadataWrapper Object? I want to clone an entity for multiple users, But some fields for each of them is different, Some fields are the same.

One way is to create the Entity for each:

// Doing in this in a loop for each user.
$e = entity_create('type', $info);
$e->{$same_field_for_all1}->set($value1);
$e->{$same_field_for_all2}->set($value2);
$e->{$same_field_for_all3}->set($value3);
$e->{$same_field_for_all4}->set($value4);
$e->{$fieldName}->set($this->getUserValue($user1, $fieldName));
// Set author and title for user here...
$e->save();

Another way is:

// Doing this only once
$e entity_create('type', $info);
$e->{$same_field_for_all1}->set($value1);
$e->{$same_field_for_all2}->set($value2);
$e->{$same_field_for_all3}->set($value3);
$e->{$same_field_for_all4}->set($value4);

// And doing this in a loop:
$clone = clone $e;
$clone->{$fieldName}->set($this->getUserValue($currntUser, $fieldName));
// Set author and title for user here...
$clone->save();

Is this sort of shallow cloning of EntityMetadataWrapper safe?

Well, It's not safe/ I don't know why yet, But, Sometimes it result in saving only last cloned entity.

It's not a good answer till it says why!


drush not able to download and enable modules whenever executing drush en  on Windows OS I keep getting this pop-up screen that tries to locate an app to open .launcher files whenever I try to execute drush en <Module_Name> commands to download and enable a module on Drupal 8. On mac nothing like this happens, I'm not sure what needs to be done in order for the commands to work.

First, use composer require for module installation.

Second, I don't use windows long time, but as I remember, there is a PATH variables that need to be configured so drush can work properly.

Take a look at this: https://modulesunraveled.com/drush/installing-drush-windows


"Global" List (Float)? Assume I have a content type with a  list field (float) that can contain the following values: a, b, c.
I created three nodes (A, B, C) with those field values.

Creating a new node, is there a way to auto clear/remove already existing values in older nodes?

For example, if I choose a in a new node, I want that in node A that value is removed.

The Unique Field module does the job of preventing duplicated values, but it doesn't allow to remove values from other nodes.

I found a solution: use a field group (Field Group) of booleans and set them as exclusive values (Exclusive value).


Sending HTML email replies using Webform in Drupal 7 How can I get Webform to send an HTML-formatted email?

You should download Mimemail to do this.

Then, in the webform options, you can create your template with the field you want using %value[machine_field_name] to get just the value or %email[machine_field_name] to get the label and value.


Bulk update lat/long taxonomy terms I have Province/City taxonomy with 5000+ terms.

I would like to add lat/long field or something and bulk update whole taxonomy so i can use it later for maps and proximity search.

Have you looked at Geofield and Geocoder modules?

I believe you can configure the geofield as a field on your taxonomy to hold the Lat/Lng. Then, you can configure your geofield widget as Geocode from another field.

For batch back-filling, Geocoder provides the drush command:

geocoder-backfill     Geocodes all nodes that have a geocoder widget but no geodata.


views entity reference to point email instead of uid in contextual filter? I'm using Drupal 7 and Views. I've been trying to sort out, entity reference to enable a contextual filter to sort by email, instead of UID as currently I am doing.

Is that possible?

Yes. If you're look to contextually filter a view based on an Entity reference's (user) email, you can add a Relationship with the value of Entity Reference: User. This allows your view rows to be join with the rows in the entity that is referenced.

With the relationship added, you can add a new User: E-mail contextual filter for the view.


Error 'Cannot redeclare ctools_menu_add_tab()' after migrating website After our hosting provider has migrated our website to a new server this fatal error occurs when accessing the site:

  Fatal error: Cannot redeclare ctools_menu_add_tab() (previously
  declared in
  /www/htdocs/mysite/drupal/sites/all/modules/ctools/includes/menu.inc:42)
  in
  /www/htdocs/mysite/drupal/sites/all/modules/ckeditor/ctools/includes/menu.inc
  on line 49

Now the mother of all questions: How can I fix this? :(

We're using Drupal 6 and – although I haven't checked it yet – all files and databases should have been copied correctly by our hosting provider.

You have ctools installed twice, in:

sites/all/modules/ctools
sites/all/modules/ckeditor/ctools

Obviously the second path must have been mistake. If you can acces your page, disable ctools and then remove second instance. If you can't, try to do it using drush. If that fails, too, consider re-migration, this time properly. If all else fails, you may try to simply remove second instance and call update.php to perform some cleanup.


How to create an blog in drupal 7? We are creating a single page website responsive one. Planning to add a blog link. Can anyone specify how to create a blog page?


Social links for each user I am looking a module which will give each user an option to create links to various social networks profiles they have.

I found Follow module but for D7 it says it is very unstable.

For the profile part, you can just use the profile2 module. It allows you to add any kind of field to user profiles. Install it, enable it, clear caches, and go to structure > profile types.  For the actual fields, you might want to use the url field module, to enable validation of urls, etc. You can then create all the url fields you want, and give them appropriate names, like "facebook page", "twitter page" etc.

To display a block on nodes authored by the user, you could do the following:

Create a view of profiles.
Create a block display for the view
Choose fields (your social media link fields)
Click on advanced and then "contextual filter"
Add "profile: user uid" as a contextual filter and click 'apply'
Under "When the filter value is NOT in the url", select "Provide default value"
Select "PHP code"
Paste in the following PHP:

$node = menu_get_object();
return $node->uid;
Click "apply" and then save your view.

You can now add your block to the content types your users are allowed to create.


Ajax error when trying to add another paragraph Drupal 8.9 and paragraph 8.x-1.11
My issue is that Ajax breaks when altering the #validate form. This is an issue for any form! It may have to do with my ajax, but here is my setup.
I have a paragraph type:
contact_information

field_phone_number (telephone from core)
field_type_of_phone (text_plain)

I have a custom module. In this custom module I am creating a form_alter on /user/register
I have:
function telephone_alter_form_user_register_form_alter(&$form, $form_state, $form_id ){
  //$form['#validate'] = array();  //commenting this in or out doesn't help
  $form['#validate'][] = 'telephone_alter_test_validate';
  //$form['field_phone']['widget']['#element_validate'][] = 'telephone_alter_test_validate';
}

function telephone_alter_test_validate($form, &$form_state) {
   echo "hi"; //prints hi, but ajax breaks
}

The validation works, prints out debugging. However, when I try to add another paragraph element, it does nothing. This is for any form. I have tried this on other forms like adding a basic page and trying to call an alter function!
the Ajax error displayed is:
[{"command":"insert","method":"prepend","selector":null,"data":"\u003Cdiv data-drupal-messages\u003E\n  \u003Cdiv class=\u0022messages__wrapper\u0022\u003E\n \u003Cdiv class=\u0022alert alert-danger alert-dismissible\u0022 role=\u0022alert\u0022 aria-label=\u0022Error message\u0022\u003E\n \u003Cbutton type=\u0022button\u0022 role=\u0022button\u0022 class=\u0022close\u0022 data-dismiss=\u0022alert\u0022 aria-label=\u0022Close\u0022\u003E\u003Cspan aria-hidden=\u0022true\u0022\u003E\u0026times;\u003C\/span\u003E\u003C\/button\u003E\n \u003Ch2 class=\u0022sr-only\u0022\u003EError message\u003C\/h2\u003E\n \u003Cp\u003EAn unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (40 MB) that this server supports.\u003C\/p\u003E\n \u003C\/div\u003E\n    \u003C\/div\u003E\n\u003C\/div\u003E\n","settings":null}]

The Ajax error is key, because if I create an alter form for any other page, I still get the error.
Any help is great! Thank you! I can provide more info if needed

I had the same issue.
It turned out every time a paragraph is added the validation method runs.
In your case, echo is illegal and it stops the following process. Try replacing it with php error_log or Devel debug functions.


Expose custom entity to views I've created an entity in a Drupal 8 custom module. Right now it's just an entity with base fields.

I want to expose these base fields to views.

I have the entity appearing on the views wizard page, but when I create the view, there are no base fields available for me to add, and the default field that views puts in there shows up as broken/missing.

I've tried referencing the comments module for examples, and have tried defining various views plugins, but I'm not having much luck.

I have baseFieldDefinitions($entity_type) defined in my entity controller. What else is required to expose this entity and its fields to views?

You need to implement hook_views_data() just like in Drupal 7. See comment.views.inc.