How to remove views first title I have a list of titles in a view block. But I never want the very first title of the view to display is this possible? I am using Drupal 7 with views 3.X

In the pager settings of your view select the wanted amount of items and then specify an offset by 1, so the first item won't be displayed.


Make a view content only appear when user is logged in In Drupal 7, I need to create a view of member-only nodes. They're all of a certain type. This type—and I've already set that up with role-based access control—can only be seen by logged in users.

Now, I can create a view called Member Area that shows these nodes, and make it accessible only to logged in users (through the View access control), but when I create a menu entry for that view, the link obviously disappears when the user isn't logged in.

What I need is a link that points to a "please log in" text (could be on a static page, whatever) when the user isn't logged in. If the user then logs in, I want to display the view which shows only the restricted content.

Giving a specific example, I currently have this. The block is conditionally shown in the sidebar only on the page called Member Area. The page displays the static You are not logged in… text.

Once the user logs in, I want to show them the view of restricted content:

The horrible kludge that I use now is that I link the user to another view in the user menu, but that's really bad UX.

Can I set this up somehow?

What I did was quite simple:

Create the view normally, without access restrictions and link it to the menu.
Make sure the nodes themselves can only be seen by logged in users.
Create a No results behavior text that tells users to log in.
Show the login block only on the view's page.


Feed Import from multiple pages Make Feed Importer go to given URL which has a list of thumbnails and links to their pages and make it check/open each of those links and scrape content from there into unique nodes importing its titles and images and so on and so on?

Is this possible or does the content has to be listed in one single page to scrape it?

I've done it with just scraping from one page or .xml feed, but how do I tell my feed to check that one page for links and go to those links and scrape content from each and every link?

Use hook_feeds_after_save( $source, $entity, $item, $entity_id)
for parsing for links the document and execute command after the importing of each feed.


Devel dsm() function in Drupal 8 page.html.twig Is Devel module's dsm() function available in page.html.twig? If it is not available, is there a way to make it available?

I am able to use dsm() in .theme file but not in page.html.twig.

I am aware of dump() function in .twig. dump() is similar to var_dump() of php and the output is not as clean as Devel module's dsm() function.

Using dsm() or dpr() in page.html.twig causes error and site does not load.

Why not just do it in hook_preprocess_page() instead.

<?php
function MYMODULE_preprocess_page(&$variables) {
  dpm($variables);
}


The commerce_product.field_produit_labels field needs to be updated almost every time I delete a field in my product types I get this message popping up in my dashboard :

ENTITY/FIELD DEFINITIONS Mismatched entity and/or field definitions
The following changes were detected in the entity type and field
definitions. Product The commerce_product.field_produit_labels field
needs to be updated.

It has not been possible to update entities with "Drush" for some time.
Why do I have these problems regularly ? This is only with the Commerce module.
How can I correct this? Without breaking my site.
ubuntu@ov-b2b650 ~/www-example-com $ drush entup

In UpdateDBCommands.php line 110:

  Drupal removed its automatic entity-updates API in 8.7. See https://www.drupal.org/node/3034742.

entity:updates [--cache-clear [CACHE-CLEAR]] [--no-cache-clear] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-d|--debug] [-y|--yes] [--no] [--remote-host REMOTE-HOST] [--remote-user REMOTE-USER] [-r|--root ROOT] [-l|--uri URI] [--simulate] [--pipe] [-D|--define DEFINE] [--druplicon] [--xh-link XH-LINK] [--notify] [--] <command>

You can quick-fix it by adding module devel_entity_updates https://www.drupal.org/project/devel_entity_updates and run the command drush entup.
Don't forget to export configurations after that.
Also, you can fix it by manually creating an update hook - follow https://www.drupal.org/node/3034742#comment-13097250


Node or static page generation I am currently working on a project where I have 2 databases: the internal site database, and an external database that contains a table with establishment information I want to display as pages on my site.

The external database can still be modified from another application.

How do I go about doing this?
Should I create a module to generate static pages, or nodes?
What are the differences, or implications of choosing either option?

What approach you want to use depends on the remote database and how dynamic the information is as well as how much data you expect to display.

If the remote DB is easy to work with and you don't need to do anything interesting with the data you might integrate with it using a custom module working directly against the remote database.

If the data needs to integrate with typical Drupal stuff (Views, Panels, Pages, Fields) then you might want to pull the data into nodes. This would still probably mean a custom module. I believe the Migrate module (http://drupal.org/project/migrate) could be a good help here.

How current the data needs to be is also a consideration. Should it checked for new content every time a certain page is visited or is it fine to run it on a cronjob in the background. Like every 3 hours?


Hide content type labels by default Field labels can be hidden for a content type by going to "Manage display" and changing the labels to hidden.

However, I rarely need to show labels.

Is there a way to have the labels hidden by default, site-wide?

I think preprocess_node should do the trick

use that in your template.php

function template_preprocess_node(&$vars){
  //Supposing that your content type name is "group"
  if($vars['type'] == 'your type'){
    $vars['content']['your_field']['#title'] = '';
  }
}


Conditional filters for views I have 4 filters for my nodes. These filters work with taxonomy terms.
So I have 4 taxony lists:

Type (a,b,c)
length (d,e,f,g,h,i,j)

If I select Type (a) then length should only give me the possibilities that actually are possible with the length for example f,g,h. Is this possible?

Yes, it is possible.
What you are asking for is typical faceted search functionality.
You should be looking in the direction of Facet API.

Cheers!


How can I generate a usable dynamic PDF from a Drupal view? My goal is to generate a PDF view of a content node. I've set up the Views PDF module with the TCPDF class, but performance is awful. Not just slow. I mean AWFUL. It's an aggravating experience when viewing a simple page of content as a PDF, and downright painful when viewing content that should be several hundred PDF pages long. Totally unacceptable.

Does anyone have a good solution for combatting this? All I'm looking to do is take a single node and offer a "view as PDF" link/functionality. It seems like this should be pretty straightforward, but I haven't been able to solve that yet.

Any help would be appreciated. Thanks!

I had never had any success with the html>pdf generating tools for PHP coming out looking 1:1 without issues ranging from style to markup to server side error with the libraries and/or incompatibility with PHP versions, package errors and whatnot.

Another option is to use PhantomJS or an equivalent tool to use a headless browser to output a PDF file for you. Note though, that PhantomJS is possibly going to no longer be maintained, as Chrome now has a headless equivalent.

However, there is a module for Drupal 7 and 8 that provides this functionality (disclosure, I am a maintainer) but it may take a little elbow grease on your end to get it to work the way you'd like. A base js controller for PhantomJS is provided, but you can alter it. If all you need is an equivalent of doing File > Print to PDF in the browser, this will do it without as much hassle as all the PHP libs.

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

As an alternative to that, there is a hosted service provider with an API you can use as well (disclosure - I have nothing to do with it) that might suit you.


How to send an email when the content is unpublished? I'm using the Rules module for sending emails. When the user adds a node, it can only be published when the admin approves it. For this I have used the content approval module.

I have made a rule which sends an email to the user when their content is published.

How do I create a rule which sends an email to the user when their content is not approved or unpublished?

hook_scheduler_api() accepts two parameters -

1. $node is the node object being processed
2. $action is either 'publish' or 'unpublish'

hook_scheduler_api()

<?php
    function yourmodule_scheduler_api($node, $action) {
  if (some condition) {
    // parameters: drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
    drupal_mail('yourmodule', 'mail key', $user->mail, etc depending on your needs);
  }
}
?>

hook_mail()

<?php

function yourmodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'this-mail-key':
      $message['subject'] .= 'your subject';
      $message['body'][] = 'text';
      // etc ...
      break;
    // etc ...
}
?>


Why some features are overriden after installation This is my hook_install:

function moocollar_web_install() {

  // enable features
  $global_features = array ('display_modes_feature' , 'field_bases_feature' , 'image_styles_feature' , 'roles_permissions_feature' , 'sitewide_feature'  , 'wysiwyg_feature' , 'menus_feature');
  $functionality_features = array ('blog_feature');

  $enable_dependencies = TRUE;
  module_enable($global_features, $enable_dependencies);
  module_enable($functionality_features, $enable_dependencies);

  // create editor user
  $role = user_role_load_by_name ('editor');
  $new_user = new stdClass();
  $new_user->name = 'editor';
  $new_user->pass = user_password(8); // random password.
  $new_user->mail = 'editor@example.com';
  if ($role) {
    $new_user->roles = array ($role->rid => $role->name);
  }
  $new_user->status = 1;
  $new_user->is_new = TRUE;
  user_save($new_user);

  variable_set('features_default_export_path', 'profiles/moocollar_web/modules/features');
}

After install the blog_feature is overriden:

drush features-diff blog_feature
Legend:
Code:       drush features-revert will remove the overrides.
Overrides:  drush features-update will update the exported feature with the displayed overrides

Component type: info
  features[field_instance][] = node-blog_post-body
  features[field_instance][] = node-blog_post-field_image
< features[menu_links][] = menu-editor-menu_aadir-post:node/add/blog-post
  features[node][] = blog_post
  features[user_permission][] = create blog_post content

Component type: menu_links
< array(
<   'menu-editor-menu_aadir-post:node/add/blog-post' => array(
<     'customized' => 1,
<     'link_path' => 'node/add/blog-post',
<     'link_title' => 'Añadir post',
<     'menu_name' => 'menu-editor-menu',
<     'module' => 'menu',
<     'options' => array(
<       'identifier' => 'menu-editor-menu_aadir-post:node/add/blog-post',
<     ),
<     'router_path' => 'node/add/blog-post',
<   ),
< )
---
> array()

But if I execute revert features via drush, the features is on default state:

drush features-revert blog_feature
Do you really want to revert blog_feature.menu_links? (y/n): y
Reverted blog_feature.menu_links.                                                                       [ok]
vagrant@precise32 (linkinicio *) httpdocs$ drush fd blog_feature
Feature is in its default state. No diff needed.

On the blog_feature.info I've the dependency and the item:

...
dependencies[] = menu
dependencies[] = menus_feature
....
features[menu_links][] = menu-editor-menu_aadir-post:node/add/blog-post
....

Thanks you all for your time.

Normally Features automatically detects ctools exportables and add the modules containing those exportables to the dependency list, unless a module requirement for an exportable was not detected, or dependent modules were installed since feature was enabled.

Based on your menu link machine name (menu-editor-...), it seems it relies on Menu Editor module and you've missing dependency to that module, therefore Features module didn't detect that component as a requirement, so it become overridden and unrevertable.

The solution is to add the missing module into dependencies list. Then either disable the feature module and reenable it, or manually enable any dependencies not enabled (see Feature Diff to expose them).

See: Troubleshooting: Reasons Features may be stuck as Overridden at Drupal.org


Likeit module count for an entity refrence field in drupal 8 I have Enabled the Like it! module for a content type called "recipe" on my website. I am able to get the value of like count for the recipe in node--recipe.html.twig. Now, in the same content type, I have an entity reference field for recommended recipes. I need to render the value of count for recommended recipes in my node--recipe.html.twig file. what changes are required and in which files please if anyone knows then help? I have very little idea about modules.

Using Drupal 8.5

  content['_field_layout']['content']['likeit']['#count']

gives me the value of count for recipe.

Just use hook_preprocess_hook() and get the referenced entities values.

function YOURTHEME_preprocess_node__recipe(&$variables){
  kint($variables);
}

For kint() you need to enable devel kint module.

Pass each entity like below:

$like_count = likeit_get_count($entity);

This will provide the likes of the entity that you have passed. Once you get the count pass it in your node--recipe.html.twig


Comment styling dependent on author's user roles I want to style comments differently depending of the author's user roles. How can i add a specific class attribute in the comment template if the author of the comment has a certain role?

I got it myself. Here is how to do it:

In your theme template.php:

function MYTHEME_preprocess_comment(&$vars) {
    // user roles
    // 1 = anonymous user
    // 2 = authenticated user
    // 3 = administrator
    // ...
    $vars['role_classes'] = '';
    $sql = "SELECT users_roles.rid FROM {users_roles} WHERE users_roles.uid = " . ((int) $vars['comment']->uid);
    $result = db_query($sql);
    foreach($result as $record) {
        $roleId = $record->rid;
        if($roleId == 3) $vars['role_classes'] .= ' comment-by-admin';
    }
}

Then change in your comment.tpl.php

<div class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>>

to

<div class="<?php print $classes; ?><?php print $role_classes; ?> clearfix"<?php print $attributes; ?>>


creating custom page template How do you create a custom page layout in Drupal 8? In drupal 7 you could do something like page--about.tpl or something. How do we do that in drupal 8?

Enable twig debugging by copying default.services.yml to services.yml and following instructions in the twig.config section. The debugging comments will display template file name hints in HTML comments in the page output.


Display Node or Entity Reference Content I can't seem to figure this one out.

Goal: To allow the back end user to select from a list of "leasing contacts" when creating a "property." And have the view show the full content of the "leasing contacts" selected.

So far I have a Content Type for "leasing contacts" with several contacts in there.
I have a Content Type for "properties" which has an Entity Reference field that references the "leasing contacts."
This works great on the back end, the user can select from the numerous "leasing contacts" when creating the "property".
HOWEVER, I can't seem to understand how to get a view to show the full "leasing contact" content. The view only displays the "leasing contact" name in plain text. How can I get the view to show not only the "leasing contact" name, but all of the other field content that's in the entity.

Any pointers would be much appreciated!

The keyword you are looking for here is 'relationship'. You want to create a relationship between your two content types using your entity reference field. Once this is enabled, all the fields available for the 'leasing contact' field will be available.

This tutorial from NodeOne is the best out there for explaining the process: http://nodeone.se/en/using-entity-reference-in-views


How do I create a TEXT column? I am trying to create a TEXT column.

function _mymodule_installed_fields() {
  return array(
    'mymodule_summary' => array(
      'field_name' => 'mymodule_summary',
      'label' => $t('Summary'),
      'type' => 'varchar',
      'not_null' => TRUE,
      'length' => '400',
    );
  );
}

I get a VARCHAR column. How do I get a TEXT column?

Given the code you are showing, which is similar to the code shown in Fields API, create new content type I take you are adding a new field to a content type, not simply creating a new table field for a database table. This explains why the code is using properties like field_name or label that implementations of hook_schema() would not use.

The values you can use for the type property are the ones described from the hook_field_info() implementations. In particular, if you look at the code of text_field_info(), you will see the following descriptions.

text: The field stores varchar text in the database
text_long: The field stores long text in the database

The confirm of what database field type is used for each entity field type comes from the implementations of hook_field_schema(), in particular from text_field_schema().

case 'text':
  $columns = array(
    'value' => array(
      'type' => 'varchar',
      'length' => $field['settings']['max_length'],
      'not null' => FALSE,
    ),
  );
  break;
case 'text_long':
  $columns = array(
    'value' => array(
      'type' => 'text',
      'size' => 'big',
      'not null' => FALSE,
    ),
  );
  break;

So, if you effectively need to use a TEXT database column  type, you need to use the following definition for the field.

array(
  'mymodule_summary' => array(
    'field_name' => 'mymodule_summary',
    'label' => $t('Summary'),
    'type' => 'text_long',
  );
);


Content node migration to user profile in Drupal 6 I have Drupal 6.x installed where we a custom node type for author data. We are implementing a new design that designates users as authors and now assigning various roles such as author.

We have some 600 authors nodes which we wish to migrate to the user base so that we can assign the users to articles again.

What is the best method for accomplishing this?

I'm assuming you're wanting to create new user accounts with these profile nodes, not migrate existing users linked to these profiles. Since you're using a custom node type and not core profile or Content Profile, there are many pre-existing solutions not available.

If these author nodes are constantly changing and you need to maintain periodic synchronization before you're ready to launch, you can set a custom class with the Migration framework. This requires some work so it might be overkill here.

More than likely, I'd say the best solution is probably the User Import module with data fed in via Views Data Export from your existing D6 site. You can create a view of your profile nodes, export it to CSV, and use that as a base to create all your new user accounts with the User Import module.


Views-overriden taxonomy/term page returns not found I am trying to override the default taxonomy/term/xxx page with a page created by views.

My view: I have followed the usual instructions with using url taxonomy/term/%, gave it a contextual filter that is validated to a term name. In the preview results box of this view, I can use a term as an argument, and get the results correctly.

But when use the url in the real site, I get a 404. Regardless what the url alias pattern is for the default taxonomy term pages, when this view is enabled no term will return a page.

Turning my view off->term page urls work
Turning my view on ->term pages stop working.

I have no other view with the same URL enabled.

I was able to solve this only by duplicating the "taxonomy" view. This view's argument configuration makes it a viable solution.

After configuring/enabling this view, you can set the taxonomy url aliases to work in the same way.

A working example: http://www.indice.gr/portfolio/all shows "all" projects, wheras http://www.indice.gr/portfolio/mobile-application shows projects under the mobile-application term. Yay!


Easiest way to test email notifications locally? I am making a forum website with email notifications. I need to test these email notifications locally. Ive only ever used MAMP so I dont have much experience setting up dev environments.

What's the easiest way to test Drupal's email notifications locally?  Can the Acquia stack do this?

You can log the emails, which also brings some sanity to your inbox. Of cause there is a module for that (or two):

Maillogger
Maillog / Mail Developer


Why does the search module break cron I was trying to work out why cron wouldn't run on my site and came across this post: http://codekarate.com/blog/drupal-6-fixing-stuck-cron-run which said that enabling and disabling search would fix it. It did, but does anyone know why search breaks cron?

The Search module implements hook_cron(), and its implementation it invokes hook_update_index() to update the search index. One of that hook implementations is node_update_index(), which

Loads some nodes whose IDs are returned from a query
Renders those nodes, and passes their body content to search_index()

If the node body contains PHP code that redirects the users to a different page, or an implementation of hook_nodeapi() redirects the users when a node is viewed, that can cause problems to cron tasks.


Vertical tabs of form fieldsets taking a long time to load UPADTE: I've been awarded a Tumbleweed badge for this question (Asked a question with no votes, no answers, no comments, and low views for a week). My gut feeling is this is about optimizing Drupal to speed up page loads, but maybe it's something else?

I have a form divided into five fieldsets. The sets are displayed on my page using vertical tabs, like this:

// Form element: vertical tabs.
$form['vertical_tabs'] = array(
    '#type' => 'vertical_tabs',
);

// Form elements: fieldset tree.
$form['Fruits'] = array(
    '#title' => t('Type'),
    '#type' => 'fieldset',
    '#tree' => TRUE,
    '#collapsible' => TRUE,
    '#group' => 'vertical_tabs',
);

...etc.

When the page loads, initially just the plain form appears. It takes about 2-3 seconds for the vertical tabs 'styles' to be applied to the form. In other words, it takes a significant time to load the finished page. Has anyone else had this problem and figured out how to stop/arrest this behaviour?

I am using Zen theme, if that makes any difference. Thanks.

I'm almost 100% certain this problem is related to slow-loading javascript; As Mołot mentioned in his comment on the question, you should investigate whether something is holding up the JS from loading and/or processing when the page loads, using browser tools.

There might be some other JS that's being added on the page that's blocking the vertical tabs JS from loading/running. Do you have any 3rd-party (Facebook, Google, Twitter, analytics, etc.) libraries loaded on the page? There are some good tips for getting these things to not block the rest of the page load here: Non-Blocking Loading Of 3rd Party Scripts In Drupal.

Otherwise, do you have a module enabled or some custom code that's hindering/slowing the progress of the page load on that form? This is less likely, but sometimes if a module does something that requires a lot of CPU time (like looping through an entire taxonomy tree to build a form element or do something fancy to it) either with PHP or JS, that can cause the page load to take a really long time.

Vertical tab rendering (as well as fieldset collapsibility rendering) is usually one of the last things to load when a page loads. Something is blocking the page load/render progress, and if you can figure out what that is, you'll find the source of the problem. Good luck!


What's inside "print render($page['content'])"? I want to style my front page in Omega subtheme I'm using an Omega sub-theme in Drupal 7.
In my front page, I have some sort of "river of news" with all content that has the "promote to the front page" checkbox checked.
I would like to create a special front page, so I've copied my page.tpl.php into a new page--front.tpl.php.

I would like to add a special CSS class to that list of content. (The list is filled with all teasers by default.) When I try to target that specific piece of content, I get only this:

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

Inside that is the content section, and the sidebars sections.

How do I target only the list of teasers?

The content of the $page array is described in hook_page_alter(), where the documentation says:

  The $page array contains top level elements for each block region:

  $page['page_top']
  $page['header']
  $page['sidebar_first']
  $page['content']
  $page['sidebar_second']
  $page['page_bottom']

  The 'content' element contains the main content of the current page, and its structure will vary depending on what module is responsible for building the page. Some legacy modules may not return structured content at all: Their pre-rendered markup will be located in $page['content']['main']['#markup'].

  Pages built by Drupal's core Node and Blog modules use a standard structure:

  // Node body.
  $page['content']['system_main']['nodes'][$nid]['body']
  // Array of links attached to the node (add comments, read more).
  $page['content']['system_main']['nodes'][$nid]['links']
  // The node object itself.
  $page['content']['system_main']['nodes'][$nid]['#node']
  // The results pager.
  $page['content']['system_main']['pager']

You can use $page['content']['system_main']['nodes'][$nid]['body'], remembering there is a $page['content']['system_main']['nodes'][$nid]['body'] for each node. Check its structure to see in which way you can add a CSS class to that array.


Customizing the register form with a new class: Why do I get this error? I'm trying to customize the register form. A user has a reference field to content of type A. However, I only want to allow values of A which satisfy a certain condition.
To achieve this, I based my code on https://www.foreach.be/blog/how-manipulate-forms-drupal-8.

I created a module with the following services.

services:
  travels.route_subscriber:
    class: Drupal\travels\Routing\RouteSubscriber
    tags:
      - {name: event_subscriber }

I defined a RouteSubscriber class.

class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
     if ($route = $collection->get('user.register')) {
        $route->setDefault('_form', '\Drupal\travels\ExtendedRegisterForm');
     }

   }
}

I also have an ExtendedRegisterForm class defined as follows.

class ExtendedRegisterForm extends RegisterForm {
     public function buildForm(array $form, FormStateInterface $form_state) {
         $form['test'] = [
            '#type' => 'email',
            '#default_value' => 'test'
          ];
         return $form;
      }
}

If I load the page to register a new user, I get the following error:

  Fatal error: Call to a member function getEntityTypeId() on null in xxxx\core\lib\Drupal\Core\Entity\EntityForm.php on line 77

I'm assuming no entity was given because the Entity still needs to be created (after the registration). Does anyone have a suggestion of what I might still need to do to get this working?

It seems like you could reduce complexity with hook_form_alter, and manipulate the options on the reference field.


Referring to an image file uploaded as `Image` type field without /sites/ I am using a content type with Image type fields to hold images uploaded to a web site. I want to display these images both on distinct pages (easy) and inline on other pages (almost even easier).

However, I don't want to expose /sites/default/files/ in the image URL, and I certainly don't want to include it in the image tag's src attribute when I refer to the image from some other page.

How do I include at an arbitrary location on an arbitrary page an image uploaded like that, without exposing the physical directory structure in the link? I tried using the URL aliases feature provided by the Path module, but it wouldn't let me point to anything in /sites as such.

You could create a symlink in the drupal root using:

ln -s sites/default/files images

and then set the src attribute to something like:

/images/myimage.jpg

Really not sure what you would gain by doing this.


How to change user badge when 'total User Points' increase? I am building a community site, in Drupal 7, and using the User Points module and the User Badges module.

My goal is that every user will always have only one badge, that will be presented near the user's name, everywhere on the website.

These are my specifications for the badge to be selected according to the amount of User Points:

0-50 points = first badge
51-100 points = second badge
101-200 points = Third badge
201-300 points = Forth badge
301 points and more = Fifth badge

I tried to use User Points Contributed modules but unfortunately there is no Drupal 7 upgrade.

I tried using the Rules module, but didn't find a way to compare the current total amount of points of the user to my specifications, (for Rules Event "User was awarded points"), so that based on the result of that comparison, the Rules Action would eventually change the badge assigned to the user.

Any suggestion to get this to work?

The key part of your question seems to be this:

  I tried using the Rules module, but didn't find a way to compare the current total amount of points of the user to my specifications, (for Rules Event "User was awarded points"), so that based on the result of that comparison, the Rules Action would eventually change the badge assigned to the user.

Indeed, for Drupal 7, there doesn't seem to be some Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn Execute custom PHP code condition, e.g. to do some type of comparison):

global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

However, there is a Rules Action "Load user points of a user", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules event that you want, e.g. to "User was awarded points", as in your question):

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

Use the Rules UI to import the above rule in your own site if you want.


Add custom config to ckeditor I'd like to customise the CKEditor config, by using the removePlugins setting to disable the elementspath plugin, so that body p etc. isn't displayed in the status bar (here's a similar, old question for D7).

I created the following CKEditor plugin, which returns an additional setting via the getConfig() method.  It has no effect on my editor fields (I've verified the plugin ID is being matched).

What's the right approach - if not this - for a config change, given I'm not loading a new plugin JS file or adding buttons?

<?php

/**
 * @file
 * Definition of \Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin\RemoveElementsPath
 */

namespace Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginInterface;
use Drupal\Component\Plugin\PluginBase;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Remove Elements Path" plugin.
 *
 * @CKEditorPlugin(
 *   id = "remove_elements_path",
 *   label = @Translation("Remove elements path"),
 *   module = "ckeditor_remove_elementspath"
 * )
 */
class RemoveElementsPath extends Pluginbase implements CKEditorPluginInterface {

  /**
   * {@inheritdoc}
   */
  function getDependencies(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  function getLibraries(Editor $editor) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function isInternal() {
    return false;
  }

  /**
   * {@inheritdoc}
   */
  public function getFile() {
    return false;
  }

  /**
   * {@inheritdoc}
   */
  public function getButtons() {
    return [ ];
  }

  public function getConfig(Editor $editor) {
    return [
      'removePlugins' => 'elementspath',
    ];
  }

}

I had a look at the CKEditor API docs and the other classes I might extend - it didn't seem to be any of:

CKEditorPluginButtonsInterface
CKEditorPluginContextualInterface
CKEditorPluginCssInterface

…though perhaps CKEditorPluginConfigurableInterface, if I wanted to configure the settings form per text format?

Then, I found a module called ckeditor_config, so I adapted it's plugin class, which extends CKEditorPlugin/Internal:

/**
 * @file
 * Definition of \Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin\RemoveElementsPath
 */

namespace Drupal\ckeditor_remove_elementspath\Plugin\CKEditorPlugin;

use Drupal\ckeditor\Plugin\CKEditorPlugin\Internal;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "Remove Elements Path" plugin.
 *
 * @CKEditorPlugin(
 *   id = "remove_elements_path",
 *   label = @Translation("Remove elements path from CKEditor status bar")
 * )
 */
class RemoveElementsPath extends Internal {

  /**
   * {@inheritdoc}
   */
  public function getConfig(Editor $editor) {
    // Get default config.
    $config = parent::getConfig($editor);

    $config['removePlugins'] = 'elementspath';

    return $config;
  }

}

Edit: And here's my module if anyone finds it useful.


can we add two search form in single site? I have a one search form which is used for all content type but i want another search form which is only for specific content type and show on specific page only. I have install the custom search module but there is no way to show that custom search module in structure block

You can use the Custom Search module so it only searches in your specific content type.

1) Enable custom search and custom search blocks

2) Now go to admin/structure/block and configure Custom Search 1

3) Scroll down a bit and click on the blue CONTENT text

Then at the bottom, in Content exclusion, check mark the content types that you do not want to show.

4) In region settings, select the region you want this block to show up in.


Create additional menu page for node that can be accessed by the nodes' alias with /page? I created a block using hook_block_view() and hook_block_info(), then set-up the page with hook_menu() using page arguments but this seems to only work for node/id/page?

This is what I have right now:

$items['node/%node/text'] = array(
    'page callback' = 'my_module_function',
    'page arguments' = 'array(1)',
);

I need it to work for the nodes alias which might be article/node title/ or journal/node title/ - they are for two different content types. Going to just article/ or just journal/ shows a View page that displays all the articles or everything from the journal.

Currently whenever I try to go to:

  article/node title/page

the article/ Panel page is loaded. However disabling the panel for article/ then going to article/node title/page causes a Page not found error, so it seems it's something to do with my hook_menu() not registering the URL aliases of the nodes?

As node/node id/page works perfectly fine.

Edit: unsure how to reopen, see comments

You have two options.

1. Using the Sub-pathauto (Sub-path URL Aliases) module.

This is based on pathauto, and will create additional aliases for node sub-pages.

This also works for other entity types such as user/123/contact -> people/geronimo/contact, if user/123 has the alias people/geronimo.

2. Write a custom wildcard loader (far more work).

I am going to use the word "slug" here, which I remember from Wordpress.

The usual node path is node/%node, which will trigger the node_load() wildcard loader. This wildcard loader only takes node ids. It does not work with node titles. So, node_load(123) gets you the node with that id, but node_load('node title') will return NULL.

You could now create a new module "mymodule", and use hook_menu() to define a separate path article/%mymodule_article_slug, and sub-paths article/%mymodule_article_slug/page, article/%mymodule_article_slug/edit, etc.

This is going to be some work, you need to look into node.module and the hook_menu() implementation found there, and copy a lot from there. Or you could use hook_menu_alter() instead of hook_menu(), and copy some of the data already registered for node/% and friends.

The essential trick now is to define a wildcard loader for %mymodule_article_slug.

/**
 * Wildcard loader callback for '%mymodule_article_slug'.
 *
 * @param string $slug
 *   Part of the url identifying the node, e.g. "pink-elephant"
 * @return object|null
 *   The node object, usually an instance of stdClass, or
 *   NULL, if no such node exists.
 */
function mymodule_article_slug_load($slug) {
  // Load the node identified by $slug.
  $node = ...;
  return $node;
}

Now it gets insteresting. How do you load the node identified by the "slug"?
There are different ways.

You could store the slug in a field on the node, and then use EntityFieldQuery to load the node with that field value. You also need to decide what to do if more than one node has the same slug.
You could use path + pathauto and find the node where the alias is "article/" . $slug. drupal_get_normal_path() can help you with that.

With method 2, your code would look like this:

function mymodule_article_slug_load($slug) {
  // Load the node identified by $slug.
  $normalpath = drupal_get_normal_path('article/' . $slug);
  if ($normalpath && preg_match('#/node\/(\d+)$/', $normalpath, $m)) {
    $nid = (int)$m[1];
    if ($nid > 0) {
      return node_load($nid);
    }
  }
}

EDIT: This only works if the "slug" does not contain any slashes by itself!


How can I hide the authoring information? Normally I would just click manage display and disable authoring information from showing, but with layout builder enabled, I don't have this option. I only have the Manage Layout option, which doesn't contain any way to disable the authoring information.

Try to disable this information in content type settings.


Can I do a scrollable calendar/events listing with a Drupal module? I have the FullCalendar module installed, and it's pretty easy to use that to put a little calendar display in a block (making it look good is another matter).
But can I use it to make an events display like the one on Metromix?
(Sorry, I guess I'm too new to post an image! Please see the link above)

I can make FullCalendar display a week's worth of events, but that's not really what's happening here.  As you can see in the example, the user can scroll left or right to get different days to display, have a particular day in the list selected, and have that selected day's events displayed below.  Those are the parts that aren't clear how to do with FullCalendar (if it's possible at all).

Can FullCalendar do this?  Is there another module that can do this?  Or do I have to do this kind of thing by hand?

Thanks in advance for any pointers!

Yes, I believe that you can do that with the full calendar module.

In the example link you posted when you click left or right though the months an ajax request is actually happening returning the next months set of events.

The full calendar module also has ajax support.

To turn ajax on on your calendar you need to look at a setting called Use AJAX under the advanced section:

There is a similar question, AJAX in a calendar view block, which may also be of interest.


How to Move Tooltip Away from Checkbox in Bootstrap Theme? I am using the Bootstrap theme as the administration theme. The tooltips get in the way of the checkboxes. How to move?

If you open up the settings for your theme under the appearance tab there should be a javascript tab. If you click that the tooltips and popover settings are displayed. You can either turn them off or make them appear below the field.


How to grant permission directly to a user other than a role? Our client frequently need to grant arbitrary permissions to arbitrary users. It's very boring and fault-prone for our client to create new roles, assign users to roles and then set role permissions.
The module user permissions can grant permissions directly to a user, but the grantee must have the powerful permission "administer permissions", which is not what I want.

Use the user permissions module.  Contrary to your objections to using this module, it is not the grantee who needs the  "administer permissions", but the grantor


Extract all images out from each node in content type Every time a new node is published within a single content type, I wish to extract (not remove) all the images out from that node's body and save the URL(s) of the images in the database. I will then use the URLs to make a slideshow of the images on a separate node.

I have three questions:

Which hook runs right before a node is published?
What's the best way of saving those URLs in the database?
Which Drupal function do I use to retrieve those URLs from the database?

Which book runs right before a node is published?

hook_node_update($node) The hook is invoked after the node is inserted/updated in the node table

  What's the best way of saving those URLs in the database?

It totally depends upon your needs, Simply you will have to save in database in your own table(s).

  Which Drupal function do I use to retrieve those URLs?

It is not clear from where you want to retrieve. Database or Node Body.

For database you need to focus on Database abstraction layer
For Node body, you will have to parse some way e.g. PHP Simple Dom Parser


Import sub view to another view It's possible to export sub view and import it to another view? For example I have views "A" & views "B" and each one has sub views [blocks - pages - ...etc]. How to export sub view from A to B?

You might be needing this module views_field_view to insert a sub view inside a view as a field.


How to create a rule that unpublishes comments that contain links? I'm trying to create a rule that does the following.

Event: After saving new content type Forum Topic
Conditions:

User has role 'authenticated', and
Content body contains link (this is the part I can't figure out)

Actions:

Unpublish Content
Show a message on the site:

  "Your user permissions currently do not allow for you to post a forum topic that contains a link. Please remove all links from your post and re-submit by clicking the following edit link: [node:edit-url]

  This precaution helps us keep our forum and comments spam free. If you would like the ability to post links, please e-mail the site admin: [site:mail]"

The general idea is that I want users to register to the forum and be able to create new forum topics but not be allowed to post links since this is the whole purpose behind spam. Once they make a few quality posts, I'll move them to a trusted user group that this rule doesn't apply to, allowing them to post links.

The reason why I don't want to use Text Formats to strip out  tags is because the spam post will still be published, minus the links. This will lead to offensive, spammy posts still showing up in the forum index.

Look at honeypot and hidden capchta before getting too many rules involved.


"set" version of field_get_items? One can retrieve field items from an entity with

// Find all terms on $node in field 'field_tags'.
$terms = field_get_items('node', $node, 'field_tags');

But is there a convenient way to do the reverse, Core, or otherwise?

// Attach new term $term to $node in field 'field_tags'.
$term = taxonomy_term_load($tid);
$node = field_set_items('node', $node, 'field_tags', 'taxonomy_term', $term);
node_save($node);

I would like to avoid the hassle of manually assigning a $term, go look in devel what the array structure looks like and then build the array by hand, as it is sometimes non-trivial.

The only issue in the core queue I could find that looked vaguely similar was about the field language api DX.

No, there is no such function.

See my comment at Language support for entity fields.


Create translated node programmatically I need to recreate the behavior drupal has when you create a translation but programmatically.

Doing $node->addTranslation('de'); on a hook insert create an empty node but I need the field to be filled with the untranslated node content.

Is there a way to achieve this instead of having to repopulate every field from the main node ?

addTranslation takes a second parameter, $values:

  An array of initial values to be assigned to the translatable fields. Defaults to none.

So in theory you should just need to make use of that parameter, and pass the node's current field values:

$node->addTranslation('de', $node->toArray());


How to login by single role if user have multiple roles? In my latest project client asked me to add extra interface after login where all roles assigned to that user will be shown and user can choose the single role and login by that role only. But i don't know how to do this in drupal. I tried with role switcher and other module but they didn't  work for me ? Any suggestions will be appreciated.

Suppose
User x have roles A B C D
x can choose single role(eg A) after login and do the work only with that role.

Create a custom module
Create a custom form where Admin can whitelist users for certain roles .. Form should have  username and roles as a list or checkboxes.
Store these settings in database - uid - roles
When a user logs in redirect user to a form where he can select user roles from above list
On Form Submit, Update user programatically and assign role to the user he selected, remove other roles that user has if any


How to create a user listing page with a tpl.php I would like to create a listing page of users of a particular role.

Inside this view, there should be another view which shows the related content for each user.

When I try to create a view the system gives me the option to use just fields, but I need to be created like a node so I can use a tpl.php file.

How can I get a tpl.php file for this?

If I create a view for the users and one with the contents(contextual filter uid), can I embed  the second view inside the view-unformatted.tpl.php?

Here I create similar page with views: http://cgart.ir/en/members

as you can see there is a list of users and 5 last uploaded image. the page created with views and latest artworks is another views.

to do that:

create first view for list users and in Format select Show:Rendered entity | Settings
create second view and configure CONTEXTUAL FILTERS and add Content: Author uid

edit user-profile.tpl.php and render second view there:

$account = $variables['elements']['#account'];
<?php print views_embed_view('second_view', 'page_1', $account->uid); ?>


Strange Views Relationship Error I've done quite a bit of googling and can't seem to find any information on this error, so I'm going to assume it's not a common one.

The error is:

  Notice: Undefined property: views_handler_relationship_broken:: $alias
  in EntityFieldHandlerHelper::query()  (line 84 of
  /MYPATH/sites/all/modules/entity/views/handlers/entity_views_field_handler_helper.inc).

A bit of information about my set up, I've been using Views to show a list of my Drupal Commerce Product displays, set up similarly to Commerce Kickstart where you have the Product Display that references the Commerce Products via the SKU. This error arose shortly after removing some fields relating to a relationship the view was using, as these fields no longer exist they cannot be re-added.

I've cleared the views cache, the site cache, to no avail. Is there any kind of database entry that may be referencing this particular relationship still?

Regards, Daniel.

Generally you shouldn't remove fields that are used by other mechanisms, like Views. Now when it's done, the best way I know is to export view, manually remove fields that was deleted from it, and re-import. And don't forget your backups.


Could it be that the drupal database doesn't work anymore after using jquery .load() After using jquery .load() in drupal 7, the database doesn't seem to work

module

   <script type='text/javascript'>
   function loadPage (id,level) {
   $.ajax({
          beforeSend: function () {
            // here you can do things before the action start
          },
          success: function () {
          $('#contenpage').load(\"$path/pages/page.php\", { 'var': [id,level]})
          }
        });
   }
   </script>

I want to use the database in the page "page" and echo the result back.

page

 $query = db_select('course_function', 'f');
  $query
      ->fields('f', array('id'))
      ->condition('f.chapter_id', $id, '=')
  ;
  $result = $query->execute();
  print_r($result);
  foreach ($result as $res) {
    $id = $res->id;
  }
echo $id;

But it does not work - do I need to use the PHP manner?

Most likely that drupal database API is not available in your page.php file because corresponding files are not included in it. What I usually do if I want to do stuff like this, is declaring a menu item:

function MYMODULE_menu(){
    $items['path/page'] = array(
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'title' => 'AJAX: Page callback'
    );
    return $items;
}

the code above adds a new page to drupal menu system and makes it available as: http://www.yoursite.com/path/page

and then in your function

function your_function_name() {
    $query = db_select('course_function', 'f');
    $query->fields('f', array('id'))
          ->condition('f.chapter_id', $id, '=');
    $result = $query->execute();
    print_r($result);
    foreach ($result as $res) {
        $id = $res->id;
    }
    echo $id;
    //You need to have exit in such callback functions to prevent drupal theme
    //functions from taking over the page processing
    exit;
}

Then in your javascript you can approach this page just like this:

<script type='text/javascript'>
function loadPage (id,level) {
$.ajax({
      beforeSend: function () {
        // here you can do things before the action start
      },
      success: function () {
          $('#contenpage').load("http://yoursite.com/pages/page", { 'var': [id,level]})
      }
    });
}
</script>


Is it possible to bypass form validation, but still save form data? I have an ECK (Entity Construction Kit) form with several required fields. The form contains a series of submit buttons.

The 'complete' button does a regular form submit, triggering the appropriate validation & submit handlers.

The 'save & close' button needs to submit the form & save the data without doing any validation, and this is what I'm having trouble with. I know I can use the #limit_validation_errors property on the 'save & close' button to remove validation, but that also removes the submitted data from $form_state['values'] in the submit handlers.

I tried rebuilding that data in a custom submit handler, re-inserting it into $form_state['values'], and then triggering ECK's original submit handler (which, in theory, should save the data), but that doesn't work:

function my_custom_form_submit($form, &$form_state) {
  if (isset($form_state['values']['no_validation_submit'])) {
    // make copies of the form variables, since they get passed by reference & modified in form_builder();
    $form_copy = $form;
    $form_state_copy = $form_state;

    // rebuild the data to get correct ['values'] in $form_state_copy;
    $form_copy = form_builder($form['#id'], $form_copy, $form_state_copy);

    // place the rebuilt ['values'] into original $form_state & call ECK's submit handler
    $form_state['values'] = $form_state_copy['values'];
    eck__entity__form_submit($form, $form_state);
  }
}

Any ideas for how to achieve this?

The solution dawned on me this morning; to get this functionality in place I need to work backwards: rather than having Drupal validate the required fields and conditionally disabling the validation, we should remove the validation requirements from the form, and conditionally add them (doing custom validation, if need be).

So, the #required parameter is set to FALSE for all fields, and a custom validation handler conditionally checks the 'required functionality.'


Does service module expect Base64 encoding for file uploads through http-post (drupal 7)? I have been having trouble getting a file to upload through http-post from my lisp application and I have noticed in all of the curl php examples I have found they have a like this:

$file = array(
  'filesize' => filesize($filename),
  'filename' => basename($filename),
  'file' => base64_encode(file_get_contents($filename)),
  'uid' => $logged_user->user->uid,
);

which includes the call to base64_encode, I am not doing this from my lisp application and I always get a response of 200 but the file is not uploaded.  I am using Services 3.x and a RESt server.

Does Services require that file uploads are base64 encoded?

Short answer yes it does. There is a create raw method but unfortunately, it doesn't work very well b/c drupal 7s file handling is a joke.

Ive created a patch that will allow you to attach files to  a node and it uses multipart form, but its a work in progress.

http://drupal.org/node/1484992


How to display 2 blocks in one view I am using quick tabs, but I want to display 2 blocks under each tab, been told I should use attachments but I don't get.

How can I achieve this?

So each tab displays 2 blocks when clicked like in the sketch.

You may try using the module Block Group. You can group multiple blocks into a single block using this module.


What's the minimum amount of code needed to have a field show up in Manage Fields? I tried copying the functions from the field module in example modules to get a field to show up in Manage Fields without necessarily any functionality

Looking at the answer to this question, only field_create_field() and hook_field_info() should do the trick but I never got that working with the following code:

function entityreference_add_new_field_info() {
  return array(
       'entityreference_add_link' => array(
          'label' => t('Entityreference link'),
          'description' => t('Entityreference link'),
          'default_widget' => 'entityreference_link_widget',
          'default_formatter' => 'entityreference_link_formatter',
      ),
    );
  field_create_field('entityreference_add_link');
}

Putting field_create_field() outside of hook_field_info() returns 'call to undefined function' error.

Update: Here's one thing I've tried without success:

function entityreference_add_new_field_info() {
  return array(
       'entityreference_add_link' => array(
          'label' => t('Entityreference link'),
          'description' => t('Entityreference link'),
          'default_widget' => 'entityreference_link_widget',
          'default_formatter' => 'entityreference_link_formatter',
      ),
    );
    field_create_field('entityreference_add_link');

$instance = array(
    'field_name' => 'entityrefernce_add_link',
    'entity_type' => 'node',
    'label' => 'The Link',
    'bundle' => 'node',
  );

field_create_instance($instance);

}
enter code here

You have already created the definition of the field, but you also need to create an actual instance of that field to use it.

$instance = array(
    'field_name' => $your_field_name,
    'entity_type' => 'node',
    'label' => $your_field_label,
    'bundle' => 'node',
  );

field_create_instance($instance);

That plus what you have above should be the minimum you need to get a field to appear in your management screen.

See the field_create_instance() docs for more info about available options.


Views slideshow numbered pager Im using Drupal 7, and I am trying to make a slide show with a numbered pager like the one shown in this page. I added PHP code in Views, thinking I could simple put PHP code, but the problem is that it is not producing the expected result.

I used this code, which is supposed to print "1 2 3 4", and that instead prints "1 1 1 1."

$i = 0;
$i++;
echo $i;

In this code I tried using one of the variables, and I think I am on the right track with this one, but it prints "10 9 8 7," while I want it prints "1 2 3 4."

$i = 0;
$i = $row->field_image;
echo $i;

I know that this is probably something simple, but I can't figure out how to save my life; any help is greatly appreciated.

Much easier way:

Add "Global: View result counter" Field
Exclude it from Display
In Slideshow setting: choose that field as the Pager Type


User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() I receive this error message when I try to fetch data from the Database Table of a custom form and print it in a table format in Drupal 9.
User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php).
Drupal\Core\Render\Element::children(Array) (Line: 349)
Drupal\Core\Render\Element\Table::preRenderTable(Array)
This is my code controller.php File code:
<?php
    namespace Drupal\ad_form\Controller;
    use Drupal\Core\Controller\ControllerBase;
    use Drupal\Core\Database\Database;

    class ad_formController extends ControllerBase{

        public function getAdList(){

            $query = \Drupal::database();
            $result = $query->select('ad_form_submissions','e')
                    ->fields('e',['id','name','gender','product','quantity','price'])
                    ->execute()->fetchAll(\PDO::FETCH_OBJ);

            $data = [];

            foreach($result as $row){
                $data = [
                    'id'=> $row->id,
                    'name'=> $row->name,
                    'crop_category'=> $row->gender,
                    'crop_type'=> $row->product,
                    'quantity'=> $row->quantity,
                    'price'=> $row->price
                ];
            }

            $header = array('ID','Name','Gender', 'Product', 'Quantity', 'Price');

            $build['table'] = [
                '#type'=>'table',
                '$header'=>$header,
                '#row'=>$data
            ];

            return [
                $build,
                '#title'=> 'Submit Ad List'
            ];

        }

    }

How to resolve this issue and fetch the Data Correctly? I'm a Beginner, So please try to simplify the answer.

You should return a render array $build. if you want to add a title to the page add title in render array $build.
You can use $build['title'] = [ '#markup' => 'Yours title goes here ];
and return the $build
and in table element use #header instead of $header


How to get a user's profile picture URL? I need to get the user's profile picture using the following code:

\Drupal::service('renderer')->renderPlain(\Drupal\user\Entity\User::load(\Drupal::currentUser()->id())->user_picture->first()->view('large'))

It returns an object with the image tag, but it fails with the _Call to a member function view() on a non-object_ error when a user has no profile picture set.

I also tried the answer to "How do I get the default user picture?", but it gives the error

  Drupal\Core\Database\InvalidQueryException: Query condition 'file_managed.uuid IN ()' cannot be empty.

The code is OK, but you have to check if the field is not empty:

if ($user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id())) {
  if (!$user->user_picture->isEmpty()) {
    $picture = $user->user_picture->view('large')
  }
  else {
    $picture = // get default picture
  }
}

In Drupal 8 don't use render service. The new template system does this automatically.


Theme template and hook_theme I have a content type 'leg' and a template node--leg.tpl.php.
I'm using sky theme. I have a custom module as well, let's say for example, mymodule.
I put the template file into sites/all/modules/mymodule/theme. And I created a hook_theme and hook_preprocess_node.
But my template is not invoked as expected. I cleared all caches.

function mymodule_theme(){
    // The base theme registers node.tpl.php.
    $templates['node'] = array(
        'arguments' => array('elements' => NULL),
        'path' => drupal_get_path('module', 'mymodule') . '/theme',
        'template' => 'node--leg',
        'preprocess functions' => array(
          'template_preprocess',
          'mymodule_preprocess',
          'mymodule_preprocess_node',
          'mymodule_process',
        ),
    );
    return $templates;
}

function mymodule_preprocess_node(&$vars, $hooks){
    if($vars['type'] == 'leg'){

    }
}

When I put my template file into sites/all/themes/sky/templates and changed path in hook_theme to that location, it works.

function mymodule_theme(){
    // The base theme registers node.tpl.php.
    $templates['node'] = array(
        'arguments' => array('elements' => NULL),
        'path' => drupal_get_path('theme', 'sky') . '/templates',
        'template' => 'node--leg',
        'preprocess functions' => array(
          'template_preprocess',
          'mymodule_preprocess',
          'mymodule_preprocess_node',
          'mymodule_process',
        ),
    );
    return $templates;
}

I would like to know it is a right way or not.
I should not place my template in the sky theme folder, am I right ?

drupal_get_path('theme', 'mymodule') should be drupal_get_path('module', 'mymodule').


If I delete enabled module files will items be stuck in the database forever? The list that populates the modules page is loaded from the files. But whether a module is enabled or is stored in the database (I assume).

If I enable a module and then delete the files will there be an database entry (to say it's enabled) in the database forever? Or will it be cleared at some time?

Will it slow down the site or clog up my database if I've cleared a lot of modules without disabling them first?

In order to get rid of module's database tables and other contents, you must first disable the module, and then uninstall it.  Deleting a module without disabling it is "against the rules", as module_exists('foo') will still return 'true' for these enabled-but-removed modules.  Since Drupal tends to call modules only via code that uses the php function function_exists to determine if hooks are available, you usually won't experience any obvious problems if you do this.  However, things could get weird if you had a situation where module B uses module_exists() on one of these modules that you removed.  The code in question could make assumptions that are only true when the hooks you deleted are executed, which could cause unpredictable behavior.  So, in short, don't do that -- always disable and uninstall your modules if you no longer need them.


How is composer including a dependent module? I have a composer managed Drupal project based on drupal/recommended-project.
I'm installing a contrib module, domain_group, and I'm seeing that composer is auto-including a required dependency, even though it's not listed in the module's composer.json. (I'm checking some other contrib modules and it seems that this is not specific to this module, but a consistent pattern across many modules.)
I run:
composer require drupal/domain_group

and it installs domain_group and domain_site_settings.
Then when I run:
composer why drupal/domain_site_settings

and it tells me that drupal/domain_group requires it.
While the dependency is not listed in domain_group/composer.json, I do see that it is listed in domain_group.info.yml.
Is composer somehow looking to the .info.yml to check for dependencies? Is this some kind of Drupal magic? What causes this? How does it work?
Update:
It seems that it's not checking the .info.yml, at least not locally. From @Clive, in the comments:

[composer why still lists the dependency] even when [the reference to domain_site_settings] is not in domain_group's local composer.json, composer.lock is deleted, the require line in domain_group.info.yml is commented out and composer cache is cleared (just checked). Where is it getting the reference?

I'm now wondering if composer why checks the remote repositories, e.g. https://packages.drupal.org/8, and if there's something special about the d.o repository that compiles extra package dependencies from .info.yml files.
domain_group/composer.json
{
    "name": "drupal/domain_group",
    "type": "drupal-module",
    "description": "This module provides integration between Domain and Group modules",
    "homepage": "http://drupal.org/project/domain_group",
    "authors": [], // etc...
    "support": {}, // etc...
    "license": "GPL-2.0+",
    "minimum-stability": "dev",
    "require": {
        "drupal/core": "^8.8 || ^9",
        "drupal/group": "~1.0",
        "drupal/domain": "~1.0"
    }
}

domain_group/domain_group.info.yml
name: 'Domain Group'
type: module
description: 'This module provides integration between Domain and Group modules.'
core: 8.x
core_version_requirement: ^8 || ^9
package: 'Domain'
dependencies:
  - group:group
  - domain:domain
  - domain_site_settings:domain_site_settings # Is composer somehow respecting this?

I think this is what's happening:

The Drupal packager gets dependencies from domain_group.info.yml, and adds them to the dependencies for the package record that composer will use.
When composer installs the package, it downloads the current version of the module code (which doesn't have the dependency in composer.json)
Composer doesn't use that composer.json for its record keeping - it stores the dependency from the packager in composer.lock, and also in vendor/composer/installed.json
composer why seems to use composer.lock first for its info, falling back to installed.json if unavailable.

So it doesn't really matter what's in the module's composer.json as far as Composer commands are concerned - it's looking at composer.lock or installed.json, which has domain_site_settings as a requirement from the original install.


Content-type linked to specific users and user-groups I am creating a system which has 2 types of user: a Member and a Group Admin. Members are put into Groups and are managed by that groups Admin. A Member can contact their Group Admin but not other Group Admins. Some of this contact data/messages should be visible to other Members of that particular Group, some information should be visible only to that Member and the Group Admin. In certain situations, a Group Admin should be able to become the Group Admin of another Group. Members can make complaints to Group Admins who are able to respond. Anonymous users should be able to make complaints, provided they provide extra information, e.g., name, address, telephone number. Ideally, when making a complaint they would be asked if they would like to create an account.

Being new to Drupal (started looking through the Docs a week ago) I'm having trouble with pretty much everything. Using Drupal has been made a requirement as it is meant to make the process easier; however, for me it is not. As there are approximately 800 different groups does this mean that I'm going to have a huge matrix of permissions? Am I going to have to create 800 different roles? I'm struggling visualising the architecture of the system and the modules I'll need. For example, I'd created a content-type Complaint; however, everyone could see it. Drupal 7 Core has no way to restrict different users from viewing specific content. I remedied this by installing a module: Content Access. Any suggestions for the architecture and modules would be useful.

Often times when using Drupal there are recipes or a collection of modules that will help you achieve your goals for a website so that your workload is  not burdened with custom PHP business logic code or SQL. Drupal helps to take away these technical difficulties when creating websites.

It sounds like you want to a site with groups of content and users. There exists active module(s) to allow easier site development of sections and groups of users within a website. The defacto module for this is Organic Groups (typically referred to as the "OG" module) and its set of sub-modules and contributed add-on 3rd party modules.

  Overview

  Enable users to create and manage their own 'groups'. Each group can
  have subscribers, and maintains a group home page where subscribers
  communicate amongst themselves.

  They do so by posting the usual node types: blog, story, page, etc. A
  block is shown on the group home page which facilitates these posts.
  The block also provides summary information about the group.

  Groups may be selective or not. Selective groups require approval in
  order to become a member, or even invitation -only groups. There are
  lots of preferences to configure groups as you need.

OG is not a small or simple module in it's administrative configuration, or it's supported API. But, it's goal is to make your stated problem easier to implement in a standard fashion/codebase for site developers.


How to change the url pattern of user revisions? How can i change the url pattern of a user revision ? I want to change

users/jon-doe/revisions/123/view

to

users/jon-doe/archive/123/view

There is no option in pathauto to influence the url patterns of revisions.

This path is defined by revisions module hook_menu(), so if you want to alter it, use hook_menu_alter() in your module.

function mymodule_menu_alter(&$items) {
  // Copy element to new path:
  $items['users/%/archive/%/view'] = $items['users/%/revisions/%/view'];

  // Optionally remove original - this may break some links!
  unset($items['users/%/revisions/%/view']);
}

And of course remember to clear the caches!


How can I use month name as contextual filter? I have a contextual filter to filter by month:

Date in the form of MM (01 - 12).

However, I want to filter by month name (january, february, march, etc.) to get nicer URL and breadcrumb.

Is there an easy way to do it?

You can programmatically alter the contextual filter value of "january" to "01 - 12" in hook_views_pre_view

/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for my_special_view.
  if ($view->id() == 'my_special_view') {
    // insert here some php magic to format "January" to "01".
    $og_arg = t('@og_arg', ['@og_arg' => $args[0]], ['langcode' => 'en']);
    $date = date_parse($og_arg);
    // assign formatted value.
    $args[0] = $date['month'];
  }
}


How to check if view is added in a feature? For Drupal views is there any way/field which tells us if your view is added to a feature or not. And if yes in which feature it is added?

I have a view which I need to check if it is added in a feature or not.I have lot of features on my site and I am searching all the features one by one to check if the view is added in any of them. Is there any other efficient way to check this?

Any guidance is appreciated.

The features export views' code in files like this: my_module.views_default.inc. Every feature module with a file my_module.views_default.inc contains views.

Manually:

Searching against those modules by using the view's machine name as an input, will show whether that view machine name is tracked or not, to any of these modules.

Using drush:

Having all your features updated drush fu-all -y do some changes to a view (save) and drush fl. The feature that will appear with an overridden status contains that view, otherwise the view is not tracked yet. To see which features contains views code do drush fc --exported and select views_view, that will narrow down significantly the searching range.

More Features & Drush


How does the private files folder need to be configured exactly? In settings.php I specified as /home/username/myfiles

Under Config > File System it shows the path, but when I add a file field to content, it does not show private upload as an option. I am wondering if it is because of how I specified the path? The path exists, and is writable. So I am confused.

Any ideas?


How can I disable parent menu link to be non-clickable? Nolink,None,Separator and other things does not work when added to URL path.
Have also Installed menu module but that did not help.
Its Drupal 7.

Thank you for your co-operation!

Install the Special Menu Items module. You can add menu items that are placeholders or separators but aren't clickable. It is found on the drupal module site: https://www.drupal.org/project/special_menu_items


How to get a section of the menu tree based on the current node? I am currently struggling to wrap my head around how the menu tree and menu link services work for outputting part of a menu with some custom requirements. Admittedly I don't have to do this very often, but it seems like there must be a way.

I tried with Menu Block, but that does not seem to be able to do what I need to do.

First, when I am on level 3 and a certain content type, (or the parent route is nolink), I need to print the current level of the menu like this:

The menu links represent what is under the current page.

Second, if it is level 2+ (and not a certain content type), the section parent needs to sit on the top as a blue link, in a different treatment:

Third, if the current page in the menu is active, no siblings are printed, only this page menu link and its children:

I started here, in a menu block:

/** @var \Drupal\Core\Menu\MenuLinkManager $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$route_params = array('node' => $node->id());

$menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', $route_params, 'main');

// Attach the top parent, if we are at level 3 (for a project) or level 2 (for a basic page)
// top parent cannot go above level 3.... but also level 2?
// show the current node menu tree and its siblings
// show the siblings if the current page has no children

$parent = reset($menu_links)->getParent();
$uuid = str_replace('menu_link_content:', '', $parent);
$parent_menu_content = current(\Drupal::entityTypeManager()
  ->getStorage('menu_link_content')
  ->loadByProperties(array('uuid' => $uuid)));

$params = new MenuTreeParameters();
$params->setRoot($parent);
$params->setActiveTrail([$parent, reset($menu_links)->getPluginId()]);

$tree = $this->menuTree->load($parent, $params);
$built_tree = $this->menuTree->build($tree);

$link = end($parent_menu_content->link->getValue())['uri'];

$element = $this->menuTree->build($tree);
$build['#items'] = $element['#items'][$parent]['below'];

if ($link != 'route:<nolink>') {
  $build['#top_parent'] = $element['#items'][$parent];
}

if (empty($build['#cache']['contexts'])) {
  $build['#cache']['contexts'] = ['user.permissions'];
  $build['#cache']['tags'] = ['config:system.menu.main'];
}

return $build;

But the children of a link (in below) don't render correctly in Twig, its blank, and I am not sure if there is some easier way to do this.

top_parent is a new theme variable I have added to menu so I can render it separately in Twig.

Edit: below now renders right - I forgot to {% import _self as menus %} in my second macro.

Found a way to satisfy all the cases without having to create multiple blocks (visibility rules would be odd) or create different menus. I could not achieve this by assuming a content type like in the question, because you could have the same content type nested until multiple areas of the menu, and not really know if the current depth you were at for it qualified as the parent (where the menu block should "begin" - not necessarily the parent of the page).

I decided to cheat a bit and use the URL and the alias pattern. If the current path matched a pattern, and the URL consisted of a certain amount of segments, I could tell I was in a specific part of the menu where the behavior should be different than others. In this case, it should use the current page and its children, instead of the parent of the current page and its siblings:

class MenuBlockEnhanced extends MenuBlock {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');

    // If we are not on a node route, get out.
    if (!$node) {
      return parent::build();
    }

    // If the menu being rendered is not specifically the sub nav, get out.
    if ($this->configuration["suggestion"] != 'subnav') {
      return parent::build();
    }

    $current_path = \Drupal::request()->getRequestUri();
    $parts = explode('/', $current_path);
    $build = parent::build();

    /** @var \Drupal\Core\Menu\MenuLinkManager $menu_link_manager */
    $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
    $route_params = array('node' => $node->id());
    $menu_links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', $route_params, 'main');
    $set_parent = TRUE;

    $params = new MenuTreeParameters();

    // I don't really know of another way to 'tell' we are on a project, since
    // a project can have projects under it. We can only rely on the path and
    // how many 'parts' are in the path - anything over 4 parts would be anything
    // nested in this section.
    if (preg_match('/programs-projects/i', $current_path) && count($parts) == 4) {
      $parent = reset($menu_links)->getPluginId();
      $set_parent = FALSE;
    } else {
      $parent = reset($menu_links)->getParent();
    }

    $uuid = str_replace('menu_link_content:', '', $parent);
    $parent_menu_content = current(\Drupal::entityTypeManager()
     ->getStorage('menu_link_content')
     ->loadByProperties(array('uuid' => $uuid)));

    $params->setRoot($parent);
    $params->setActiveTrail([$parent, reset($menu_links)->getPluginId()]);
    $tree = $this->menuTree->load($parent, $params);

    // Transform the tree using the manipulators you want.
    $manipulators = array(
      // Only show links that are accessible for the current user.
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      // Use the default sorting of menu links.
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $this->menuTree->transform($tree, $manipulators);

    $link = end($parent_menu_content->link->getValue())['uri'];

    $element = $this->menuTree->build($tree);
    $build['#items'] = $element['#items'][$parent]['below'];

    if ($link != 'route:<nolink>' && $set_parent) {
      $build['#top_parent'] = $element['#items'][$parent];
    }

    if (empty($build['#cache']['contexts'])) {
      $build['#cache']['contexts'] = ['user.permissions'];
      $build['#cache']['tags'] = ['config:system.menu.main'];
    }

    return $build;
  }

}

The caching strategy comes right from what would normally be there, frankly I probably do not even need to specify it since I am already calling parent::build() and just reduce that code.

In the template, I resolve the "do I print just siblings, or this page and its children?" by using the in_active_path check, and faking a control break in Twig macro (see: break = true):

{% import _self as menus %}

{{ menus.menu_links(items, attributes, 0, top_parent) }}

{% macro menu_links(items, attributes, menu_level, top_parent) %}
  {% import _self as menus %}

  {% if items %}
    {% if top_parent %}

        {%
          set parent_list_classes =
          [
            'secondary-nav__item',
            'secondary-nav__item--parent'
          ]
        %}

        {% set parent_link_classes =
          [
            'link',
            'link--left-arrow',
          ]
        %}

          {{ link(top_parent.title, top_parent.url, { 'class': parent_link_classes }) }}
          {{ menus.menu_child_links(items, attributes, 0) }}

    {% else %}
      {{ menus.menu_child_links(items, attributes, 0) }}
    {% endif %}
  {% endif %}
{% endmacro %}

{% macro menu_child_links(items, attributes, menu_level) %}
  {% import _self as menus %}

    {% set break = false %}
    {% for item in items if not break %}
      {%
        set list_classes =
        [
          'secondary-nav__item',
          item.in_active_trail ? 'is-active'
        ]
      %}

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

        {% if item.below and item.in_active_trail %}
          {% set break = true %}
          {{ menus.menu_child_links(item.below, attributes, menu_level + 1) }}
        {% endif %}

    {% endfor %}

{% endmacro %}

The menu works exactly as asked for all cases, and will go all the way down to its maximum depth and back up the chain (with the parent blue link appearing up top).


Tried to Inline CSS with AdvAgg but still get errors in Google My Right-to-left site uses clean Bootstrap subtheme and has CDN, Internal caching (including Boost), Minification, Compression and aggregation, but still I get very low grades with all that has to do with CSS performance. Therefore I tried to inline all the CSS in my site via AdvAgg (please see image), what helped me in another theme, but not this time...

Is there anything else you think I should try?

Your setting for Inline CSS on specific pages is wrong. The path you should set is:

node/*


Transfering a drupal site from localhost to online and viceversa I am about to finish my first Drupal site and I wish to upload it on the server. However, I am going to add content when the site is online but every time I make a change online I would like to add that change to the site on localhost (changes in content, new module additions, etc.). What is the least time consuming way to achieve this?
With .html sites it is very easy because you only need to have the .html file saved offline and online and that it is. What things do I need to consider with a Drupal site? I would like to always have the exact same files, modules, content, configuration on the online version and the offline version of my site.

Thanks in advance.

the best way will be to use Git to keep you code updated and Features to keep you configuration up to date.

A good free source code hosting for git is BitBucket. It gives you unlimited private repositories but limited users. Github gives you unlimited users but you pay for private repositories.
Anything you change in code can be hosted in one of those code hostings and you can push it from dev (your local) and pull it from your production environment (live).
Git keeps track of all your changes.

  Git is a free and open source distributed version control system
  designed to handle everything from small to very large projects with
  speed and efficiency.

For site configurations you can use Features

  the features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.

You can use Features module along with:
Strongarm

  Strongarm gives site builders a way to override the default variable
  values that Drupal core and contributed modules ship with. It is not
  an end user tool, but a developer and site builder tool which provides
  an API and a limited UI.

  An example of such a variable is site_frontpage. In Drupal this
  defaults to node, which ensures that the front page gets content as
  soon as some exists, but for many Drupal sites this setting is simply
  wrong. Strongarm gives the site builder a place in the equation - an
  opportunity to set the site_frontpage to something that makes sense
  for their site.

and Features Extras

  Features Extra provides faux exportables (via Features) of several
  site-building components

This will be a good way to keep your code and your configuration aligned between two environments.

Second option, if you are not familiar with Git, you can just use an FTP software, download or upload files and then use Backup and Migrate

  Back up and restore your Drupal MySQL database and files or migrate a
  site between environments. Backup and Migrate supports gzip, bzip and
  zip compression as well as automatic scheduled backups.

  With Backup and Migrate you can dump some or all of your database
  tables to a file download or save to a file on the server or offsite,
  and to restore from an uploaded or previously saved database dump. You
  can choose which tables and what data to backup and cache data is
  excluded by default.

For your files folder you can use an FTP software.

To synronize nodes, you can use Deployment.

  The Deploy module is designed to allow developers to easily stage
  Drupal content from one site to another. Deploy automatically manages
  dependencies between objects (like node references). It is designed to
  have a rich API which can be easily extended to be used in a variety
  of situations.

Here is the documenentation about the module. Create 2 sandboxes and give a try to it. It also works with features.

For code and configuration sync, I strongly suggest you to use Git and Features.


How to pass value generated in the form submit function to another function? I have a question related to drupal 7 form api and module development.

I have a very simple module with a function like this. It gets called by hook_menu when a certain path xyz is visited.

function myview_mainpage() {

  $content .= drupal_render(drupal_get_form('myview_form'));
  $content .= "Some additional stuff here";
  return $content;
}

My form looks like this (it's from the examples module):

function myview_form($form, &$form_state) {
  $form['description'] = array(
    '#type' => 'item',
    '#title' => t('A simple form with a submit button'),
  );

  $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
  );

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

And my submit handler looks like this:

function myview_form_submit($form, &$form_state){

 // I do some sql stuff and generate html content based on the value that was submitted in the form
  $variable = "

Some stuff
...';

}

And now I need to somehow pass the value of $variable to the function myview_mainpage() so it can print it out.
So in a nutshell: User submits a from, some processing is done based on the value submitted and then the results are displayed under the form when it is displayed.

Maybe I could use $form_state['redirect'] to redirect the user to the page xyz but I don't want to send the value of $variable in the address bar of a browser.

Any ideas? This feels like it should be done quite easily but I can't find a way to do it.

You can store that information in the user session. There is always a redirect after a form submission so you need to persist it somewhere because PHP is a stateless.

Simply add your data to $_SESSION['yourmodule'] and then in the mainpage() function check if something is there and display it.

If that information is not temporary and must be there on the next visit too, persist it in the database in a custom table.


How to access the Webform Mysql View I enabled the module Webform Mysql Views (https://www.drupal.org/project/webform_mysql_views). Enabled the webform for which I want to create the view through here - http://YOURWEBSITE/admin/content/webform/mysql

I am still unsure how can I actually see my view in this case. Where do I find it? I was expecting it under the results section just in case but I am unable to find it.

Thanks.

This answer is probably not timely to pal4life, but for anyone else still looking for answers.... this view doesn't show up via the Views module per say.  It is best used in conjunction with other modules or code.

For example, I wanted to get filtering functionality on my Webform views and using the Webform MySQL View module seemed to be the recommended way to go.  However, you will most likely need to install the Data and Schema modules as well.  A great walk through on how to use all three together to create filterable, sortable webform data via Views can be found here:

http://knackforge.com/blog/sivaji/displaying-webform-submission-data-drupal-views#comment-1085


How is user input sanitized? I had to develop a Drupal 8 based website for a client. This client has a quite strict configuration for its firewall and filters the characters used in POST values. It happens to be a bit too restrictive on the contact form for the taste of the marketing department. The security team would consent to lift some character limitations if I could list them the measures used by Drupal and Webform to filter/sanitize user inputs.

I am pretty confident that Drupal does a good job in that regard. I expect a mixture of htmlentities(), filter_var(), custom functions calls and other related configurations but I couldn't find any details. All my searches on the subject spawns answers around the fact that Drupal does sanitize its input, but nothing concrete.

How does Drupal sanitize the user input?

Drupal uses Twig's autoescape feature, which in turn uses escape, which itself uses htmlspecialchars to prepare markup safe for output.

SafeMarkup::checkPlain() preceded the autoescaping (deprecated now), so you may see that used, and HTML::escape can be used if you need to do it manually for whatever reason.

As with all versions of Drupal, filtering is done on output only, not input, so filter_var and friends aren't involved.


Weird permissions problems for sites/default/files I have this weird problem related to permissions on a VPS where I run 2 Drupal 7 websites.

I have an old site, which was migrated over several hosting providers and VPS setups. I also have a freshly installed website.

The new one works perfectly and I can set it to aggregate and compress CSS files plus JavaScript files. All is smooth and without errors.

The old one... each time I set it to do this, It gives me errors such as:

The specified file temporary://filepIYgt4 could not be copied to public://js/js_IaQHoIpFqzgiVl19GZEd2HEQg6iqLy6d1_xllBmEbqE.js.
The specified file temporary://fileTbJH3r could not be copied to public://css /css_Lnc8IK4qbp4ueX76wBYIBGAqVihLWtCHHNP7WBSphEM.css.

Both websites are configured the same way. The difference though seems to be in the permissions set for the sites/default/files folder. The new website (which works fine) has the permissions set to 0777 and the group and owner are set to apache.

The old website (which generates errors) has the permissions set to 0777, the group to psacln and the owner is the user I'm using to login to the website via SSH or FTP.

If I change the owner and the group to apache for the old website, things still don't work. I get warnings like these:

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/css owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/js owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

Warning: realpath(): SAFE MODE Restriction in effect. The script whose uid is 10002 is not allowed to access /var/www/vhosts/.../httpdocs/sites/default/files/ctools owned by uid 48 in DrupalLocalStreamWrapper->getLocalPath()

As you can see, Drupal still can't write to the same troublesome folder. :(

What am I doing wrong? Any advice how to fix this?

I managed to figure this out with the help of the company providing the hosting. So, I'm sharing the solution, in case others have similar issues.

The solution is to make PHP run as a "FastCGI application", instead of an "Apache module". This way, Drupal uses the same user I use to upload files via FTP, when it creates files, etc.

The new website worked fine because I used the one-click installer offered by the hosting provider, which ran everything using the apache user. The old website did not do this.

This solution & problem should apply to all hosting providers using Plesk.


How do I direct link a view to a taxonomy menu? I have created a vocabulary with over a hundred terms on three levels (parent/child/child) and used Taxonomy Menu to create a custom menu.  Selecting a menu item brings up a  default menu page with the description and a list of teasers of content that has the vocabulary term in a field.  I would like it to use a view to manage the content display.  IS there a way to direct the menu items to a view? I cannot find a way to change the link generated by the taxonomy menu module.

Edit to clarify the question:
Taxonomy menu generates a user defined menu block that will call up the taxonomy term selected. Unfortunately it locks the path (so it can regenerate the menu from the vocabulary if it changes).   I am looking for a way to generate the menu but change the path to display the view rather than the term page offered by taxonomy menu.

If I understand well your question, I think that you can show your menu with the Expose Filter fature of Views:

first add the filter related with your taxonomy:

then select the type of your menu (for example: dropdown) to expose:

and finally, you can expose these filter to visitors, to allow them to select terms to see just the content related:

I hope I have understood, and that information be useful. Here is an example of the view with results according a selection:


How to create views grouped by title I want to build a view sorting it on the basis of the term field. I need to show the term as a title in each group, like this:

Term 1:

node1
node2

Term 2:

node3
node4

Term 3:
...

How can I achieve this?

Steps to show the view in this ways is

Create an Unformatted view showing Title and Terms.

Term field should be excluded from the display.
Do a grouping of the term field.(Unformatted Format -> Settings)

Save the view and check the result of the view.

Hope that this helps.


Apply comments votes to parent node (with Rate module) My site have a fivestar field in comments, where users gives their vote and the points are applied to the parent node. This is possible using Fivestar module, following this instructions: http://drupalclinic.blogspot.com.es/2011/09/add-fivestar-ratings-in-comments-and.html

Could the same be done with Rate module (https://www.drupal.org/project/rate) and without custom coding?

No, it is not possible.

And also unlike Fivestar module, where the rating field can be made visible in node/comment form and node/comment display, the Rate module allows you to add the field only on node/comment display, not on form.


Cannot create custom translated path alias for /user/login I cannot create a path alias for spanish translation.

When I try to create, it says Route is invalid or you don't have access

Saw this but it doesn't have an answer: https://www.drupal.org/project/drupal/issues/236915

How can I translate the /user/login path?

You can try this module: https://www.drupal.org/project/rename_admin_paths
Should do the job... Good luck!


Do All Drupal themes support subtheming? I heard that only some themes can have a subtheme.
Is this true?

No, of course it isn't true. All themes can be subthemed. Subtheming is a part of Drupal's core and themes cannot simply turn it down. You can always create a theme, name it's parent theme and override some CSS.

Fun starts when you want to override things from template.php, or if parent theme provides advanced configuration - not all themes are built in a way that makes subtheming easy. But even if it's not easy, it's not really blocked.


Why does this simple javascript execute multiple times? Why does this javascript execute 2-4 times per page load:

// mei_library_turn.js
(function ($, Drupal) {
  Drupal.behaviors.mei_library_turn = {
    attach: function() {

      console.log('ready1');

      // There would be a lot more code in here, but I've stripped it all out to debug.

    }
  };

})(jQuery, Drupal, drupalSettings);

That is the entirety of the javascript file.  What could possibly be causing this to fire multiple times?  The script is not included in the head of the document multiple times.

Most often, when I load the page, it fires 3-4 times.  Sometimes just two times.

I realize once() can be used to mask problems like these, but it adds complexity to scripts and I would like to understand what is causing the code to execute multiple times in the first place.

Here is the page where I attach the library:

public function book($marc_num) {

    $output = [];

    $output['something']['#attached']['library'][] = 'mei_library/librarybook';

    return $output;

  }

Here is my libraries file:

librarybook:
  version: 1.x
  js:
    js/mei_library_turn.js: {}

Behaviors will be executed on every request, including AJAX requests.

you can use the once function to make sure it is only triggered once.

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

       $('main', context).once('mei_library_turn').each(function () {
          console.log('ready1');
       };)

      // There would be a lot more code in here, but I've stripped it all out to debug.

    }
  };

})(jQuery, Drupal, drupalSettings);