How to get the base url? (Drupal 7.22)
We need to create a menu link to an external site, "https://example.com/some/path"
/some/path is static, whereas "https://example.com" depends on site instance, such as

web-dev.example.com

web-qa.exmple.com

web-rc.example.com

I would think that this could be accomplished with $GLOBALS['base_root'];
for example:
$url = $GLOBALS['base_root'] . '/some/path';

On local (laptop) $GLOBALS['base_root'] resolves correctly, but on CentoOS
$GLOBALS['base_root'] resolves to [http://default]

How do we dynamically get the actual current site domain?
This can't be so hard, what are we missing?

If this is a fully bootstrapped Drupal site, the superglobal $base_url, should get you what you want. See: https://api.drupal.org/api/drupal/developer!globals.php/global/base_url/7

However, these globals are not initialized until Drupal is fully bootstrapped.

If you need to sniff the base URL before Drupal is fully bootstrapped you can use the PHP $_SERVER superglobal.

For example:

function _get_base_url(){
  $protocol = ($_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != "off")) ? "https" : "http";
  return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}


Theme settings doesn't work When i dpm that $vars, in classes key, there is no r_style class, whyyyy? I tried clear cache through devel module, but still the same, what i am doing wrong?

name = JH Template
core = 7.x
engine = phptemplate

styles[all][] = css/style.css
settings[bg_style] = 'r_style'

theme-settings.php

function jh_process_html(&$vars) {
    $vars['classes'] .= ' ' . theme_get_setting('bg_style');
    dpm($vars); // in classes string isn't r_style class
}

EDIT: the real question is, why theme_get_setting('bg_style') returns NULL

SOLVED: that jh_process_html function must be in template.php file, but i don't understand that drupal :D, because that function was executed even in if it was in theme-settings.php, but actually just sometimes and it causes some fails like that theme_get_setting returned null. I don't know why this happened, but it's really funny after so many years of development of drupal, this magic happened.

Try this...

function jh_preprocess_html(&$vars) {
$vars['classes_array'][] = theme_get_setting('bg_style');
}

You need to do this at an earlier stage of the processing.


Combine fields – images and text I want to have content type tutorial, with descriptions step by step, consisting of text paragraphs and pictures as an explanation (like clickable thumbnails or just picture).

I know how to add field like text text and image, add set a possibility of make it's number unlimited. But how allow user to arrange order of pictures and text?

Example:

TITLE of PAGE

PARAGRAPH 1

PICTURE 1

PARAGRAPH 2

PICTURE 2

PICTURE 3

PARAGRAPH 3

PARAGRAPH 4

You can use field collection it allow you to make a subform inside a form so you can add more than subform and arrange them


Remove library from page based on node field value We have a content type, Basic Page, where we may want to include 3rd party CSS such as Bootstrap. However, this 3rd party CSS may conflict with our custom theme, mytheme. On the Basic Page, we added a custom field of type Boolean, field_include_css, that a content editor can set to true if they want to use the Bootstrap CSS instead of mytheme.

How would we remove all the libraries added to the page that come from mytheme?

Here is what we tried, but did not work.

function mytheme_preprocess_page(&$variables) {
  $node = $variables['node']'
  // Basic page's machine name is page.
  if(is_object($node) && $node->getType() == 'page' && $node->field_include_css->value == '1') {
    unset($variables['page']['#attached']['library']);

    // above line didn't work so we also tried these, but they failed too.
    $variables['page']['#attached']['library'] = '';
    $variables['#attached']['library'] = '';
    unset($variables['#attached']['library']);
  }
}

Drupal has dedicated theme hook, hook_page_attachments_alter, for this scenario. Your theme can hook into it, check the rendered route (for your node type), and take action on the $page['#attached']['library'] render array accordingly:

function MYTHEME_page_attachments_alter(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if (!is_null($node) && $node->getType() == 'page') {
    //@TODO: remove the appropriate library items from $page['#attached']['library']
  }
}


How do I automatically add links on the right sidebar in drupal 7? Let's say I have a few articles about weight training. How do I populate the right sidebar blocks with related links to current article?

I've just implemented related content using views following this tutorial. If you prefer using a module you got even more choices.


Why JS doesn't work on a saved page? I've tried to save /admin/structure/block page and open it with Firefox 14.0.1. After this I cannot drag blocks. Why is that? There are no errors in the console. How should I debug such behavior? I need this to better understand why doesn't Drupal work for JS-loaded content. The symptoms look similar.

The Drupal's jquery.once.js is to blame. Deleting every *-processed class worked.


Can I remove the experimental module warning from /admin/reports/status? My drupal 8 site is showing a experimental modules enabled warning under /admin/reports/status. I vaguely remember to have them enabled at a certain time, but I forgot where.

I don't use any of them, how can I remove the warning and disable the experimental modules again?

I have currently no experimental module enabled, but the warning is still displayed:

There is an experimental module that it's not shown on the screenshot given in the question: the Place Blocks module. Its .info.yml file is the following one, on Drupal 8.7.x.

name: Place Blocks
type: module
description: 'Allow administrators to place blocks from any Drupal page'
package: Core (Experimental)
version: VERSION
core: 8.x
hidden: true
dependencies:
  - drupal:block

Since it contains the hidden: true line, it isn't shown in the list of available/installed modules, in the same way modules used for the tests aren't shown.

You could ask now how it is possible to install a module that isn't shown in the list of the modules. The answer is that on Drupal 8.3.x, the module was not hidden.

name: Place Blocks
type: module
description: 'Allow administrators to place blocks from any Drupal page'
package: Core (Experimental)
version: VERSION
core: 8.x
dependencies:
  - block

Drupal 8.4.x was the first Drupal 8 branch to hide it.

As for uninstalling it, you need to edit the core/modules/block_place/block_place.info.yml file, remove the hidden: true line, or change it to hidden: false, clear the cache, visit the Extend page, and uninstall it. Be careful of not changing the line indentation for that file, as a wrong indentation can cause issues.
Since it requires to edit a module file, it could be tricky to make Drupal notice the change. I normally visit the Extend page after I edited a module file as in this case, install a core module I don't need, uninstall it, visit another page, and go back to the Extend page. At this point, I am sure Drupal caught the change I done to the module file.


Search template page in Drupal 7 In search results page,

the search form and search results are in the content area.

Can we insert another block between the search form and results list? Or adjust the order for example put "spelling-suggestions" on the top of the form, then add another block between the form and search extra provided by display suite.

If without existing templates, guessing we will have to modify the $node['content'].

Any ideas are welcome, thanks

<form id="search-form" class="search-form" accept-charset="UTF-8" method="post" action="/search/all/test">

One result

My current method is dirty:

  $build['search_form_resort'] = $build['search_form'];
  unset($build['search_form']);

Then put the $build['search_form_resort'] under the $build['suggestions'].

Read more:
http://api.drupal.org/api/drupal/modules%21search%21search.pages.inc/function/search_view/7


Is there any way to view dpm() data other than printing it on page? I have an issue with dpm() in that it never seems to return data (and before anyone asks:

Yes devel is installed
Yes I am logged in as admin
Yes print $messages is set
Yes the permissions are correctly set
No the data set is not empty ( dpm($node) and dpm($content) return an empty field)
Yes it did work previously / on ocassion

it does return a message field, but it is just empty).

Is there any other way to view dpm() data, like using Drush or something? I know I should really 'fix the dpm issue' but I have asked around and there does not seem to be an answer.

I know you say you are logged in as admin but even so just check the permission "Access developer information" is checked for the admin role just in case that makes a difference.

I've also heard of dpm not working as a result of modules not being uninstalled before they are deleted. Maybe try this module to see if that helps.

Another option would be to see if kpr() works instead.


Display field content in views single field template.. STUCK! Welcome,

I'm working with Hero slider and views to display slider from nodes in custom type. Where I am now, is:

created node type with fields like title, content, picture and background picture,
created views for dysplay this content, hide all fields, last one is background field, in this field i wrote rewrite twig code do dysplay all fields with some if function to choose prefered slide type and display content right way in every slide,
what I need is make wrap around every li element with slide content, because views filter out  markup, and I can't get slide with responsive background.. life would so much easier with that filter go away.
I work with views-view-field--slider.html.twig that is displayed correct from my template.
I cant display my link to image for background in code:

{{ output -}}

I feel lost with data = row[field.field_alias] tried kint, dump and a lot of various combination of twig code.. looks like I am missing some basics or simple target code to this field. Help me..

Ok, so how I solved it... Maybe there is other, better solution?

I rearrangement my fields in view: first with content, title, pictures and links,
I've added one more custom text field with rewrite - then I put in this rewrtite all fields above with some twig function to display this in different ways and hide this field to.
Then I've added  last field, field_background which is one with slide background picture. I turn it to display just URL of picture and write rewrite inside to display:

{{ field_background }}  )">  {{ nothing }}

wher nothing is my field with all content stuf inside.

I've edited twig template for last field and write something like this:

<.div style="background-image: url( {{ output }}

so when views start rendering content it create code from my last field which is wrapprer with background image around content form other fields above.

Well, it's work, my slides run with background picture. But I dont fell good with that, I think there is better way to get it in one field.


Drupal 7 ubercart roles assignment ineffectual Nothing happens when I test in the sandbox with paypal standards payment and everything set up through ubercart for recurring subscriptions and feature added role assignment, when I edit product subscription roles assign on purchase to go to certain role and the payment goes through the sandbox I get redirected back to site but the role has not changed to reflect the purchase. What am I missing here?

In case this happens to anyone else, when using the sandbox if configured so output becomes payment pending, role assignments will logically not work.

You just need to login to your developer paypal site and click on the test account you are using in settings and switch payment review to off.


How do I add column to existing table on module installation? I want to add an extra field to the users table from a custom module. I am not sure how exactly can it be done. I'm sure it is done in mymodule.install file.
Should I use db_add_field, or is there any other way? And where should I implement it? hook_schema (but the schema is already defined), or hook_install?

For the sake of giving a (hopefully) complete answer:

You will need to alter the schema of an existing module, signalling the change to the system. So implement hook_schema_alter().
You will need to implement hook_install() to actually add the field to the database.
You will need to implement hook_uninstall() as well, to remove the extra field when the module is uninstalled. You might need to do extra cleanup at this stage.

An example which alters the Webform module's webform_submitted_data table:

function MYMODULE_schema_alter(&$schema) {
  $schema['webform_submitted_data']['fields']['extra'] = array(
    'description' => 'Some random extra info.',
    'type' => 'text',
    'size' => 'big',
  );
}

function MYMODULE_install() {
  db_add_field('webform_submitted_data', 'extra', array(
    'description' => 'Some random extra info.',
    'type' => 'text',
    'size' => 'big',
  ));
}

function MYMODULE_uninstall() {
  db_drop_field('webform_submitted_data', 'extra');
}


What are the major differences between Views Datasource and Views data export? I'd like to create dynamic XML feed export using View based on my content type nodes.

There are two huge modules: Views Datasource (17k usage) and Views data export (67k usage) which sounds pretty similar.

On Views data export homepage we can read that:

  Views Datasource allows exporting to XML/JSON among many others, but is geared towards small exports.

Does it mean Views Datasource should be used only for small exports?

In other words, what are the main differences between these two modules? And what are the preferred ways (use cases) of using one over another?

Views Datasource can be thought as providing a view format that takes over the whole page; each submodule you enabled (JSON/RDF/XHTML/XML) provides a format that it outputs the view as a specified document type without your site theme.

Views Data Export can be thought of providing an attached exportable format of some complementary view format (e.g. a Page view formatted as a table that as an exportable CSV file); when enabled, it provides a new view display that you can make available at a specified path and attached to existing view as a button which can be configured to be a downloadable attachment.

There is some overlap (e.g. both could be used to produce an XML-producing custom path), but only Views Datasource provides a JSON (unless you use some other contrib module), while Views Data Export has other options (e.g. batching support) that make it better suited for large data exports.


Field shows nulls as zeros I defined the hook_views_data in order to display some data from a custom table in the database. One field is a nullable decimal(5,1). The value of this field is displayed correctly in the view but shows nulls as 0.0. "No results behavior" seems to have no effect on it in any way. The field is defined as follows:

$data['customview']['value'] = array(
        'title' => t('value'),
        'help' => t('the requested value'),
        'field' => array(
            'handler' => 'views_handler_field_numeric',
        ),
        'sort' => array(
            'handler' => 'views_handler_sort',
        ),
        'filter' => array(
            'handler' => 'views_handler_filter_numeric',
        ),
    );

Using PHPMyAdmin, I can verify that the values are null. Any custom properties I should add to the definition of the field in order to allow nulls (Display them as empty or dash)?

There are some issues in the views queue that can help out with fixing these issues. This issue is very similar to the issue you are having (Empty rounded numeric fields not hidden properly). It has a patch that should fix the issue that has been reviewed and tested by the community but has not made it into dev yet. You could either patch views or write your own numeric views handler to fix this issue.


Is there any way to use a jQuery overlay to confirm/reject node deletion? When I delete a node (any type of node, presumably), I'd like to have the confirmation happen through a jQuery-like yes/no dialog popping up over the page, rather than being redirected to a separate page with the "This action cannot be undone" message.  This being the 21st century and all...

http://bootboxjs.com/ would seem to be a good candidate for handling the dialogs, but the question is how to tie it into the form and node deletion processes, ideally without hacking core and/or patching everything in site.  Has anybody thought this through?

You might be able to do that with:

https://drupal.org/project/ctools_automodal_admin

  Provides automatic modal support for any hook_menu() paths that have
  'modal' => TRUE defined. This makes it easy to add optional modal
  support in any contrib module and helps reduce the burden on module
  developers to support modals.

If you added the node delete path, perhaps node/%node/delete to the modal paths, it may just work.


SimpleTest: How to make multiple Ajax posts and then save the data? I have a form with AJAX buttons that add items to a list. To SimpleTest the form, I need to make the AJAX post:

$this->drupalPostAJAX(NULL, $edit, array('op' => 'Add Item Button'));

...then POST the resulting $edit object with the Save button.

$this->drupalPost('admin/structure/fms_report/create', $edit, t('Save'));

My question is, how do I get the resulting $edit object after the first AJAX POST happens?

On subsequent tests of a form that has already been loaded and posted, this call will submit the form to the same URL with the field values resulting from any previous activity:

$this->drupalPost(NULL, NULL, t('Save'));

The $edit argument is only to submit new field values. And, passing NULL for $path uses the currently loaded page. So, to test my AJAX button that adds items to the form:

$this->drupalGet('path/to/my/form');
$this->drupalPostAJAX(NULL, NULL, array('op' => 'Add Item Button'));
$this->drupalPostAJAX(NULL, NULL, array('op' => 'Add Item Button'));
$this->drupalPost(NULL, NULL, t('Save'));

I was able to verify after this that two items had been added to the form as expected.


How do I invoke web services? I am working on a site, and I want to integrate my site with an external site; for that, I need to use web services to get data from the external server. I don't know the technology used by the server.

I have to work as client. Can any one please tell me hoe to call web services from my site? Please write any code if it is required. Will drupal_http_request() help me?

I am using Drupal 6.

You should have a look at the Services module. You can use XMLRPC and/or REST server (and many more) to communicate with your remote server. Link to the documentation.

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.


Create template suggestion for item-list.html.twig I have to change the markup and I have to add CSS classes to themes/classy/templates/dataset/item-list.html.twig. But only for a specific item-list.html.twig in a specific block.

How do I create a preprocess function, which create a template suggestion for this item-list.html.twig? So I am able to use e.g. item-list-facets.html.twig?

I think it's better to use hook__theme_suggestions_HOOK_alter:

Something like this:

 /**
 * Implements hook__theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_item_list_alter(&$suggestions, $variables) {
  $suggestions[] = 'item_list__' . str_replace('-','_',$variables["attributes"]["id"]);
}

Just make sure that in your suggestions name you use _ instead of -, otherwise you will get suggestions in the debug, but Drupal won't use it.


Is Search API module 'English-speaking' only? I am developing a multilingual (English-Ukrainian) Drupal website using Entity translation module. Everything went smooth before I tried to use the search module. I have Search API, Database search, Search API Entity Translation and Search API Entity Translation Database Search enabled and configured.

As far as I understand, only the English version of content is being indexed. All search queries in Ukrainian have zero results.

As an experiment I added some English words to the page in Ukrainian and used them as search terms. To my surprise, the page containing these words immediately appeared in search results. Furthermore, when performing the same seach from the English version, the English version of the Ukrainian-language page containing these keywords was retrieved (there are no such keywords in English version).

Is it possible for Drupal search to index content in Ukrainian (or other cyrillic language)? Are there any guidelines or tutorials how to acheieve this in multilingual environment organized with Entity translation?

UPDATE:

Continue experiments.  I have three nodes, all of them translated. After disabling "Search API Entity Translation Database Search" module the situation changed. Two of nodes have their Ukrainian versions indexed only, the third one has only English version indexed. I have re-indexed the website several times. All three nodes and their translations are similar.

You;d need to use the Search API Entity Translation module to have this work as expected.

Going further if you wanted more control of the system and were using Database based indexes you would also want to install Search API Entity Translation Database Search


Display node in user profile page I created a content type called successful story.

In user profile page user-profile.tpl.php, I have inserted a link to create a successful story

<?php print l(t('Add a successful story'), "node/add/successful-story"); ?>

For example, an user called user1 clicks on the link, and creates a successful story.
I want to display the successful story the user created into their respective profile page

I add this code into template.php

<?php

function mytheme_preprocess_page(&$variables, $hook) {
  global $user;
  $uid = $user->uid;
  $nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful story'))->fetchCol();
  $variables['ss_node'] = drupal_render(node_view(node_load($nid)));
}

?>

Then I add this code into user-profile.tpl.php

<?php

  global $user;
  $user_id = arg(1);

print $ss_node;

?>

I hope I'm clear. Thanks for your help !

It won't be available directly in the template. First you should query the content created by that user and then pass it to template file using preprocess function. Finally render the node.

First to find the node created by the user

$nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful_story'))->fetchCol();

(Hope the user creates only one node or else you got to check it)

Then get the node content

$variables['ss_node'] = drupal_render(node_view(node_load($nid)));

The final code should be like

function template_preprocess_page(&$variables, $hook) {
  global $user;
  $uid = $user->uid;
  $nid = db_query("SELECT nid FROM {node} WHERE uid = :uid AND type = :type", array(":uid" => $uid, ":type" => 'successful_story'))->fetchCol();
  $variables['ss_node'] = drupal_render(node_view(node_load($nid)));
}

Finally you can just print the $ss_node in user-profile.tpl.php


"Can't create table errno: -1" when trying to create the cache_rules table on D7 I'm having a very strange problem.  I have a website on Pantheon (Nginx) that I attempting to import into my local dev environment, but when I import, it is failing when it gets to the cache_rules table.  So I dropped the cache_rules table on the server DB, dumped the DB, and imported it, and then tried to re-create the cache_rules table with the following command:

CREATE TABLE IF NOT EXISTS `cache_rules` (
  `cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.',
  `data` longblob COMMENT 'A collection of data to cache.',
  `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
  `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.',
  `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).',
  PRIMARY KEY (`cid`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';

which I found here.  I am running the command in phpMyAdmin.

However, when I do that, I get this error message:

"Can't create table errno: -1"

I've attempted to search for this but the explanations suggested that it was usually caused by trying to create a table that had a key that depended on another table that hadn't been created yet, but that is not the case here.

I can run the exact same command above with a different table name (e.g., cache_rules2) and a cache_rules2 table will be created without a problem-- so it's only the specific name cache_rules that is causing this issue, whatever it is.

How can I further debug this to figure out why it suddenly doesn't want to create a cache_rules table?

When importing/exporting databases from/to Drupal try using Backup & Migrate as this only attempts to backup the structure of the cache tables rather than the data too.


Set users password in code? I would like to be able to change a users password in code.

Since user_load returns an object, and user_save wants an array, this is non-trivial.

I assume someone has figured out a quick and easy way to do it.

My current solution looks like:

db_update('users')
  ->fields(array('pass' => user_hash_password('some_password')))
  ->condition('uid', 1)
  ->execute();

But I don't like that this bypasses most hooks.

You just need to call user_save() using code similar to the following one.

$edit['pass'] = 'New password';
user_save($account, $edit);

$account contains the user object for the user account to alter. I get you load it using user_load(), but it could also be the user object for the currently logged in user. In the latter case, Drupal will regenerate the session using the following code (part of user_save()).

  // If the password changed, delete all open sessions and recreate
  // the current one.
  if ($account->pass != $account->original->pass) {
    drupal_session_destroy_uid($account->uid);
    if ($account->uid == $GLOBALS['user']->uid) {
      drupal_session_regenerate();
    }
  }

The password in $edit['pass'] is the plain password. user_save() will replace it with its hash using the following code (at the beginning of the function).

if (!empty($edit['pass'])) {
  // Allow alternate password hashing schemes.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  $edit['pass'] = user_hash_password(trim($edit['pass']));
  // Abort if the hashing failed and returned FALSE.
  if (!$edit['pass']) {
    return FALSE;
  }
}

As alternative, you could use drupal_submit_form().

$form_state = array();
$form_state['user'] = $account;
$form_state['values']['pass']['pass1'] = 'New password';
$form_state['values']['pass']['pass2'] = 'New password';
$form_state['values']['op'] = t('Save');
drupal_form_submit('user_profile_form', $form_state);

In this way, if you have any module that, for example, validates the password, its code would be executed, and you would get any error code from form_get_errors().


Remove comment link from node teaser I want to remove comment link (actually it is li element) from node teaser view on homepage and term listing. I want ways to do in controller/service or in template or if possible in admin.

I have created links--node.html.twig in my template and place the following code:

{% if links -%}
  {%- if heading -%}
    {%- if heading.level -%}
      <{{ heading.level }}{{ heading.attributes }}>{{ heading.text }}</{{ heading.level }}>
    {%- else -%}

{{ heading.text }}

    {%- endif -%}
  {%- endif -%}

    {%- for key, item in links -%}

        {%- if item.link -%}
          {{ item.link }}
        {%- elseif item.text_attributes -%}
          {{ item.text }}
        {%- else -%}
          {{ item.text }}
        {%- endif -%}

    {%- endfor -%}

{%- endif %}

as here was told. But it did not help my as links go in loop. I could insert if condition. But I do not know variables. I tried dump item from loop but a page was loading without the end. I do not want to use twig in to search for needed item. Actually I need the right way(s) to remove comment link.  If I can check for key, item in links if item.name != "comment" it could be great. But I prefer do it in code like in proper way without hacks.

Firstly, dirty way. In the template links--node.html.twig change this line {%- for key, item in links -%} to {%- for key, item in links  if key != 'comment-add' and key != 'comment-forbidden' -%}. This is for removing 'comment-add' and 'comment-forbidden' link. If you also want to remove links count apend the line with and key != 'comment-comments'. A simplier way to achieve this is to replace all ifs with if 'comment' not in key. Twig's in.

The second is more right way. The point is in using the hook hook_node_links_alter(doc). This hook alter node links behaviour. There is a core comment module. It realy worth looking if you want to know how node comment works. It requires drupal 8 module knowledge. The service responsible for node comments links is comment.link_builder and defined in core/modules/comment/comment.services.yml. And while observing core/modules/comment/src/CommentLinkBuilder.php you can find that it add different links to render array and all logic. So comment is just a module. So back to hook. It alters node links and add comment links. So you need to remove it again. To do it you can define your own module to create a hook. In module directory you need to create MODULE.module file and place the following code there:

use Drupal\node\NodeInterface;

function kapusta_node_links_alter(array &$links, NodeInterface $node, array &$context) {
  unset($links['comment__comment']);
}

Here nothing special, just implementing hook_node_links_alter. It removes comment link.

The third way is more elegant but need more work. It is based on similar things as the second way. The point is to rewrite the service core/modules/comment/src/CommentLinkBuilder.php. For this you need to define your own module. Then you will create a service with the similar name to CommentLinkBuilder.php. The symfony (framework drupal is using) will rewrite the service from comment module. And you will get your profit. So firsly you duplicate the service. To do this you create MODULE.services.yml in your module folder. The file content is the following:

services:
  comment.link_builder:
    class: Drupal\kapusta\CommentLinkBuilder
    arguments: ['@current_user', '@comment.manager', '@module_handler', '@string_translation', '@entity.manager']

Where do I get this? From core/modules/comment/comment.services.yml. Just replaced class with my own. Then you create that class. You will get the file modules/custom/kapusta/src/CommentLinkBuilder.php with the following content:

<?php

namespace Drupal\kapusta;

use Drupal\comment\CommentLinkBuilder as Base;
use Drupal\Core\Entity\FieldableEntityInterface;

class CommentLinkBuilder extends Base{
  public function buildCommentedEntityLinks(FieldableEntityInterface $entity, array &$context) {
    return [];
  }
}

'kapusta` is my module name. So that's it.

P.S
How I found it. I debugged variables in the twig {%- for key, item in links -%}. I discovered tha value of key in each iteration. It were comment-* keys I wrote about in the beginning. Then I search the project files by comment-add and found CommentLinkBuilder. With xdebug I came to the hook. Then I realize that it is just simple module. Hope this helps.


Programmatically / by Rules, remove reference of a deleted user from contents created by that user. A user [content_editor] got deleted and the content created by this user is referring to anonymous user.  While an administrator is editing that content, administrator is receiving user doesn't exist. The error goes off when we re-assign the content to administrator or an existing user. As the user has created paragraphs, nodes etc how do we track contents created and referred by the user as user id is already deleted?

How can we remove these references and save the content without error message.

I thought we can use Rules API to create a simple rule which will force save any entity if an admin is saving the content, then save the content. But the rules API is providing me only nodes and not entities which means paragraphs will still refer to old deleted user. How can I overcome this. Is there a programmatic solution to this problem?

supposing the content you want to reassign is of node type, here is how to do it programatically (in a hook_update_N() per example or /devel/php or drush ev...)

  $deleted_uid = 42;
  $reassigned_uid = 80;
  // Reassign nodes (current revisions).
  module_load_include('inc', 'node', 'node.admin');
  $nodes = \Drupal::entityQuery('node')
    ->condition('uid', $deleted_uid)
    ->execute();
  node_mass_update($nodes, ['uid' => $reassigned_uid], NULL, TRUE);
  // Reassign old revisions.
  db_update('node_field_revision')
    ->fields(['uid' => $reassigned_uid])
    ->condition('uid', $deleted_uid)
    ->execute();

hope this helps


Programmatically Create 'full_html' Page Node in Drupal 7 So I'm able to create a page programmatically, BUT even though I'm specifying the 'full_html' filter, the page is being created with the 'filtered_html' filter which means that the code I'm writing to the page after it's created is being stripped out.  Here's the line I'm using to set the filter type:

$node->body[$node->language][0]['format'] = 'full_html';

Why is the filter type being ignored when the node is created?

Thanks in advance,
Bryan

OK, as it turns out, the 'body' field is not called 'body' in our Drupal installations; it's called 'field_page_body'. Changing that in the code made everything work.


How to get alter value of a views field programmatically I've developed a Views field plugin that extracts the value from another field in the view in order to apply some math. The plugin works great at getting the original value of the field. However, I would like users to be able to get the rewritten value of a given field. I've been searching around, but can't seem to find any documentation on this.

With the following code I can get the value of another field:

public function getValue(ResultRow $values, $field = NULL) {
  parent::getValue($values, $field);

  $field = $this->options['data_field'];
  $value = $values->_entity->get($field)->value;

  // I have some logic here that's not necessary for this question.

  return $value;
}

What would I need to do within the above function to get the value of $field if $field had been rewritten via someone checking the "Override the output of this field with custom text" checkbox?

This is how I went about getting the "alter" value for my project:

if ($this->displayHandler->getHandler('field', $field)->options['alter']['alter_text'] == 1) {
  $value = $this->displayHandler->getHandler('field', $field)->options['alter']['text'];
}
else {
  $value = $values->_entity->get($field)->value;
}


Why do I get "Command pm-disable needs a higher bootstrap level to run"? Running drush dis varnish in the Drupal directory gives give me this message.

  Command pm-disable needs a higher bootstrap level to run.

Running drush --debug dis varnish -y gives the following output.

  Phar detected. Proceeding to drush_main().
  Loading drushrc "/home/user/.drush/drushrc.php" into "home.drush" scope.     > Cache HIT cid: 8.1.14-commandfiles-0-erased
  Bootstrap to phase 0.
  Bootstrap to phase 6.
  Drush bootstrap phase: bootstrap_drupal_root()
  Initialized Drupal 7.59 root directory at /usr/share/www/Drupal
  Find command files for phase 1 (max=6)
  Cache HIT cid: 8.1.14-commandfiles-1-erased
  Cache HIT cid: 8.1.14-annotationfiles-1-erased
  Drush bootstrap phase: bootstrap_drupal_site()
  Initialized Drupal site default at sites/default
  Find command files for phase 2 (max=6)
  Drush bootstrap phase: bootstrap_drupal_configuration()
  Find command files for phase 3 (max=6)
  sql-query: SELECT 1;
  Executing: mysql --defaults-extra-file=/tmp/drush_erased --database=dune --host=localhost --silent  < /tmp/drush_erased
  sql-query: SHOW TABLES;
  Executing: mysql --defaults-extra-file=/tmp/drush_erased --database=dune --host=localhost --silent  < /tmp/drush_erased
  Bootstrap to phase 1.
  Bootstrap to phase 6.
  Bootstrap to phase 5.
  Command pm-disable needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command.
  The drush command 'dis varnish' could not be executed.

drush status and drush updb work. The output of the first command is the following one.

Drupal version         :  7.59
Site URI               :  http://default
Database driver        :  mysql
Database hostname      :  localhost
Database port          :
Database username      :  drupaluser
Database name          :  dune
PHP configuration      :  /etc/php.ini /home/user/.drush/drush.ini
PHP OS                 :  Linux
Drush script           :  /usr/local/bin/drush
Drush version          :  8.1.14
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :  /home/user/.drush/aliases.drushrc.php
Drupal root            :  /usr/share/www/Drupal
Drupal Settings File   :  sites/default/settings.php
Site path              :  sites/default

This generally means that drush can't identify the site information, e.g. which settings.php to use.

A quick fix is to cd into the directory with the setting.php file for the site.

A more permanent fix is to create a site specific drush alias for the site and use it.  E.g. drush @mysite dis varnish. See this Drupal page.


Advance search between two content types that are linked by entity reference fields I have "linked" 2 content types (Type A and Type B) by a field using the entity reference module.  They are "linked" by the other node's ID number.  For example, the entity reference field would have an input that says: "Select the node ID which is related to this content".  Now I would like to implement a smart search.

For example, if someone searches for Type A, the search should also return the content of Type B that is "linked" to Type A based on that entity reference field.  Can this be done with search or Views?  In quasi-SQL, it would be something like:

"SELECT * FROM TypeA, TypeB WHERE TypeA.field_A=TypeB.nid"

In Views this called "Relationships".

Create view that show "Type A", then in filters add "Type B" to be also allowed.
Then add relation on field that you use for entity reference and made this relation required.

Now "Type B" content will be also displayed in view if related "Type A" is match search criteria.


Content for textgroup views is not allowed for translation because of its text format I have this problem with a view's header. I am allowed to enter a translation but the translated text is not rendered when the view is displayed in that language.
I have the following warning in the Views interface.

content for textgroup views is not allowed for translation because of its text format

I read other posts suggesting to visit Configuration » Regional and language » Multilingual settings and verify the text format is selected. These posts were addressing the problem for blocks and they didn't solve my problem.
Any similar experience or solution?

I had the same problem, then found a solution. I'll show you the details with screenshots.

First enable Internationalization Views (i18nviews).
Create your custom view. For example, I'll simply list the nodes related to Article content type.
Add a header:

Click on "add" next to Header section

Add "Global: Text area"

Type your header text, and select your input format. Please note that I selected "Filtered HTML" here!

Click Apply

After saving the view, you'll see notice, telling that this header text can not be translated, so in my case:
"The string views:list_articles:default:header:views:area:content for textgroup views is not allowed for translation because of its text format."

Go to admin/config/regional/i18n/strings (Home » Administration » Configuration » Regional and language » Multilingual settings » Strings)
Check the appropriate text format you used above, when adding a header text, it must be the same - so in my case, it's "Filtered HTML" -, and then click Save configuration.

Now go back to your custom view, and on the right dropdown menu, click "translate view":

Now you'll see this:

Click on one of the "translate" links. After that, you'll see the following screen, and a message that the appropriate string for the header text translation has been created - which means from now on, you can translate it!

Scroll down to the appropriate header text, and translate it:

After translating, click on "Save translation".
On the following screen, you can see that some translations have been saved.
Now when switching to the other language, you'll see that the header text is translated! You are READY!


Locked out of Drupal 8 site, and new user can't get in I have an odd problem. My new Drupal 8 site is a distro, purchased from ThemeForest. After installing it, I thought I created a new user correctly but maybe the name had disallowed characters. In any case, after logging out for the first time, I can't get back in, even when using the browser-stored un/pw or my stored record. I then created a new user in Drush, elevated it to admin, and still can't get in, saying it doesn't recognize the user. I tried applying for new password, but when I try the link, I get this:

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

So then I thought, maybe I should have set my trusted domains to fix the error in the Status Report. I then edited my settings php to set my domain as trusted, similar to what I did for another Drupal 8 site that is side-by-side in the same public_html folder.

However, one difference is that the site I'm now locked out of is being redirected by htaccess. I had to do this because my hosting service by default wants to put my primary-domain site in the root of public_html, and I wanted it in a subfolder, just like the other sites. So I created this htaccess rule to point the main domain to a particular folder:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.mydomain.com$
RewriteCond %{REQUEST_URI} !folderitresidesin/
RewriteRule (.*) /folderwhereitresides/$1 [L]

Those are the most relevant facts I can think of. Now the question is: does this htaccess redirect affect login?  Do I need to do anything to make sure Drupal understands this htaccess redirect? Or is it something else?

I've looked into the "Drupal\Core\Routing\TrustedRedirectResponse" message but that seems to b aimed at redirecting to external urls. I don't see how that applies to me.

Thanks in advance to any good samaritan who can help!

For a while it seemed that adding localhost to the Trusted Host settings in settings php did some good, then I realized it didn't so I removed it, leaving just the lines below:

$settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';
$settings['trusted_host_patterns'] = array(
'^mydomain\.com$',
'^.+\.mydomain\.com$',
);

I think the Trusted Host settings is critical for several reasons. But then out of the blue I somehow found I can enter the site by logging into

mysite/user/login

Even though it throws the error page with this message:

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.

However I'm actually logged in. All I have to do is append the site folder name to the path then I'm in.

http://www.mysiteurl/sitefolder/

In fact, I can just log in by going to

http://www.mysiteurl/sitefolder/user/login

The sitefolder added to the URL seems to be an alternate url for the entire site. I don't know if that will cause a problem but at least most of my problems are solved for now.

I hope this helps somebody. It seems to result from shared hosting not letting me install my primary site to a subfolder in public_html without making a fancy adjustment in htaccess.


How do I get values of checkboxes? I'm using Drupal 7 and have added checkboxes to a node.

$results = query();

foreach ($results as $result) {
  $name = $result['name'];
  $resultarray[$result['id']] = $name;
}

$form['friends'] = array(
  '#title' => "results",
  '#type' => 'checkboxes',
  '#options' => $resultarray,
);

On my node the checkboxes show.

Now I'm struggling to get the values of selected checkboxes.

function friendmodule_form_submit($form, &$form_state) {

  $friends = $form_state['values']['friends'];

  // do what ever with $friends
}

But nothing displays. I've tried echo $friends, print_r, display them as a Drupal message, but nothing is showing.

What should I do to get the values of selected checkboxes?

Assuming that your $resultarray variable in the form actually has some data in it, this code will get you a list of the ids that have been selected:

function friendmodule_form_submit($form, &$form_state) {
  $friend_ids = array_filter($form_state['values']['friends']);
}

When a checkboxes element is submitted all of the original option keys will be in the $form_state['values']'friends'] array, but only the ones that have been selected will have a positive value; the rest will have a value of zero, so you need to use array_filter() to extract only the IDs for options that have been selected.

Also, at the moment you have a syntax error in your submit function (an extra closing )), maybe that's what is causing the error.


Rendering a content type with Views, in Drupal 7 I have 3 content types and I'd like to render two of them using Views. But there is not option when I can mark this 2 types.
I can mark "show all," "show first type," or "show second type," but I can't choose 2 of 3 types.

How can I do it?

To create a list of two content types in Views you can't set it directly in the 'wizard'. For now just select 'All', at the bottom click 'Continue & Edit'. To only show two content types go down to 'Filter Criteria' and click 'Add'. Find 'Content: Type' in the list and check it, then click 'Add and configure filter criteria'. This will allow you to select the content types you'd like to show. Finally click 'Apply'.


How do I prevent form caching? I have a form using AJAX that will be used by many users at once, authenticated and anonymous users as well.

What precautions should I take to prevent data leaking between users (especially anonymous)?

I disabled the cache on route level via no_cache option. Is that sufficient or should I use \Drupal\Core\Form\FormStateInterface::disableCache() or maybe something else as well?

What precautions should I take to prevent data leaking between users (especially anonymous)?

You shouldn't have to do anything special. not even disable render cache.

Form data is only cached after the first ajax request and then it is for the specific form build Id (which is unique) only. That means that while the form is generated and cached in the page cache, the first request for every request for every user will rebuild the form from scratch.

There used to be a bug in core at some point in 8.x (long before 8.0) where the new user entity including its UUID was cached on the register form and then only one user could register every 6h because the others had UUID conflicts. The form cache changes fixed this.


How do you exclude 'drush' & 'drupal console' requirements from a drupal-composer/drupal-project install? When I create a Drupal project with

composer create-project --keep-vcs drupal-composer/drupal-project:8.x-dev myD8 --stability dev --no-interaction

it installs

Latest version of drush is installed locally for use at vendor/bin/drush.
Latest version of DrupalConsole is installed locally for use at vendor/bin/drupal.

I installed & maintain system instances of drush & drupal console.

I don't need the local installs.  I don't want to install them to disk at all.

How do you configure the 'composer create project ...' to not require/install drush & drupal console?

You can remove these after the fact:

composer remove drush/drush
composer remove drupal/console

However, it is recommended that you should use local installs of Drush and Drupal Console when using Drupal 8. If you use global versions of these tools, then you run the risk of running into dependency hell - incompatibilities between requirements of Drush or Drupal Console that do not align with what is used in Drupal 8.  When you use a global cli tool to bootstrap Drupal 8, then the cli tool will load two autoloaders.  If the same library exists in both autoloaders at different versions -- even just a "dot release" difference -- then you could get into a situation where every command aborts with an unrecoverable error.

If you only maintain a single version of Drupal 8 on your system, and carefully keep the versions of Drush and Drupal Console in alignment with that, then it will typically work, so you may remove the local version if you wish. The diagnostic efforts required when something goes wrong is quite extensive, so be cautious if you make this choice.


Generating Main content nodes based on SQL data (associated with users) This is the first fully fledged website outside of a blog that I've ever configured, so please forgive any glaring errors I make in my logic.

My website is a ranking website: people create a profile for their website with an image, title and description, and users (who have separate 'voter' profiles) vote based on the website they visit. Voter and Websites are distinguished by a field.

All of the other profile details (image, desc ect.) are also stored in fields, and votes are recorded with an SQL table.

My website then displays the image and description of each website, in order of descending number of votes. (a ranking)

This is where I encounter my issue. In order to display these values properly (scrolling through pages) I need to display them as nodes. I have no idea how to generate these nodes.

From what i have understood about the problem you are facing, i believe its advised using the content type for profile as well as the votes. Here is the CCK field to use the vote field.
https://www.drupal.org/project/rate
It would be very easy for you to create view if all fields are part of content types.


Sign up with no price What we need is essentially a free product order. We need viewers to be able to sign up for free classes where there is a limit on the number of students. The registration requirement and the inventory limit indicate that it should be a shopping cart function, but the module that allows for free orders is only available in a Drupal 6 module. Is there such a function for Drupal 7?

Ubercart for D7 has a built in free order payment method so the UC Free Order module isn't needed here. You can configure the conditions under which the payment method is available under the payment method configuration page (Store > Configuration > Payment method).

If you need to limit available purchases, the included UC stock module enables restricting products to a limited quantity of available purchases.


What does it mean "Rebuilding" in a feature? Can it be resolved? I did some changes in my local environment, then I updated the 'feature'.

When I try to deploy the change to another environment, but before I can start the 'revert' operation, some parts of the feature are marked as 'Rebuilding'.

The feature components are:
- Field bases
- Field instances
- Strongarm

Additional details

I cannot use drush in the deployment environment.
This happened once in the past and it resolved itself after clearing the caches.

Drupal's "Features" reflect a status of:

rebuild when rebuilding database for latest code for unoverriden features
revert when rebuilding database for latest code for any state features

Rebuilding updates features that are not deliberately overridden for latest code changes. It works during cache clear but can be slow if there are several features enabled on the site, and if there is a lot to clear in Drupal's caches.

If the server/cache clear and rebuild process are interrupted and freeze up, you may need to reset the lock on the feature state.  See https://www.drupal.org/node/928730

If you find this happens frequently, try increasing the mysql timeout and php memory limits.

You may also want to refer to this troubleshooting post about "overridden" features:  https://www.drupal.org/docs/7/modules/features/troubleshooting-reasons-features-may-be-stuck-as-overridden


Progress of a user on completion of a book Is there a way to show the progress of a user on navigation through a book?

The best solution will show % of pages that user opened/completed in current book.

My approach here would be flagging all the pages of the book and show a overview of total pages / flagged pages.


Is it possible to get rid of content duplicates? I've got a site, mysite.com. Now I'm trying to add blog on it at sub-domain, blog.mysite.com, using the Domain Access module.

When I create an article in blog, with alias blog.mysite.com/article-alias, it is available from main site, by URL mysite.com/article-alias. At the same time, main site articles, like mysite.com/about are available from blog by URL blog.mysite.com/about. No matter which affiliate I'm sending this article to, or which source site I choose, it still happens. Today, I've found that some of such pages were indexed by Google as duplicates, despite having canonical tag.

Is it possible to get rid of such pages with this module settings, or with the help of some additional modules? Still, I can't find no solution.

You can manage your Robots.txt file through Drupal using RobotsTxt module. This way you can exclude whatever content you want from Google, etc.


How to weight a block above a custom form I'm creating a page with a form with the hook_menu:

function my_module_menu() {
  $items['rsvp'] = array(
    'title' => 'My Page',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('my_module_form_search'),
    'access arguments' => array("access content"),
    'access callback' => TRUE,
  );
}

I also have created a block that is to display in the content area of the rsvp page. Right now the form shows above the block. How do I reverse that?

In Drupal 7 the output from a page callback will be rendered inside the standard 'Main page content' block. As such it is available to be re-ordered like any other block in the system through the admin UI.

All you need to do is visit the administer blocks page ( http://mysite.com/structure/block ) and move your block above the 'Main page content' block.


Images break with wrong href; clearing caches fixes! Occasionally we will have graphics in various places on the site that are missing because of incorrect hrefs with unknown subdomains and are fixed when the caches are cleared. So an incorrect link

https://www.xfdg.oursite.com/sites/image.jpg

is only fixed after cache clear

(correct https://www.oursite.com/sites/image.jpg)

We are also seeing results in Google that have weird unknown subdomain URLs, in the same manner as the image URLs.

I had read in https://www.drupal.org/node/1992030 “Protecting against HTTP HOST Header attacks (prevent your site from thinking it is someone else)” that it could be spam or errors with Drupal’s cron could be responsible.

Any ideas or directions?

More than likely, your server is responding to multiple domain names, either by being the default or matching/wildcards for ServerName and ServerAlias (using Apache terminology here; nginx and IIS have similar concepts).

So, the problem is that you get a request to www.example.com, and Drupal serves that page up and uses that URL as the base.  It will also respond to www.subdomain.example.com and use that as the URL base.  The problem you see is that the subdomain request is the one being cached, and the hostname isn't part of the cache ID.

The general solution to this is to set up a canonical redirect in either the Apache config or the .htaccess file for your site (I prefer in server config).  The rule would look something like this

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
  RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
</IfModule>

When you do that, Apache will redirect everything to https://www.example.com.  Over time, Google will fix its indexes because of the 301 redirect, or you can try to submit manual delists.


Every user is logged in as admin user I have a weird problem with my new Drupal 7 site. This is also my first Drupal site.

I have now two users: admin1 (has admin rights) & user1
at first, when I logged with admin1, everything was fine
when I logged in as user1, on the hovering admin panel it says that the logged in user is admin1, and this user has admin rights although they don't show on the DB. If content is added by user1, the creator is admin1
I added user2 with no admin rights. Everything went fine until I logged out user2: now the admin1 do not seem to have admin rights anymore but the user2 has them
I tried to disable nginx caching and it seems that it's off, but the problem still remains
Earlier, my site was on LAMP-stack without problems. At least not similar to this. Apache needs too much memory so I switched to LEMP-stack, and this problem arised. So, I assume the problem is somewhere on my nginx-configuration.
All this time, on the database, only admin1 actually have the admin rights

I am using the 7.34 core but the same problem existed with 7.33 as well. The site is hosted on DigitalOcean on a server using Ubuntu 14.04 x64. The webserver is nginx 1.4.6-1ubuntu3.1

@kalabro Actually, it was Drupal problem, but in my own code, not in the core or some module. As a Drupal newbie, I had used "global $user" at a template file to show the current logged in user's username on the menubar... When I removed this, problem was solved.


Adding a 'post to everyone' option in Drupal Commons At present, Drupal Commons posts must be added to one or many groups or to trusted contacts. I would like to add a "public" post that everyone can see in their feed. This is simply a meta group that all members belong to given that my community is a smaller, private intranet.

So, I would like the post to have 3 options. 1) Post to a group(s), 2) post to trusted contacts, 3) post to the community.

Has anyone implemented this ?

Ok, I think I have enough information to help. Just because something is listed as a Group Post (i.e. something that can be posted into a group) doesn't mean it needs to be. In other words, by nature of not selecting any groups you are effectively leaving the piece of content out of the group context.

Then, I might consider simply modifying the view which powers the user feed (this is a view that ships with Commons) and including non-group posts with a specific flag/tag. So to recap:

Create a tag (using taxonomy) or a flag (using this module) that effectively denotes a piece of content being non-group specific. e.g. public
Instruct your users by way of a bit of help text on the node type that they should use that tag and not post into a group.
Modify the view powering a user's feed (I think this is called Activity Stream IIRC) to include your newly tagged or flagged content.
Fancy bonus: Use a bit of JavaScript to disable the group field if either of the above flag/tag conditions are true. (Pseudo-Code: if node has tag public then disable list box)

That should get you there. Hope this helps.


Show Filename of uploaded files in "Field Collection" Field I have a requirement where I have to show files uploaded within a category.. I used Field Collection Module of Drupal for it and made fields in the following way, where each category is a field collection item which has a title field and a multi value file field:-

Now, my end result is to show it in a Search Results Page. When someone searches for a keyword, and it matches the uploaded filename, the file should show in the Search.

I tried views, etc, but I can't output it. Any help please on how to output the file names for the search keyword through Search Results in Drupal ?

You can create a search display using Display Suite (https://drupal.org/project/ds). By enabling DS and DS Search you will get some search options done through DS.


View rest/page copycat In view, when I set the settings to field field1 in Page, the same settings apply to field1 in Rest export. How do I get rid of it?

I see that everything is copied. I deleted the field from Rest export, and it disappears also in Page.

When you click on add / remove / edit a field / filter / sort / contextual filter etc.. at the very top, you need to change the For All displays to This page (override) so it does not affect all the other views. You only need to do this for the first time, it will remember your setting.

Note: field / filter / sort / contextual filter etc... each have individual settings.


How to theme video_embed_field per node type I have two seperate node types and d8 with media installed

in both node types there is a field called video using video_embed_field on a deeper layer in the theme because it uses media entity.

I try to find out how to alte the content of

video-embed-iframe.html per node type.

I am new to d8 and twig.

How can i td this inisde a theme without the need of a custom module

cold i theme the video field per contetn type and then display all template contetn in video field based on an if condition?

Twig naming pattern for the field per content type is

field--field-name--content-type.html.twig

Read more on Twig naming convention here.

update

Media entity seems to be following custom template suggestions, that unfortunately are not documented anywhere. See function media_entity_theme_suggestions_media() here for template suggestions patterns. It does not include per content type template suggestion, but you can try overriding it in a custom module.


Recommend a theme function to modify the 'Submitted by' line for a node? I would like to theme the 'submitted' by date without editing the node.tpl.php file. In other words, in the template.php file.

I know this has been answered thousands of times before, but for the life of me I cannot find a good solution when searching.

Can someone suggest a theme function that uses format_date() or other means to manipulate this however I see fit? Specifically, I simply need to say Submitted by: admin 2012/10/10 but I would like something to keep in my toolbox as this problem comes up on every single project I do.

You can alter the node info using template_preprocess_node
function template_preprocess_node(&$variables) {
 // your code
}

The $variables array contains the following arguments:
$node
$view_mode
$page

This is the default value
$variables['submitted'] = t('Submitted by !username on !datetime', array('!username' =>
  $variables['name'], '!datetime' => $variables['date']));

You can override is as you wish. Give a try.


Defining and manipulating help text for a path Ok, this is a very basic question. If I create a 'page' in drupal using 'add content'. Does this new page (and the path defined for it, say, through 'pathauto') automatically get registered with a callback as a menu item so I can reference it's path in a custom module somehow?

For example, I tried the following code. Case #1 doesn't show anything on that page (a page created the typical way through the admin UI). The second case displays the help text correctly when I go to admin > modules > mymodule and click the 'help' link.

So what's going on here?

function mymodule_help($path, $arg) {
  switch ($path) {
    case 'services/software-training/webinars':
      // Help text for the simple page registered for this path.
      return t('This is help text for the simple page.');

    case 'admin/help#testmodule':
      // Help text for the admin section, using the module name in the path.
      return t("This is help text created in the page example's second case.");
  }
}

A quote from the documentation (subheading Parameters):

  $path: The router menu path, as defined in hook_menu(), for the help that is being requested; e.g., 'admin/people' or 'user/register'. If the router path includes a wildcard, then this will appear in $path as %, even if it is a named %autoloader wildcard in the hook_menu() implementation; for example, node pages would have $path equal to 'node/%' or 'node/%/view'. For the help page for the module as a whole, $path will have the value 'admin/help#module_name', where 'module_name" is the machine name of your module.

This means that the following should work for you:

    function mymodule_help($path, $arg) {
      switch ($path) {
        case 'node/YOUR_NODE_ID':
          // Help text for the simple page registered for this path.
          return t('This is help text for the simple page.');

        case 'admin/help#testmodule':
          // Help text for the admin section, using the module name in the path.
          return t("This is help text created in the page example's second case.");
      }
    }


How do I query a content type with custom fields in the 'condition' statement I need to query a content type both returning and filtering on conditions of custom fields.

$query = db_select('node', 'n');
$query  ->fields('n',array('field_customfield1','field_customfield2'))
        ->condition('type', 'myContentType')
    ->condition('field_customfield3',$user->uid,'=')
    ->condition('field_customfield4',$anemailaddress,'=');
$foundrecord = $query->execute();

This doesn't seem to work. My issue is I can't figure out how to reference the custom fields in queries.

Any help GREATLY appreciated!

You'd be better off using an EntityFieldQuery for this:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'myContentType')
  ->propertyCondition('status', 1) // in case you need it
  ->fieldCondition('field_customfield3', 'value', $user->uid)
  ->fieldCondition('field_customfield4', 'value', $anemailaddress);

$results = $query->execute();

if (isset($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  foreach ($nodes as $node) {
    $customerfield1 = field_get_items('node', $node, 'field_customerfield1');
    $first_value = $customerfield1[0]['value'];

    // etc...
  }
}

Even though it's more code, and more overhead, it has advantages over going into the database tables directly.

You don't need to make the JOINs yourself
EntityFieldQuery respects node revisions, which will be harder to keep track of well using a custom query
Your code is now portable if you decide to change the storage backend for fields to something other than MySQL (MongoDB for example).


How do I upgrade the PHP version used? I've been away from Drupal a few years. I now want to develop a site. I see it's up to version 9. However, when I tried to install Drupal 9 in DevDesktop to get a feel for it, I got the message PHP version too old. I'm selecting the highest PHP version, 7.1.12, and still get this message. I know D9 likes PHP 7.5 or something, but how do I get that?
Should I simply upgrade PHP locally, independent of DevDesktop? Or is DevDesktop now old school, replaced by something better?

The latest version of Acquia Dev Desktop (released on May 21, 2020) is compatible with Drupal 9: It added support for MySQL 5.7 and Drush 10; PHP has been updated to versions 7.2.28 and 7.3.15.
Since Drupal 9 requires PHP 7.3 or higher, you need to select version 7.3.15 for Drupal 9, or you will get the error message you saw.
References

The release notes for Drupal 9

The download page for Acquia Dev Desktop


Overriding css file in theme.info not working as expected I am trying to remove nice menus css, as per the notes in my Zen theme .info file.
I have added the below to the info file, and I haven't provided replacements in my theme so they should be removed.

stylesheets[all][] = nice_menus.css
stylesheets[all][] = nice_menus_default.css

However they are still being imported. Cache cleared.

Thanks

EDIT: I'm aware this can be achieved using hooks, but would like to do it at theme .info file level, unless I am mistaken and it is not possible to remove contrib module .css in the theme .info file.

Try disable/enable theme. Yes it likes a trick. It seems info files are parsed when modules/themes are enabled/disabled.


Rules data selection tokens I have a rules data selection token that looks like this
[order:products:0:node:author:uid]
In data selection mode that works perfectly, and adds the exact data right where I need it.
But when I am trying to add that kind of token into the mysql with this, using "execute custom php code" inside that rule using this code

$nid = db_insert('mytable') ->fields(array(
  'uid' => $uid,
  'username' => $username,
  'addr' => $address,
  'destination' => "[order:products:0:node:author:uid]"
))
->execute();

I am getting no error as a response, but only a blank field 'destination' with no value in mysql. All the other fields are filling correctly. What could possibly be a problem here?

You might want to use token_replace.

You can use it like this:

$token = token_replace('[order:products:0:node:author:uid]', array('order' => $order));

So $order is your order.


How can I remove the checkbox from tableselect form header only? How can I remove the checkbox from tableselect form header (Drupal 7) only? I am looking for any configuration if available that can be applied in the below sample code:

$form['listings'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('No Listing available.'),
);

The checkbox on the header is the Check all one. As the documentation about the tableselect form element says, just set the #js_select property to FALSE. In your case, the code would become the following one.

$form['listings'] = array(
  '#type' => 'tableselect',
  '#js_select' => FALSE,
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No Listing available.'),
);

See also the code of theme_tableselect(), the theme function responsible of rendering tableselect elements.

// Add an empty header or a "Select all" checkbox to provide room for the
// checkboxes/radios in the first table column.
if ($element['#js_select']) {

  // Add a "Select all" checkbox.
  drupal_add_js('misc/tableselect.js');
  array_unshift($header, array(
    'class' => array(
      'select-all',
    ),
  ));
}
else {

  // Add an empty header when radio buttons are displayed or a "Select all"
  // checkbox is not desired.
  array_unshift($header, '');
}


Change the "Create [content type]" title I allow registered users to create content of type X, so they can go to the /node/add/X page and fill in the form. However, I want to give this page a bespoke title, i.e. "Make an X" rather than "Create X". I have tried adding a string override in settings.php, and also tried with the string overrides module. However, neither of these worked.

What is the best way to do this? (I don't want to install another module if I can avoid it, I already have too many and this seems like a trivial issue).

You could do:

function MY_MODULE_NAME_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'myContentType_node_form') {
         drupal_set_title('Your custom title');
     }
 }


Subscriptions does not send out "update" notifications I am logged in as user/1 and have subscribed to a particular node. I then edited the content of the node and have ticked the "Send subscriptions notifications" option.

I did not receive an "update" notification. Why might this be the case?

By the way, I've enabled the following modules:
* Subscriptions UI
* Subscriptions Mail (+ Mail Editor + Token)
* Content Subscriptions

I am logged in as user/1 and subscribed to a number of nodes. Updating them does not send email notifications.

The settings I've got turned on are as follows:

admin/config/system/subscriptions

Unlisted content types - none

Blocked content types - none

Node form position - Fieldset above node links

Node form visibility - Always display the fieldset

Expand the node form fieldset

admin/config/system/subscriptions/userdefaults

Nodify poster of own posts Send interval - As soon as possible

On updates - ticked

Send interval - Hidden

On updates - hidden

admin/config/system/subscriptions/intervals

1|As soon as possible 900|Every 15 minutes 3600|Hourly 10800|Every three hours 86400|Daily

Do I need to enable "* Taxonomy Subscriptions (e.g. forums!)" for the subscriptions to work?

Also, not sure if this is required, but I went to admin/config/system/mail-edit and added a template fornode-type-basic_page for the Subscriptions Mail module. However, this made no difference in email updates being sent :(

First you need to check your email sending capacity of your website.
Second check that you did the correct configurations for subscriptions module.
Finall you must run the cron (or set the timer for cron) for sending email updates for subscriptions

If you want to test at the final step, just run cron manually


Help with a dynamic select list of flags for webform so I've been trying to implement a 'sample request' feature on my site. I had tried to use the webform views module, which worked except that I couldn't add checkboxes to the view that displayed and webform views doesn't play well with the latest release of webform.

I found this Sample Request w Views, Flag, and Webform tutorial, which is basically exactly my use case.

I've created my own module, and am stuck with some of syntax in the view and options parsing array function. The article mentions that I need to reference the title of the nodes 'owner' but I'm not 100% on how this applies to my implementation.

I've altered the code so the function names reflect my custom module, my predefined view of my flag, but I can't get the list to show up in my predefined lists options. I think this is because I don't have the right field referencing my node's title, but I'm not sure. Also the dpm() statement didn't fire.

I know this is a lot, thanks in advance.

 function webform_hook_select_options_info() { $items = array(); if (function_exists('_MODULE_user_flag_sample_requests')) {
 $items['MODULE_user_flag_sample_requests'] = array(
  'title' => t("Sample Requests (User Flag list)"),
  'options callback' => '_MODULE_user_flag_sample_requests',
 );}return $items;} function _MODULE_user_flag_sample_requests() {$view = views_get_view('webform_flag_views', TRUE);$view->set_display('webform_options');$view->execute();$options = array();dpm($options);if ($view->result) {$row_class = $view->style_options['row_class'];$attributes = $row_class ? " class='$row_class'" : '';
 foreach($view->result as $item) {
   $options[$item->nid] = '<a' . $attributes . '>' . render($item->field_field_img[0]['rendered']) . ' ' . $item->field_ref_node_title . ' (' . $item->node_title . ')' . '</a>';
 }}else {
 $options[0] = t("Nothing");}return $options;}

It is not webform_hook_select_options_info() it is webform_hook_webform_select_options_info().
(If your module name is webform_hook)
The MODULE parts are the places, where you should enter your modul name.
Inside the foreach you need to enter valid fields from your content that listed inside the view.
Be sure that the Flag Modul is working.


Context Filter with Path Alias in URL Quick Summary: how do I pass a alias in a URL to a view's context filter, when that view is located somewhere in the site.

I've read dozens of similar articles, but nothing that directly makes this clear for me, so if someone has some insight, I'd be grateful.

I have a Content Type: "Artists" with an pathauto alias as so: artists/picasso
I have a Content Type: Artwork with an entity reference to artists.
A given Artwork might have an alias as such: artwork/minotaur (which is a work referencing picasso)

What I want to do is create a view, have it live here: (artwork/artists/picasso) that shows all Artwork by Picasso.

My trouble is: I can get the view set up, but it only displays correctly if I have the NiD in the URL path. For example: /artwork/artists/1 (with 1 being the Nid for the Picasso node)

How can I get the view to accept "picasso" as an argument to use in the location I want (artwork/artists/) for instance.

I have no trouble if I attach a view to the artists/picasso page as a block. I can show all works by him there, but I want to show works by him in another location.

It seems like this should be obvious, but I cannot find a clear answer as to how to implement. Your help is greatly appreciated."

A more robust solution that avoids needing to ensure unique node titles would be to write a custom Views Plugin Argument Validator that converts a contextual filter to node ID.

In your case in which you want to validate node path aliases, you would want to extend the class views_plugin_argument_validate_node in views/modules/node/views_plugin_argument_validate_node.inc to overwrite options_form() to provide your own option. You probably want something like this:

function options_form(&$form, &$form_state) {
  parent::options_form(&$form, &$form_state);
  $form['type'] = array(
    '#type' => 'select',
    '#title' => t('Filter value type'),
    '#options' => array(
      'convert_path_alias' => t('Node path alias converted to Node ID'),
    ),
    '#default_value' => $this->options['type'],
  );
}

You would also need to overwrite validate_argument() to convert the argument (path alias) passed into the function into a node nid, set $this->argument->argument to the converted node nid, and return TRUE if the path alias was successfully converted.


How can classes be removed from panel panes? Is there a way to remove the default 'panel-pane' classes, without creating hundreds of templates for different entities, and while still keeping the option of adding custom classes to panes?

By admin panel. When you edit a panel page, click on a cog of the pane that does not need styles. Check styles. Choose no styles. There few options. I do not remember exactly how it is called. It exists there. Check it ...


Strange behavior while assigning the role programmatically I used this code to set role to a user :

    user_external_login_register($form_state['values']['name'], 'beneficiaire');
    $account = user_external_load($form_state['values']['name']);
    $form_state['uid'] = $account->uid;
    $account->roles[]= 3;
    user_save($account);

My user is weel registered as admin, but if I logout and login, my user has an empty role in addition of the administrator.

Replacing 3 by administrator does not fix.

Do you have an idea of what's going on?

Thanks.

This is the roles element in $user object ( $user->roles )

roles => array(
  2 => "authenticated user",
  4 => "Site Administrator",
  6 => "Author",
),

You must set the user role like:

$user->roles[ROLE_ID] = 'ROLE_NAME'


How to send email in every 7 days to in-active users that is not logged in since 7 days? I want to send mail in every 7 days i.e please login site, you are not logged in since 7 days, only for those users which are not logged in since 7 days. I have already created an event i.e After creating new user a/c. But I don't think so that this event is good for existing users.

What event I need to add? What condition am I apply to check [account:last-login]<7 days & send mail in every 7 days.

Please Help. Thanks

In order to send an email to the user with 7 days of inactivity. Do the following:

A. Install Rules and Scheduler where Scheduler depends upon Tokens and Entity API

B. Once you have installed and enabled all the above modules, then you can start configuring your rule. To achieve what you want, do the following steps:

Add new rule (Configuration -> Workflow -> Rules)
Give it a name (i.e. user_login ) and select the event as "User has logged in", leave the tags field out and Save the rule
After saving the Rule, go back to Rules using the breadcrumb (i.e. URL), when you are back in the Rules window, you should see your recently created rule (i.e. user_login)
Select Component from top-right-hand-side-of-the-page (There should also be a tab named Scheduler, if not there then enable the module)
Inside component, select Add new component
Choose Action set as Component plugin and press Continue
Give it a name (i.e. send_email_to_inactive_user)
Skips Tag
From Variables section, Choose DATA TYPE as User, give it a LABEL (i.e. inactive_user), give it a MACHINE name (i.e. inactive_user), ignore USAGE and press continue and the page should refersh.
Now under Actions add an Action
Select Send email
TO, click on switch to Data Selector then reference the label of variable created in previous screen (i.e. inactive-user:mail) colon mail
Provide a subject to your email
Provide a message to your email
Provide a from to your email
Then save, now you should see the send_email action which is attached to the component.
Go to the Rules and create an Action for your rule with event (User has log in)
Select the value of action as Schedule component evaluation and it should open a window with combo box containing your recently created component (i.e. send_email_to_inactive_user), choose it
for * Schedule Evaluation Date * provide a value (i.e. +10 minutes or +7 days or +15 weeks)
for Identifier provide a value that will help you identify the scheduled task among other tasks (i.e. 7 days inactive reminder for [account:uid], where the [account:id] is replaced by the logged-in-users-id)
Last option, select account for INACTIVE_USER's data selector
Save and you should see the schedule component evaluation under Actions

You are done. If you pay close attention, the Rules evaluates The component when a User log in, the component then schedules an email to be send to the user +7 days (or override the existing one, updating the schedule time duration) and the scheduler sends the email when the time come. So Rule is used to evaluate the component and component is used to setup/update scheduler and scheduler is used to send the email.

In case you have not followed me, or can't figure out then here are my working sample exports for Rule & Component, just import them and change the values accordingly and save. Test it by logging in and then go to Configuration -> Workflow -> Rules -> Schedule and you should see a scheduled event for exactly (i.e. +7 days or +10 minutes from the time you login).

Important component first:

{ "rules_send_email_to_inactive_user" : {
    "LABEL" : "send_email_to_inactive_user",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "inactive_user" : { "label" : "inactive_user", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "inactive-user:mail" ],
          "subject" : "test inactive user",
          "message" : "test inactive user message",
          "from" : "raf",
          "language" : [ "" ]
        }
      }
    ]
  }
}

then import the Rule:

{ "rules_user_login" : {
    "LABEL" : "user_login",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_login" : [] },
    "DO" : [
      { "schedule" : {
          "component" : "rules_send_email_to_inactive_user",
          "date" : "+7 days",
          "identifier" : "7 days inactive reminder for [account:uid].",
          "param_inactive_user" : [ "account" ]
        }
      }
    ]
  }
}

To test whether it is working you can execute it right away and you should get the email in your inbox.

Good luck man, if you needed further help, then Google is your best friend.


Update node revision programmatly If i try to update node revision like this:

$node = node_revision_load(59);
$node->set('publish_on', null);
$node->save();

or simple save:

$node = node_revision_load(59);
$node->save();

I have a PHP memory error, (i have 1gb allocated)

When you load a node, you should always check if it exists (is not null) before calling a method:

$node = node_revision_load(59);
if ($node) {
  $node->set('publish_on', null);
  $node->save();
}

But this is not the cause for the memory error. This is more likely a recursive thing. For example you are saving again and again until the memory is filled up.


Adding a filter to a view "or" remove results? I've got a view that is trying to show three different content types (Lesson, Drill, Exercise), each with three different flags(Lesson Flag, Drill Flag, Exercise Flag), each of those flags have 3 fields (Review Date, Review Date, Lesson Status).  I only want to display items that have a flag with REVIEW date <= today, OR learning status of Incomplete. But when I add the OR condition that the flags learning status = incomplete, all of the results of the other two content types are removed. (IE, before adding the filter I have 7 items, after adding the filter the view only shows one item that wasn't there before)

This seems to defy my understanding of how the "or" condition works, and I'm curious why this would happen.

Here's a picture with the filters I have set up:

Is there something I'm not understanding about how the OR condition works? Or an existing bugs in views 7x.3x that causes them to behave badly?

I figured this out.  In order to prevent this behavior, I had to check "reduce duplicates" in the filter, as well as remove some "required relationships.


Progress bar advances, operations does nothing I'm trying to create a batch to import users. I used this (http://pastebin.com/duTbxpgd) as an example, but somehow it's not working. I see the progress bar advancing and It's showing the right number of rows I'm processing. But what I'm trying to do in the operation function isn't executed.

Here's my code:

function form_submit($form, &$form_state) {
  batch_import_users();
}

function batch_import_users() {
  db_set_active('mysqldb');

  $result = db_query("SELECT * FROM {users}");

  db_set_active('default');

  $batch = array(
    'title' => t('Importing users ...'),
    'operations' => array(),
    'init_message' => t('Commencing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'finished' => 'batch_import_users_finished',
    'progressive' => FALSE,
    'file' => 'users.inc',
  );

  foreach ($result as $row) {
    $batch['operations'][] = array('batch_create_user', array($row));
  }

  batch_set($batch);

  batch_process();
}

function batch_create_user($row, &$context) {
  // Here I'm just trying to get some output so I know the operation is called, I'm not actually importing the users yet.

  drupal_set_message($row->uid . ' : ' . $row->login);
  dd($row->uid . ' : ' . $row->login);

  $context['results']['processed']++;
  $context['message'] = $row->login;
}

function batch_import_users_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message('Importing users has finished.');
  }
  else {
    drupal_set_message('Some error.');
  }
}

Am I missing something or doing something wrong? Any help is very much appreciated.

Try below code

$operations = array();
foreach ($result as $row) {
  $operations[] = array('batch_create_user', array($row));
}

$batch = array(
  'title' => t('Importing users ...'),
  'operations' => $operations,
  'init_message' => t('Commencing'),
  'progress_message' => t('Processed @current out of @total.'),
  'error_message' => t('An error occurred during processing'),
  'finished' => 'batch_import_users_finished',
  'file' => drupal_get_path('module', 'user') . '/' . 'user.inc',
);

Also add path to redirect after batch process

batch_process();


Get array length of a multiple fields of a node content type I'm developing a site with Drupal 8. I made a custom content type, with a lot of fields; in particular I have a field called field_categoria_del_libro_presen that is linked to a taxonomy term. It's possible to specify more than one value. I used kint() to obtain the structure of the node. Here:

field_categoria_del_libro_presen
→array(2) target_id
  1
    "1"
  2
    "4"

how can I get the length of the array?

Confirmed that as suggested in the comments, the following works quite well:

count($node->field_categoria_del_libro_presen);

Here the count would be 2 (based on the example in the question).

This works because even though the field_categoria_del_libro_presen property on the node object is a EntityReferenceFieldItemList, it implements (by way of implementing ListInterface) the native PHP \Countable interface.


Dynamically add User into a role I have set up a Drupal site to connect to an external payment gateway (not using Drupal Commerce) for subscription-based billing. So making use of Drupal Webform, I have created forms for users to provide their payment information. Live site will be behind SSL.

What I would like to know is:

Where do I start by taking the details of the completed Webform and submitting it to the Payment Gateway's XML web service? Essentially, what I'm looking for is some hook into when the form is filled in, to trigger some code (which I already have setup and tested in a separate plain PHP app) to call the Web Service; and then
Based on the response that I get from the Payment Gateway, to add the logged in user to a specific role?

Your help will be greatly appreciated! Thank you in advance

While you could utilize hooks like hook_form_FORM_ID_alter setting custom #validate & #submit functions or hook_webform_submission_insert, I've had better success using the Payment module and writing a custom Payment Method class.


How to add data to a message type custom field that's inherited by all message instances? I'm using the Message module, and I have some message types. Each message type needs to have a node reference field on it whose value would not change for the entire message type. But different values per message type.

Right now I can create a new message type with a field on it, but the instances of messages are generated programmatically on demand as sent.

What I ultimately need to do is generate a token based on the value of this field.

So how would I go about creating a value that would be inherited by all instances of a message type? Ideas?

Any advice useful. Sort of don't know what functions would be useful here and the docs really don't address this use case.

I didn't actually figure this out. I probably could have by looking at the way commerce orders get attached via entity reference to messages and done that. Instead, I used the commerce order that was attached to the message, which had the commerce store ID, to load the field on the organic group that was referencing the store and then add that field as a token.


RedirectResponse not working I'm in the process of porting my modules from D7 to D8. No real problems so far, but...

I have a multistep form from where I need to redirect to /node/add/xyz in the last step. (All required input form data is stored in D8 TempStore before the redirect).
In d7 I used the simple and functional drupal_goto('node/add/xyz') function which is gone in D8 for whatever reason.

I looked into core modules to see how it is done in the D8 way and it seems RedirectResponse() from the Symfony routing system is the way to go. However doing something like this:

return new RedirectResponse(url('node/add/xyz', array('absolute' => TRUE)));

But this is silently ignored, no error, nothing. I read that doing RedirectResponse from somewhere in the code may not work. So my next idea of doing it was to use a form redirect in this way:

$form_state['redirect_route'] = array(
  'route_name' => 'node.add',
  'route_parameters' => array(
    'node_type' => 'xyz',
  ),
);

even without any effect. I'm out of ideas and wish drupal_goto() back. Hopefully someone out there can help me out!

Thanks in advance
bzrudi

Form redirects haven't changed between Drupal 7 and 8; you still need to use $form_state['redirect'] (incidentally drupal_goto() shouldn't be used within form submissions in Drupal 7, it can mess things up).

Within your form class's submitForm() method, you can use

$form_state['redirect'] = 'node';

Or

$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

Full info can be found in the FormBuilder::redirectForm() docs


How can I set up Drupal so people can collaborate on content development prior to making it public I have a small website which, from a modules perspective, I want to keep as simple as possible.

Apart from displaying content, a main purpose of the site is to facilitate collaborative authoring and publishing of: articles, product updates and case studies.

To achieve this I would like individual contributors to be able to create & edit content prior to public release (just to be clear, I'm not looking for concurrent editing here).

This seemingly simple requirement leaves me stumped because unpublished content seems unavailable for further editing by the original creator, let alone co-collaborators.

Similarly, some items of content will need periodic updating. To achieve this I expect they will need to be reviewed, updated & debated offline, but in a way that leaves the current version public.  The update process needs to allow multiple authors to edit in private prior to republishing / making the updated content public.

I'm at a loss as to how this is most easily achieved - would appreciate any advise that leads to a simple solution.

The near defacto-standard for this in Drupal 7 is the Workbench Moderation module, which is part of the broader Workbench suite.  From the module page:

  Workbench Moderation adds arbitrary moderation states to Drupal core's
  "unpublished" and "published" node states, and affects the behavior of
  node revisions when nodes are published. Moderation states are tracked
  per-revision; rather than moderating nodes, Workbench Moderation
  moderates revisions.

and about Workbench in general:

  Workbench is a suite of modules which provide easier content
  management for content administrators. Each of the "Workbench" modules
  has been tested to work with the main Workbench module, and with the
  other modules in the Workbench suite. The Workbench suite is modular,
  allowing site builders to build the workflow that best suits the
  content administrators on their site. The Workbench suite provides
  authors, editors, and publishers with a unified interface for managing
  content relevant to them. It allows people to focus on content, rather
  than on learning Drupal.

This is highly tailorable to your particular organization, and all organizations differ.  You didn't list out a lot of additional requirements, but typically you would create roles (Author, Editor, Publisher, Admin), and then define which role can do what (eg, Authors can only edit their own content, Editors can edit all, but only Publishers can make nodes public).  Additional controls can be implemented with Workbench Access.

I have deployed solutions based on this for many organizations, mostly with success.  I also like this solution, compared to others, as this module suite is "site-builder friendly".  This means, that I can get the basics going for a site, and then have non-developers on the team work with clients to tailor it for their needs.

When it doesn't work well, it is usually because the organization doesn't really want content workflows as opposed to needing them.

This solution is also providing the base for the Content Moderation initiative for Drupal 8.

That said, depending on your situtation Groups / Organic Groups may be a better fit (as described in another answer).  I would take both solutions for a test drive to see what works best for you.


How to programmatically know a required select list has no value on node add/edit form page? For a required field using select list widget, if there is no options, the field will show only one "-Select one-"  value on the node add/edit form page. So, how to know that by coding?

It will depend on the field type. For a list field with text/numeric values, the output of the field API function field_info_field() contains allowed values within its settings element. This field data can be fed into list_allowed_values() to retrieve either the static or dynamic list of allowed values for the field.
For example:
$field = field_info_field('field_myfield');
$values = list_allowed_values($field);
if (count($values) > 0) {
  // There are allow values
}
else {
  // There are no allowed values
}


Clear Example for drush rsync exclude paths I've seen many exclude path examples here on stack exchange. But I can't figure out the way to make it work.

To keep it simple :

We have two aliases @self  and @live

we have a theme called themename in /sites/all/themes/themename

in the theme folder we have a subdirectory called node_modules because of the use of gulp in our development workflow.

How can we make sure to exclude /sites/all/thems/themename/node_modules/ when syncing with drush rsync @self @live ?

drush rsync has an  --exclude-paths parameter that will allow you to exclude your node_modules directory.

Have a look at the parameters for rsync.

You should be able to do something like :

drush --exclude-paths=sites/all/themes/themename/node_modules rsync @self @live

Because the Drush rsync command uses strict option handling, the --exclude-paths option must appear before the rsync command name.


Output image src via JSON I have worked out how to use dynamic routing and JsonResponse() in a custom controller to output pure JSON, with no HTML at all. I would like to do the same with an image — for the page to output an image header and the image itself to the browser, with no HTML, as though the address were simply a file path to an image.

Is this possible?

Something like the following could help you.

Just Set $filepath  and $filename with your desired values.

$filepath = "/path/to/my/image/chart.png";
$filename = "chart.png";

$response = new Response();
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', 'image/png');
$response->setContent(file_get_contents($filepath));

return $response;