Adding template suggestion for twig based on page and content type Actually twig only suggest templates files name like this:
<!-- FILE NAME SUGGESTIONS:
   * html--node--20.html.twig
   * html--node--%.html.twig
   * html--node.html.twig
   x html.html.twig
-->

But I would have 2 kinds of template suggestion (like on my D6 website):
One based on page + content type : page--CONTENT-TYPE.html.twig
And other based on nodes + content-type : node--CONTENT-TYPE.html.twig or page--node-CONTENT-TYPE.html.twig
Actually I have a function in my .theme file like this but nothing change about suggestions:
function starterpf_d8_2019_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
}

Code found here
Thanks for help
EDIT: after exploring the output HTML, I get the page suggestions like this:
<!-- FILE NAME SUGGESTIONS:
   x page--front.html.twig
   * page--node.html.twig
   * page.html.twig
-->

So, can I add different kind of suggestions with putting together part of your codes ? Like this:
function starterpf_d8_2019_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
  #Suggestions pour les nodes
   $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    $suggestions[] = 'page__' . $node->bundle();
    $suggestions[] = 'page__node_' . $node->bundle();
  }

  #Suggestions pour les types de contenus
   if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page__'.$content_type;
  }
}

And if I only want to create a file like node--CONTENT-TYPE.html.twig instead of a page one ? Interesting in use of node--CONTENT-TYPE-nid.html.twig too.
And what would be better to use ? Knowing that I include field datas inside template to theme easily them ?
In some use cases I will need to theme depending taxonomy term, is this native with D8 ?

Try this out:

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function myModule_theme_suggestions_page_alter(&$suggestions, $variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    $suggestions[] = 'page__' . $node->bundle();
    $suggestions[] = 'page__node_' . $node->bundle();
  }
}


How to assign the user login block to header region I created a user and I logged in as the user by visiting xxx.com/user. I just visited xxx.com/user. I see the user name but I do not see any log out button. I am not sure how I logout.

Thanks.

D

The Drupal core User login block doesn't display a login/logout link; it only displays a form for logging in an anonymous user. If you want a block to display logout, the User Menu block displays user-specific menu links that also includes a logout link when a user is logged in.


How to add field to fieldset by ajax? I have a fieldset with one field by default. I want to add new fields by ajax (button "new item"). I can do it for usual field, but I have a problem with fieldsets.
How to do that?

For usual fields I do it like below:

$form['add_item'] = array(
    '#type' => 'button',
    '#value' => t('Add item'),
    '#ajax' => array(
        'wrapper' => 'content',
        'callback' => 'add_more_ajax',
        'method' => 'append',
        'affect' => 'fade',
    ),
);

function add_more_ajax($form, &$form_state) {
    $form['image'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#default_value' => '',
        '#upload_location' => 'public://images/',
    );
    return $form['image'];
}

First - ajax callback should not make any persistent changes to $form. It's only duty is to return proper part of form array. Render all elements in form creation function:

mymodule_form($form, &$form_state) {
  $form['image'] = array (
    '#type' => 'fieldset',
    '#title' => t('images'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (empty($form_state['image']['count'])) {
    // Keep number of fields either in form or form state, both works.
    $form_state['image']['count'] = 4; // Default number of elements
  }
  elseif( isset($form_state['triggering_element'])
      and $form_state['triggering_element']['#machine_name'] == 'more_images_button' ) {
    // If form was triggered by proper form element, increase counter
    $form_state['image']['count']++;
  }
  // Loop to create elements
  for ($i = 0; $i < $form_state['image']['count']; $i++)
  {
    $form['image'][$i] = array (
      '#markup' => "
$i
",
    );
  }
  // And our button
  $form['image']['more'] = array (
    '#type' => 'button',
    '#value' => t('More'),
    '#ajax' => array (
      'callback' => 'product_more_images',
      'wrapper' => 'product_images',
      'method' => 'replace',
      'effect' => 'fade',
      'prevent' => 'submit',
    ),
    '#machine_name' => 'more_images_button',
  );
}

// Now callback function is trivial
function product_more_images($form, $form_state) {
  return $form['image'];
}

Of course it's only a sketch, with all off topic parts removed.


Saving default field values on node_insert I would like to automatically save a CCK field which will be determined by the data in the $node object. Using node_save in this instance will cause an error so I need a way to simply insert the additional field into the database.

One obvious way is to simply call db_insert but I'm not sure that this is the best way to do this since most of the information in this table is automatically generated and I'd like to leave that up to Drupal if I can.

What is that standard approach in this case?

Thanks!

You could probably do this in hook_node_presave(), e.g.:

function MYMODULE_node_presave($node) {
  // Get a value made up of other submitted fields, e.g.
  $computed_val = $node->field_first[$node->language][0]['value'] + $node->field_second[$node->language][0]['value'];

  // Assign that value to the other field
  $node->field_computed_field[$node->language][0]['value'] =  $computed_val;
}


getting 404 error while developing an example module I have created custom module named hello
my files are

hello.info.yml  is

name: Hello
type: module
description: 'My first Drupal 8 module.'
package: Awesome modules
version: 1.0
core: '8.x'

hello.module file is

<?php

use Drupal\Core\Routing\RouteMatchInterface;
function hello_hello_world() {

    return t('Hello Drupal 8 World!');

}

** hello.routing.yml** file is

hello.content:
  path: '/hello'
    defaults:
       _controller: '\Drupal\hello\Controller\HelloController::sayhello'
  requirements:
    _permission: 'access content'

and last one is HelloController.php is under hello/src/Controller folder

<?php

namespace Drupal\hello\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 *
 */
class HelloController extends ControllerBase {
    /**
     * [sayhello description]
     * @return [type] [description]
     */
    public function sayhello() {
        return array('#markup' => hello_hello_world());
    }
}

when we browse this page mywebsite.com/hello it gives a 404 error page.

Note: module is successfully enabled from admin

The indentation of your hello.routing.yml file is wrong. It should be as the following one. (See user.routing.yml.)

user.pass:
  path: '/user/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
    _title: 'Reset your password'
  requirements:
    _access: 'TRUE'
  options:
    _maintenance_access: TRUE

Indentation in YAML files is very important, since it changes the file content.

Notice that you can use _access: 'TRUE', when the page doesn't require a specific permission. The _maintenance_access: TRUE line is not necessary. If you use it, users have access to your route even when the site is in maintenance mode; other requirements are still respected, so you could have something similar to the following.

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

Before making any changes, uninstall the module, fix the file, and re-install the module.

As side note, you don't need the use Drupal\Core\Routing\RouteMatchInterface; line in your hello.module file, since you aren't using that PHP interface.


Menu with contextual links from view Each user, lets say performer has profile page (which is node, not default user page) which is visible and can be made once..
Band (for example "Cool Band") can create image gallery, video gallery, bio, concerts etc...
On registration each user has to enter unique profile name (field_profile_name, in our case Cool Band)

After registering, user picks band node and path is created as his main profile page with pathauto (sub-pathauto is installed too):
example.com/performer/[node_author_field_profile_name] = performer/cool-band

After saving the node he gets new role which can not make new nodes of this type, and link can not be changed.

Views contextual are setup to show different content made by user, resulting in paths:
example.com/performer/%/photo-gallery = performer/cool-band/photo-gallery
example.com/performer/%/video-gallery = performer/cool-band/video-gallery
example.com/performer/%/concerts = performer/cool-band/concerts

What i can not figure out is how to create sidebar menu block which will lead to those pages, so when site visitor lands on any bands page he can see sidebar with links to other part of bands pages.  Sidebar menu should show link like this:

example.com/performer/cool-band/photo-gallery
example.com/performer/cool-band/video-gallery
example.com/performer/cool-band/concerts

I have tried to create view (users) with "overwrite this field as a link" and link is: performer/[field_profile_name]/photo-gallery etc., but i can not get the contextual right way.

Considering your previous question and our conversation you left out quite some details ;)

The sidebar should appear on the band-page (and the child pages photo-albums, etc) only right?

Create a Views block (type: content) with a contextual filter Content: nid and choose Provide default: Content ID from URL.
Then under format make sure it is set to fields not to content.
Add a field Content: path and hide it from display.
Add a field Global: textarea, enable replacement tokens and use the path as a base path, so you enter all your urls like:

Photo gallery
Video gallery
...

This should give you a list of links that all use the path alias of the band-page node, and then attach another path item to it.

The only thing you won't have is an active trail, so the active page will not be highlighted in the menu. I don't know how to achieve that.

And finally make sure to only display this block on band pages and direct child pages, otherwise you'll get some strange links. Since you are using Sub-pathauto all links should continue to work even if you are visiting a child page, as long as you don't use a stand alone node as child (in this case the path will resolve to that node page).


Why my site is blocked by too many connection errors? I've created a simple website with a few pages on my local computer. I have Drupal installed in my XAMPP directory, so the directory looks like this: c:\xampp\htdocs\drupal\<all the drupal files sit here>.

I've signed up for a domain and I'm trying to upload my Drupal site to the web hosting company to go live.

I searched for many sites for step-by-step instructions how to do it. This is what I got and this is what I did:

Backup my drupal database on my computer.
Create a new blank database on the host.
Upload my local files on my computer to the host (I assume I need to upload all the files inside the Drupal directory, is that correct?)
Import my backed up database to the host.
Change the settings.php in the host. Is that the only file and place I need to change?

This is what I changed:

$databases = array (
'default' =>
  array (
    'default' =>
    array (
    'database' => 'yyyyy_xxx',   <== Can I use a different database name than the one I use on my localhost?
    'username' => 'yyyyy_xxx',   <== Can I use a different username than the one I use on my localhost?
    'password' => '12345',       <== Can I use a different password than the one I use on my localhost?
    'host' => '<www.my new site's domain name.com>',    <== Should I be using my new site's domain name here or localhost since all the files are sitting at the web hosting company's server?
    'port' => '',
    'driver' => 'mysql',
    'prefix' => '',
   ),
 ),
);

When refreshed my webpage and I've got the following error:

Error:
The website encountered an unexpected error. Please try again later.
Error message:
PDOException: SQLSTATE[HY000] [1129] Host 'box373.bluehost.com' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' in lock_may_be_available() (line 167 of /home3/<my website>/public_html/includes/lock.inc).

I've logged into my account on the hosting company using Putty and went to public_html/ and entered mysqladmin flush-hosts. Now I've got the error:

mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'xxx'@'localhost' (using password: NO)'

The xxx is the database name I used on my localhost. The new database name on the host is yyyy_xxx. Is it still referring to my localhost database even though I've changed the settings in settings.php file on the host?

I would appreciate if somebody can help me and give me some insights how to fix this problem.

Is this the correct procedure to upload files to the host for my website to go live?
Besides settings.php file, are there any other files I need to change?
How do I unblock mysqladmin using flush-hosts? Some websites suggest to include username and password to login to mysqladmin. I've entered mysqladmin -uyyyy_xxx -p12345 flush-hosts and I got the following error:

mysqladmin: refresh failed; error: 'Access denied; you need (at least one of) the RELOAD privilege(s) for this operation'

How do I prevent this problem to happen again? I just uploaded a few files to the host and I got this problem. In the future, I am going to upload the complete website to the host with way more files. I would like to find out the correct way to launch a Drupal website.

MySQL blocks clients which error made while connecting to protect MySQL from malformed client.

So first, you need to find what sort of error it is.

In example by checking MySQL error log in data directory (typically hostname.err) or if you've drush installed, by drush watchdog-show.

You may also increase max_connect_errors (what is current value?) maximum value depends on architecture (check Manual).

But this is not real solution if error is frequently occurred.

FLUSH HOSTS can help you to eliminate blocked host. E.g.

mysql> FLUSH HOSTS;

Source: Why MySQL connection is blocked of many connection errors?

Please note that to use mysqladmin properly, you need to have access to root account. If you don't have it, use FLUSH HOSTS command as above.


Can customizable products work out price based on the number of uploaded files? I'm using Drupal Commerce and would like to develop an online photo printing service like shutterfly.com and snapfish.com.

I wonder if it's possible using customizable products to count each uploaded file/photo and charge accordingly? If not, what other way can I achieve this requirement?

The answer is "yes"

I originally posted the answer here: https://drupalcommerce.org/questions/16291/can-customizable-products-work-out-price-based-number-uploaded-files

Export of the rule that proves it's possible:

   { "rules_files_price_multiplier" : {
      "LABEL" : "Files Price Multiplier",
      "PLUGIN" : "reaction rule",
      "OWNER" : "rules",
      "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
      "ON" : { "commerce_product_calculate_sell_price" : [] },
      "IF" : [
        { "entity_is_of_type" : { "entity" : [ "commerce-line-item" ], "type" : "commerce_line_item" } },
        { "entity_has_field" : {
            "entity" : [ "commerce-line-item" ],
            "field" : "field_upload_all_the_files"
          }
        },
        { "list_count_is" : {
            "list" : [ "commerce-line-item:field-upload-all-the-files" ],
            "op" : "\u003E",
            "value" : "0"
          }
        }
      ],
      "DO" : [
        { "variable_add" : {
            "USING" : { "type" : "integer", "value" : "1" },
            "PROVIDE" : { "variable_added" : { "file_multiplier" : "file_multiplier" } }
          }
        },
        { "LOOP" : {
            "USING" : { "list" : [ "commerce-line-item:field-upload-all-the-files" ] },
            "ITEM" : { "list_item" : "Current list item" },
            "DO" : [
              { "data_calc" : {
                  "USING" : { "input_1" : [ "file-multiplier" ], "op" : "+", "input_2" : "1" },
                  "PROVIDE" : { "result" : { "result" : "Calculation result" } }
                }
              },
              { "data_set" : { "data" : [ "file-multiplier" ], "value" : [ "result" ] } }
            ]
          }
        },
        { "commerce_line_item_unit_price_multiply" : {
            "commerce_line_item" : [ "commerce_line_item" ],
            "amount" : [ "file-multiplier" ],
            "component_name" : "fee",
            "round_mode" : "1"
          }
        },
        { "drupal_message" : { "message" : "[commerce-line-item:line-item-id]: File Multiplier = [file-multiplier:value]" } }
      ]
    }
  }

NOTE: This will still not update the price as the person is uploading files.


Why can't I override my menu in Drupal 7 with theme_menu_tree? I'm working in drupal for the first time and I'm coming along nicely and learning as I go. I need to remove the UL and LI from my menu so I've been doing some research and "MYTHEME_menu_tree_menu_name" was suggested to override the container. As A test I'm trying this in my template.php file:

function storm_menu_tree__menu_social_media($variables) {
  return '' . $variables['tree'] . '';
}

Where "storm" is my theme name. My menu name is "Social Media" but D7 shows the machine name as "menu-social-media".

When I test this nothing is affected. What am I missing?

I should note this is a sub-theme based off Zen Theme.

--- edit ---

this is what I'm using to call the menu:

<?php
$menu_name = 'menu-social-media';
$menu_id = 'social-media';
print theme('links', array('links' => menu_navigation_links($menu_name), 'attributes' => array('id' => $menu_id, 'role' => 'navigation', 'class'=> array('links', 'inline'))));
?>

Drupal 7 theme can implement a THEMENAME_menu_tree__MENU_NAME() or THEMENAME_menu_link__MENU_NAME() function to override theme_menu_tree() or theme_menu_link() for a specific menu.

References for overriding the specific menu:

https://gist.github.com/gagarine/3201854
https://gist.github.com/henrijs/6225177

Can you once try passing $variables as reference to the THEMENAME_menu_tree__MENU_NAME() as below:

function storm_menu_tree__menu_social_media($variables) {
  return '' . $variables['tree'] . '';
}

Note: Clear the cache after making the changes to the code in order to make sure implemented changes reflects on the site.


Render image programmatically based on field content I am templating a resource page that has 5 different types of resources. I want to display a specific icon based on the type of resource. I want to do this programmatically so that later, users can upload a document, choose what type of resource it is, and the icon will automatically be displayed.

Now I'd like to be able to complete the logic of this inside the node--resource-asset.html.twig template using a for or if statement.

This is the kint display for the field_resource_type array. I want to generate the icon based on the markup string. This is what I've tried

{% for markup in content.field_resource_type %}
{% if markup == 'Datasheet' %}

{% elseif markup == 'Whitesheet' %}

{% else %}

{% endif %}
{% endfor %}

Nothing renders. Any suggestions on what I should be using as the key to call the correct part of the field?

You have two primary things avaiable in a node template.

content: That contains rendered markup. Use it to print stuff.

node: This contains the node object with the raw values. Use this for comparisons and accessing the unformatted values. The same raw values would also be accessible through #items in content, but it's much more complicated to access.

So in your case, access the value with node.field_resource_type.value.

Note that this contains the key of the list field, and not the displayed label. I would recommend to always specify explicit keys (e.g., put datasheet|Datasheet in the allowed values field). Then you can also reliably translate those labels if you have a multilingual site and your template doesn't break.

Unless you actually have multiple values in there, you also don't need a loop. But if you do, you can loop over it with for item in node.field_resource_type and then use item.value.

See also http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet


Add extension .csv to file created with Views Data Export To export user data into a csv I've setup a view display of type data export succesfully.
I've setup a path "admin/people/export" and when visiting it will return a file.
The file is a csv file but it's created without the extension .csv.

Is there a way to create this file with this extension?

Thanks in advance

In the view settings click on Format: CSV File > Settings

In the dialog box that appear, be sure that Provide as file is selected. In the Filename field that appears when that option is selected, leave the default value (%view.csv).

%view, which adds the view machine name to the filename, is only one of the available replacement tokens. As visible in the screenshot, the other ones are:

%display
%exposed
%timestamp-full
%timestamp-yy
%timestamp-yyyy
%timestamp-mm
%timestamp-mmm
%timestamp-dd
%timestamp-ddd
%timestamp-hh
%timestamp-ii
%timestamp-ss


place own block from module to the left of the screen This is the first time i'm making a module for drupal.
In my module I create a block with a vertical menu in it.
I would like to place the block glued to the left of the screen (out the wrapper).

So far i tried to make my own region in the module (which worked) but I can't get the region to appear in the website. I know i would have to do this in the page.tpl.php from the theme, but I'm trying to do this through my module only.

So is there a way to make the website take the region?
Is there a other/better way to place the block to the left?

thanks in advance!
TL

You have to edit your theme's template to create a new region.

You will need to add something like:

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

Without this nothing in that region will ever get rendered.

You will also need to add it to your themes .info file.

For more information see: How do I create custom regions in a theme?


Custom grouping by taxonomy term in view I made a view with taxonomy and nodes, groupped like this:

term 1
    subterm 1
        row
        row
term 2
    subterm 1
        row
        row
term 3
    subterm 1
        row
        row
    subterm 2
        row
        row
term 4
    subterm 1
        row
        row

But I need grouping by term like this:

term 1
    row
    row
term 2
    row
    row
term 3
    subterm 1
        row
        row
    subterm 2
        row
        row
term 4
    row
term 5
    row
    etc.

please any ideas, i wasted a lot of time to find the hook and tpl.php for this (tpl. or hooks - ?)

Groping things in view not that easy, and what i suggest you here to save your time to use views_field_view which allowed you to insert view inside view.

So simply make 3 displays each one for level and pass the argument between them, that should not take more than 5 min


Use the Services-3.x node resource to create a new *unpublished* node Is there a way that I can force a node to be unpublished by using the
node resource?

Requirement: Site A defines a content type 'item' which is published
by default. Site B needs to create 'item' nodes on A, and these
auto-created nodes should be unpublished.

function toolreq_test_create() {
$toolreq_endpoint = variable_get("toolreq_endpoint", "");
$options = toolreq_service_login();
if (!is_array($options)) {
    print "error<p>";
    return;
}
//create a node

$node_data = array(
                      "title"=>"DHC Tool 04 dev",
                      "type"=>"item",
                      //"status"=> FALSE, //ensure unpublished
                      "status" => 0,
                      "language" => "und", //lanugage neutral
                      "field_webpage"=>array(
                                                  "und"=>array(0=>array("url"=>"http://berkeley.edu",)
)
)
);

//use json
$options['headers']['content-type'] = "application/json";
$options['method'] = 'POST';
$options['data'] = json_encode($node_data);
$request = drupal_http_request($toolreq_endpoint . '/node', $options);
}

Since the node table's status field is the mysql INT type (with a
default of 1), I would think that I could pass status=>0 in the above
code, but doing that results in a published node. I have tried passing
0 using both JSON and x-www-form-urlencoded data.

If I use status=>FALSE and use JSON, the node is created as
unpublished, but I think that this is equivalent to inserting '' in the node.status field which results in a mysql warning:

mysql> INSERT INTO `bamboodirt`.`node` (`nid`, `vid`, `type`, `language`, `title`, `uid`,
`status`, `created`, `changed`, `comment`, `promote`, `sticky`, `tnid`, `translate`)
VALUES (NULL, 21, 'item', 'und', 'sql insert test', '0', '', '0', '0', '0', '0', '0', '0',
'0');
Query OK, 1 row affected, 1 warning (0.03 sec)

mysql> SHOW WARNINGS
+---------+------+----------------------------------------------------------+
| Level   | Code | Message                                                  |
+---------+------+----------------------------------------------------------+
| Warning | 1366 | Incorrect integer value: '' for column 'status' at row 1 |
+---------+------+----------------------------------------------------------+

I would live with that warning, but my webhost's mysql is less
permissive and I get a real error (durning node_save() I think) on
that server:

"SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'status' at row 1"

(Here's the thread over at Pantheon http://help.getpantheon.com/pantheon/topics/json_node_create_works_on_localstack_fails_with_error_500_on_pantheon.)

Is there a way that I can force a node to be unpublished by using the
node resource, or do I need to write my own resource?

Try setting the 'status' field to TRUE or FALSE instead of 0 or 1.


Migrate both public and private files I am using Migrate Drupal-to-Drupal and migrating a D6 database to D7.

In D6, I have private and public files. They are in one field. In D7, I have a public file field and a private file field.  Migrate d2d MigrateNode class puts the source file field info in the 'upload' field which can only be mapped to one destination field:  public or private attachments.

My question is: Is there any way to conditionally check the value in the upload field in order to map the 'upload' to either the public or private field based upon that value?

I could not figure out a way to conditionally map content to public and private fields in one migration.

But, I did figure out how to resolve the issue.

I migrated all d6 files, public and private, to the d7 public attachments field.
I created a query that finds all the private files migrated into the public attachments field:

SELECT * FROM migrate_map_f43b6e55cfile mm inner joinfield_data_field_attachments fa on mm.destid1 = fa.field_attachments_fid inner join file_managed fm on fa.field_attachments_fid = fm.fid where fm.uri like '%private%' and fa.entity_type = 'node' order by fm.filename

The private files can be identified because they will have 'private' in their URI.

I iterate through the query results and switch the private files from the public attachments field to the private attachment field.

This process, while requiring an additional step after the actual migration, works perfectly.


Files migration failed I am trying to migrate Drupal 7 site to Drupal 8. Other migration processes work well, but only file migration fails.

I have files in sites/default/files/.

This is my migrate_plus.migration.upgrade_d7_file.yml

uuid: c6ddfa39-c76a-4457-ba30-8db364387f45
langcode: en
status: true
dependencies:
  module:
    - file
id: upgrade_d7_file
migration_tags:
  - Drupal 7
label: Files
source:
  plugin: d7_file
process:
  fid: fid
  uid: uid
  filename: filename
  uri: uri
  filemime: filemime
  status: status
  created: timestamp
  changed: timestamp
destination:
  plugin: entity:file
  source_path_property: filepath
  urlencode: true
migration_dependencies:
  required: {  }
  optional: {  }

And, I execute it with this drush command:

drush8 migrate-import upgrade_d7_file

This process returns this error message:

Processed 446 items (0 created, 0 updated, 446 failed, 0 ignored) - done with 'upgrade_d7_file'

What am I doing wrong here?

First off, when there are failures, check the messages table to see what the specific failures are:

$ drush8 mmsg upgrade_d7_file

In this case, I'm sure what you'll find is that it couldn't copy the files, because it couldn't find them - your .yml file does not include source_base_path, so there's no way for the migration to know where to copy the files from.

I'm guessing when you ran drush migrate-upgrade --configure-only to generate your migrations, you forgot --legacy-root - this value (either the address of your site such as http://www.example.com if you want to scrape the files directly over the web, or an absolute local filepath if you've copied the files onto your D8 server) will be used to set source_base_path in your destination configuration.


How to get a view result programmatically without exposed filters respected I have some views of display page which I do not want to show to public if there would not be any result when accessed without any exposed filters set. I have a custom views access plugin and a custom access checking class which can handle the access granting.
My idea so far is that I would like to run the view a first time during access checking without exposed filters. In this way I could find out if the view would ever deliver any results. I tried it in the following way:
  $view = Views::getView($view_id);
  $view->setDisplay($display_id);
  $view->setArguments([$politician_id]);
  $view->execute();
  $result = $view->total_rows;

The problem is: as soon as an user comes to this page with query parameters in the url set by exposed filters these exposed filters are used for this view query as well. I did not find any way to tell the class in $view to execute without exposed filters. I even tried to set these exposed filters data in the following ways but even then the filter data in the query parameters is still used to filter the result set:
  $view = Views::getView($view_id);
  $view->setDisplay($display_id);
  $view->setArguments([$politician_id]);
  $view->initDisplay();
  $view->initHandlers();
  $view->setExposedInput([]);
  $view->exposed_data = [];
  $view->exposed_raw_input = [];
  $view->execute();
  $result = $view->total_rows;

I want to achieve that in this way because I want to use this logic for several views. It would be so smart to simply re-use the arguments and filters set in the views instead of hardcoding a new custom database query as the settings in the views might change. I hope someone can help me.

Thanks to 4k4 (see comments). The solution is to set some dummy exposed filter data:
  $view = Views::getView($view_id);
  $view->setDisplay($display_id);
  $view->setArguments([$politician_id]);
  $view->setExposedInput([
    'dummy' => ''
  ]);
  $view->execute();
  $result = $view->total_rows;

In this way it works.


What is the machine name for the Date Posted? I'm using Views and have it set to fields. Can anyone tell me what the machine name of Content: Post date is? I used Time ago in my selection.

If you are talking about the 'ID' of the Content: Post date in Views, it is: created

You can find this under the Theme: Information link under the 'Advanced' settings block (in D7/Views 3) or the 'Basic settings' block (in D6/Views 2).  After clicking that link, find the name of the field and find the ID in parenthesis next to the field name.

Example: In this case you should find Field Content: Post date (ID: created)


How to use dash in namespace? I have installed a library using composer.json https://github.com/nuovo/spreadsheet-reader

Now in vendor I'm getting a folder structure like:

Now I want to use excel_reader2.php class inside my controller.

and I'm using it like:

use nuovo\spreadsheet-reader\php-excel-reader\excel_reader2;
use nuovo\spreadsheet-reader\SpreadsheetReader;

but it is giving me fatal error

  Parse error: syntax error, unexpected '-', expecting ',' or ';'

Is there any way to use folders containing '-' (dash) in their names?

If that package is doing it correctly, then it registered its classes with composer and it should just work.

If it doesn't use namespaces (which you could see by opening the file), then just write new ClassName and it should work.

That is assuming you installed the dependency correctly, it needs to be in your main vendor folder, not the one of a module or so.


rule to remove "Public files directory Not fully protected" in nginx? I use D7 with nginx and php5-fpm on Linux and get this security warning:

  Public files directory Not fully protected

I see here that one needs to use this snippet in Apache's htaccess to resolve the issue:

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</files>

Just wondering what should be the nginx equivalent rule?

Update: I already have this in my nginx configs:

root   /path/to/drupal;
}

location ~ [^/]\.php(/|$) {
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;
        if (!-f $document_root$fastcgi_script_name) {
                return 404;
        }
        try_files $uri =404;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
}

The .htaccess file won't have any effect in Nginx. You'll need to add your own rules to prevent PHP execution in the files directory.

e.g:

# Allow access to index.php only
location = /index.php {
  include fastcgi.conf;
  fastcgi_pass    127.0.0.1:9000;
}

# Any other attempt to access PHP files returns a 403.
location ~ \.php$ {
  return 403;
}

However, to fix that error message, you can actually just delete the old .htaccess file and Drupal will recreate a new correct one.

Note: the check is in system_requirements with the line

if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {

It only checks for that line, Drupal doesn't currently validate an actual PHP request to the relevant directory to test the handler.


Taxonomy filter exposed to user that dynamically only includes terms attached to currently published content Background:
a) Taxonomy: I have built as site that allows users to tag content of a particular content type with tags.  The system started with a pre-existing taxonomy before any content was added, but has grown organically as users add content and terms of their own.  What this means, of course, is that at any time, some of the terms in the taxonomy, may not be attached to any currently published content.

b) View with Exposed Tag Filter:  As a means to allow users to find material of interest, I have exposed the Tag Field as a filter for a tabular view of the content.  The Filter is a drop down list.  When a user selects a tag from the list, the view is appropriately filtered to the matching items.

Problem:
As the taxonomy has grown, a good proportion are not, at any time, attached to any content.  Thus, it is frustrating for the user to filter the table with a tag list that includes these terms, as they yield 0 results.

Requested Help:
Therefore, I am looking for a way, that the terms shown in the tag filter are dynamically limited to only those that are attached to currently published content.  It is not clear to me how to do it.  I would greatly appreciate any advice on how this may be accomplished.

You should have a look at Views Selective Exposed Filters, part of the Views Hacks module. It will limit the taxonomy terms to those in your view's result set.


How to add conditional javascript to theme? I'd like to use Selectivizr script to emulate CSS3 selectors in IE6-8.

But I'm having a hard time adding it to my theme. So far tried:

1) Forcing this into html.tpl.php head section:

<!--[if lt IE 9]>
<script src="<?php print base_path() . path_to_theme(); ?>/js/selectivizr.js"></script>
<![endif]-->

But base_path() doesn't seem to return anything in D7 (at least in html.tpl.php - maybe in page.tpl.php...). And I know this isn't the Drupal way to do it anyway.

2) Adding to my theme's .info file:

scripts[] = selectivizr.js

But then it's unconditional, of course :(

3) Using drupal_add_js() in my template.php.

But again, I'm not sure that it can be set conditionally there?

This is how I've added html5shiv in my template.php file:

$html5shiv = array(
  '#tag' => 'script',
  '#attributes' => array( // Set up an array of attributes inside the tag
    'src' => drupal_get_path('theme', 'mythemename') . '/js/lib/html5shiv.js',
  ),
  '#prefix' => '<!--[if lte IE 8]>',
  '#suffix' => '</script><![endif]-->',
);
drupal_add_html_head($html5shiv, 'html5shiv');


How can I hide the label saying "URL*" from content creation form when using the link module? I'm using the link module to ask the user for a link. I have disabled the link text (I.E> the text that would be inside the anchor tag) so the user wouldn't be asked for a title. What I would expect to happen is that I wouldn't see the field label, followed by the label "URL*". However, it isn't so.

As an example, my field label is Download link. What I see in the node creation form is a label like Download link* and then another label with the text URL*. Is there a way to hide the latter (the one saying URL*)?

Look at the Manage Display tab of your content type. On that page you can set how the label is displayed:

Above
Inline
Hidden

and how your link displays:

Title, as link (default)
Title, as plain text
URL, as link
URL, as plain text
URL, absolute
Domain, as link
Short, as link with title "Link"
Label, as link with label as title
Separate title and URL
Hidden


How to create a tick list which one role can alter for 'lesser' roles to see? I would like some pointers as to what might be the best approach to this issue please?

An admin role needs to be able to interact with a list of nodes for a fitness site. They need to be able to show/hide these nodes in a list for 'lesser' roles.
In addition to this the admin needs to be able to mark the node as complete so that the 'lesser' role can see this update. ie

Admin sees options to amend node list:

Lose 10 lbs - Show - Mark as complete

Attend 2 sessions - Hide - Not marked as complete

Run 3 miles this week - Show - Not marked as complete

'Lesser' role sees:

Lose 10 lbs - Complete.

Run 3 miles this week - Incomplete.

Obviously, I would like to be able to extend this list so that each user is able to see a list that is unique to them, which the admin role has interacted with to show/hide and complete/incomplete different sections.

I'm puzzled as to what approach I ought to take and would really welcome some suggestions to get me started.

Thanks.

From the interface that you have outlined, I could see that the 'Flag' module might be really nice for the administrator and user to interact with this kind of list.  In a list of nodes, flags would allow in place editing, changing the status, without going into each individual node.

You could configure the names of flags, status, and transition.  It would also be possible to assign permissions as to who has permission to change flags between states, and to allow users to change some of the flags themselves.

http://drupal.org/project/flag

To restrict what is seen by the users in the lists, perhaps you could build two similar views blocks: one showing all of the nodes (for administrator), and the other filtered only to show those with flag set to 'show' (for normal users).

The options in each view can be configured to selectively shown each block only to the appropriate role, and then both blocks could be embedded at the appropriate place.

Please note, that is not really enforcing permission to view the hidden nodes, and that a user could find them if they really try hard. It's just being selective about what is shown in the lists.

I was not able to quickly spot an existing module in drupal.org which would set node access by flag status.  You may have some luck with some further searching.

However  you can use 'Rules' to take actions on flag changes.  I think you might be able to pull something together by setting up a series of rules which then assign individual node permissions using 'content access' or another node access module of your choice when the show/hide flag changes state.

Otherwise you could use node_api and write your module to enforce your particular access rules  based on flag status.


How to nest form into another form? I have 2 modules. Let's call them Publisher and Publication for discussion's sake.

Publication module requires Publisher module. Publisher module provides form to edit publisher's data. Publication module provides list of publications with reordering and adding capability, and it can be limited to display only publications by one publisher.

Now, I want to nest publisher's publications form at the bottom of his data edit form. I would prefer to avoid writing same code again - I want to keep validation functions and submit functions as they are now, just have it on one screen, with one submit button.

Subform seems to be unmaintained and buggy at this point and Multiple forms seems to skip validations altogether, that makes both of them unusable for me.

You can use the admin/content page as a reference to combine forms. There, the filter form and overview form are passed as elements in a new $form array.
Coming from the content administration callback function in the node.admin.inc file:

/**
 * Menu callback: content administration.
 */
function node_admin_content($form, $form_state) {

  $form['filter'] = node_filter_form();
  $form['#submit'][] = 'node_filter_form_submit';
  $form['admin'] = node_admin_nodes();

  return $form;
}


Views 3: filter nodes such that an entity reference on the node corresponds to the current user I'm creating an approval/review workflow with notifications.
The content type we're reviewing is called a "Scholarship", and the first review is being carried out by an Intern (interns are a role in my permissions schema).
The Scholarship type has an entity reference to a user, of type "intern", which an admin can assign.

I need to create a view for each Intern such that she sees a list of the Scholarships that are assigned to her, in other words all Scholarships where the entity reference field "Intern reviewer" is the same as the logged-in user.

I've got a page display that correctly returns the title of each of my Scholarship nodes. I've created an relationship with the entity that's referenced in the ER field, so as to connect with the assigned intern. I then created a Contextual Filter on the "Intern Reviewer" field, set it to provide a default value, and selected the UID of the current user as that value.

Unfortunately this isn't returning any results. Methinks this may have to do with the fact that what's stored in the ER field is the Intern's username, whereas the contextual filter is using the UID of the logged-in user. Perhaps I need to find a way to provide the current logged-in user's login name as the fixed filter value?  In any case, if anyone has any ideas I'd be grateful to hear them.

The steps to create a view that lists all nodes of type scholarship that are referenced to the current logged in user:

Add new view, showing content of type scholarship
Add a relationship: Entity Reference: Referenced Entity
Add new filter: User: Current
Select Yes for the option Is the logged in user
Save.


How to hide field if blank I have a view created which has a column 'Price'. I also I have another column 'Special Price' in the same view, but 'exclude from display' is selected.

In views, click the price field > rewrite results > Rewrite the output of this field > I added the below:

  $[field_price]

  Special $[field_special_price]

I would like to display the special price only if the special price field has a value. If the special price field has no value, I only want to display the price field value. I am not sure how I can modify it ?

Thanks,
 D

I am new to drupal. Sorry if I am not clear.
In the views, I would like to put price and special price in the same column. I will add some css to special price. If I un-selected exclude from display for special price, then special price will be in another column which I do not want to do.

Please visit the page and see the price column.

http://bettylist.com/ac/myview

Thanks.

Then dont exclude special price from display and customize that field. There's an option @ No results behavior, where you need to check Hide if empty.

THEN, all you need to do is to style the two fields where they're both present.

That's the simplest way. There is another way, where you exclude both from display and add another field at the end "Global text area", where you can play with the tokens and rewrites.


Add node programmatically including CCK field I'm pulling content from a web service and adding the nodes programmatically.  Here is my code so far:

foreach($content as $key => $value) {
    $node = new stdClass();
    $node->title =  $value['title'];
    $node->type = $field_map['type'][$value['type']];   // Use remote type as key in field map array to get local type
    node_object_prepare($node); // Sets some defaults. Invokes hook_prepare() and hook_node_prepare().
    $node->language = (isset($value['language'])) ? $value['language'] : LANGUAGE_NONE;
    $node->uid = $GLOBALS["user"]->uid;
    $node->status = $value['status']; //(1 or 0): published or not
    $node->promote = $value['promote']; //(1 or 0): promoted to front page
    $node->comment = $value['comment']; //2 = comments on, 1 = comments off
    $node->created = $value['created'];
    $node->changed = $value['changed'];
    $node->sticky = $value['sticky'];
    $node->translate = $value['translate'];
    $node->uuid = $value['uuid'];

    $node = node_submit($node); // Prepare node for saving
    node_save($node);
}

The example I'm following says to add cck fields like this:

// Entity reference field
    $node->field_customer_nid[$node->language][] = array(
        'target_id' => $form_state['values']['entity id'],
        'target_type' => 'node',
    );

I'm having difficulty because my CCK fields will vary depending on the content type that is being pulled form the web service. My fields are stored in the following format:

$value['field_publish_date']

How could I go about adding the fields to my node?

First I would recommend using this type of structure for crating nodes progmatically

$node = new stdClass();
$node->type = 'story';
node_object_prepare($node);

If you're worried bout the content type being an issue use a switch statement by passing the content type in:

swicth($field_map['type'][$value['type']]){
  case 'story': //populate fields of story type;
    break;
  case 'page': //populate fields of page type;
    break;
}

Also if you are using a web service to import nodes I would suggest that you use the Feeds module http://drupal.org/project/feeds rather than creating them manually. I'm speaking from experience .


IEF with custom profile2 type not work I have node reference field attached to profile2 type entity and I can't add new entity to user profile. Even as admin (uid=1).

See my screenshoots for details

view user profile

add node to user profile

save changes and see no changes at all

Big WTF for me. Thought is is permissions related but why it's not working for superuser also. When I'm using IEF with node to node reference all is working.

I need advice how to resolve this issue. What check first, etc.

No chance for working: https://www.drupal.org/node/2043177

!@#!@#!


How to let a user switch between blocks that need to be shown? I have pre-defined blocks A,B and C that are meant to be placed in the sidebar_first region. What I would like to achieve is: a visitor could select the block that needs to be displayed for the sidebar_first region when click on a dropdown button containing option A, B and C. This dropdown button should exist somewhere on the same page of these blocks (means the visitor will not do it in the admin pages).
For example, if Option A is selected by default, then only Block A should be shown. If the visitor clicks on Option B, then Block A will be hidden (or removed) and Block B will show up.
The way I could think of is to disable and enable blocks programmatically on clicking the dropdown button, and then refresh the region via ajax, but I have no clue how this can be acheived. I am also open to other approaches.

For Drupal 8, there is the Block Tabs module:

  This module provides basic tabs function for Drupal. Deep integration with Drupal8's API, Plugin, Block, Entity and Config API. Provide simple tabs functions, you can control the CSS by your self. Based on jquery.ui.tabs...Tab type using Plugin system, it is very easy to extend.

For Drupal 7:

The Quicktabs module might work for you.

  The Quicktabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes and other quicktabs. You can create a block on your site containing multiple tabs with corresponding content.

You would create a Quicktabs instance (Admin > Structure > Quicktabs) with the blocks you want to display. You can select a default block, and load the blocks with or without AJAX. With certain render options, you can choose to maintain a history of the user's selection.

The Quicktabs Styles sub-module provides various tab styles (enable the Quicktabs Styles module to use them and visit Admin > Structure > Quicktabs > Styles to preview them). Or you can style the tabs with your own CSS. Examples of some of the included styles:

Once your Quicktabs instance is created, you would add the block to the sidebar region (Admin > Structure > Blocks). Example:

If you need the selection element to be a dropdown menu instead of tabs, you might be able to use a custom renderer plugin. From the Quicktabs README.txt:

  Another way to extend Quicktabs is to add a renderer plugin. Quicktabs comes with 3 renderer plugins: jQuery UI Tabs, jQuery UI Accordion, and classic Quicktabs. A renderer plugin is a class that extends the QuickRenderer class and implements the render() method, returning a render array that can be passed to renderer service (\Drupal::service('renderer')). See any of the existing renderer plugins for examples. Also see Quicktabs' implementation of hook_quicktabs_renderers().


Automatically block user that access /wp-login.php Is it possible to block any users IP if they try to access a specific URL such as /wp-login.php page which does not exist on Drupal.

Basically to automatically blacklist the user, for days or even forever.

Trying to implement this as a security measure. For those who are looking for ways to hack the site.

You can use autoban ip
You have to at least enable Autoban and Autoban Core Ban Provider modules from this package.
Then go to configuration > people > automatic ip address bans
and add a rule with this settings

type page not found
Message pattern wp-login.php|/otherURL|anotherURL
pattern (can be left blank)
Threshold 1 (after how many attempts to ban them)
IP Ban Provider Core Ban

NOTE: above I have added multiple patterns delimited with | just to demonstrate the possibility
After setting this everytime your cron runs this module will run and it will look through the watchdog messages and ban the IPs that match the above rule.


How do I move content from one field to another? I have created a field called people_field. I used this in another content type as an existing field. The problem is now it's screwing up a view that uses the field in a relationship.

So what I want to do is keep the content but make move all the data from one filed into a new field, if that makes sense?

I can't figure a way to do this without losing all my data.

Let's consider that your content type is article and existing field is field_old and new field is field_new. Then you can use the script at once to copy all the data from old field to new field.

$article_nodes = node_load_multiple(array(), array('type' => 'article'));
foreach ($article_nodes as $article_node) {
  $article_node->field_new = $article_node->field_old;
  field_attach_update('node', $article_node);
}

Am not sure, if this is what you are looking for.


My submit function for the node form doesn't execute I need to add my submit function to the node insert/edit form.

Here's my code.

function yrv_event_trainer_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
    if (in_array($form_id, ['node_veranstaltung_edit_form', 'node_veranstaltung_form'])){
        // Here we're adding our submit function before standard one.
        array_unshift($form['#submit'], 'yrv_event_trainer_submit');
    }
}

function yrv_event_trainer_submit(&$form, FormStateInterface $form_state){
// Here's code inside my submit function
}

But when I'm pressing the "Save and publish" button on the form, this submit function doesn't execute.

For example, I can't debug it having set a breakpoint inside the submit function.

But the array $form['#submit'] has my submit function.

Could you clarify me, what can be a reason of the problem ?

In node forms the submit callbacks from #submit are not executed. Instead, there are executed submit from #submit property of submit form element.
You should add the submit in this way:

$form['actions'][$action]['#submit'][] = 'yrv_event_trainer_submit';

Here is an example too.


How to disable max length validation on an entity form? How do I disable the #maxlength validation on a field I've added to the user entity form?

Let me explain: I want my field to be 10 characters long in the database, so I've set a max length of 10 at the field UI. However, at the form level I want it to have a formatting mask that makes it be 14 characters long.

Even though I could disable its #maxlength property via hook_form_alter and get to enter more than 10 characters, the validation for such property is still up when I submit the form.

Since I don't want to remove the mask via JS by the time the form gets submitted, my intention was to to bypass form validation only for the max length property of this field (or even for the whole field) and then at a presave hook I'd remove the mask and store only the original 10 characters to the database.

Hope I've made it clear.

Thank you.

You didn't give an explanation of your rules for your input, but for an example, imagine that the format of the required value is XXX-XXXXXXXXXX, where X is a numeral, and the hyphen is always at position 4.

Change the maxlength on the HTML input to allow more characters. Add your own validation handler to be run before the default validation handlers. Add your own submit handler to be run on submission.

use Drupal\Core\Form\FormStateInterface;

function HOOK_form_alter(array $form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'some_form_id') {
    if (isset($form['some_field'])) {
      // Change the HTML max length to 14.
      $form['some_field']['#maxlength'] = 14;

      // Insert a custom validation handler to be run BEFORE
      // the default handlers.
      array_unshift($form['#validate'], 'my_module_FORM_ID_validate');

      // Add your own submit handler to deal with the submitted values:
      $form['actions']['submit']['#submit'][] = 'my_module_FORM_ID_submit';
    }
  }
}

In the validation handler, parse the value in this handler, replacing the value in the field with the 10-character value, so it can pass validation. Store the other 4 characters in the $form_state

function my_module_FORM_ID_validate(array &$form, FormStateInterface $form_state) {
  if ($value = $form_state->getValue('some_field')) {
    // Check that the submitted value is in the right format, and
    // parse the value into $matches.
    if (preg_match('/(\d{3})-(\d{10})/', $value, $matches)) {
      // Store the 10-digit value in the field, to be passed through
      // default submit handlers.
      $form_state->setValueForElement('some_field', $matches[2));

      // Store the other three digits in the $form_state.
      $form_state->set('some_key', $matches[1]);
    }
    else {
      // The submitted value was not in the correct format.
      $form_state->setError($form['some_field'], t('Some Field must be in the format XXX-XXXXXXXXXX where the Xs are numeric'));
    }
  }

}
Use the values as necessary in the submit handler.

function my_module_FORM_ID_validate(array &$form, FormStateInterface $form_state) {
  $key1 = $form_state->get('some_key');
  $key2 = $form_state->getValue('some_field');
  // Do what you need with these values.
}


Line break in Page / Node Titles Is there some way we can use <br> or javascript line breaks in Node, Page and/or Block Title fields?

I have found there is good reason why Drupal restricts html in titles. If you need a subtitle, it is best to create an additional field in the content type, then position it using the Display Suite module.


In Views, how can I show only the results for content that has been tagged with two taxonomy terms? I'm using Drupal 7:

I have a taxonomy term view that uses two contextual filters (i.e. taxonomy/term/%/%). Under 'Relationships' I have selected: 'Content: Taxonomy terms on node'. Under this relationship I have selected two vocabularies. Under 'Contextual Filters' I have selected: '(terms) Taxonomy term: Term ID'. Within the contextual filter I've selected 'Display contents of "No results found"' under 'WHEN THE FILTER VALUE IS NOT IN THE URL'.

The reason for two contextual filters is because the content is tagged with two term reference fields each of which correspond to a different taxonomy vocabulary.

The problem is that the results I get are not filtered by the second taxonomy term.

For example, if some content has been tagged with 'board of directors' (tid = 29) and 'people' (tid = 34) then everything that is tagged with 'board of directors' displays under taxonomy/term/29/34 even if they have not been tagged with 'people'.

How can I configure my view so the results are filtered according to two taxonomy terms?

I'm not sure why are you using Relationships for this. Simply, from "Contextual Filters" section, create a "Content: Has taxonomy term ID". In that filter's settings -> "More" settings -> Check "Allow multiple values" which:

  If selected, users can enter multiple values in the form of 1+2+3 (for OR) or 1,2,3 (for AND).

i.e. go to view_path/29,34 will filter results by both terms.

Hope this helps.


Add class to empty Panels regions How can I add a css class (.empty-panel-region) to Panel's regions that don't contain any panes?

The following works with all standard renderers (default/IPE).

There is no preprocess possibility for the regions, so some extra work is needed.

First add the following preprocess function to your template.php of your theme or your own module (change MY_THEME accordingly).

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_THEME_preprocess_panels_pane(&$vars) {
  // Determine if a panels panel (region) is empty.
  // Every pane needs to be checked for content.
  // Set the result on the panels display object.
  if (empty($vars['content']) || (isset($vars['pane']->IPE_empty) && $vars['pane']->IPE_empty)) {
    if (!isset($vars['display']->panel_is_empty[$vars['pane']->panel]) || $vars['display']->panel_is_empty[$vars['pane']->panel] ) {
      $vars['display']->panel_is_empty[$vars['pane']->panel] = TRUE;
    }
  }
  else {
    $vars['display']->panels_is_empty[$vars['pane']->panel] = FALSE;
  }
}

Then you can use the data in the $display->panel_is_empty array in your PANELS-LAYOUT.tpl.php files to conditionally add extra classes. (Change 'PANEL' to the specific region.)

<div class="panel-panel <?php print !empty($display->panel_is_empty['PANEL']) ? 'panel-panel-empty' : ''?>">
  <?php print $content['PANEL']; ?>
</div>


Seach API Solr database service I have a Drupal 7 installation on Linux with Tomcat 6 and Apache Solr.

Drupal can connect to Apache Solr, but the search only works for the "database service" class, even though I used the same settings when I created the server with "Solr Service" class.

Is there any way to troubleshoot the Solr index directly from linux box or Tomcat?

Does {Your drupal site}/admin/config/search/search_api show a "working" (Green tick/check mark) next to your server settings? If so press 'edit' and this should provide you with a connection link to your solr installation being served by tomcat.  The URL should be something like

  http://{IP of server with Solr on}:8080/solr

If in a browser you do to http://{IP of server with Solr on}:8080/solr/admin you should see a solr web query page that will allow you to query the solr server directly.

This should help indicate if solr is indexing the drupal content or not.  On my localhost server a URL to return everything would be

  127.0.0.1:8080/solr/select/?q=%3A&version=2.2&start=0&rows=10&indent=on

In the event you can't contact the tomcat server (And assuming your firewall is correctly configured, not all systems allow 8080 through by default) I found the article very helpful for installing and configuring Solr on Tomcat 6.


Redirect a node to it's custom view I've created a view "myview" for a custom content-type.

Now I want: Any node of that content-type to be automatically redirected to that view page.

For example, if a user types: http://my-drupal-site/node/4 and that node is of my desired content-type, it needs to be redirected to http://my-drupal-site/myview/4

What I can do:

What I can do now is writing in my theme's template_preprocess_node() function following lines:

function myCustomTheme_preprocess_node(&$variables) {
    $arg1 = (int) arg(1);
    $isArg1Int = (is_int($arg1) && $arg1) ? (true) : (false);

    if (isset($variables['node']->type) && $isArg1Int) {
        if ($variables['node']->type == "MY-DESIRED-CONTENT-TYPE") {
            // REDIRECT!
            drupal_goto('myview/' . $variables['node']->nid);
        }
    }
}

That's pure hard-code, and I don't like it. Is there some elegant solution, may be using URL aliases or something like that?

You can use Panels like Patrick suggests, but Panels requires a lot of resources and it's a bit of a waste to only use it for this simple case.

There are different approaches to this, one could be to react to the full view of the node:

/**
 * Implements hook_node_view().
 */
function hook_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'type' && $view_mode == 'full' && arg(0) == 'node') {
    drupal_goto('url/' . $node->nid);
  }
}

The if statement if true if the node is of the correct type, is being view in full view and the url is node/..., which should limit to node being view the standard way.

Another way of doing this, would be to use the redirect module or something similar to setup redirects for all nodes of the type to the view. A weakness to this approach could be path alias. But that way you would make a permanent redirect which is more SEO friendly.


Why Drupal does not see permission from custom module? I tried disable and reinstall module, but with no luck, clearing cache does not work too. Module name is bip_menu_perm:

/**
 * Implements hook_perm()
 */
function bip_menu_perm_perm() {
    drupal_set_message('test');
    return array(
        'administer menu permissions' => array(
            'title' => t('Administer menu publishing permissions per user'),
            'description' => t('Users with this roles can edit menu publishing permissions'),
        ),
    );
}

What I am doing wrong here? This function does not invoke on permissions page.

The hook is called hook_permission() in Drupal 7, it changed names from hook_perm() (Drupal 6)

  This hook can supply permissions that the module defines, so that they can be selected on the user permissions page and used to grant or restrict access to actions the module performs.

Make sure you clear Drupal's caches once you've made the change so it gets picked up.


Best way to add a search function to user profiles So my client would like to have a search function added to user profiles, because the number is growing rapidly and filtering based on role, etc, isn't working for them.

How do I add a search to the user profile page? This is under User Management > Users > List

You could code up a form_alter() in a custom module that could put search in that admin page.  Or, you could just use www.yourhost.com/search/user to search user accounts.  And if you have advanced search and are using content profiles, you could also restrict your regular node search to that content type, eg type:profile terms to search for in those nodes.


Is there a module that will let me set up site-wide notifications like Stack Overflow's orange one? I'm looking for a Drupal 7 compatible module that will let me set up site-wide notifications similar to Stack Overflow's orange bar (Welcome to this site, read the FAQ etc.). I haven't been able to find one.

Please note that I don't want to display system messages like this, I want something where I or other selected users can set up custom ones.

Check out the list of modules for Displaying Status Messages — some of these might provide a good starting point.


Prevent site from being indexed by search engines? I have two requirements for my site

I don't want my site to be indexed by search engines
Anonymous users should not be able to see any content of the site

I would have been satisfied with ip restriction in the .htaccess file but I cannot use that because this site is part of a multisite setup and as far as I know one cannot use .htaccess files in sites/mysite1/.htaccess and I don't want to go down the symlink route at the moment.

Right now I am using:

Shield (for Apache authentication and to prevent non content elements from being previewed)
Metatag (<meta name="robots" content="noarchive, nofollow, noindex, noodp, nosnippet" />

but thinking about it some more I thought that perhaps just using the Shield module wil prevent my site being indexed. Or even just disabling the  View published content permissions?

So my questions are:

Will the Shield module prevent my site from being indexed?
Will disabling the View published content permissions prevent my site from being indexed? (with the downside that part of the site can be previewed)

Question 1: Shield will deny access to anyone that doesn't know the credentials, including robots.  Using this module should be suffiscient for the use case you describe.

As long as you use Shield, metatags doesn't matter.  If you do not use Shield, the metatag you list will prevent your site to be indexed by polite search engines (such as Google - read about Google's policy here).  It will have no effect on some other (impolite) search engines (such as Baidu).

Question 2: Disabling "View published content" for the anonymous user role will prevent any content on the site from being indexed.  Your site itself, and the placeholder string that is shown to the anonymous user when viewing published content is disabled ("No content has been created yet.") is still visible and may be indexed by search engines.


How do you wrap an image with a link? In Drupal 7 this was done with the l() command and setting the html option to true. I have found the Link::fromTextAndUrl() method in Drupal 8 but no mention of something similar to the html option.

[EDIT]
I think i was not clear with my original question. This is not for an image field; i was simply asking how to wrap a link around:

<img src="path_to_my_img">

This way should be bulletproof:

use Drupal\Core\Link;
use Drupal\Core\Render\Markup;

$url = $node->get('field_url')->getValue();
$imageUri = $node->get('field_image')->entity->getFileUri();
$image = [
  '#theme' => 'image_style',
  '#style_name' => 'medium',
  '#uri' => $imageUri,
  '#width' => 200,
  '#height' => 100
];
$rendered = render($image)
$linkMarkup = Markup::create($rendered);
$link = Link::fromTextAndUrl($linkMarkup, $url);
$link = $link->toRenderable();
render($link)


Profile 2 different types with single edit form I am using the profile2 module to create different types of information for the user.  One of these profile types are filled in on the registration page.

What I am trying to accomplish is combining the registration form profile with another profile so that they can be edited on the same form page.

For example: The fields of Profile-Registration and Profile-Info must all be editable on www.website.com/form/%user/edit.  These fields are rendered with views, and are working perfectly.  It is just the editing I am trying to figure out.  I am not sure how to go about achieving this.

It could be accomplished using Panels:

  The Panels module allows a site administrator to create customized
  layouts for multiple uses. At its core it is a drag and drop content
  manager that lets you visually design a layout and place content
  within that layout. Integration with other systems allows you to
  create nodes that use this, landing pages that use this, and even
  override system pages such as taxonomy and the node page so that you
  can customize the layout of your site with very fine grained
  permissions.

and Profile2 Panels Module:

  Page Manager (Panels) support for Profile2.

  With this module you can take over Profile2 paths with Page Manager.
  Now it is possible to theme your Profile2 edit and view pages with
  Panels.

If you're not familiar with panels, there are numerous resources and tutorials out there


Get Webform submission count using custom module I would like to get the submission count of a user using custom code in my module. Which variable stores this?

I tried to do dsm on $node and there was an array for webform inside the $node object but in that array I couldn't find the submission count for the current user. But then, $node shouldn't contain that value, of course. So how do I get this value?

Okay. I figured it out.

There is a function webform_get_submission_count in the webmodule includes file that does. Just added these lines and got it my count. Sweet and simple.

module_load_include('inc', 'webform', 'includes/webform.submissions');
$mysubmission_count = webform_get_submission_count($node->nid, $user->uid);


Adding an editable field to a custom block module I have a custom module that registers a 'block' and echoes some HTML content.

I want to make this customisable to admin users, which means enabling 'Configure' for the block: with one textfield, and a drop down when you can select a node of a specific type.

How do I go about starting this:
A) Enabling 'Configure' for the block
B) Choosing/Coding Fields that store variables, seen when you click 'Configure'
C) Echo the variables in the block module code

Thanks for your help!

I believe the block example module should show what you want


How do I show the site slogan? I am trying to set up my first web site using Drupal 8 an Bootstrap. Unfortunately I wasn't able to show the site's slogan in Bootstrap theme. The slogan is set in /admin/config/system/site-information but is not shown.
So I thought by my self, it may not be printed in page.html.twig and tried to include it there. It's preamble says:

 * Available variables:
 * Site identity:
 * - front_page: The URL of the front page. Use this instead of base_path when
 *   linking to the front page. This includes the language domain or prefix.
 * - logo: The url of the logo image, as defined in theme settings.
 * - site_name: The name of the site. This is empty when displaying the site
 *   name has been disabled in the theme settings.
 * - site_slogan: The slogan of the site. This is empty when displaying the site
 *   slogan has been disabled in theme settings.

So I tried to print the slogan by including

{{ site_slogan }}

But this does not have any effect at all.

Can somebody please tell me, how to print the site slogan in Bootstrap?

[The lack of documentation and stable modules and themes should have been considered a release blocker for Drupal 8, but this is only my opinion and off topic here!]

After some desperate digging I found the solution (come on Drupal guys, don't be shy, give us some documentation!): Go to /admin/structure/block and click the 'configure' button of the block named 'Site branding'. There you can choose which parts of site branding are shown.


How to relate two views from same node I have searched through all the questions, but I can't seem to find the information, I need. Accept my apology, if this has already been covered.

On a site for a law firm, I have a content type, called "People" (not the same as User) with multiple fields containing information about each individual.
I want to display part of a node in a page view, and other parts (such as image, contact details etc) in a block view. The page and the block view has to be related, obviously.
I can only find answers on how to relate nodes/files with each other. Not just from a single node.

I cannot get my head around how to filter it, and how to use the contextual filter function. I understand as much, that the context must be with the NID. I just need a 1,2,3 ...

Drupal version 7.22, Views 3

I'll appreciate any help, thanks

Christian

EDIT: OK, it's solved. And in the end, it wasn't as complicated. Thanks to Rémy, to steer me in the right direction just using normal node (no need for a Page view here)

Here's what I found:

1) No need to fiddle with PHP templates here. Under Content type, just decide which fields, you want to see on your page. Make the others hidden.

2) In Views, create a block view (in this case), under Advanced - Contextual filters, select Content: NID, select Provide default value - Content ID from URL.

The main source of confusion for me was I 'wanted' it to rely on alias in the path. It doesn't. Views isn't checking for that at all, but only for actual node ID - e.g. 108, 109 ...

for the page view use the normal node, and hide the stuff you want to display in one of the block in your node.tpl.php.

then create a new view showing your contenttype, with the actual node id as contextual filter. make block displays, put the fields you need for your different blocks in each block.
add the block in to the page, only showing it for the actual contenttype.


Cv website development problems I am trying to achieve something like this http://www.vooshthemes.com/gallery/jamba/ in Drupal.
Its a CV website, what confuses me is how to deal with fields.
If u visit the link i provided above u'll see Experience, Expertise,Education and Training  Category in which u can mention from which year to which year u worked where and what was you task.

My problem is how do i enable the user to add more fields just like in the Cv example page??
i will be using Drupal 7.
any suggestion will be apppreciated.

There are a number of ways you could do it, depending on how friendly you want the ui to be and how comfortable you are customising drupal.

I would look at the Field Collection module - http://drupal.org/project/field_collection. It should let you create a group of fields that can be treated as a single field.

ie you could create an 'Experience' field collection consisting of Title, Experience, Duration, Summary and whatever else you need. Then the end user should be able to add multiples of these if you set the field to allow multiple values.

I am saying should because I haven't directly used this module myself, in a similar situation I have created a custom form widget containing the multiple elements. Thats is potentially a more complicated exercise. You could see an example of what might be required there in the Examples for Developers module : http://drupal.org/project/examples


How to put 2 'views' side by side in 1 region using the bootstrap theme? Is there a way to place 2 separate views (mine in particular are in block), and set them beside in each in a region? I am using the bootstrap subtheme and specifically the content region. I am using drupal 7.

You need to use CSS. Inspect element with your browser, find the div class of the 1st view and use

.view-myviewname { float: left; }

JS Fiddle Example


Integration of two sites (one is Drupal-based, the other isn't) I'm trying to integrate two sites (one is Drupal-based, and the other isn't), and I need single sign-on. How can I realize it?

I have sites on different domains.

If you want to do your authentication externally to Drupal, you could use the Secure Site module.  You'd still need mod_auth_cookie to avoid double-password entry, but at least the username and password would be the same.  I don't see mod_auth_cookie anywhere out on the internet any more, but I've got the code and could re-publish. As I mentioned in my comment above, it needs a little work.

Another way to avoid double password entry would be to put your sites at example.com/drupal and example.com/other, and protect all of example.com with Apache basic authentication.


How to comment out code in a .tpl.php template If I want to remove parts of .tpl.php file what are my options other than removing them permanently?
HTML comments < !-- --> work but print the part in the HTML source.
PHP // comments or /* */ don't work.

For example, how could I comment out a block like:

    <?php if ($logo): ?>
      <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
      <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

    <?php endif; ?>

I actually prefer to use this way

<?php if (FALSE): ?>

  <?php if ($submitted): ?>
    <?php print $submitted ?>
  <?php endif; ?>

  <?php if ($terms): ?>
    <?php print $terms ?>
  <?php endif;?>

<?php endif; ?>

This make it easier to put the block back in (change FALSE to TRUE), or attach a variable to the conditional.

EDIT:

To address your example, I would do it one of two ways

<?php if (FALSE): ?>
<?php if ($logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
  <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>
<?php endif; ?>

or

<?php if (FALSE && $logo): ?>
  <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo">
  <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

<?php endif; ?>

I would normally lean towards using the second in my daily work.


Publish dynamic pages? I want to create a website with form, where users can insert the information in the form and then on form submit, information goes into a database table and also goes to the third party API.

Administrators can modify the specific record and add more information, and then publish this record as a web page with a unique URL.

Is it possible in Drupal 8?
How can I achieve that? Is there any specific module I need to use?

I'm not sure if in D8 webform submissions are useable, fieldable entities yet.

Although I believe the EForm module may work as you expect. Allowing you to define forms the public can fill out and then very easily turn the content into drupal "pages" or reachable content at some url pathauto pattern.

Allowing the public and administrators to modified different fields, or subsequently edit submitted data is a Roles/Permission issue that drupal Core or other modules such as Field Permissions will let you achieve.


How to control field_group quantity - control field group quantity I Cant speak english very well.So sorry if my post is not very good.

When we add a field like text input or file field , we can control number of quantity of thats field.for example if number of a text field set "unlimite",user can click on a button for add another field.

So I want to give possibility to user that after click on "ADD BUTTON" a new field group add to form fields.

If show a table bottom of form (involve added field groups) , this is very good.

example :

textfield1     textfield2    textfield3

  add button

(after click this button or submit above fields , another 3 textfields show to me and submitted textfields show bellow on a table)

Is any module for this work?
thank you for your response beforehand.

Field group is used for purely cosmetic purposes. If you want to enable the functionality you describe, use Field Collection.


Translate custom field in countries module I am using the Countries module in a multilingual site and I added a custom field to it.

The countries itself support translation for its own field, but is there a way to translate content for the custom fields added to it?

Consider using the Entity Translation module to get this to work.

In doing so, if you run into an error like "The entities of type Country do not define a valid base path: it will not be possible to translate them.", then review the issue about "Countries is not integrating properly with Entity Translation" (status = needs review).


List publications by same Author on Staff page I'm using the biblio module to manage publications on my site. I've a content of type "Staff" that display all workers. These workers have publications that are listed on the publication page (using the biblio module).
Now the Staff node has a field name (wich content the workers first and last name). Now I want to list all biblio (publications) that has the same "Author name" as "Staff name" on a staff page.
The idea is to link Staff name with biblio Authors name, and use this to list every publication containing this workers (staff) name on this particular workers page.
At the end, I'll habe to add pulbications just once and they will be listed on every workers page containing the name of the author.
How can i achieve this? I've tried everyting i could, but could not find a solution. Thanks for your help.

use views and add a relationship to the author inside the view


Go to specific page in view using node id I have a view composed of single nodes with a pager. Is there any way to link to a specific page in this view using the node id? I can see that the pager uses a page variable in the url, but that carries no information about the node. I can go to a specific node in the view using contextual filters, but if I don't want to filter the results, I just want to jump to a page in the pager by using the node id. Filtering makes the pager disappear (of course).

Is there a way to pass in a node id to the view, use that information to set the pager to that node, and not lose the pager?

You want to link to a node title thats in a view from another page, and not loose your pager ? (correct my summary if thats incorrect) ...

You can do this by using an ID anchor when building the link to the node.

If needed, use a Views field to output an html anchor per node title:

add field Node NID, exclude from View output
add field Node NID, rewrite HTML as <a name=[node:nid]>

Then build a link to your View including the anchor reference.

$vars['view-scroll-to-node'] = l('some node title', '/your/view/path#'.$nid);


How is password hashing/encryption performed? I am fielding a question for a project that is asking if we use Blowfish crypt in Drupal, or, if we could.

The class that performs password hashing in 8 is PhpassHashedPassword, based on https://www.openwall.com/phpass/. On that site, it states:

  At this time, if your new project can afford to require PHP 5.5+,
  which it should, please use PHP's native password_hash() /
  password_verify() API instead of phpass. This new API also happens to
  support the CRYPT_BLOWFISH and CRYPT_EXT_DES hashes used by phpass,
  but unfortunately it does not support the phpass portable hashes
  (which are portable across all versions of PHP as long as you use
  phpass).

It goes on to state:

  The preferred (most secure) hashing method supported by phpass is the
  OpenBSD-style Blowfish-based bcrypt, also supported with our public
  domain crypt_blowfish package (for C applications), and known in PHP
  as CRYPT_BLOWFISH, with a fallback to MD5-based salted and variable
  iteration count password hashes implemented in phpass itself (also
  referred to as portable hashes). (phpass versions up to 0.4 also
  included an intermediary fallback to BSDI-style extended DES-based
  hashes, known in PHP as CRYPT_EXT_DES, but this has since been dropped
  except for authenticating against pre-existing hashes of this type.)

When reviewing the class in Drupal 8, it does not make use of password_hash, or password_verify. It also appears to use sha512 as the algo. I can't find anywhere if bcrypt or Blowfish or CRYPT_BLOWFISH is used.

I did find this issue regarding supporting Blowfish style passwords but not one for creating them. I assume if I wanted to import their current userbase with Blowfish style passwords, I would need this patch.

Would it be difficult to implement my own class to do this that uses Blowfish? Are there any implications in Drupal of doing this? Why did version 8 opt to stick go with SHA-512? This project will be on PHP 7.2, so I don't care about PHP 5.x BC/reasons/etc.

Potentially related: https://stackoverflow.com/questions/16014282/why-crypt-blowfish-in-php-is-considered-better-when-it-produces-shorter-hashes

Why does Drupal 8 use PHPass / sha-512?

PHPass was originally implemented in Drupal 7, with custom code in order to use sha-512 instead of md5 which was used by other implementations at the time, and then ported to Drupal 8.
Drupal 8 originally supported older versions of PHP where the password functions were not available, and didn't yet use composer to adopt an existing polyfill.
It was (and still is) a low priority to update the hashing service after it was initially ported from Drupal 7.

Would it be difficult to use Blowfish instead?

There's a module for that - as mentioned in the issue you linked the PHP Password module replaces the core service with one that understands legacy hashes, but will upgrade them to bcrypt when possible.


How to disable cron from running while another time consuming process takes place? We bulk upload nodes on our Drupal site.
Those nodes need to be Solr indexed all at once, without having to wait for cron to index them.
The cron job indexes apachesolr_cron_limit nodes per run. As a result, if I have 40.000 records, I have to wait too long.

A solution I implemented is, creating a button which indexes all remaining. The button runs the code below.

function mymodule_index_all_remaining() {
  variable_set('cron_safe_threshold', 0); // Doen not work.
  module_load_include('inc', 'apachesolr', 'apachesolr.admin');
  $env_id = apachesolr_default_environment();
  apachesolr_index_batch_index_remaining($env_id);
  variable_set('cron_safe_threshold', 10800); // Does not work.
}

My problem is that we have cron running every 3 hours and when the cron begins (while the mymodule_index_all_remaining is still running), I get HTTP 502 error.
The same error occurs if I try to  index the remaining from admin/config/search/apachesolr Index all queued content.

So I need to alter the cron interval, which can been seen under admin/config/system/cron, "Run cron every".
This interval is stored in a static variable cron_safe_threshold.
I tried to set it to 0, but it doesn't work. I cannot change settings.php as I really want cron to run evey 3 hours when the indexing does not run.
Is there another way to pause cron jobs from running while another process takes place?

Do you recomment another way to index remaining without having the 502 error?

You can use Elysia Cron. This module is a enhanced Cron that has, apart of many other improvements, a global disable option. As they say in a bug report this variable may help you:

  It disables ALL cron tasks. (No cron will be executed).

Also Elysia Cron allows you to set complex schedules so you may fix your problem just with the right schedule.


Let Gmap center on the users geolocation, but still load all the node markers onto the map For a website I am building I have a used a map to display all the nodes inside my country, by using a view. When the map is loaded, it shows the whole country (by standard settings in the Gmap module).

What I would like to do having this map centered on my location, but still show/load all these node markers that are spread across the map.

I manage to have the map centered on my location by using Filters and SmartIP in the view, but offcourse this limits the loaded nodes to only that location. I do not want to filter anything, just center the map. I am new to Drupal, and can't figure out how to make this work.

I can clarify after my comment on your question is addressed but if I had to guess I would say you are using an nid contextual filter to center the map?

If so, that is why you aren't getting other nodes.

Alternatives are:

Add the Global: Null contextual filter and pass the nid through that. The null contextual filter will not affect results at all.
Keep using the nid contextual filter, but check the "Exclude" checkbox in the "More" fieldset of the filter. This will mean all nodes except the given nid will be displayed, but the given nid can still be used to center the map.

Use whichever method gives you the functionality you want.


File upload hook - how to integrate existing file manipulation code into Drupal I want to create a waveform image for every mp3 file I upload in a Drupal 7 website (as admin), and store it as a png for display in the frontend.
I can use this script in order to do that.

I want to know what is the Drupal way of integrating that script, specifically:

I guess that functionality will go into a module; where should I hook? file upload (there will be more than one file types to upload, and I would just want to work on the mp3)?
how should I save the resulting waveform picture (where in the filesystem and how would I attach it as a field to my custom node type)?

As I'm new to Drupal (but experienced with PHP), I would appreciate a detailed response, but if you know of a module that already does that - I couldn't find it - that would be the shortest answer possible. :)

Thank you!

Create a content type with a file field to upload the mp3 file.
Create a custom module and implement hook_node_presave. There you can do whatever you want with your node before it gets saved.
For the file handling have a look at File interface.


Using hook_node_submit() from a custom module I have built a custom module named 'ABC'. I have created a content type 'CT' having some text fields. When a user add content of type 'CT' and Save/Preview the form, I want to use the values that the user added in the form and make a web service call and update the form values based on the data returned from the web service call which would further be saved to database.

I am using hook_node_submit() as below.

function CT_node_submit($node, $form, &$form_state) {
  global $user;
  //dpm($user);
  $nameofuser = $user->name;
  $timezone = $user->timezone;
  $title = $form['field_title']['#value'];
  $pid = $user->uid;
  $pname = $user->name;
  $rurl = $form['field_recording_url']['#value'];
  $purl = $form['field_presenter_url']['#value'];

  $kdetails  = array (
     'nameofuser' => $nameofuser,
'title' => $title,
'pid' => $pid,
'pname' => $pname,
  );
  Make_A_WebService_Call($kdetails, $form, $form_state);
}

The problem is that when I am calling the above code from ABC.module file, the code is not being called on clicking the Save/Preview button.

hook_node_submit() will only be invoked for the module implementing the associated content type. If module A defines the content type, module B cannot implement hook_node_submit() on module A's behalf, unless it specifically calls the function module_B_node_submit().

If you want to hook into the validation process of a node form you can use the standard hook_form_alter(), e.g.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    $form['#validate'][] = 'MYMODULE_node_form_validate';
  }
}

function MYMODULE_node_form_validate($form, &$form_state) {
  // Logic here...
}


Associate Every Displayed User Name With Corresponding users.data Table Row Updated:

I would like data from the users.data table displayed with every "User Name" however it is displayed.

As an example, I have this in hook_preprocess_page_title():

function hook_preprocess_page_title(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {

    $gUD = \Drupal::service('user.data');
    $routeUID = \Drupal::routeMatch()->getRawParameter('user');
    $gudValue = $gUD->get('module', $routeUID, 'name');

    if ($gudValue = $moduleValue)) {
      kpr('Success!');
    }

  }

}

The route entity.user.canonical allows me to reference the viewed user, and so I can use \Drupal::routeMatch()->getRawParameter('user') to get the non-current user ID. (it's not the route that counts, but my ability to reference the users.data table for the displayed user)

And this in hook_preprocess_username():

function hook_preprocess_username(&$variables) {
  $gUD = getUsersData();
  $gudValue = $gUD->get('module', $variables['uid'], 'name');
}

So what I am looking for is something like:

hook_preprocess_HOOK() {
  $UID = // From displayed user name.
  \Drupal::service('user.data')->get('module', $UID, 'name');
}

for each displayed user name.

The problem here: get user id from username or email without logging in, is that I don't know, and cannot manually enter the username value.

A couple of examples where the username is displayed on a page without using the username field:

Views field Name (not linked to user, uses views field base)
User type entity reference field (format display label, uses field base)

hook_preprocess_page_title() and hook_preprocess_username() are pretty straight-forward. And I believe I know where/when this template/hook will be used, but I am still having trouble defining a couple of other instances, and determining the best hook to alter the output as needed.

It sounds like you should start with what you don't want.

Drupal::currentUser()->id() will retrieve the current user's UID. From there, you can use the UserStorage::loadByProperties() method you referenced to pull the UID by user name. The last step is add code to check Drupal::currentUser()->id() doesn't match the UID found from UserStorage::loadByProperties()


PHP Fatal error: Class 'Drupal\Core\DrupalKernel' not found I have installed the EntityPrint module in drupal 8 for the pdf conversion.

Followed below procedure:

  curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer composer config repositories.drupal composer https://packages.drupal.org/8

  Run: composer require "drupal/entity_print 2.x" in the site docroot/.

https://packagist.org/packages/mikehaertl/phpwkhtmltopdf
https://packagist.org/packages/dompdf/dompdf
https://packagist.org/packages/tecnickcom/tcpdf

I have installed the above packages using, as the entity print module insisted to install it in drupal page.

Once the installation was done, drupal site was crashed, while checking the error log, I got the following:

  [error] FastCGI sent in stderr: "PHP message: PHP Fatal error: Class 'Drupal\Core\DrupalKernel' not found in /var/www/html/drupal/index.php on line 16" while reading response header from upstream

I have uninstalled the packages but unable to disable entity print. Since my drush command results in error.

Can anyone please help me to find out?

Try the following:

Check if autoload.php file exists and it includes the right path to your vendor/ folder.
Clear any external cache services if in use (e.g. Memcached or Redis).
If you're using PHP 5.x, you should use PHP 7.x instead.

To rebuild your site from scratch based on your composer.json file, try the following steps:

Backup and delete the /core and /vendor directories completely.
Delete the composer.lock file.
Run: composer install.
Run: composer update.

Source: D8 conflict resolution.