Display user picture below content type article How can i display user name and picture below node article.
My theme is based on panels so i dont know where to write code for it. Or any admin option.

Thanks

There is a module that comes with the Ctools module called Views Content Panes. Enable that. Also a good idea to enable the Context module, can be fetched here:
https://www.drupal.org/project/context

Views Content Panes is used to output Views as panel panes.

Import code for a View that will be a good starting point for your solution is provided at the end of this answer. This view will display the Article's author username and picture.

You may need to edit the "Argument input" setting in the view.

I set it to use the "From context" option, and the required context of Author.

This has a good chance of working immediately, but we may need to go further into your panels configuration if it doesn't.

After enabling the Views Content Pane module, and importing and saving the view, you will be able to add the newly created pane to your panel.

Import this view code:

$view = new view();
$view->name = 'user_name_and_pic_for_articles';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'User Name and Pic for Articles';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Picture */
$handler->display->display_options['fields']['picture']['id'] = 'picture';
$handler->display->display_options['fields']['picture']['table'] = 'users';
$handler->display->display_options['fields']['picture']['field'] = 'picture';
$handler->display->display_options['fields']['picture']['label'] = '';
$handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['picture']['link_photo_to_profile'] = FALSE;
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'not found';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Username and Pic for Articles Content pane */
$handler = $view->new_display('panel_pane', 'Username and Pic for Articles Content pane', 'panel_pane_1');
$handler->display->display_options['argument_input'] = array(
  'uid' => array(
    'type' => 'context',
    'context' => 'entity:node.author',
    'context_optional' => 0,
    'panel' => '0',
    'fixed' => '',
    'label' => 'Author: Uid',
  ),
);


Is there a way to hook on cache clearing? For a big institution website, with heavy caches, I'd like to generate caches as soon as possible, so that no user may arrive on cache generation...

I have a cron set all minutes that does it, by executing a few functions and requesting critical pages, but what I'm looking for is a way to know when the cache has just been cleared, preferably a hook, so I can launch this generating-functions.

Any idea ?

The way to do this is to use hook_flush_caches in combination with register_shutdown_function. Example code:

/**
 * Implements hook_flush_caches().
 */
function mymodule_flush_caches() {
   // After caches are cleared we will run mymodule_cache_rebuild()
   register_shutdown_function('mymodule_cache_rebuild');

   // We don't want to add any custom cache-tables, so just return an empty array
   return array();
}

/**
 * Rebuild expensive cache items that need to be rebuilt immediately.
 */
function mymodule_cache_rebuild() {
  // Do the cache rebuild work here
}

Using register_shutdown_function means that our cache-rebuilding function will be called after the caches have been cleared. We are abusing hook_flush_caches in a way that it was never intended to be used, but this should do exactly what you need.


Adding javascript to module and access drupalSettings without jQuery I am trying to create a Drupal 8 version of the Mautic Drupal module. Currently I have just ported the Drupal 7 version as is, and the script for Mautic forms along with the tracking pixel is printed in a block. Mautic now uses a tracking script and I want to update the module to use it. The tracking script looks like this (notice the Mautic base url required):

js/mautic_drupal_tracking_code.js

(function(w,d,t,u,n,a,m){w['MauticTrackingObject']=n;
    w[n]=w[n]||function(){(w[n].q=w[n].q||[]).push(arguments)},a=d.createElement(t),
        m=d.getElementsByTagName(t)[0];a.async=1;a.src=u;m.parentNode.insertBefore(a,m)
})(window,document,'script', + drupalSettings.mautic_drupal.mautic_drupal_tracking_code.base_url + '/mtc.js','mt');

mt('send', 'pageview');

The script is showing on the page, but as I am trying to avoid jQuery, I can not find out how to access the drupalSettings variable.

My module code is updated and not in sync with the github repo. Here are a description of the files:

mautic_drupal.libraries.yml

mautic_drupal_tracking_code:
  version: VERSION
  js:
    js/mautic_drupal_tracking_code.js: {}
  dependencies:
    - core/drupalSettings

mautic_drupal.module

/**
 * Implements hook_page_attachments_alter().
 *
 * @param array $page
 */
function mautic_drupal_page_attachments_alter(array &$page) {
  $config = \Drupal::service('config.factory')->get('mautic_drupal.settings');
  $mautic_url = trim($config->get('base_url'), ' \t\n\r\0\x0B/');

  if ($mautic_url != '') {
    $page['#attached']['drupalSettings']['mautic_drupal']['mautic_drupal_tracking_code']['base_url'] = $mautic_url;
    $page['#attached']['library'][] = 'mautic_drupal/mautic_drupal_tracking_code';
  }
}

On the site, the script is showing, and the base url setting is set. But alas, I can not access the settings in my javascript, I can only find examples of how to do that in jQuery scripts.

Is this possible to do in pure javascript?

You can try to set a weight on the js file:

  js:
    js/mautic_drupal_tracking_code.js: { weight: -18 }

There is a core issue, that the dependencies don't get the correct priority. The weight is a workaround for this:

Replace custom weights with dependencies in library declarations

If you can't get drupalSettingsLoader.js running in the correct order, you can for testing purpose put the code to load the json array at the top of your custom js:

(function () {

  'use strict';

  var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');

  window.drupalSettings = {};

  if (settingsElement !== null) {
    window.drupalSettings = JSON.parse(settingsElement.textContent);
  }
})();


How to patch your htaccess file correctly in composer.json After running composer update my Drupal installation gets updated, but it also changes the content of the .htaccess file each time.

How can I correctly patch it?

In the scripts section of your composer.json file, use the following:

"post-drupal-scaffold-cmd": [
  "patch -p0 < patches/htaccess.patch"
]

(this requires "drupal-composer/drupal-scaffold" in your require section)


How do you create a make file and minify it for pdf.js? I want to install the PDF module. In the modules "Getting Started" instructions, I read the following sentence:

  Make pdf.js file in the pdf.js/build directory by following the README.

The README file includes these instructions:

  In order to bundle all src/ files into a final pdf.js, issue:

$ make

  This will generate the file build/pdf.js that can be included in your final project. (WARNING: That's a large file! Consider minifying it).

How do you accomplish this from a Windows machine?
Does it require the web server to be a linux machine?
Does this require SSH'ing into the remote host?

How do you accomplish this from a Windows machine?

No, you can't run make command in Windows; maybe you want to check cygwin.

  Does it require the web server to be a linux machine?

Final .js file can be placed anywhere, Windows or Linux. You need a Linux machine to create it.

  Does this require SSH'ing into the remote host?

If you want run make command in your server, you need ssh-ing.


Need way semi complex way to display author posts in views So I have an interesting request and I'm hoping some of you guys here might know a decent way to solve this.  On one of our homepages we have a block that shows current authors posts.  This was a simple view that just showed authors posts sorted by date.  However now they want something a bit more specific detailed below.

In stead of just random posts, the first request is that is shows 5 post but of each post they should all be a specific author and NOT repeated in any way.  For instance you have Author A, B, C, D , and E.  The view would look like this.

A = His/her latest post

B = His/her latest post

C = His/her latest post

D = His/her latest post

E = His/her latest post

So each highlighted author shows their latest post and none of those authors repeat.

The next thing they want is an ability to pick and choose WHO those top 5 authors will be.  So one week it might be A, B, C, D, and E; but they next week it could be F, A, H, J, and Y.  This seems like a fairly complex view and not to mention the interfaced required for the UI portion.  Thoughts?

It looks like you might want to use views>advanced>other aggregation to make the posts distinct on the author field.
Summary
Create a view of nodes that displayed recent posts by selected authors, then ensure that each author did not repeat by making them distinct.
To allow the site administrators (or other users by role) to  select authors
I would suggest using a flag to indicate the top authors. You could then  sort the view by the flag date (make sure you create a relationship to the flag) and limit the view to 5 results
Solution (updated)
To 'filter by distinct', install views_distinct module, and in your view of recent nodes by selected author, set a filter (in author uid field settings) based on the author uid field:

Here is an export of an example view of article nodes (does not include flag selection for portability):
$view = new view();
$view->name = 'drupal_answers_97449';
$view->description = 'http://goo.gl/gQLr2A';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'drupal answers 97449';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Top 5 authors';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'name' => 'name',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = 'author';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = 'post title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'drupal-answers-97449';


how to create rules to send email notification for node reference content? I have two content types: job posting and job application.
The job application content type has a node reference field for job posting. Whenever  users create a job posting node, other users can send a job application to that job posting by filling the fields.

How can I send a notification to the user who had posted the job application node when the node has been created?

Sure, with the Rules module create a new rule with this configuration:

At admin/rules/trigger/add choose a name for your rule
In the Event dropdown choose After saving new content and click 'Save changes'
Add a condition of: Content has type under the Node heading in the conditions dropdown
Add an action of: Load a referenced node under the CCK dropdown heading and choose the node reference field you want to use (the one in the job app content type) and click 'Save'
Add another action: Load a user account under the User dropdown heading. In the User id field, add <?php print $referenced_node->uid; ?> and click 'Save'
Add a third action: Send a mail to a user under the System dropdown heading, changed the Recipient dropdown to Loaded user and configure the Sender, Subject, and Body of the email and click save.

Now when a user creates a job application an email will be sent to the user who created the referenced job posting (assuming there is a value in the node reference field, it should be required).


Custom module pages not rendering when added to admin menu I have a custom module that outputs some sql reports in a table with a csv button.  These are SQL tables that are not accessible via views which is why I had to make this module.
Now when these links are accessible through the frontend (ie do not have 'admin' in the path ) the page and table's contents render just fine.
$items['custom_report/glp_report'] = array(
'title' => 'GLP Report',
'description' => 'Report for Guided Learning Pathways.',
'page callback' => 'op_reports_page',
'access callback' => 'op_reports_permission',
 //'theme callback' => 'op_theme',
'type' => MENU_NORMAL_ITEM,
);

When I switch this to an admin path only the table headers render but no content.
$items['admin/custom_report/glp_report'] = array(
'title' => 'GLP Report',
'description' => 'Report for Guided Learning Pathways.',
'page callback' => 'op_reports_page',
'access callback' => 'op_reports_permission',
 //'theme callback' => 'op_theme',
'type' => MENU_NORMAL_ITEM,
);

Theme_debug is on and I can see that on the frontend the bootstrap block.tpl serves the table correctly

however on the admin page it loads block/block.tpl

Hypothesis
Drupal Admin theme is different than the frontend theme.  For whatever reason, this new theme uses a different template and that different template can't render my output.
Approach 1 Create custom template for the page
So I wanted to force a custom template hoping that would fix the module override:
Here is the page callback:
function op_reports_page() {
$page = drupal_render(drupal_get_form('op_reports_form', 'glp'));
$page .= op_reports_table('glp');

$page = array
(
'op_reports_page' => array
(
// Note - we will register theme_my_page in the next step
'#theme' => 'glp_reports',
'#contents' => $page,
),
);

return $page;
}

Here is the theme_hook:
function op_reports_theme()
{
  return array
  (
    'glp_reports' => array
    (
      'variables' => array('contents' => array()),
      'template' => 'op_theme', // don't add .tpl.php
    ),
  );
}

Template file:

<?php print t('My Page'); ?>

  <?php print render($contents); ?>

Outcome
While this renders for frontend, on the admin I get a blank content section.
Approach 2 force the theme through the hook_menu
Using the theme callback you can tell Drupal how the page should be rendered
Hook Menu:
  $items['admin/custom_report/glp_report'] = array(
    'title' => 'GLP Report',
    'description' => 'Report for Guided Learning Pathways.',
    'page callback' => 'op_reports_page',
    'access callback' => 'op_reports_permission',
    'theme callback' => 'op_theme', //name of bootstrap extended theme
    'type' => MENU_NORMAL_ITEM,
  );

Outcome
Blank page on admin page
Approach 3 hook_custom_theme
Hook_custom_theme should override any theme with the machine name theme
  function op_reports_custom_theme(){
    return 'op_theme';
  }

Outcome
Blank page on admin page
Ask
So while I appreciate getting stripes on my Drupal white belt, I would really just like to know the best way to make my custom module render output on an admin path.

All I can suggest is to look at page callbacks that already render on administrative pages (like the ones in core). There should be nothing special between a core or third-party module in this respect.

More thoughts:

You should not call drupal_render() in a page callback. Return the render array and let core do the rendering
No need for 'theme callback' in a menu definition here


Rest Export JSON format I'm new to Drupal and I've very excited about the possibly of headless as it will align with my current skillset and let me be productive more quicly while I continue to learn Drupal. (I come from a full stack .NET background using consuming REST services on the frontend).

I'm having some trouble with the JSON format.

I've set up a REST Export view in Drupal 8.3 that returns a custom content type. It includes a three fields: title, body(plain text), and an image.

The result that I get has a lot of escape characters and I'm not sure how to get it to just return the plain text data.

Here is the result that I get:

[{"title":"A test for the json api","field_body":"This is a test. It\u0026#039;s pretty awesome and I love you.","field_test_image":"\/drupal\/sites\/default\/files\/2017-04\/Adam_Dickison_1.png"}]

What I'd like to get back is this:

[{"title":"A test for the json api","field_body":"This is a test. It's pretty awesome and I love you.","field_test_image":"/drupal/sites/default/files/2017-04/Adam_Dickinson_1.png"}]

I've checked my php.ini and magic_quotes_gpc is set to 'Off'.

Can anybody help me figure this out. I didn't see any general settings. I've changed all of the field settings to remove html and to give me just the plain text.

Thanks in advance.

On your view page,  click on the 'Field settings'. i.e.

Format:
Show: Fields | Settings

Click on the 'Settings'. You will see a popup window. And select the 'RAW OUTPUT' for the respective field. Also, you can provide ALIAS for the field.
I guess you were looking for this option.


Get relationships between tables when no foreign keys are present How can tell the relationships between tables when no FKs are being used?

Just started working on a (partial) data export from Drupal MySQL database with ~1000 tables that contains hardly any foreign keys. Forgive my ignorance but I don't even know whether this is standard modus operandi in Drupal or some sort of anomaly. I have been expecting FKs as on most RDBS that I ever worked on FKs were present.

Entity API is being used extensively and so is data versionning if that makes any difference.

I know I could capture all the SQL queries hitting the database at runtime and then, assuming all the queries were run, I could tell how joins are made.

But looking for simpler way to tell relationships between tables similar to the one below.

You have 3 possible options, but you most likely want to start with #2 and combine it with #3.

Use php to print out the Entity Metadata Wrapper for various nodes objects of different types.
Use the Devel Module and view the Node object
Use Views

If the Entity definitions were properly implemented (a huge IF) it is possible to print out the relationships using entity_metadata_wrapper from php.  You can even write it out to a file from command line using Drush but this will take some advanced skills.  However, this typically results in tens of thousands of lines, an overwhelming amount of information, with many circular references.

Using the Devel Module will be much easier as you can simply click down into what the Node object is presenting.  This may not show all the fields if they aren't filled out so you will want to create a test Node of each type with data in each field. If filled properly this may help relate structures when looking at the raw MySQL data as well.

Using Views, Drupal's built in query builder, will help you either understand the schema or just export it by adding the Views Data Export module. You will want to start from a perspective of particular Node type (a content type).  Each Node type will show fields it can access and you should be able to build the queries from there.  You may need to add Relationships (joins) to get all the data depending on how the developers built the system, its hard to say. Drupal will limit you to only the tables that are defined with Relationships.

You can see the MySQL Queries you are building at the bottom of the page if Show the SQL Queries is enabled in the Views settings tab (/admin/structure/views/settings).


Drupal vs Options Indexes? I have an .htaccess file with Options Indexes FollowSymLinks, my /apache2/sites_available/default file also has these options and AllowOverride All.

If I do these things outside of Drupal it's working (if I go to a directory without an index file, I see a file directory listing), but inside Drupal I'm getting

  The requested page "/sites/default/files/" could not be found.

Also, I am able to to access files within the files directory. For example if I went to /sites/default/files/someFile.pdf... it would be able to access it fine. I want to have it so that if I link to a directory within the files directory and that directory does not have an index file... it will display a directory listing of all the files/folders within. Something like:

http://3.bp.blogspot.com/_rhuioznu6Us/TBmeWAr_G2I/AAAAAAAAAFE/tKCclPXdq2M/s1600/apache.png

I think Drupal is doing something based on the fact that I get my Drupal headers above the message that the page couldn't be found. How do I stop this?

The files below show some of the things I've tried...

apache2/sites_available/default contains:

DocumentRoot /var/www/default
<Directory />
  Options Indexes FollowSymLinks
  AllowOverride All
</Directory>

<Directory /var/www/default/>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  Allow from all
</Directory>

default/files/.htaccess contains

Options +FollowSymLinks
Options +Indexes
RewriteEngine Off

You don't need the Indexes on your web server. Its actually not recommend on a live environment. For testing purpose it can be useful sometimes.

If you don't have your files directory I would recommend you to created a files directory

sudo mkdir sites/default/files # Creating files directory
sudo chmod a+w sites/default/files # Permissions

After that you can you try  this on your default configuration file...

<DIRECTORY />
      Options FollowSymLinks
      AllowOverride None
 </DIRECTORY>

 <DIRECTORY /var/www/drupal_site/>
     Options +FollowSymLinks
     AllowOverride All
 </DIRECTORY>

Source: https://github.com/darol100/lazydubuntu/blob/master/bin/includes/skeleton

And then re-start your server.

If this does not solve your problem here is a similar question (with the same error)

And here is the answer.

  This is a known problem, a natural result of clean URLs

  When you are on http://example.com/?q=node/15 and the browser sees a relative "files/filename" path it resolves it as
  http://example.com/files/filename. The ?q= part does not pretend to be
  a path, so the browser does not use it.
  When you are on http://example.com/node/15 and the browser sees a relative "files/filename" path it resolves it as
  http://example.com/node/15/files/filename because it considers node/15
  as a real path.

  So, when you use clean URLs the file links must have a front slash
  (and possibly a path if Drupal's home page contains an URL path). The
  browser sees the absolute path "/files/filename" and resolves it using
  the bare domain name. You need to edit all the file paths in the
  content and add a front slash.

  Alternatively, try the http://drupal.org/project/pathologic module
  which tries to be smart about it (or one of the other modules
  mentioned there).


Categorize Feeds with taxonomy terms automatically I want to fetch the content from various RSS sources into my site to display them in a section. I have installed the Feeds module and created the feed to fetch from, along with the Content Type that will host the fetched news, but I'd like to categorize them in order to display then in different groups using Views (i.e.: 'news', 'technology', 'sports', etc.).

Is there any way to tell the Feeds module to add a value to the generated node's "Category" field (whether this is a taxonomy term or text field)?

If you add a term reference field to the feed node, you can map the value to the feed item node (inheriting values). The term can then be added when creating the feed node.


Render React Components in Twig Templates I am using React JS in my theme (installed via NPM), and exporting views using REST. I want to render the JSON view data into React components and call them in the twig templates.

The way I have it working now is I have js/main.js importing components eg: js/components/slider.jsx etc. The component files decide where to render. Eg:

ReactDOM.render(
  document.getElementById('elementid')
);

I have a gulp task running which bundles, transforms ES6 - ES5, and uglifies all the JS imported in js/main.js into js/script.js which is the only JS loading from the theme. I'm not sure if this is the best option for performance.

Maybe another option is to compile each component (ES6 must be transformed to ES5) into it's own JS file and define them as libraries, which can be then called in the twig templates?

I have tried to use TwigReactDirective but I get errors following the instructions.

Are there better options / ways of doing this?

After doing some research, I found 3 options to render React components on the server side.

Use the PHP V8Js extension to run an embedded V8 engine
Execute node.js processes on demand
Run a node.js rendering daemon for rendering

Rendering on the server side is beneficial for performance of the initial page load. Using the V8Js extension and a twig extension like Tesonet seems like the best option for me.

V8Js installation instructions can be found here

Some other good options to try out are: React Renderer or symfony-react-sandbox or React Bundle. Symfony React Sandbox integrates React Bundle. React Bundle integrates React Renderer.

Read more here


how to pass a parameter to a route of type _entity_form With some help I could create a route to an extended register form: as this form is an "entity form", my route have this type and the definition of this new form has been made in hook_entity_type_alter

The last part of the path of the route is a role name; and the user submitting this form (registering itself) should get this role.

Here is the code:

1-Extending the register form

class RegisterByRole extends RegisterForm
{
    public function form(array $form, FormStateInterface $form_state, $role = null)
    {
        $form = parent::form($form, $form_state);
        if ($role) {
            $form['test'] = [
                '#markup' => '<p>Test:' . $role
            ];
        }
        return $form;
    }
}

2-Adding a new entity form to the entity_type definition/annotation

function my_module_entity_type_alter(array &$entity_types) {
    $entity_types['user']->setFormClass('role_registration', 'Drupal\my_module\Form\RegisterByRole');
}

3-Creating the route

my_module.register:
  path: '/register/{role}'
  defaults:
    _entity_form: 'user.role_registration'
    _title: 'Register by role'
  requirements:
    _permission: 'access content'

Unfortunatly, the $role parameter is not transmitted...

With the help of 4k4 who have all the credit for this answer, I have created a controler which, in turn, build my register form (I no longer need to extend the register form).
Before building the form, the controller must create a user and assign the role (coming from the parameter).

Here is the code

1-Create the route with rid as the parameter and a _controler key:

my_module.register:
  path: '/register/{rid}'
  defaults:
    _controller: '\Drupal\my_module\Controller\RegisterByRoleController::content'
    _title: 'Register by role'
  requirements:
    _permission: 'access content'

2-Create the controller with rid as the parameter (src/Controller/...):

    public function content($rid=null) {

      $user_with_role = \Drupal\user\Entity\User::create();
      $roles = Role::loadMultiple();
      if ($rid && isset($roles[$rid])){
          $user_with_role->addRole($rid);
      }else{
          throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException();
      }

      $form = \Drupal::entityTypeManager()
      ->getFormObject('user', 'register')
      ->setEntity($user_with_role);

      $form_build=\Drupal::formBuilder()->getForm($form);

      //here is the trick I used to check the role
      $form_build['account']['roles'][$rid]['#checked']=TRUE;
      return $form_build;
  }

Everything works well: the form is displayed, the rid is transmitted to the controller but the is still a problem:

The "transmitted" role's checkbox is not checked in the register form!

Any Hint?

I answer myself: it seems there is no way to achieve this "automatically", I will have to check "myself" the check boxes... see the last comment here: Default value for form entity

This is why is have added this line in the code $form_build['account']['roles'][$rid]['#checked']=TRUE;


How to add a width attribute to a responsive image with srcset? When using a responsive image with srcset the width and height attributes are not available in twig. Both of them are NULL When an image is uploaded that is too small images are stretched or blown up as described in this post: Responsive Images, The sizes Attribute, and Unexpected Image Sizes

Being able to set a with equal to the pixelsize of the image would solve this issue. How can I make these attributes available for twig?

This is not going to be easy due to Drupal's way of rendering images, you should not touch this unless you know how to write code. The code below is untested, but should give you a direction.

function THEMENAME_preprocess_responsive_image_formatter(array &$variables) {
  //this is the hook where you do get access to the image file entity
  //don't use 'width' as attribute name, it might get unset by Drupal in the following hook
  $variables['responsive_image']['#attributes']['data-original-image-width'] = $variables['item']->width;
}

function THEMENAME_preprocess_responsive_image(array &$variables) {
  //this is the preparing the rendering, here you can set the width attribute again
  $variables['#attributes']['width'] = $variables['img_element']['#attributes']['data-original-image-width'];
}

This is code just an outline, and most likely will only work if responsive images module is configured for an single img[srcset] and will not work with <picture> tags.

The hooks are quite good documented though, check the API docs for more information

hook_preprocess_responsive_image_formatter

hook_preprocess_responsive_image


Can't access admin after moving localhost to live server Almost finished my site and thought I have completed the puzzle but there is one last frontier in my way and a rather annoying ankle-biter...

I moved my site off my localhost onto my live server everything was successful until I tried to login the first time and was denied access.. I requested a new password through the email I provided when i created the site on my localhost but the emails do not come to my inbox but when i try to recreate the process on my localhost I get the email and can change it etc. I have tried going into my DB>users>browse> and change my password and put MD5 so it becomes encrypted but still no success on the live site.

I have tried to search online for the answer but have been going in circles and would like to see if anyone can offer some advice I am novice level and eager to learn so if responding kindly use terms a novice would be familiar with, thank you.

Install drush
Go to your drupal-core/sites/mysite folder in command line
type sudo drush uli
The console will print a link, use that to access your site as user 1


override view Use administration toolbar i have a view that using administration toolbar. Problemis theme suggestion is not showing the template names that should override the template. i guess because its using the administration toolbar .. What i am trying to acheive is showing the whole comment body, when the edit link is clicked
 , instead of going to an other page. How can i force drupal to show suggestion view templates. And is there a better idea.

I found out that  i need to do a custom module then do theme hook suggestion.

function my_module_theme($existing, $type, $theme, $path) {
    return array(
    'views_view__comments'=> [
        'template' => 'views/views-view--comments',
    ]);
 }

And then template in yout admin theme , or in your custom module. In my case in module forlder templates/view.


Forbidden 403 http request using deployment module When I use the deployment module on my local websites it works perfectly, I make a devlopment plan, add one or more endpoints, I select some nodes and then I deploy the plan and run Cron.
This way nodes that I selected are copied to my other sites in the multisite set-up.

When I use the exact some set-up for my live websites I get this error when executing the Cron:
Link to image: http://imageshack.com/a/img401/5973/bwju.png

This has to be something with the permissions when I look it up on the net but I cannot find a solution.
Link to module: https://drupal.org/project/deploy

Is there anyone that has tested this module and had the same issue and fixed it?
Or is there someone that can tell me what to fix to make it work?

Thanks in advance

The answer to my own question:

Add this to your .htaccess file (I have put it at the top):

#
# Apache/PHP/Drupal settings:
# Paste the code under this sentence
<Limit PUT>
    allow from all
</Limit>


Custom (cck) fields are being ignored during the migration using migration-tools 4.x. Only title and body is imported. How do I fix this? I'm running a migration from Drupal 6 to Drupal 8, following roughly the advices in the http://pnijjar.freeshell.org/2017/drupal8-migrate/ guide.

At the moment, only title and body for each node is being imported for each node, despite definitions being correctly put into the .yml files generated by drush migrate-upgrade --configure-only . See an example migrate_plus.migration.d6_node_event.yml below.

I can't figure out what is wrong.

uuid: 51bc9a5e-6caf-4b7a-9b08-e34312467c89
langcode: en
status: true
dependencies: {  }
id: d6_node_event
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 6'
migration_group: migrate_drupal_6
label: 'Nodes (event)'
source:
  plugin: d6_node
  node_type: event
process:
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: und
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  body/format:
    plugin: migration_lookup
    migration: d6_filter_format
    source: format
  body/value: body
  body/summary: teaser
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
  field_organization:
    plugin: iterator
    source: field_organization
    process:
      value: value
      format:
        -
          plugin: static_map
          bypass: true
          source: format
          map:
            - null
        -
          plugin: skip_on_empty
          method: process
        -
          plugin: migration
          migration:
            - d6_filter_format
            - d7_filter_format
          source: format
  field_startend:
    plugin: iterator
    source: field_startend
    process:
      value:
        plugin: format_date
        from_format: U
        to_format: U
        source: value
  field_event_venue:
    plugin: iterator
    source: field_event_venue
    process:
      value: value
      format:
        -
          plugin: static_map
          bypass: true
          source: format
          map:
            - null
        -
          plugin: skip_on_empty
          method: process
        -
          plugin: migration
          migration:
            - d6_filter_format
            - d7_filter_format
          source: format
  field_event_speakers:
    plugin: iterator
    source: field_event_speakers
    process:
      value: value
      format:
        -
          plugin: static_map
          bypass: true
          source: format
          map:
            - null
        -
          plugin: skip_on_empty
          method: process
        -
          plugin: migration
          migration:
            - d6_filter_format
            - d7_filter_format
          source: format

...

What version of migrate_upgrade are you using? I see things like

      plugin: migration
      migration:
        - d6_filter_format
        - d7_filter_format

there, but --configure-only should have generated

      plugin: migration
      migration:
        - upgrade_d6_filter_format
        - upgrade_d7_filter_format


What is the best caching solution for website with a lot of content? We are building a website with over a million nodes. Those nodes also have paragraphs which increases the number of entities. Therefore, the cache tables are getting bigger and bigger, especially the cache_entity and cache_render tables.

What is the best way to avoid the database to get too big (we're talking hundred of gigabytes) ? Is memcache a solution here or is it just deporting the problem of disk space ?

The basic cron task doesn't clear the tables. We were also thinking about setting a cron task to execute "drush cr".

According to that post and that issue, Drupal 8.4 will have a better cache table management.

Part of the solution could be to compress those cache tables where the typical values to cache are quite big and allow for a high compress ratio. I think render caches fit that description very well.

See e.g. issue [#1281408] and a comment on another issue mentioned in comment #23.


Field Collection fields causes errors in array_flip functions in /includes/entity.inc This is a follow up question from this question. I now am sure that it's the Field Collection module that causes the error message "Can only flip string and integer values!". My previous question was about HOW to find which module causes the error. I have now used Xdebug and Atom to backtrace the stack like this:

When the error arises on row 175 in /includes/entity.inc I have these values in the variable $ids:

$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;

As you can see it's an array in an array, which causes the error, as array_flip() only can flip integers and strings, not arrays.

The array in an array value comes from row 8016 in /includes/common.inc:

function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
  if ($reset) {
    entity_get_controller($entity_type)->resetCache();
  }
  return entity_get_controller($entity_type)->load($ids, $conditions);
}

Going one step further back in the stack, the value comes from these rows in sites/all/modules/entity/entity.module:

function entity_load_single($entity_type, $id) {
  $entities = entity_load($entity_type, array($id));
  return reset($entities);
}

And if you bare with me, one more step back in the stack... to sites/all/modules/field_collection/field_collection_entity.inc, where I find these rows (row 265):

  public function hostEntity() {
    if ($this->fetchHostDetails()) {
      if (!isset($this->hostEntity) && $this->isInUse()) {
        $this->hostEntity = entity_load_single($this->hostEntityType, $this->hostEntityId);
      }
      elseif (!isset($this->hostEntity) && $this->hostEntityRevisionId) {
        $this->hostEntity = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
      }
      return $this->hostEntity;
    }
  }

Now to my question... what happens is that the host entity id (26391) is passed up the stack once for every field collection field that exists on the page. 10 field collection field instances = 10 error messages on row 175 in /includes/entity.inc (and equally many on row 388).

Can anyone tell me what I might be doing wrong? I suspect I have drawn this error upon myself. All other posts I have read among the issues for Field Collection suggests that this shouldn't be a problem any more. Otherwise I would have posted this in as an issue for Field Collection.

The field types I am using in these Field Collection fields are: Image, Long text and Link.

What more info can I give you to solve this problem? I am not an expert coder, so maybe there is something obvious in the stack above, that I don't see?

In case anyone has the same problem, try to update the module to the DEV version. In the above case the php error messages mentioned disappeared.


Is it correct to make queries to DB in preprocess functions? I've just started using Drupal after long experience of using other framework.
When I do something new, I'm scaring to crash performance because of my incomprehension.
So, my problem:
I want to add dynamically some data from database to some existing page region.
For example, I want to add list of child terms to taxonomy term page. And I don't need to change any other things on this page, so I don't want to turn on View.
Is it normal to query data in preprocess functions?
My solution for D7 was like this:

function mymodule_taxonomy_term_view_alter(&$build) {
  if ($build['#view_mode'] == 'full') {
    $children = taxonomy_get_tree($build['#term']->vid, $build['#term']->tid, 1);
    foreach($children as $term) {
      $build['children'][] = (array)$term;
    }
  }
}

function mymodule_preprocess_taxonomy_term(&$variables) {
  if($variables['vocabulary_machine_name'] == 'catalog') {

    if(count($variables['elements']['children'])) {
      $items = array();
      foreach($variables['elements']['children'] as $term) {
        $items[] = array(
          'data' => l($term['name'], 'taxonomy/term/' . $term['tid'])
        );
      }

      $variables['content']['children']['#markup'] = theme('item_list', array('items' => $items, 'title' => 'Text terms list', 'type' => 'ul', 'attributes' => array()));
    }
  }
}

Any comment are welcome.

No, it's not incorrect to query the database in a preprocess function. If the information is required to render the page, putting a query in a preprocess function is an acceptable choice. Plus, in this particular case taxonomy_get_tree() caches results, so there is very little cost associated with repeated fetches.

Regarding Views, yes there is some overhead associated with it, but it employs a sophisticated caching strategy, and is ultimately just so powerful and useful that most sites use it. You could probably solve this current problem with no custom code by using a Viewfield.

These questions provide a lot of interesting background on Drupal performance.


Create product programmatically I have a product with a custom field, according to this. I know I can create product with

$cp = commerce_product_new('product');
$cp->is_new = TRUE;
$cp->revision_id = NULL;
$cp->uid = 1;
$cp->status = 1;
$cp->created = $cp->changed = time();
$cp->sku = $product[sku];
$cp->title = $product[name];
$cp->language = LANGUAGE_NONE;
$cp->commerce_price = array(LANGUAGE_NONE => array( 0 => array(
 'amount' => $product[sale_price] ? $product[sale_price] : $product[retail_price],
 'currency_code' => 'USD',
)));$product[retail_price];
commerce_product_save($cp);

but I have some custom field.

How can I create a Drupal Commerce product programmatically with full custom fields?

Is  $cp->myfield1='22'; sufficient?

A commerce product is an entity like any other, so...

$cp->field_my_field[LANGUAGE_NONE][0]['value'] = '22';


Accessing external data in a field When creating a content type I would like to have a field type that could be used to call a rest service or make a db call to an external database.  Does this exist?

To the best of my knowledge, no, there isn't a module out there to do this. I have seen something similar done in the past though, where a node would have an id of some sort provided, and a module would connect to an external service to load in information for the node.

I suspect you might want to think about writing a custom module to do this. If you haven't taken a look at https://drupal.org/developing/modules yet you might want to. Just remember when modifying functionality of Drupal you should never hack the core, but create/use a module instead.

I think what your gonna want to do is architect a way to know what you need to pull and from where, then use hook_node_view to change/add the data you pull from your DB/external service (https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_view/7)


Best approach for creating databases for sub-sites I have to create a website that has about 1000(in future thousands) sub-sites. How should I create database for this sub-sites? Creating a separate database per site, or creating for example 10 databases, each one for 100 sites(using table prefixes), or ...?

The option to use table prefixes exists because some hosting providers limit the number of databases. Don't use this feature unless your hosting provider is one of those.


Writing a patch on a sandbox/dev install using a git branch I'm working with a Sandbox/Dev hosted VM with Drupal 7 and Commons 3. I want to write and perhaps contribute a patch. Having the site under local version control with git, I create a new branch write and test the code.

However, I'm at a loss how to create the patch file between the two branches (master and writing-patch).

Do I switch back the master? How do I compare two branches and properly put that into a patch file with the intention of sharing with a module maintainer? I'd like to do this properly and put as little work on the maintainer as possible.

Go to the module you want to patch and do a:

git diff original_branch final_branch > /path/to/file.patch

Test it by applying the patch to the initial module:

patch -p1 < /path/to/file.patch

or

git apply --index /path/to/file.patch

More info:

http://linux.about.com/od/commands/l/blcmdl1_patch.htm

https://drupal.org/node/707484


Webform override only certain groups of fields in webform-form template My question is about overriding webform-form.tpl.php.
I am using Webform 4.x-beta1 and Twitter Bootstrap framework. I would like to reuse bootstrap classes in my form to make it responsive. I got already how the override works. I would want to find out is it possible to only override the markup of certain groups of fields, for example to put 3 fields that are in the middle of the form inline using row-fluid class in the wrapper div, without changing the placement of these fields.
Ex:
---some fields that don't need to be overwritten---
---3 overwritten fields----
---some other fields keeping the correct order---
---2 overwritten fields---
etc.
My form is about 100 fields, and as far as I understand, I will have to revisit each and every field in order to achieve what I need.
I am sorry if I mixed you up in my explanation, I am pretty new to Drupal.
Thank you in advance

Finally I created several css classes that I add either to element wrapper or to the input element itself, and I position each element accordingly.

If your form is not too long, and you don't mind creating other webform elements, you might want to wrap the fields that you want to put on the same line in a fieldset, you give row-fluid class to the fieldset, and all is good. This obviously also depends on the functioning of the form, some modules don't work as expected with nested fieldsets, ex. webform add more module (at leat las I checked it didn't, was about a month ago)

In my case I didn't want to do this, as the form is long and complicated and it could've broken some functioning.

Cheers!


How do I access the first value of a multiple value text field using replacement patters inside a rule? For example, lets say I have a list of objects each stored as separate values of a text field. How would I access the individual values? I have tried using delta and I have tried using entity token but nothing has worked. I hope my syntax was just a little off.

Have a look at the tutorial about "Using Entity Reference in Rules". Starting from about 2:50, and up to about 4:15, it shows how in a Rules Action you can access the 1st, or 2nd, or ... value of a multiple value field, provided you also included a Rules Condition like "Entity has field" (related to the multi value field). So if you have a content type with a multi value field with (say) myfield, then you'd use node:myfield:0 for the very first value of that field (or node:myfield:1 for the 2nd value, etc).

However, the same tutorial, starting from about 4:20 and up to about 6:40, also explains how to loop through multiple-value references, using a Rules loop, and which I think is more appropriate to answer your question.  If you're not familiar with such loops, then I strongly recommend to also have a look at the tutorial titled "Lists and loops".


Show taxonomy only when logged in I have a content type with two taxonomy terms: "Intern" and "Non-Intern"
I want the items with "Intern" to only be visible when logged in. How do I achieve that?

You can use Taxonomy access module to access control for user role.

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


Views module doesn't call hook_node_view() when set to display fields I use Drupal 7 with Views and want to override some node field output in a view (namely change its Title to something I want). To accomplish that I set the view to display Fields and not Context or Rendered Entity and select Title and Body from the list of fields. And here is where the problem lies:

I have a (homemade) module that makes use of hook_node_view() hook to modify Body and Teaser text. When I display article body as a Field in the Views this hook for some strange reason is not called (on Context and Rendered Entity all works correctly). So I need a way to either:

override Title output while NOT setting my view to display Fields, or
find a way to call hook_node_view() while setting my view to display Fields.

Is there a way to do it?

Upd: provided a screenshot showing that hook_node_view() is not called on teaser when setting Show to Fields (left pane) but called when setting Show to Content (right pane):

screenshot showing that hook_node_view is called on teaser when setting Show to Content and is not called when setting Show to Fields http://ari-linn.nightmail.ru/views_and_hook_node_view.jpg

Upd 2: Okay, I did some Drupal colonoscopy and it even works though I can't say whether it is the right way to do things (probably not). I found out that when you render context Drupal apparently thinks you want to render a normal node but when you render fields Drupal is at a loss and doesn't think you're dealing with nodes anymore. Thus it doesn't fire any node hooks including hook_node_view(). If anyone still needs to run their functionality of hook_node_view($node, $view_mode, $langcode) they can use hook_views_pre_render(&$view) though access to node $view_mode and $langcode will be gone.

In case people out there are interested how I override node titles in taxonomy views, here is the scenario. My task was to override node Title with the value of another field, SortKey, and do it only in taxonomy views. I'm happy with "Britney Spears" node title at the main page but when it comes to taxonomy I want her to display "Spears, Britney".

I personally thought it to be tiresome and bothersome to deal with fields (they mess up all my CSS) and found a hack in Views 7.x-3.3: if you set Show parameter in your view to Fields and select Material:Rendered Material AND any other field (you can exclude it from display, just make sure Rendered Material is not the only field you load) you'll get a neat and tidy Node object at $view->result->_field_data. I fail to explain how it is so but it's there, and you can bend it to your needs, and what is even better Drupal will think you're rendering a node and fire all node hooks on it. I pray though that Views coders won't remove this wonderful hack in later versions ruining my code.

Here is the code:

/*
* Changes MYARTICLETYPE title to sortkey on taxonomy views pre-render
*/
function MYMODULE_views_pre_render(&$view)
{
    if($view->name == 'taxonomy_term')
    {
        foreach($view->result as $i => $value)
        {
            $node = &$value->_field_data['nid']['entity']; //it's a real node, yes.
            if($node->type == 'MYARTICLETYPE') //override titles only for this type
            {
                $node->title = $node->field_sort_key['und'][0]['value'];
            }
        }
    }
}

The title of your question is.

  Views module doesn't call hook_node_view() when set to display fields

That is working as intended. The reason is that it's not a node that's being rendered, but just a bunch of fields and attributes that belong to a node that is being rendered.

One way of fixing hook_node_view not being called, would be to actually render the nodes.

If the problem is that the field is not rendered as you which, the best way of dealing with that, would be to alter the rendering of the fields, instead of trying to make Drupal act like you're rendering a node when in fact you're not.

The easiest, cleanest and most flexible way to do that, would be to create some custom field formatters for the fields in question. Field formatters are like theme functions for the fields, and you can in views select which field formatter to use when you want to render a field. It requires some work, but gives great flexibility. That would make your hook_node_view obsolete as you can use field formatters when fields are rendered under the manage display tab in the field settings interface.


REST access denied to vote I have enabled the following modules on the site: VotingApi, Like&DisLike, Rest, RestUI and other depending modules

I use POSTMAN as my client and write my GET and POST request from it.

I have Resource "Content" and "Vote" enabled with all methods, auth and format.

I have created a REST Export view of the content and vote.

When I try to GET and/or POST to create a content I was able to do it successfully.

But when I use POST to vote on the content, I get a 403 response. I have provided a correct credentials on it, with header same as content has.

In Drupal browser logs, it says:

Type    access denied
Date    Friday, June 30, 2017 - 07:12
User    Anonymous (not verified)
Location    http://example.com/entity/vote
Referrer
Message /entity/vote
Severity    Warning
Hostname    172.17.0.1

Here is my POST request:

{
    "type": [
        {
            "target_id": "like"
        }
    ],
    "entity_id": [
        {
            "target_id": 2
        }
    ],
    "value": [
        {
            "value": 1
        }
    ],
    "value_type": [
        {
            "value": "points"
        }
    ],
    "user_id": [
        {
            "target_id": 1
        }
    ]
}

You probally haven't added permissions for anonymous user to do a GET/POST request to the given endpoint. Go to permissions, search for rest and enable "Access GET on [rest resource]" (Access GET on Node rest resource resource)


Views display of every user's flagged nodes grouped by flag type I am using views and the flags module to create a site where users can flag node items  with multiple flags/flag types. For my example, a user can flag nodes (content) items with one of three flags: fruits, veggies, or other.

User 1, name and profile picture

flag-fruits     flag-veggies     flag-other
------          ------           ------
apple           carrots          pork
orange          celery           ham
cherry                           soda

User 2, name and profile picture

flag-fruits     flag-veggies     flag-other
------          ------           ------
lime            artichoke        trout
banana          lettuce          barley
cherry          ginger           soda

User 3, name and profile picture

etc…

I have tried setting up the relationships in Views using content (node) item listings and Users' Flagged Content relationships. With Grouping Fields I can manage to relate a single flag type to each user, so…

User 1

flag-fruits
------
apple
orange
cherry

But I really need the view to show each flag under each user in a list. I have been attempting this with the [ViewField][1] module and also regular Views Attachments, but so far with no luck. Is this even possible? Panels maybe?

[1]: http://drupal.org/project/viewfield

For grouping, I have used Views Grouped Table to good effect. You might also look at Views Complex Grouping, a more recent module.


How to create a view showing content linked with an entity reference field? I have 2 content types: Developments and Carousel Images. Carousel Images has an entity reference field to select the Developments page it is linked to.

I simply want to create a view which will display on all Development pages, but only show the images which are linked to it. So the Development page called 'London' will display a view with all Carousel images where 'London' is selected in the entity reference field.

I have tried using contextual filters and relationships but not been able to get this working.

Any ideas?

OK, finally worked out how to do it. Thanks to this video which explains it all: https://www.youtube.com/watch?v=4Pdii7aFIvc&t=392s
However, in case anyone else is stuck you need to first create a relationship based on your entity reference field, sthen create a contextual filter using node:id based on url. This is all you need to do.


is there is any way to include files? I am writing PHP code in a rule, where I include another PHP file.

include_once 'google-api-php-client/src/Google/autoload.php';

Where do I need to include files?

You can use module_load_include() to include a PHP file.

module_load_include('php', $type, 'includes/google-api-php-client/src/Google/autoload');

Where type can be either theme name or module name. I guess in this you are building some drupal module so it must be module type. In which case it will look for autoload.php file inside your name module directory. However internally it will do the require_once instead of include_once :)
You can use Libraries API module to include a php file. For this you will have to keep this google-api-php-client inside libraries folder. And you will perform these steps to implement it.

function hook_libraries_info() {
  $path = libraries_get_path('google-api-php-client');
  set_include_path($path."/src/" . PATH_SEPARATOR .  get_include_path());
  $libraries['google-api-php-client'] = array(
  'name' => 'Google OAuth2 Library',
  'vendor url' => 'http://code.google.com/p/google-api-php-client',
  'download url' => 'http://github.com/google/google-api-php-client/archive/master.zip',
  'version arguments' => array(
    'file' => 'src/Google/Client.php',
    'pattern' => '/LIBVER = "([0-9\.a-z]+)/',
    'lines' => 40,
  ),
  'versions' => array(
    '1.0.5-beta' => array(
      'files' => array(
        'php' => array(
          'src/Google/Client.php',
        )
      ),
    ),
    '1.1.5' => array(
      'files' => array(
        'php' => array(
          'src/Google/autoload.php',
        )
      )
    )
  ),
  'files' => array(
    'php' => array(
      'src/Google/Client.php',
    ),
   ),
  );
  return $libraries;
}

Note: The version is 1.0.5-beta, so you may need to change the version as per your API version.

Then to include this library in another module.

function hook_init() {
  $path = libraries_get_path('google-api-php-client');
  if ($path) {
    set_include_path($path."/src/" . PATH_SEPARATOR . get_include_path());
  }
}

Since it comes it composer.json/autoload.php you can use these modules to load it automatically from libraries folder.
X Autoload, Composer Autoload, Composer Vender Autoload, although you will still need to define the location inside your module.

Using the XAutoload module

   function mymodule_libraries_info() {
     return array(
       'google-api-php-client' => array(
         'name' => 'Google Client Library',
         'xautoload' => function($adapter) {
           /** @var \Drupal\xautoload\Adapter\LocalDirectoryAdapter $adapter */
           // Scan sites/all/libraries/google-api-php-client/composer.json to look for
           // autoload information.
           $adapter->composerJson('composer.json');
         }
       )
     );
   }


Adding Count Up module to custom front page My end goal is to put several Count Up numbers on my custom front page. But I'm having trouble getting it implemented.
First, I installed the Count Up library (https://github.com/inorganik/CountUp.js) and put it in the libraries directory.
Then in mytheme.libraries.yml, I put
countup:
  version: 1.0
  js:
    /libraries/countup.js/dist/countUp.umd.js: {}
  dependencies:
    - core/jquery

And then in page--front.html.twig, I put
{{ attach_library('mytheme/countup') }}

0

When I flushed the cache, I got this error: "Uncaught ReferenceError: CountUp is not defined".
What am I missing here? I'm pretty weak at JS so it could be something obvious.
Thanks!

Working sample:
     <!DOCTYPE HTML>

       <meta charset="UTF-8">
       <title>CountUp.js</title>

0


Using search api programatically I have read and tried https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code

I am using drupal 8 and using the default content index for testing. I am able to run the following code and I get a result count, but not result items.

$index = \Drupal\search_api\Entity\Index::load('default_index');
$query = $index->query();

// Change the parse mode for the search.
$parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
  ->createInstance('direct');
$parse_mode->setConjunction('OR');
$query->setParseMode($parse_mode);

// Set fulltext search keywords and fields.
$query->keys('');
$query->setFulltextFields(['title', 'name', 'body']);

// Do paging.
$query->range(20, 10);

// Set one or more tags for the query.
// @see hook_search_api_query_TAG_alter()
// @see hook_search_api_results_TAG_alter()
$query->addTag('custom_search');

// Execute the search.
$results = $query->execute();

echo "Result count: {$results->getResultCount()}\n";
$ids = implode(', ', array_keys($results->getResultItems()));
echo "Returned IDs: $ids.\n";

Count shows a value but I can't get any result items.
I tried with $query->keys(''); $query->keys('*'); and some value $query->keys('some value');
In all cases the count seems to be correct. The search therefore seems to be executed correctly, but how can I retrieve the items?

//first just run this line
    kint($results);
    //and then you can uncomment the next lines, in my case I needed the response key 'elasticsearch_response'
    $response = $results->getExtraData('elasticsearch_response', []);
    $hits = $response['hits']['hits'];
    foreach($hits as $hit){
      kint($hit);
    }


how to create new image size with new image style with php code in drupal 7? I want to create a new image style in Drupal 7, with a name like front_video_thumbnail. I want to use this size image on front page. I wrote code in template.php preprocess_page(), like the following one.

$img = theme('image_style', array('style_name' => 'front_video_thumnail', 'path' => $value['uri']));
$content =l($img, $node_url, array('html' => TRUE));

No image is showing, because no image has been created in the new style folder.

How can I make this new image style created in the style folder?

You have to go to Configuration => Image Styles. Create the Image Style with the name front_video_thumnail and once it's configuration is saved your code should work.


How to set DataDefinition::create('integer') to allow bigint numbers I'm trying to create a FieldType in Drupal 8 which needs to be stored as bigint.
I set the field in the schema:

public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
  'columns' => array(
    'value' => array(
      'type' => 'int',
      'size' => 'big',
      'not null' => FALSE,
      'unsigned' => TRUE,
    ),
  ),
);

}

I then added the propertyDefinitions:

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
  ->setLabel(t('Field value'));

return $properties;

}

When trying to add an integer of more than 9 digits I get following validation error:

  This value should be of the correct primitive type.

How can I get this correct?

Thanks!

I do not believe there is a solution for this.

Typed Data Manager will always add the PrimitiveType validation constraint plugin for any primitive data type (data type implementing PrimitiveInterface). This plugin does not provide any options for the filter_var native PHP function, which is required to set max_range. This option itself must be less than the PHP_INT_MAX constant. Furthermore PHP_INT_MAX is signed and BIGINT is unsigned. 10 digits should be supported by PHP_INT_MAX for even 32-bit systems as long as it is below 2147483647, which is probably the case for your PHP build. You could try using a 64-bit version of PHP.

There are three alternatives given the signed/unsigned caveat above:

Create a Data Type plugin (that does not extend on PrimitiveInterface) to handle bigger integers.
Alter the constraint plugins and replace PrimitiveType with your own constraint plugin that allows for this or does its own logic. Hope that no other module will do this for the same plugin.
File a core issue and patch Drupal core so that Typed Data Manager allows to pass options and PrimitiveType plugin uses those options. This is trickier than it seems because those options would need to be a part of the DataDefinition (in a backwards-compatible API change), and then extracted out as options into the constraint.

My preferred way would be to get rid of PrimitiveType constraint altogether in Drupal 9 and use specific Symfony constraints.


Failed asserting that two strings are equal in a patch I have submit a patch on community but I am getting an error in result that Failed asserting that two strings are equal.
This is the patch.

index 31bf064..fa079cc 100644
--- a/advagg_css_minify/yui/CSSMin.inc
+++ b/advagg_css_minify/yui/CSSMin.inc
@@ -422,7 +422,10 @@ class CSSmin

         // restore preserved comments and strings in reverse order
         for ($i = count($this->preserved_tokens) - 1; $i >= 0; $i--) {
-            $css = preg_replace('/' . self::TOKEN . $i . '___/', $this->preserved_tokens[$i], $css, 1);
+            $preserved_tokens = $this->preserved_tokens[$i];
+            $preserved_tokens = htmlspecialchars($preserved_tokens);
+            $pt_replacepattern =  preg_replace('[^A-Za-z0-9@*.#:/ \-]', '',$preserved_tokens);
+            $css = preg_replace('/' . self::TOKEN . $i . '___/', $pt_replacepattern, $css, 1);
         }

         // Trim the final string (for any leading or trailing white spaces)
@@ -582,7 +585,10 @@ class CSSmin
         // one, maybe more? put'em back then
         if (($pos = $this->index_of($match, self::COMMENT)) >= 0) {
             for ($i = 0, $max = count($this->comments); $i < $max; $i++) {
-                $match = preg_replace('/' . self::COMMENT . $i . '___/', $this->comments[$i], $match, 1);
+                $comment = $this->comments[$i];
+                $comment = htmlspecialchars($comment);
+                $replacepattern =  preg_replace('/[^A-Za-z0-9@*. \-]/', '',$comment);
+                $match = preg_replace('/' . self::COMMENT . $i . '___/', $replacepattern, $match, 1);
             }
         }

It looks like the problem might have to do with HTML escape sequences for quotes, ampersands and other meta-characters (at least in part).

Compare these lines:

-  content: '/* \" \' */';\n
+  content: '/* quot  */';\n

and these:

-}"]{color:red}q[style*="quotes: none"]{quotes:none}q[style*='quotes: none']{quotes:none}q:after{content:": colon & escaped double \" quotes \"."}q:after{content:' (brackets & escaped single \' quotes \') '}q:after{content:"I'm Quote"}'
+}"]{color:red}q[style*="quotes: none"]{quotes:none}q[style*='quotes: none']{quotes:none}q:after{content:": colon &amp; escaped double \&quot; quotes \&quot;."}q:after{content:' (brackets &amp; escaped single \' quotes \') '}q:after{content:"I'm Quote"}'

Hopefully that sets you on the right path. Don't just look at your diff, look at the PHPUnit test to see exactly what test you are failing. Good luck!


How can I display multiple taxonomy terms on a node? I have a Drupal6/Ubercart setup. My products are categorised with taxonomy but we have a requirement that products can be placed into multiple category hierachies. For example, one product might be in:

Homeware
   Kitchens

and

Kitchens
   X Kitchen Range

The other requirement is that when displaying the product, the heading should show the breadcrumb of the hierachy as well as the category
name. This would be dependent on how the user got to view the product. If they went through the menu Homeware > Kitchens, this would be the breadcrumbs/heading displayed and vice versa.

How could I achieve this?

If you want a product to show up in multiple categories you simply enter all terms from the category vocabulary in the product edit mode. The hierarchy you need to  build up in the menu system not in the vocabulary.


Translate Drupal's built-in English to another kind of English I need to translate the American English Drupal core currently provides out of the box to a variation of English. I know I can use string overrides but there are too many that I need to override. Essentially I need to create my own custom language based off english. Suggestions?

You can do this with the Locale module, which is provided by core.  Steps are for Drupal 7.  This assumes you want to completely replace the built-in English with your own custom version of English (which will still show the strings for the built-in English unless you have translated/edited them).

Enable the locale module.
Go to languages admin (/admin/config/regional/language).
Click edit for the English (built-in) language.  Add en as the Path prefix (this will allow you to add your own language without a path prefix.)  Save.
Click "Add a language"
Choose "Custom language", set a language code, set both language names to English,  leave Path prefix and Language domain blank, and choose Left to right for the Direction.
Go back to the language list (/admin/config/regional/language) and set your new English as the default language.  Then uncheck Enabled for the built-in English.
Translate all the strings you want to modify on the translation screen (/admin/config/regional/translate/translate).


Commerce Coupons, Discounts, and Tax not appearing on Checkout Review page So I'm able to apply coupons on the Checkout page. Quantity-based discounts also appear on the Checkout page. As does basic state-based Sales tax. But, when you continue from there, you select a shipping service, and then continue to Checkout review. At this point, the coupon is gone, as are the discounts and tax.

The coupon entered still appears in the form, but the Granted Amount is now $0.00.

I'm losing my mind on this one because I'm dealing with a site that is (was) 95% complete when this started happening. I must have introduced something stupid along the way.

Solved! Rules was the culprit. By rolling back to the previous stable version, all of the problems with checkout disappeared. Everything applies correctly to the Checkout Page, and is still there when I get to Checkout Review.

Just to be clear, I replaced the current stable version of Rules (7.x-2.8) from January 2015 with the previous stable version (7.x-2.7) from May 2014.


Two Body/text areas for a multilingual site When creating a new node, I want 2 body text areas, each one for one language (one in English, and one in German ).

How can I have 2 body areas when create a node?

Edit the content type that you are using or create a new one and add another field to it.


Services 3 JSON format [null] at end of all result I am using services module recently i have noticed that i am getting all responses along with [NULL] at the end. So my app dev team is unable to parse the JSON.

What i am doing wrong ? What may be the possible causes for this ?

I think it happens with my custom module only.
But i am sure i am using  drupal_json_output with sufficient parameters.

I have posted this question a few weeks ago, but my app dev tem fixed it. Now i am facing it again. Any help ?

/**
 * Implementation of hook_services_resources().
 */
function noteresource_services_resources() {
  return array(
    'gymcam' => array(
      'actions' => array(
        'sendmail' => array(
          'help' => 'Send gymcam to admin',
          'callback' => 'gymcam_sendemail',
          'access callback' => 'gymcam_resource_access',
          'access arguments' => array('sendmail'),
          'access arguments append' => TRUE,
          'args' => array(
            array(
              'name' => 'uid',
              'type' => 'int',
              'description' => 'The uid of the logged in user',
              'source' => 'data',
              'optional' => TRUE,
              ),
          ),
        ),
      ),
    ),
  );
}

function gymcam_sendemail($data) {
  $data = array('status' => 'error', 'msg' => 'Mail not sent');
  drupal_json_output($data);
}

I dont know why do you need to convert the data to JSON format. My idea is that you just return an array. The returned data of your custom service will be based on how we call it.

function gymcam_sendemail($data) {
  $data = array('status' => 'error', 'msg' => 'Mail not sent');
  return $data;
}

If you want to use JSON for returned data, just call /gymcam/sendmail.json


How to configure my local Drupal site to contact my local Apache Solr server? I installed Apache Solr server on my local machine and installed the Apache Solr Search module on my Drupal 7 site. When I configure the module and click submit an error message appears:

  Your site was unable to contact the Apache Solr server.

But when I go to http://localhost:8983/solr/#/ my Solr admin opens.

You haven't added any cores to Solr and you need to add at least one core and adjust the connection properties.

You will probably need the Solr 7 config from Search API Solr Search, as Apache Solr Search only has config for 5.x. The commands you need to run are: (replace CORE with the actual name)

cd /opt/solr/server/solr
sudo mkdir -p CORE/conf
sudo cp -R search_api_solr/solr-conf/7.x/* CORE/conf
cd /opt/solr
sudo -u solr ./bin/solr create -c CORE -d server/solr/CORE/conf

This should take the config files and create a core with those files. Then adjust your connection to http://localhost:8983/solr/CORE


Alter menu item markup in Drupal 8 I am trying to play around with Drupal 8 menu. How I understand now menu is a service, so how to alter menu output in Drupal 8? Is there any documentation? Because googling show no useful results.

What I am trying to achieve is move active class from <a> element to parent <li> element, this should be possible to do in .twig template (I wouldn't like that) so how to get menu in Drupal 8 and alter it's attributes?

There is one central problem: the active class is not always added in PHP, but
for non-anonymous users its calculated using some javascript, see "active-link.js".
For anonymous users, its calculated in
\Drupal\system\Controller\SystemController::setLinkActiveClass


Error in executing drush command I am trying to execute drush command from my project root directory and i am getting following error

bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See drush topic docs-aliases for
details.
 * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell.

This message occurs with a working site if the site settings.php file is not in the sites/default directory but a sites/example.com directory. In that case to specify the uri of the site you wish to address you use the syntax

drush --uri=example.com [command]


drupal on postgresql vs mysql vs mariadb Anybody using PostgreSQL with Drupal? I know MySQL is preferred for Drupal but I have an existing PostgreSQL instance running on the server. I might as well use it rather than use more resources by running MySQL (MariaDB) unless there are major drawbacks in using PostgreSQL.

So, how does running Drupal on MySQL compare to Drupal on PostgreSQL?

Also, are there differences between running Drupal on Oracle's MySQL vs MariaDB?

The occasional issue you can hit, is that a contrib module is either just badly written because the author didn't know better, or, more rare, deliberately used mysql specific functionality for some reason, meaning that the module simply won't work on your site.

I've only had this on a single occasion though, and it caused issues during installation. A quick hack of the modules install file, and everything worked out well from there on.

It's unlikely to be much of an issue, and I'm myself running some personal things on postgresql just get familiar with it.

Drupal doesn't care if you use mysql or mariadb. They're the same thing to Drupal.


Which access control module will allow me to use limit visibility of individual nodes? There are a ton of Access control modules. Choosing one is difficult. The current use case is that I have a single video content type. Some videos are public and some are private that are only accessible by role. I want to be able to set each node (public or private) and then ensure that they do not show in taxonomy term pages and views pages unless they are logged in. Which module is best for this use case? Note that the term and view pages will be the shared but I need private ones to automatically removed if they are not logged in. Which access control module will meet these needs?

BAM!
Taxonomy Access Control to the rescue.
Access control for user roles based on taxonomy categories (vocabulary, terms).

Automatically controls access to nodes (based on their taxonomy
terms).

Configuration page for each user role.
Three node access permission types: View, Update, Delete.
Two term access types: View tag, Add tag.

Just create a term called something like "Members only" and add that term reference to your video content types.


Access description field for file in a view Gents, I have two fields that accept multiple file uploads.  One of those fields has file descriptions enabled.  I need to access those field descriptions in my view, but I don't see the file description field popping up in the list of available file fields.

I've added the relationship fid for the field that has multiple files associated with it.

So, I'm confused as to how I'm supposed to get the file description view exposed.  How do I do so?

Let me know if I need to clarify further.

You can get the file description to display by adding your file field (just as Content: fieldname), then choosing to 'Rewrite Results'. For the Replacement Text, there is an option to use [field_fieldname-description].

Reference: http://drupal.org/node/1128270#comment-5253600


Disable Taxonomy Generated Teaser List Pages I have a site that uses the Taxonomy module to categorize content. The vocabularies and terms are used as arguments and filters in various Views. I do not want the Taxonomy module to generate its own pages at URLs like "/taxonomy/term/1,2" . Is there an easy way to disable this functionality?

Just install the Views module and enable the Taxonomy Term View. This will give the option to set the access permissions to Authenticated or Administer or any role or permission, preventing the page from being viewed by the public or robots.

PS: if you are not using Views, you have not yet discovered Drupal.


Base table missing on Database Restore Problem

I just tried to revert to a recent backup and got a very strange error.

Wiped database.
Deleted drupal base folder.
Copied in new Drupal folder (from backup).
Ran install.php

Re-installing was successful (except for the failure to send an email), but on loading the site I got the following error:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mysite2.languages' doesn't exist: SELECT * FROM {languages} ORDER BY weight ASC, name ASC; Array ( ) in language_list() (line 2727 of /srv/www/mysite2/public/includes/bootstrap.inc).

Any idea what could've caused this?

My Thoughts

I've not restored the the database yet so I don't quite understand what could cause this? None of the modules that I have in my build should begin enabled after a basic install.

But it does seem as if some part of my folders or modules are interfering with a basic drupal install, calling something which doesn't exist yet and blocking me. Even though they shouldn't be enabled.

Solved by Clive. I had memcached running. It had stored chunks of the code from my original site and tried to run them on the new version. Clearing or restarting memcached solved the problem.

Edit:

An overly simplified explanation of memcached for anyone who's unsure what I'm talking about.

Memcached caches chunks of code. It's best illustrated by a contrast. Varnish caches a static picture of a page and sends that to people when it's requested. It will bypass PHP processing completely.

Memcached won't stop the processing for the page happening each time, but it will remember chunks of the processing and deliver the result straight from the cache.

When I wiped my server and reverted to a backup I forgot to restart memcached. This means that memcached had still remembered chunks of my PHP code. This code didn't fit in with the older revert of my website so I got a horrible error. Restarting memcached or flushing the memcached cache will solve this.


Localisation of node published date I have a Drupal site and the standard language is Danish. However the date on the nodes is rendered in English. I can't figure out why.

If i put a date field in a content type it displays correctly following my custom date format.

Any suggestions on how to solve this?

Drupal provides a clean way of formatting dates any way you want throughout the entire site. Simply apply the settings that you're expecting for Danish:

Format dates in Drupal 6


How a module can override theme suggestion? Basically it was How to tell Drupal to look for templates in module directory? but I'll reword it, as I don't want to define a new theme (reason was already given).

What I want to do: in my module I have a file node--attach.tpl.php which is a modifed version of node.tpl.php. Now I want that, if view_mode = 'attach' then this file is used. Also, theme should be allowed to override it with its own node--attach.tpl.php in theme folder.

This code works for me:

function MYMODULE_theme_registry_alter(&$theme_registry) {
  $mod_path = drupal_get_path('module', 'MYMODULE');

  $theme_registry_copy = $theme_registry;       // munge on a copy
  _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', 'pow', $mod_path);
  $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);

  $hooks = array('node');
  foreach ($hooks as $h) {
    if (!isset($theme_registry[$h]['theme paths'])) {
      $theme_registry[$h]['theme paths'] = array();
    }
    _MYMODULE_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
  }
}

function _MYMODULE_insert_after_first_element(&$a, $element) {
  if(is_array($a)) {
    $first_element = array_shift($a);
    if ($first_element) {
      array_unshift($a, $first_element, $element);
    }
    else {
      array_unshift($a, $element);
    }
  }
}

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['view_mode'] == 'attach') {
    $vars['theme_hook_suggestions'][] = 'node__attach';
  }
}

I know you've seen nearly that exact code before from looking at your other question, but there are a couple of changes from the code in the article. It should work after clearing the caches (just once!)

Using the above I added a file called node--attach.tpl.php to my module folder, cleared the caches again, and the output from that template file was shown for the node.

Then I added node--attach.tpl.php to my theme folder, cleared the caches again, and the output from the new template file was shown.


How to add content to a main page First Drupal site. I have a custom content type of 'books' which I want to add to the 'books' basic page. I literally have no clue how to do this, or what is the best 'Drupal' way of doing this.

The default Drupal setup is to display a list of all nodes that have their "promoted to front page" box checked.

If you want to display a single node rather than that list, you can create that page and then change the default front page in admin/configuration/site-information by pasting in that page's path to the front page field.

If you would like to display a list that is different from the default list, (like, you want to add filters or display fields or something) then you can install and use Views to override the default or to create a new page and set it as the main page in site-information settings as described.


How to show a Views attachment in other region or create a block acting as attachment? I have a view with two displays: page and attachment. The exposed filters are the same for both the displays, and I used the Inherit exposed filters in the attachment settings.

I want to put the attachment in a specific theme region. How can I print the attachment in a different region?

The "pink" box is the attachment, which contains a Leaflet map. The user can select either one of the filters and see the results in the box map and the page below (node1, node2, node3, ...).

This is a screenshot of the view page as it is now.

Either of these solutions could work for me:

Be able to display the attachment display in another region, then the
page display under it
Have a block that functions in the same way as an attachment and
inherits all exposed and contextual filters in the way an attachment
would do

I tried to use views_embed_view() in a custom PHP block. The block shows correctly the attachment, but the filter doesn't work with the new block.

$view_name = 'indoor';
$display_id = 'attachment_1';
print views_embed_view($view_name, $display_id);

I think the problem is the AJAX parameter view_dom_id passed to the block.

This is what i want:

At moment I fixed with contextual filter query by disabling the ajax and get query from URL. This way I can use separated block for the map.


Custom block template doesn't print content I have custom block template built based on Drupal 7 examples, but it always returns empty content for me:

<?= $block->title; ?>

<?= $block->content; ?>

Though when I call it from my page.tpl.php it works well:

$block = block_load('block', '1');
    $output =     drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
    print $output;

I just need to control where I output the title and content, having my own HTML layout for them.

Please assist.

THanks

Avoid short tags as not all servers support them.

Use:

<?php print $block->content; ?>

Instead of:

<?= $block->content; ?>

Also in block.tpl.php I would expect to see <?php print $content; ?> instead of $block->content.


Responsive Grid View appearing in single column I'm trying to create a responsive views grid. I installed the the Views Responsive Grid module. The problem is when I select that option the images appear in a single column instead of appearing in the specified columns. How do I fix this?

You need to apply some css rules to the output. Basically, assuming each div of the grid has a views-content class, give that class a float:left and some margin. Or if you use a responsive theme already, set the correct classes to the output in Views UI...

As per the Views Responsive Grid:

  In order for the columns to work you'll need to specify the class name
  of your columns. For example, if your theme utilizes a grid, like
  Twitter Bootstrap does, you would specify "span3" as the column
  class(making sure to use the correct span size). This will make sure
  your column adhere to the grid in your Bootstrap based theme.


Tokens for multi-valued fields? In D7, it seems the token for fields (e.g., [node:field_date]) just returns the rendering of the field. So if the field is multi-valued, this token returns all the values rendered together. However, I'd like to be able to access specific delta values of the field separately using tokens, e.g. using [node:field_date:0] or similar syntax. I also want to be able to chain the token, e.g. [node:field_date:0:long].

Has this been done before? My solution would be to use hook_token_info_alter to mark the field's token as dynamic, then do my own parsing in hook_tokens_alter. But if I do this, will I lose the ability to chain the token?

Have you tried Entity Tokens? It's part of Entity API module.

There are long discussions about date tokens: Date issue about date tokens and Entity Token issue about multi-value field tokens.


Creating a node via REST - Entity reference field value not updating I'm trying to create a node on a Drupal 8 site via REST. Passing all the values to create the fields work fine apart from the field that is an entity reference field. The field is an entity reference to Drupal users. Drupal creates the node, there is no validations errors, but the entity reference field has no value. I've tried changing 'target_id' to 'value', same thing, the node gets created without errors but no value is given to the user entity reference field.

Any ideas?

$serialized_entity = json_encode([
    'title' => array(
      'value' => 'some_title',
    ),
    'type' => array(
      'target_id' => 'node_type',
    ),
    '_links' => array(
      'type' => array(
        'href' => $base_url . '/rest/type/node/node_type',
      ),
    ),
    'entity_reference_field' => array(
      'target_id' => $entity_id, // This does not work. Using a valid uid.
    ),
    'normal_field' => array(
      'value' => 'some_data',
    ),
]);

I managed to get working by changing this...

'entity_reference_field' => array(
  'target_id' => $entity_id,
),

to this...

'entity_reference_field' => array(
  array('target_id' => $entity_id),
),

I also had to disable using an entity reference view as the 'Reference type' on the field and just have the option as 'Default'. Not sure if this is a bug or if there's something wrong with my entity reference view.


How can you prepopulate a field based on another field's value? this one was easy in Drupal 7. I defined a condition "If field A has value B, then field X will automatically get value Y".

How can I get this working for a Drupal 8 webform?

FYI, the module maintainer will send you here if you enter a support question - he will not answer it in the issue queue.


How to use content type tokens File path in file and image field? I want to have one field for header images, but sort them by type of content. Sadly, when I try to do that, I get:

  The File directory is using the following invalid tokens: [content-type:machine-name].

there is no "avaliable tokens" link under File path box, but when I click generic one, I get:

Current date - Tokens related to the current date and time.
Current page - Tokens related to the current page request.
Current user - Tokens related to the currently logged in user.
Random - Tokens related to random data.
Site information - Tokens for site-wide settings and other global information.
Variables - Tokens for variable values.

Now, I can add Node to the list with File (Field) Paths, but that's overkill. I want more basic thing - content type or more generic bundle tokens. And they are not provided. Is there something I'm missing?

One way to do it, is to use File (Field) Paths, as node provides content type "subtokens" like:

[node:content-type:machine-name]

Problem with any other implementation will be caused by the fact that fields can be attached to things that does not have content types.

This answer is limited to nodes, so it's only a partial one, but it will do the trick in many cases.


Apache Solr integration on shared hosting with cpanel If I do not have any other access to my site's remote server other than file manager via CPanel, is there a way I can get Apache Solr up and running on my Drupal 7 site? The remote host does not provide me with shell access. Does anyone know a tutorial link for this?

No, in this case, you cannot do put Apache Solr on your server.  I just had a client who had the same problem. You have 2 options:

Setup a second server that has shell access, and will index you site for you
Use someone else's preconfigured Apache Solr already, such as Acquia Search (not free)