apachesolr search form block that points to search page I have a custom search page configured in apachesolr_search module which displays only products as results (bundle:product_display). I want to create a simple block that contains an input field for a keyword and the submit button, and when the user submits the form it should direct to the specific search page.

I haven't found an easy way to do that. Other developers seem to modify the core block search form, but this does not help as I will have the same requirement in many pages over the same website (many apachesolr search blocks pointing to different apachesolr pages).

There is an issue queue asking for such feature:
https://drupal.org/node/326375

I also found a module (a sandbox) for Drupal7 to export for each search-page a search-block:
https://drupal.org/sandbox/incrn8/1315802


Is there a way to create a taxonomy path redirect? I am trying to create a taxonomy redirect for specific taxonomy URL. Basically what Taxonomy Redirect did for Drupal 6 but for Drupal 7. I have searched the Drupal 7 API for hook_term_path but don't see it.

Finally, I need these links to be associated with particular profile2 profiles.

Is this possible?

Instead of hook_term_path you can use hook_entity_info_alter.

A small example

function MYMODULE_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_term']['uri callback'] = 'MYMODULE_term_uri';
}

and then you can implement you version of MYMODULE_term_uri function.

Hope it helps.

Also if you want the D7 version of the module you mentioned you should try
http://drupal.org/project/entity_path


How do I set my custom module to use a template for a specific page? I have created a custom module that adds some form elements to nodes of specific content types. Another part of this module requires a specific formatting output of data that is a little more complex than using $form[''].

How can I tell my module that for a specific function, it should load a certain template file?

Template files are associated with theme functions. To use a template, the theme function that is declared in hook_theme() must report that it is using a template file, and this is done adding the "template" property.
For example, the following definition used from the Node module says to Drupal that for the "node" theme function, it needs to use the "node.tpl.php" template file; every times a module calls theme('node', …), Drupal will know to use that template.

function node_theme() {
  return array(
    'node' => array(
      'arguments' => array('node' => NULL, 'teaser' => FALSE, 'page' => FALSE),
      'template' => 'node',
    ),
    // …
  );
}

For a page that is visible on http://example.com/parcels, Drupal checks for a template file named "page-parcels.tpl.php" exists, and use it in that case. The template files are looked in the directory of the currently set theme, though; this mean that the template is not found if it is in the directory of a module.


How to remove "Time Zone" element "user_register_form" form using hook_form_alter I analyzed the "Create new account" page of drupal by using hook_form_alter and $form variable. as you see, #form_id value is: "user_register_form" and other elements are as following:

attributes->Array
administer_users->Array
#attached->Array
#cache->Array
account->Array
language->Array
#entity_builders->Array
#process->Array
#parents->Array
user_picture->Array
actions->Array
#form_id->user_register_form
#type->form
#action->form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM
#build_id->form-78GnGyO2iwZsooojZLCOiAw9pYXyDqngJ5C0DU_EzUQ
form_build_id->Array
form_id->Array
#id->user-register-form
#method->post
#theme_wrappers->Array
#defaults_loaded->1
#tree->
#validate->Array
#submit->Array
#theme->Array
contact->Array

I want to remove "Time Zone" element of this form (user_register_form), which of this array elements should I unset to remove that element?

EDITED

As @KrishaWeb and @Kevin said:
Drupal 8 provided admin path at: admin/config/regional/settings to do it.


How to make different users profile pages for different user types in Open Atrium2? I have 3 different user types and I want to provide a specific profile edit page for each. The user type is set when registering for an account. I have the profile fields associated to each user type created in config/people/accounts, but I'm lost on how to create the separate pages for each user type and then to trigger the loading of the correct page based on the users type.

I have not find a such module in the OpenAtrium bundle. You can use the contribute module https://www.drupal.org/project/profile2
Profile2 allows for creating multiple profile types, which may be assigned to roles via permissions (e.g. a general profile + a customer profile)


Place a Page before Context Blocks I want to achieve this result in my Drupal front page:

[Headers]
[Welcome Block]
[View of contents]

So I created a Welcome Page (as a Basic Page), and put it as a Front Page from site configuration.
Then I add the view by the context module.

The problem is that the welcome page appears after the view, at the bottom of the page:

[Headers]
[SECTION Content]
  [View of contents] (view, added with context)
  [Welcome]          (Basic Page with path /welcome)
[/SECTION Content]

A possible solution is to make a Block instead of a page, but I would have no more welcome/ path where to link the front. I want also to use a page so that editors can edit, update and translate that when needed. With blocks I should add higher permissions. My purpose is just to show the welcome basic page before the view of contents.

You can use panel page for this.
Create a panel, set it is as front page and pull the things you want to pull like blocks, views, nodes etc.


Remove paper size options on node add forms Node add forms show some paper size options no matter who the user is, even regular authenticated users. It seems to be part of the Printer, email and PDF versions module.

I added the following code to my helper (let's call it my_helper) module, as suggested here:

/**
 * Implements hook_form_alter().
 */
function my_helper_form_alter(&$form, &$form_state, $form_id) {
  // Hiding the print fields that print.module puts into the node form.
  if (strpos($form_id, '_node_form') !== FALSE && !empty($form['print']['print_pdf'])) {
    foreach ($form['print']['print_pdf'] as &$print_field) {
      $print_field['#access'] = FALSE;
    }
  }
}

I am also using the Simplify module to hide certain form elements but this isn't coming up as an option there.

Edit: I looked at the system table in MySQL to see that the weight of the module was 0, so I added a .install file to change the weight to 10. But still not seeing an affect.

   function my_helper_update_7100() {
        db_update('system')
        ->fields(array('weight' => 10))
        ->condition('name', 'my_helper', '=')
        ->execute();
    }

Cross-posting my answer from drupal.org as these two pages are the first results in google.
https://www.drupal.org/project/print/issues/2714635

  I just fixed this on my works web site. The form alter code needs to be added in an #after_build callback as the paper size and orientation fields don't exist yet in the form array in using hook_form_alter. Here is a complete example.

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

  // Hiding the print fields that print.module puts into the node form.
  if (strpos($form_id, '_node_form') !== FALSE) {
    $form['#after_build'][] = 'mhfa_pdf_form_alter_after_build_remove_print';
  }
}

/**
 * Remove pdf print controls.
 */
function my_module_form_alter_after_build_remove_print($form, &$form_state) {
  unset($form['print']);
  return $form;
}


How do I preprocess "extra fields"? Drupal allows you to create "extra fields" through hook_field_extra-fields.

I'd like to be able to load javascript (among other things) in my module, based on the presence of one of these fields, but I can't seem to find a hook that will fire before it renders.

I've tried hook_preprocess_HOOK (for mymodule_preprocess_field), but that didn't work. You can detect for it on hook_preprocess_node, but that doesn't work if the field is being rendered individually, or a in a view. Any ideas?

It depends on what fields you are dealing with.

hook_field_extra_fields() allows you to define extra fields for any entity, then the field itself is added in a hook that runs when the entity's content is being generated.

That is the place where you need to add the js.

In that hook you can modify the fields you care about and add your js using drupal_add_js() or #attached.

#attached is generally more resilient to caching as it lives with the field render array.

Use #attached like this:

$form['YOURELEMENT']['#attached']['js'][] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';

For example, if the field you want is being added to nodes, you would implement hook_node_view() or hook_node_view_alter() something like this:

function MODULENAME_node_view($node, $view_mode, $langcode) {
  if (isset($node->content['EXTRAFIELD'])) {
    $node->content['EXTRAFIELD']['#attached']['js'] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';
  }
}

or in hook_node_view_alter() it would be like this:

function MODULENAME_node_view_alter(&$build) {
  if (isset($build['EXTRAFIELD'])) {
    // Change its weight.
    $build['EXTRAFIELD']['#attached']['js'] = drupal_get_path('module', 'MODULENAME') . '/javascript.js';
  }
}

The same principle can be applied to other entity types, like users, which would use hook_user_view() or hook_user_view_alter().

If your field is on multiple entity types you might have to use multiple of these implementations, or even better, you could use hook_entity_view() or hook_entity_view_alter(), which allow you to target all entity types in the one place.

If you need to make sure your hook runs after all other modules' implementations of that same hook then you can either set the weight of your module higher than others or use hook_module_implements_alter() to make sure your module runs last.


Add class to new posts with Views I have a view (using Views module), which displays a list of all Titles of a custom content type. What I want to do is add a CSS class to the posts that are new (posted within 24 hours for example). I am guessing I need to create a custom module to do this, but am confused where to start. Any help is appreciated.

You may want to simply make use of the existing field available in views called:

  Content: Has new content  values
  Add that as a field or use it to customize another field, it is pretty handy.

Some more information on what constitutes as NEW or UPDATED:
for how long is Content considered "new" by the filter criteria "Content: has new content"?


How can I aggregate information from about 30 Drupal sites in one place? I have about 30 websites on Drupal. I'm looking for module or service where i can aggregate information from all websites in one place. I need information about number of nodes, comments, users, Drupal core and modules versions. Something like acquia insight but for more sites and cheaper :)

The Similar Module Review's Administration module wiki lists several options.

The following show some usage statistics, as well as Drupal core and module updates:

Droptor (Requires paid service for more than 1 site.)
Drupal Remote Dashboard
Network Manager (Drupal 7 version doesn't exist yet.)
Sentry Server (Drupal 7 version doesn't exist yet.)


How to add a timer in views? I have created a view which displays a list of product in table grid formate with four rows. I have fields related to the product like image,price,descriptions and so on. Now I want to create a field which should display the  discount time left for each product. I tried to use jQuery countdown timer module to implement this but it didn't work. Can any one suggest which module I can use to create a timer field in Druapl7.

I think you were on the right track.

Check out this issue comment: http://drupal.org/node/685956#comment-4412688

It links to a GitHub repo, from which you can find a fork at https://github.com/blackice2999/jquery_countdown/tree/7.x-1.x that appears to contain a Drupal 7 port.

Try that.


Read Drush config file I am creting a module with Drush integration. My challenge now is how to read the Drush config file in ~/.drush/myconfig.drushrc.php.

I tried drush_load_config_file but it is not working.

drush_load_config_file($context, _drush_config_file($context, 'deployment'));

Sounds as if you are looking in the wrong place to integrate your module with Drush.

You need to create a drush folder within your custom module and create a YOURMODULE.drush.inc file inside with appropriate Drush hooks.

Here's an example code:

/**
 * Implements hook_drush_command().
 */
function boilerplate_drush_command() {
  $items['boilerplate-hello'] = array(
    'callback' => 'boilerplate_hello_command',
    'description' => dt('Sample Drush command for boilerplate module.'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'arguments' => array(
      'name' => dt('Optional. A name which will be greeted upon running the command.'),
    ),
    'aliases' => array('boilerplate-hi'),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 */
function boilerplate_drush_help($section) {
  switch ($section) {
    case 'drush:boilerplate-hello':
      return dt('Sample Drush command for boilerplate module. It will just greet you, optionally with a name you provided.');
  }
}

/**
 * Command to download the Chosen plugin.
 */
function boilerplate_hello_command() {
  $args = func_get_args();
  $name = (!empty($args[0])) ? $args[0] : FALSE;

  if ($name) {
    drush_log(dt('Hello @name!', array('@name' => $name)), 'success');
  }
  else {
    drush_log(dt('Hello there!'), 'success');
  }
}

This will allow you to run the command using drush boilerplate-hello or drush boilerplate-hi (alias). If you pass an argument, for example drush boilerplate-hello ninjascorner it will take it as an argument, which is the functionality you need.

This is taken from my Drupal module boilerplate. The Drush integration from there is working, so you can install the module and play around with it to see how it works.


How to limit Node refernce field selection to user own nodes? If there are 3 content types that user can create A, B and C. A is main content, B and C  are secondary content types, each time B or C created they automatically have reference to A. My goal is to make possible optionally create reference on C node to B, by displaying check list (when C node is edited/created) with B nodes from same A node. This nodes can have only 1 author and only 1 main A node, so C2 can not be referenced to A1 or B1, only to A2-B2, even if they have same author.

What can be the best way to create such reference filter/pernissions?

Thanks

You can create a View of type References, and then configure the Node Reference field to use that View.

So you configure the View to only list nodes that the current user is the author of, and any additional filters you want.  That should give you what you want.

Look for this area when you edit the Node Reference field:


Import issue in other languages using csv file to drupal node creations I am trying to import a csv file using parsecsv-for-php library.The given csv file is in Catalan language.

The thing is that when i just try to create nodes with given csv data it is throwing me this error like this while importing PDOException: in field_sql_storage_field_storage_write() (line 448 of /modules/field/modules/field_sql_storage/field_sql_storage.module).

To resolve this issue, what i did is that used utf8_encode function for each fields and avoided that error.

After successfully importing, the issue over here is that, this is the body text in csv

Thomas Alva Edison va anunciar la invenció del fonògraf l’any 1877, fent una demostració aquest mateix any. L’any 1878 el va patentar als Estats Units. Inicialment per enregistrar va fer servir cilindres de cartró recoberts d’estany, per finalment utilitzar cilindres de cera sòlida. Aquests van ser comercialitzats l’any 1889. La competència amb els discos sonors va acabar per eliminar els cilindres de cera cap els anys 1920s. Tot i així van sobreviure uns anys més com a suports d’enregistrament a oficines amb el dictàfon.

and the imported body text in the drupal i have displayed as image

If u compare both u will know there are certain differences in the body text such as

l`any in csv body text is getting imported in drupal as lany

d`estany is getting imported in drupal as destany

d`enregistrament is getting imported in drupal as denregistrament

I just want the same text to imported in drupal too with out missing any symbols or special characters. what am i doing wrong.

I have attached the my uploaded csv file formats too.

Only this character(') is not coming up properly in drupal.Any help on this is really appreciated.Thanks in advance

I found a way to overcome this issue. What I exactly did is that, in the imported view, I just added another charset=ISO-8859-1 which retrieves back the symbols or characters from db and displayed them properly.

<?php
drupal_add_http_header('Content-Type', 'text/html; charset=ISO-8859-1,utf-8');
$new_output = utf8_decode($output);
echo $new_output;
?>

That put back all special characters or symbols which was missing.


In the contextual filter of the view add Userpoints Transactions:
User
In views fields add Userpoints Transactions: Timestamp. I see that you do not want to display date in views, so mark it as Exclude from display.
In grouping setting of your view select Userpoints Transactions: Timestamp


Slide effect with JQuery I'm not very good with Javascript/Jquery, and I don't understand something.

I display a full size image when the user arrives for the first time on the homepage. If the user scrolls, the image disappears slowly and the homepage appears.

To hide the image, I use the jquery function .hide(). It works correctly, but I want another animation because the default isn't very elegant.

To do that, it seems I need to include core/jquery.ui, but even if I include it in my dependencies for my library, I get the following error:

  TypeError: r.easing[this.easing] is not a function

And if I include core/jquery.ui.effects.slide, I get this error:

  TypeError: g[i] is undefined

Here my code:

my_module.libraries.yml

home:
  js:
    js/home.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
    - core/jquery.cookie
    - core/jquery.ui.effects.slide

js/home.js

(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.behaviors.pre_home = {
    attach: function (context, settings) {
    $(window).scroll(function () {
      var popup = $('#pre-home');
      console.log("Hide"); // Display correctly when I scroll
      popup.hide("slide", {direction: "top"}, 1000); // Doesn't work in this case, work I remove all parameters but not with the effect I want.
        });
    },
  };
})(jQuery, Drupal, drupalSettings);

I don't know what I'm doing wrong.

A big thank to @No Sssweat  for the answer. My methodology was good, I done an error in the definition of the direction.

So, you need to include the core/jquery.ui.effects.slide in your libraries.yml file and follow this documentation http://api.jqueryui.com/slide-effect/.


How to validate a form without the user pressing submit? Right now I am working on a custom module where I have a 'view' page for viewing fields from my custom table in my database. The page basically just lists the field labels and values. I plan to have a feature to email the information on the page when the user clicks on a link/button, but only after certain fields are valid. Now if the fields aren't valid, I want to redirect to an 'edit' form page so that the user can edit certain fields. I also want to apply the form validate functions at the same time, so that inputs the user has to fix would already by highlighted in red.

However after looking at the form api and form quickstart guides, it seems to me that the only way to do that is to have the user click a submit button. Is there anyway to apply a validation function to the form right after it is loaded?

Clientside Validation will do your job.

You may however have to modify a javascript a little bit by incorporating jQuery('input').blur(function(){ //invoke the clientside validation });


What date format is required to import entityform submissions via feeds? I am trying to import entityform submissions. When using feeds and feeds entity processor it asks for a default value for the "date submitted". I have tried several date formats and none of them are accepted.

I have tried

m/d/y

mm/dd/yy

mm/dd/yyyy

month dd, year

unix timestamp

What format does this need to be in?

Checking the code is seems the validation is done by entity module entity_property_verify_data_type which checks for numeric values regarding a date field. So try

yyyymmdd
20170627

not working

valid date


View filter by nid via relationships I have a content type Project with an entityreference user field field_project_team where you can assign users to the project.

I also have a content type Task with an entityreference field field_parent_project pointing to its parent Project and an entityreference user field field_responsible where you can choose one of users to be responsible for this Task.

I want the Task field options to include only those users who are mentioned in field_project_team of the parent node.

I've created a user type view  with entityreference display for this, where I want to filter users by their belonging to field_project_team of the project with nid from field_parent_project, but can't configure it correctly.

What i'm actually trying to do:
1) When you create a Project node, you can select users who will be a working team for this very project. I've already done it with a field_project_team - an entityreference user select list, which selects users with the role I need via user view with entityreference display.
2) You can create Task nodes for each Project. Each Task node should be connected to its parent Project. I'm doing it like this: on a Project node page I have a button "Add task" which opens Task node add page via the link like node/add/task/[xxx] (where [xxx] is a nid of the parent Project node). Then in the Task content type i have an entityreference field field_parent_project which is prepopulated from URL, so I can get the parent node reference filled automaticly when adding a new task.

All above mantioned works fine, but i try to achive one more thing:
3) When adding/etiting a Task node you should be able to assing this very task to some users to make them responsible for performing this task. In the Task content type I have an entityreference user select field called field_responsible where you can select users. But I want to see in this field not all site users, but only those who are already selected as a Project team - in the field_project_team of the parent Project. To get such a filtered user list I've changed the field_responsible settings ENTITY SELECTION mode to Views: filter by an entity reference view and created a user view with Entity Reference display called "Project team users" to filter users.

My problem is that I can't configure the display in a right way to get only those users I need, i.e. those who are already selected to be a Project team of a parent Project referenced from a Task via field_parent_project field.

This is my View display:

And some explaination:
1. A bridge to the Content entity that is referencing User via field_responsible
2. A bridge to the Content entity that is referenced via field_parent_project (relationship with Content referencing User via field_responsible)
3. Context filter via Content:Nid (relationship with Content referenced via field_parent_project)to get the Nid of parent Project
4. Was trying to add Content:Nid filter related with Content referenced via field_parent_project to filter by the Nid of parent Project.
5) "5" is a Nid of a test Parent project. The Project node with such a Nid exists on the site and some test Taks have reference to it as to parent Project.

In final, it doesn't work. I think I'm missing smth very simple with this but can't realize what... Will be very thankful for any help.

Please take a look at the views export below, this will give you user values. This will work on editing the task but not when you are initially creating the task (as the field_parent_project does not yet have a value stored against it).

$view = new view();
$view->name = 'test';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'Test';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Test';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_project_team_node']['id'] = 'reverse_field_project_team_node';
$handler->display->display_options['relationships']['reverse_field_project_team_node']['table'] = 'users';
$handler->display->display_options['relationships']['reverse_field_project_team_node']['field'] = 'reverse_field_project_team_node';
/* Relationship: Entity Reference: Referencing entity */
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['id'] = 'reverse_field_parent_project_node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['table'] = 'node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['field'] = 'reverse_field_parent_project_node';
$handler->display->display_options['relationships']['reverse_field_parent_project_node']['relationship'] = 'reverse_field_project_team_node';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Contextual filter: Content: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'node';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['relationship'] = 'reverse_field_parent_project_node';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Entity Reference */
$handler = $view->new_display('entityreference', 'Entity Reference', 'entityreference_1');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'entityreference_style';
$handler->display->display_options['style_options']['search_fields'] = array(
  'name' => 'name',
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'entityreference_fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;


Can't enable panels in page-node Hello I'm building a multilingual (en/el) website using views panels taxonomy etc etc and other modules.All was fine with the world when suddenly I decided to customize the page-node by adding a panel layout which I created. The problem is that even when I saved the panel layout and the content on /node/%node nothing happened when I view an article. The article page ?q=node/3 for example remains unchanged.

I'm trying 2 says to find the solution but no luck at all.
Any info will be greatly appreciated, thnx in advance.

I recreated the website and added multilingual modules at the end. Now it works fine... still though I have no idea what was wrong...


Custom node field type should also support content block; what should I do? I'm using the Paragraphs module for nodes. Here is a quote from its project page:

  Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users.

But the type is not in the add select on admin/structure/block/block-content/manage/basic/fields/add-field.

It would be nice, if this module could offer the paragraphs field type also for Content Blocks (or other field type creating modules their types).

Has someone an idea, what the module maintainer has to do along general lines? I want to ask this as a feature request in the module's issue queue. But it would be nice if I can give some hint to the maintainer.

From looking at the code, the module does not define a field type. It just defines a widget for entity reference fields.

So, what you need to create instead is an entity reference field that points to paragraphs, and then select the Paragraps widget on "Manage form display".

But that should be exactly the same for nodes as well?


How to add separator field to user profile I'm creating new fields for the user profile.

I have this:

Company Name
City
Logo
etc

I need to add a new field or some kind of header/separator with this "CONTACT INFORMATION"

and then a bunch of other fields

Name
Email
Address

Basically I need to divide the fields by sections, I just need it to be visible, no programming purposes.

Option 1:
Add one contact field that has cardinality 3 and stores the name, email and address.

Option 2:
Alter the form and put name, email and address in one fieldset.


How does Drupal determine the context in which to display the admin theme? One of the great things about Drupal 7 is the inclusion of an admin theme, Seven. But how does Drupal determine whether to display the administration theme, or to display the site's theme?

Is it path-based (i.e., everything under admin), or something else?

There is now a hook for this: hook_admin_paths(). As usual, the default configuration is in system_admin_paths() but there are many other implementations in core, search for _admin_paths.


How to place custom module template file in theme folder I am using Drupal 6, and I have created a custom module which is in the  "sites\all\modules\custom" folder; in the same folder there is also the custom.tpl.php file.

I want to place the custom.tpl.php file in the theme folder.

Here is my code:

function custom_menu() {
  $items = array();

  $items['custom'] = array(
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_page() {
  $result = db_query('SELECT * from node');
  return theme('custom', array('output' => $result));
}

function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
      'template' => 'custom',
     ),
  );
}

function template_preprocess_custom(&$variables) {}

Well you can place in the theme folder or you can leave it in the module. Drupal will look in both places. So if your implementation of hook_theme is a template, Drupal will look for the following files:

themes/bluemarine/custom.tpl.php
modules/custom/custom.tpl.php

If you read the documentation for hook_theme you'll get your answer for the question when you get to the path key:

  path: [...] Ordinarily the module or theme path will be used [...]


How do I assert for a link's href AND link text in a functional test? In a functional test, I can use WebAssert::linkByHrefExists() to check that a link with a specific href exists on the page. And I can use WebAssert::linkExists() to check that a link with a specific link text exists on the page.

But there's no guarantee that these two will find the same link! How do I check that a link on the page has the expected href AND text?

Perhaps a better approach will be assert by XPath selector \Drupal\Tests\BrowserTestBase::xpath something like '//a[@href="' . $url .'"][contains(text()=\'Some text\')]' as XPath. Check this post about matching text and this about matching url.


Add javascript to a content type form in Drupal 7 I'm trying to add a custom javascript file to my article content type forms (add/edit).

I've tried mythemename_preprocess_page, hook_form_alter and  theme_content_type_node_form to no avail. They both seem to pick up the page i'm on, not the form in Drupal's Overlay with the form in it.

Obviously I want the Javascript to fire only when I'm actually on the form. So just putting the Javascript in a onReady function in a sitewide js file won't suffice.

My current setup in template.php:

function zeilschepen_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'node-accommodation-form':
      $form['#after_build'][] = 'zeilschepen_after_build';
      break;

    case 'views_exposed_form':
      if (isset($form['field_country_value'])) {
        $form['field_country_value']['#attributes'] = array('placeholder' => array(t('Land...')));
      }
      break;
  }

}

function zeilschepen_after_build($form, &$form_state) {
  $theme_path = drupal_get_path('theme', variable_get('theme_default', NULL));
  drupal_add_js ("$theme_path/js/test.js");
  return $form;
}

And test.js:

(function ($, Drupal, window, document, undefined) {

    Drupal.behaviors.test = {
        alert('test');
    }
})(jQuery, Drupal, this, this.document);

This:

node-accommodation-form

Is the HTML ID of the form, found in $form['#id'] (confusing I know). You need the internal ID, which is

node_accommodation_form

As in:

function zeilschepen_form_alter(&$form, &$form_state, $form_id){
  switch ($form_id) {
    case 'node_accommodation_form':

Using #attached, as mentioned in comments, is far preferable to drupal_add_js() when you get to that part.

As an aside, you may find coming back to your code later on a bit easier if you separate out your form alters like so:

function MYMODULE_form_node_accommodation_form_alter(&$form, &$form_state, $form_id) {
  // Logic specific to the accommodation node form, no need to check form ID.
}

Also, as noted in another answer, theme hooks are only run when the theme is actually in use. So if you're using the admin theme for your node edit forms, your code will never run. If that's the case, you need to move the logic to a module.


How do I show the members in a block, contextually filtered by the currently logged in user? In my project every group member will only ever belong to a group; some group members have the Group Administrator role.

I would like to create a view block to satisfy this story: As a user with the Group Administrator role I need to see a list of all members in my group so that I can easily access their information from any page.
Putting it in another way: I need to show a block on every page that lists all members of the group that the currently logged in user is an administrator of.

The permission stuff is simple enough. What I'm struggling with is the contextual filter on the view, and I'm thinking now that I'll need to do some code customization. I can't just add "UID of currently logged in user".  Am I missing the right configuration?

I just found this approach of making a custom block. I'll start going down that path but still very curious if I'm missing something.

Based on that link from Drupal.org, I'm currently doing the following:

/**
 * {@inheritdoc}
 */
public function access(AccountInterface $account, $return_as_object = FALSE) {
  return $this->groupMembership[0]->hasPermission('view group_membership content') &&
  count($this->groupMembership[0]->getGroup()->getMembers()) > 1;
}

/**
 * {@inheritdoc}
 */
public function build() {
  $build = [];

  //$build['group_member_block']['#markup'] = 'Implement GroupMemberBlock.';
  $build['group_member_block']['item_list'] = [
    '#theme' => 'item_list',
    '#list_type' => 'ul',
    '#wrapper_attributes' => [
      'class' => [
        'group-member-list'
      ]
    ],
    '#items' => $this->getGroupMembersItemList(),
  ];

  return $build;
}

protected function getGroupMembersItemList() {
  $group_members = $this->groupMembership[0]->getGroup()->getMembers();
  $items = [];
  foreach ($group_members as $member) {
    $user = $member->getUser();
    $items[] = [
      '#markup' => $this->getGroupMemberName($user),
    ];
  }

  return $items;
}

It is a pretty darn simple way to do it. For some reason, I expected to be able to hop right into views and build it though.  Again, maybe I'm missing something simple.

One custom solution that is doing the exact same thing in my case is to create a view-block and show group content of type group membership. Then add the relationship Group content User, require this relationship, filter by plugin Group membership. Then add a contextual filter Group content: parent group. Add all fields you want to show in the view and use the relationship Group content user to display name, id, email etc.

Now the "custom" part in my solution is a tiny module that implements the hook_views_pre_view() and adds the gid of the currently logged in user to the $args array of that specific view like this: $args[0] = $gid;


How do I theme a custom form? I generate a simple module "myformtest" with a simple Class form "MyformtestForm". I want to use a different theme for the form.

I followed this great tutorial. I added a "_theme_suggestions_alter" hook in my "myformtest.module", I activated twig debugging and I loaded the form page.

My "suggestion theme" is present and its name is "form--myformtest-form.html.twig". Then in my module directory:

I added a sub-directory "templates"
I added the twig file "form--myformtest-form.html.twig" in the sub-directory "drupal/modules/custom/myformtest/templates"

In the twig file, I added this simple code. (I copied it from the drupal/core/themes/classy/templates/form/form.html.twig and added the h1 html element for override)

TEST

<form{{ attributes }}>
    {{ children }}
</form>

I clear caches (drush cr) and I reloaded my form page. But the html element h1 ("TEST") doesn't appear! Where is my mistake?

UP

I did it ! I added the hook theme in my .module file :

function myformtest_theme($existing, $type, $theme, $path)
{
  return array(
    'form__myformtest_form' => array(
      'render element' => 'form',
      'template' => 'form--myformtest-form',
    ),
  );
}

But.... ! When I load my form page, the html element h1 "test" is displayed but not the form :/ I thinked my .twig file override the form.html.twig default theme.

Did I miss something ? Why the form doesn't displayed, how can I fix it ? And how can I pass a custom array from my build method of form Class to my twig template ?

I've just been encountering a similar problem. And solved it like following.

In my MYMODULE.module file:

function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'mythemename' => [
      'render element' => 'form',
      'template' => 'my-template-name',
    ],
  ];
}

In the $form:

$form['#theme'] = 'mythemename';

And finally in the my-template-name.html.twig template:

<div class="someclass">
  {{ form }}
</div>


One account, one email, two different usernames I am trying to create a social website that each member can create two different profiles with two different usernames, one public and one private. The member should be able to toggle between profiles the same way you do with facebook when you toggle between your main profile and a different page you own. The member is able to post new nodes as his/her private username or public username by simple toggling between the two.
I have been researching many modules such as profile2 and subuser. The problem with subuser is that you can switch between your main account and the subuser easily but you can't switch between your subuser and the main user except if you logout first. Also, with the subuser, you are required to add another email address for each subuser. It would better if there is only one email address access to both accounts. What is the best solution?

Due to drupal architecture you should go with a custom solution that create a second account for the user when he register by adding a global known prefix for unique fields that would be used when switching the user account.

Say user registered with mail someuser@somedomain.com you will make another account using that mail someuser.{global_key}@somedomain.com having {global_key} set in code you will use it for logging the user when he needs to switch accounts.

Scenario:

user registered
in custom module implement hook_user_register() and create another account for the user by using the {global_key}
if user needs to switch account do login by adding the prefix {global_key} to username (you could add to password or let password be the same) let switch account be a hook_menu implementation reading the

  global $user object and create a new account using {global_key}

-user forget password send the reset password link with a query parameter identifies the account will be reset by implementing hook_mail_alter

Hope that helps!


Apply conditionally an image style on an User Profile page At the moment the module “Image Styles Rules” is only available for drupal 7, is there another  way to apply conditionally an image style depending on the aspect ratio of the image (portrait or landscape) in Drupal 8? Specifically to be applied to the image profile of an user, on his/hers respective profile page.

This module auto image style, is also available for drupal 8.

It describes:

  Allows to apply an image style depending on whether the orientation of original image is portrait or landscape.

So it might be what you want.


Using the menu API, how do I get only the enabled links? Using the code below I am able to get all the titles and links from the main menu, however, I only need the enabled ones.
I have been searching for an answer for a couple of days but have been unable to find any.

$tree = \Drupal::menuTree()->load('main', new MenuTreeParameters());
foreach ($tree as $item) {
  $title = $item->link->getTitle();
  $url_object = $item->link->getUrlObject();
  array_push($menulinks, $title);
  array_push($urlformenulink, $url_object);
}

Please assist.

Set onlyEnabledLinks() on the menu tree parameters:

$parameters = new MenuTreeParameters();
$parameters->onlyEnabledLinks();
$tree = \Drupal::menuTree()->load('main', $parameters);


How to create a basic message - notifications system displaying a real time message counter badge? I'm looking for a way to create a basic current user notifications system for my site, e.g.:

"some user" has created a new "group"
"some user" has joined your "group"
"some user" has posted a node in your "group"
"some user" has written a "review" for your "article"
"some user" has commented your "review"
etc...

I imagine this system as a simple menu link with a counter badge attached to it showing the number of new unread notifications just like this site or linkedin.com site.

When clicking upon this link current user will be directed to a page showing the user's new notifications and the counter will be then set to 0.

I believe what I need is the Heartbeat or Message module, combined maybe with Menu badges. But I'm not sure what to choose and how to start. Any advice?

For real time messages, you will need the Node.js integration module. You can use Heartbeat, the Taskbar and the Message modules together to show notifications.


Distinct classes for each row in views-table Is there a code that I add to my views style tables file that will give me distinct classes for each row in a views-table? or is there a module? I am working in Drupal 6

I have two ideas:

1) with :nth CSS selector you can reach every row you want with your style rules. For example the third row can be selected with the selector:

.table-class .tr:nth(3) td { background: red; }

2) with jQuery


How to use nodereference_select in custom form (set default value) D6 I am building a custom form using the Form API. I want to show a nodereference_select in my form. However I have some difficulties setting the default value and the list of values.

//Create array of values
$items['6039']="MT";

// add field
$field = content_fields('field_nodereference_select');
$form['#field_info']['field_nodereference_select'] = $field;
$form += content_field_form($form, $form_state, $field);
$form['field_nodereference_select']['#weight'] = 6;
$form['field_nodereference_select']['#default_value']=$items;
$form['field_nodereference_select']['#options']=$items;

When I render the form I see the widget but without any values.
When I am able to render the $items array, my next step would be to executing a view (because the nodereference_select is using a view to select certain values). and fill the $items array with the values.

Any help on this one?

I've managed to use such a field widget in a custom form in the following manner

  $field = content_fields('<field name on a node type>', '<node type that uses this field>');
  $form['#field_info']['<field name on a node type>'] = $field;
  $form += content_field_form($form, $form_state, $field);

I don't know if it would work without a node type actually having such a field.
I had a node type with that reference so I could "invoke" that.

The resulting form element does not look like a simple select element, it does not have '#options' and '#default_value' is fancy too.


Attaching Theme Library to Custom Module I have a subtheme called bootstrap_subtheme. It has a library called global-styling. I created a custom module called telephone_alter. In telephone_alter.module, I have the following:
function telephone_alter_form_user_form_alter(&$form){
  $form['#attached']['library'][] = 'bootstrap_subtheme/global_styling';
}

it does not load the bootstrap_subtheme library stylesheet. I do dump($form) and get the following:
  "#attached" => array:1 [▼
    "placeholders" => array:1 [▼
      "form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM" => array:1 [▼
        "#lazy_builder" => array:2 [▶]
      ]
    ]
  ]

seems like the attachment isn't even grabbing it. Yes I am using the right form alter according to the api: hook_form_FORM_ID_alter() and my ID is user_form . It does fire off, if I attach css from within my module's folder, but not my subtheme. Any help would be great! Thank you.
One more note:
my root dir is as follows:
modules
   -telephone_alter
theme:
   contrib:
      -bootstrap
   custom:
      -bootstrap_subtheme

Here is bootstrap_subtheme.libraries.yml:
global-styling:
  js:
    js/popper.min.js: {}
    js/bootstrap.min.js: {}
    js/global.js: {}
  css:
    component:
      css/style.css: {}
  dependencies:
    - core/jquery
    - core/drupal

Based on that structure, you're referencing the library incorrectly.
It should be $form['#attached']['library'][] = 'bootstrap_subtheme/bootstrap_subtheme.global-styling';
As noted in a comment below, the duplicate use of the theme name may not be necessary, and $form['#attached']['library'][] = 'bootstrap_subtheme/global-styling'; should work according to the docs. (Note the use of a dash, matching the library name versus an underscore in your code.)


The requested page "/user/password" could not be found. need to reset my password I'm using Drupal 7.

For some reason my admin password on mysite wont work, when I click forgot pass word I a presented with The requested page "/user/password" could not be found.

I don't know what is causing the reset password page not to show, I thought it may be tabtamer but I disabled that by setting status to 0 in my database.

It might be a Facebook connect module as I only allow users except admin to login via Facebook but as I can't log in to my site I can't check.

How can I reset or log into my site if I do not know the password and the page to request a new one isn't working?

You could try the following drush command:

drush uli


Drush does not work invoking the local Drush I have installed new D8 on a remote server using this way https://github.com/drupal-composer/drupal-project .
I have pulled files from GitHub and I have run 'composer install' for getting the all vendor files include the local Drush (/vendor/drush/drush/)
When I run 'drush status' or 'drush core-status' on the root (or '/web') website directory I have:

vagrant@drupalvm8:/var/www/drupalvm/test8$ drush core-status
PHP Warning:  pcntl_exec(): Error has occurred: (errno 8) Exec format error in /usr/local/share/drush/includes/startup.inc on line 412
Warning: pcntl_exec(): Error has occurred: (errno 8) Exec format error in /usr/local/share/drush/includes/startup.inc on line 412
Error has occurred executing the Drush script found at /var/www/drupalvm/test8/vendor/bin/drush.launcher (errno 8) Exec format error

This Drush issue has been fixed in the recent version (8.1.5 and above) by refactoring how the code was using Phar class.

Here are updated steps how to install Drush using phar (as per install.md):

# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
php -r "readfile('http://files.drush.org/drush.phar');" > drush
# Or use our upcoming release: php -r "readfile('http://files.drush.org/drush-unstable.phar');" > drush

# Test your install.
php drush core-status

# Make `drush` executable as a command from anywhere. Destination can be anywhere on $PATH.
chmod +x drush
sudo mv drush /usr/local/bin

# Optional. Enrich the bash startup file with completion and aliases.
drush init

Or by the following one-liner:

sudo install <(curl http://files.drush.org/drush.phar) /usr/local/bin/drush


Where does the value of entity come from in a field of a content type? Where does the value of entity come from in a field of a content type?

I am trying to understand how the property (if it is a property) entity is related to the field.

This question is more informative, I describe my case below.

I have a type of content News, in this I added field of type image called "field_image" with a limit of a single value.

Type of content: News
Field: field_image

Debuggin:

I programmatically load the node:

// Return Drupal\node\Entity\Node;
$node = $this->entityTypeManager->getStorage("node")->load(1);

// {\Drupal\file\Plugin\Field\FieldType\FileFieldItemList}
kint($node->field_image);

// {Drupal\file\Entity\File}
kint($node->field_image->entity); // from where comes from entity?

From the last example I show above ($node->field_image->entity), where does the property entity appear, how can field_image access it and know that it is a file type field?

I'm just trying to understand these internal Drupal relationships.
Thank you very much for helping me understand this.
regards

It's literally magic (well, PHP magic methods anyway).

FieldItemBase implements __get(), which will respond to any property on the object (existing or not):

public function __get($name) {
  // There is either a property object or a plain value - possibly for a
  // not-defined property. If we have a plain value, directly return it.
  if (isset($this->properties[$name])) {
    return $this->properties[$name]->getValue();
  }
  elseif (isset($this->values[$name])) {
    return $this->values[$name];
  }
}

And the image field type extends the entity reference field type, which maintains an entity property (see EntityReferenceItem::propertyDefinitions).

So when you request the non-existent entity property on the field class, FieldItemBase hooks it up for you via the $properties array, and you get an entity back.


Remove link from $title in comments I'm using Drupal 7. When I post a comment to an article, its title looks like comment title.

I need only the “comment title” to be displayed, without the link.

I found the code in the comment.tpl.php template where the title of the comment is printing.

  <?php print render($title_prefix); ?>
  <h2<?php print $title_attributes; >><?php print $title>

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

As is said in the file description, $title already contains the link, so I can’t change it!

  $title: Linked title

Does anybody know if there is a way to print the comment's title without a link?

Instead of

<?php print $title; ?>

You can do:

<?php print check_plain($comment->subject); ?>


ubercart recurring payment for paypal Does any one have experience of implementing uc_recurring module along with paypal as I have configured it as per the documentation specified from module's documentation but its still not working.

Any insights on it would be helpful.

Tks,
Vil

After going through all the configurations, I found out that skipping review order step was causing the problem.Now its working fine.

Tks
-Vil


drupal 7 default table to store form values I am new to drupal and creating a module consist of a form. Now I want to store values in database, please tell me what is the default table in drupal to store form values?
Like in WordPress we have wp_option table to save data.
Is there any default table in drupal or I have to create new one?
What is the exact use of node table?

You can use Drupal variable system, please read the following article: https://www.drupal.org/node/1111260

You can create you own table, just use hook_schema for it: https://api.drupal.org/api/function/hook_schema/7

If you to get information from your users by form and store it, please check the module webform:  https://www.drupal.org/project/webform

Node table used for storing main information about nodes (it's some type of content). Node can by "Article" or "News", etc. More you can read here: https://www.drupal.org/documentation/modules/node


Geocoder not working with “Geocode from another field” I'm trying to make Geocoder work but encountered the following issue: I installed Geocoder 7.x-1.2, and I want to use it with content from another field, namely Location 7.x-3.0-rc2. I installed Leaflet to try to display my nodes. When I create new nodes, the Geofield is not filled in anymore(it remains empty whatever the address I try to use). I installed Address Field 7.x-1.0-beta4 instead of Location but the same issue persisting.

Are there common issues that would make the geocoding fail? If not, is there a procedure to try to debug this?

The issue can be solved by installing the other version of geofield module Geofield 7.x-2.0-beta1 (don't use the 7.x-2.x-dev version).


Hook into node/entity creation/insert Functionally, what I want to achieve is to duplicate a node (with a different node-type) when creating/inserting.

To be more precise: I have two content types: news and press-release. What I want to achieve is that when a press-release is made in admin, a news item is automatically created as well.

I looked into D8 hooks (hook_ENTITY_TYPE_insert to be specific), but can't get it to work, the documentation is confusing to me. This is what my .theme file looks like:

<?php
/**
 * @file
 * Bootstrap sub-theme.
 *
 * Place your custom PHP code in this file.
 */

/*
 * Implements hook_ENTITY_TYPE_insert().
 */
function hook_persbericht_insert(Drupal\Core\Entity\EntityInterface $entity)
{
    if (isset($entity->field_duplicate_to_news) && $entity->field_duplicate_to_news[0] === 'on')
    {
        // create a new news-article here
    }
}

Any help and suggestions are welcome

Whenever in drupal documentation it says to use "hook_" it means to replace "hook_" with the name of your module or theme.  Often on this site, you'll see "mymodule_" used as an example.  When you see "ENTITY_TYPE" in a hook description that is usually going to be "node" "taxonomy_term", "user", etc., it is not the bundle, or subtype of an entity.  Drupal nodes are labelled as "Content Types", which is synonymous with bundle.  Bundle is the term used across many different entities and is a backend term, while they are labelled different things on the front-end for different entity types.  For nodes, they are "Content types", for taxonomy, they are "Vocabularies".

You wouldn't want to use the bundle in your hook if it's looking for "ENTITY_TYPE", so "persbericht" ("press release") isn't correct.  You'd want to use node.

Themes can only implement a small number of hooks, such as alter hooks.  They can't implement CRUD operations.  So you'd want to put this in a custom module.

use Drupal\node\Entity\Node;
/**
 * Implements hook_ENTITY_TYPE_insert().
 */
function mymodule_node_insert(Node $node) {
  if ($node->bundle() == 'press_release') {
    $copy = Node::create([
      'title' => $node->getTitle() . ' copy!',
      'type' => 'article',
      'status' => 0,
    ]);
    foreach ($node as $key => $value) {
      // Copy values from all fields (fields start with "field_").
      if (strpos($key, 'field_') === 0) {
        if (isset($copy->{$key})) {
          $copy->{$key}->setValue($node->{$key}->getValue());
        }
      }
    }
    $copy->save();
  }
}


How to achieve MuchoMenu Multilingual functionality? I have used MuchoMenu in my site. Now I'm struck at translation.

There is no option to translate the MuchoMenu, also there is no translation strings available. How do I translate the menu links specified in the muchomenu?

Looking their module code, it appears as though they did not encapsulate many of their strings in the t() function. Therefore it's not exposed to Drupal's string translation functions. Unless you want to undertake the task of fixing it then, unfortunately, it's not available.

You could also lodge a bug in their issue queue and maybe that will motivate some discussion on their end.

Regardless, as long as mucho menu uses Drupal's native menu handler, it SHOULD still use the same functions for translation for links. Assuming you set up the menu to be translatable the links should be exposed as any other menu in Drupal.


Edit markup element permission I'm using webforms on Drupal 8.5.1 . I want to add some custom, arbitrary text to the form, so I chose to add a markup element. We want to have the text at the top of the form "Thank you for taking the time to fill out this survey. In order to serve you better..."

When the dialogue comes up, I see this:

From appearance and clicking, it seems like there is a missing textarea on the widget where I would enter the markup, right under the header "HTML markup".

I'm not sure if this is a problem with my install, my settings, or perhaps a bug.

I've looked at permissions and administrators have all webform permissions checked, and they are greyed out, so they can't be unselected. The account I'm using is an administrator account.

I am new to Drupal 8, and even more so its webforms. Is there something wrong in my settings?

The missing editor is most likely a bug.  You should see what is being logged in the browser's JS console.

@see https://drupal.org/project/webform/issues/2936147


Module to display a website's favicon when displaying a link to it I'm looking for a module that will display a website's favicon when display a link to that site. Specifically, I want to enable it to one certain Link field.

For example, if a user edits a node and uses the URL https://www.facebook.com/pages/Drupal/8427738891 in a Link field, I want to display the favicon https://www.facebook.com/favicon.ico.

Ideally, the module can cache the favicon locally (there are several benefits for this)

(Also: See my other question, if there is some a module that can do both it'll be great)

i believe this will work for you https://www.drupal.org/project/link_favicon_formatter

hope this helps:)


How to create a view showing the products from a user's company? I'm trying to create a relationship between a field on a user profile and a field on a content type.

User Profile
Company Name - This is an entity reference that pulls names from a Company content type.
Product - contains a field company which also pulls from a Company content type.

I'm trying to create a view which will show a user products his company carries.  So the view is a user view.  Contextual filter is the UID of the logged in user. Now trying to create the relationship to pull in fields from the product content type.

Basically, I'm trying to create a query that will show products where the product.company is equal to the user.companyname.

To achieve it with the current content architecture:

Create view of users.
Add a relationship Entity Reference: Referenced Entity. Mark it as required. This will make a connection between the user and the company.
Add another relationship Entity Reference: Referencing entity. Before saving add the value of the Relationship select list and select the relationship created in step #2. Mark this relationship as required too. This will make the connection between user company and the product.
You should now get the fields of products you could add to the view using the relationship you have built at step #3


LDAP Authentication + Drupal Registrations possible issue I wish to have a site that allows for both LDAP authentication and plain old Drupal authentication (Drupal users without LDAP accounts). LDAP accounts will be employees, while Drupal accounts will just be all other types of users.

I foresee a problem with this in the future: What if a new employee is hired and the username (which is mandated by business rules) is already taken by an existing user. For example, a user "Jason Smith" created an account jasons. A new employee "Jason Sutherland" is then hired and an LDAP account is created for him jasons. Using the LDAP module http://drupal.org/project/ldap, the employee jasons would essentially be locked out of our Drupal site. And no, we cannot ask the user to change their username.

What are my options here? I first thought of forcing LDAP accounts to login by their email, disallowing any users from registering with the suffix @company.org. Since this should be unique, this could potentially solve the issue. Is this a viable solution? How could I do something like this? Would this require hacking the LDAP module a bit? Do I have other options?

If anyone is interested, here are some methods of resolving this:

You can do a force creation of all ldap users before putting your
application into production. Edit I've written a module for this: http://drupal.org/sandbox/mrryanjohnston/1308882
You can require everyone to authenticate with their email addresses.
    This, too, requires a few modules and a little bit of figuring
    out, but it can work. This module is the result of some of those
    efforts: http://drupal.org/sandbox/branana/1300714


How to use one field with different settings I have a field that determines which category my content belongs to, stored in a taxonomy vocabulary. The field is used in both the content type and the user profile. Users may select a category, but they can select only one and definitely not more. The content however can belong to more categories, in my case 2. So the field settings should be different, but that is impossible when using a single field. Whenever i change the maximum number of values in useraccounts to 1, the field in the nodetype changes to 1 also.

I use the same field to be able to make some views (starting from a user's perspective) to display content based on the users choice.

I see three possible solutions:

Somehow use a field alias, enabling me to define the same field in 2 different ways. But i haven't found a mod for field aliases;
Define two seperate fields with seperate settings. But i can't filter my output in a View based on the value of another field. Also, using a contextual filter won't work because there is no value to pass in the URL;
Set the max value to 1 and add the same node twice, one for each category. Which is not the way to go, obviously.

Any clues to avoid option #3 ? I use D7 btw.

Thanx,
Cas

Set the maximum number of values to unlimited.

Then using hook_form_alter change the categories select to only allow 1 value on the user profile form:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'user_profile_form':

            //dpm($form);
            $form['field_category'][LANGUAGE_NONE]['#multiple'] = false;
            break;

    }
}

If need be you could also add an additional validation handler here to add some custom server side validation to make sure that the user is not selecting more than 1 department.


Getting a block inside main content I have created a Drupal page which consists of the main content of my page, text plus a photo, a nested box which is just a button and a views block which is the third element. What I want to do though is make the nested box go below the views block which is only possible if I add the views block to the content page class but I am not sure how to do it. Any ideas?

You can place your blocks in the "content" region and then you can arrange them in the correct order on the blocks page, admin/structure/block.

See screenshot below for Drupal 7 example.


Entity field query pager only loads first page How do I load any page other than the first page with Entity Field Query pager?

$query = new EntityFieldQuery();

$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->pager(4)
  ->execute();

This returns the first 4 nodes. If i have 12 nodes, how do I return page 2 nodes 4-8 or page 3 nodes 8-12.

The documentation states I can only pass $limit and $element. Have I missed something? What's the point of a pager that only loads the first page.

Here are some pointers:

The query looks fine
Try adding the parameter ?page=1 to your request and you should see different items. Page 0 is the one you see by default.
You need to display the pager object while building your output, like:
$output['pager'] = array('#theme' => 'pager'); This will make the pager visible and allow users to click on back/next buttons to navigate through pages to see other items which are not on the current page.


How do I put an article in a block? I don't think I understand Drupal too well yet.  I have an article.  In the theme I chose it has the various blocks.  How do I put an article on a given block area of a theme?

I see the modules I can assign to a block in a specific region, but I have things articles I want to put in the block.  I don't need who's online, recent comments, etc.

I don't know if there is any shortcut to put the article into Block, but usually I use Views for that. After installing Views Module

create new Views and select content of type Article
Check on Create a Block and Continue and Edit
In Fields, Select the fields you want to display eg: Article Title, Description, etc.
Use the Filter to filter results.

If you want to display only the latest Article, then use Sort by Post Date Desc and in Pager settings display max items to 1 with No Pagination option.

Go to Structure->Blocks and select your theme and you can enable/disable what blocks you want to display and where. If you are unsure about the regions in theme then click Demonstrate Block Regions

This looks one heck of a task, but playing around Views would make you more comfortable with Drupal.


How to insert fields into a link field in twig? We have several fields on our Article content type, one of which is a Link field. In a twig template we would like to display a
 such that all of it is clickable with different fields inside of it.

Current node--article.html.twig

  {{ label }}

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

Modified node--article.html.twig template to make entire
 clickable (desired output).

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

Is there another way I should be doing this?

I was looking for something similar to below. It would output what is under the Modified node--article.html.twig (above)

{{ link(label, url)|insert(content.body, content.field_subtitle, content.field_category) }}

I don't see anything for the insert tag in Twig or Drupal, but you can preprocess the url variable in mytheme.theme and pass it to the template, giving you what you want:

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

The url variable would be created in the preprocess function.

If its a standard link field, you could try:

$link = $node->get('field_link')->getValue();

if (!$external) {
  $variables['url'] = Url::fromUri($link['uri'])->toString();
}
else {
  $variables['url'] = $link['uri'];
}

Edit: totally forgot the line that checks if it is external.


How to Reorder menus (not menu items) I have the standard Main Menu, Management Menu, User Menu, etc., plus a bunch of custom menus. They are consistently shown in the same strange order (not in the order created, not alpha, not alpha by machine name) when shown in /admin/structure/menu/manage/. I can't determine a logic for the order.

I use Footer sitemap to place links in the footer and the various menus show up in this same order. I can find no way to change the weight of entire menus or reorder them. The database table I found was sorted alphabetically by machine name and not in the order I see at /admin/structure/menu/manage/. Any way to control this order?

You could probably try the alternative module Sitemap. They fixed the ordering issue in their latest version (7.x-1.3).


Language switcher doesn't work with my views I am new to this forum, but I hope to get an answer to my problem. Searching 2 days already, bur no success...

I have a multilingual (French and Dutch) D7 website. Besides the needed core modules enabled, I installed the i18n module and the variable i18n module. As for normal pages, everything works perfect. I have a menu for each language, the menu links refer to the correct pages. I have also a language switcher, which works perfect with my nodes.

Now comes my problem. I created a view to display a teaser of all products. Look at http://www.solarine.eu/solarine/ to see what I mean. I made a view for the Dutch language (called "producten"), and one for the French ("produits"). When you access the pages by the main menu, they display correcly (5 products for Dutch, only 1 for French). BUT if you use the language switcher to toggle between languages when visiting the products page, the content of the views stays in the wrong language.

Can anyone please help me with this? It MUST be possible to solve this, but after 2 days searching on different websites with no result, I am out of ideas.

Many thanks!
Steven

It is possible to solve this with Views, here is how:

Go to your view's edit page.
Add a Filter Criteria called 'Content translation: Language'
In the popup that comes after that, select 'Current user's
language'
Save the Filter Criteria and your view as well.

After this, this view will only show items that are the same language as the language you are using at the moment on the website.

You can however set a specific language to your view as well with the same criteria. You just have to select a language instead of 'Current user's language' and that view will only list content that are in that specific language.


Drupal 7: how to display the content of the field without the label in node--type.tpl.php? I created a content type called Community (machine name: community).

So I created file node--community.tpl.php to rearrange the fields.

I can do it like this...

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

it prints (with Phone in bold)...

Phone:
(888) 555-555

But I just want it to display the raw value with no label and no surrounding HTML. I just want  to print (888) 555-555.

How can I do this?

You can do this by editing the Content Type and managing the display of your fields - click the Manage Display tab.

Once in there, you can change the label to hidden.

See screenshot:


custom multiple values form element I have a field with multiple values and i want to make form element more intuitive to work with.

I thought the easiest way would be to create custom html and include it in form, with the other elements. Is this ok?

Now the problem is, on form submit i can't access any of these values in this fields that are not native form elements. Is there a way to convince drupal to take in into $form_state['values'];

I know the right way is to create custom form element but i am afraid it would took me too much time.

Is there a way to convince drupal to take in into $form_state['values']

Yes...use the Form API :)

To expand; Drupal builds and caches the fields for a form on the server side, and uses that cache upon submission to make sure the form hasn't been altered. Drupal, rightly, sees the injection of arbitrary HTML into the structured form as an attack vector, a security hole which must be plugged up.

Consider what would happen if this weren't the case - a client using your form could inject some HTML form values, overriding your particular intentions for the form submission. As Drupal cannot possibly reconcile the context in which that HTML string was added, it has no way to know if it's come from a trustworthy source.

Bottom line - if you want to add a field to a form that's managed by the form API, your code absolutely needs to conform to the same API - the alternative is to fight against it, which is never fun.

It's physically possible to get around the validation, but the amount of time it would take to convince Drupal to accept your injected form values, and at the same time keep it secure, would far outweigh how long it would take to use the form API as it was intended.


Can't set a file->description field in a paragraph programmatically I am running a drupal 7 migration into Drupal 8 paragraphs. I am retrieving the source fid, mapping from the file migration, getting the dest file id, getting the source file description, and then creating a new file paragraph that just contains a public_file field.

Problem is that I can't find a way to set the description field of the file? I can create the paragraph with the file fine.

I have tried the following (where field_files is the name of the field in the paragraph)

$file->set('description', $file_title);

.

$file->field_files[0]['description'] = $file_title;

.

$paragraph->set('field_files', $file);
$paragraph->set('field_files_descriptions', $file_title);

I have tried creating a test paragraph through the front end containing a description field and inspected the values, and there isn't anything obvious where I can set the value,

$testparagraph = $paragraph->getFields();
$testfile = $file->getFields();

The description value is only here in the paragraph entity

$testparagraph['field_files']->list[0]->values['description']

I'm at a bit of a loss where I can set this description.

The answer was incredibly simple

$paragraph->field_files->description = $file_title;


Multiple Contextual Filters I am trying to filter views output using Parameters from url with views contextual filter.
There are two fields on the content type :

1.field_sku
2.field_width

I simply added the contextual filter for the first one , but as i add the second filter it doesn't work.
Is it posibble to add multiple contextual filter to a view?

It is because how you get them,contextual filter usually get from url and when you have 2 , you should have 2 parameter in url , as example  it should something like "mysite.com/3/reza",
this is one step, another step is that you  specified in your contextual filter that which arg is for this filter(put your default value in raw value form url,then you see path componet), (in my sample 3 is arg(0) and reza is arg(1) ) and if you  observe this note it work for you correctly.


How to backport db_merge() to drupal 6? I am converting a module from drupal 7 to drupal 6. I have a query in drupal 7.
The query contains function db_merge()

   db_merge('facebook_rules_user_tokens')
    ->key(array('uid' => $form_state['user']->uid))
    ->fields(array(
      'user_grant' => $form_state['values']['facebook_rules_allow'],
    ))

Which function should I use in d6 for the above sql?

From the MergeQuery docs

An ANSI SQL:2003 compatible database would run the following query:

MERGE INTO table_name_1 USING table_name_2 ON (condition)
  WHEN MATCHED THEN
  UPDATE SET column1 = value1 [, column2 = value2 ...]
  WHEN NOT MATCHED THEN
  INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...

Other databases (most notably MySQL, PostgreSQL and SQLite) will emulate this statement by running a SELECT and then INSERT or UPDATE.

You need to do a SELECT using db_query first, to find out if your data already exists.
Then you can use drupal_write_record, which will do either an UPDATE or an INSERT depending on whether or not you populate the tables primary key(s).


Upload a file by Ajax without submitting the form I want to upload a file by Ajax (without submitting the form) than process in backend, and clear the field to allow to add another file. Is it possible with Drupal 8? Can anyone provide an example?

I tried this one but without success.

$form['input']['file'] = array(
  '#type' => 'managed_file',
  '#upload_location' => "public://$file_dir/",
  "#upload_validators" => array(
    'my_file_validator' => array(),
  ),
);

My questions are:
1. How to add an extra process callback (backend) ?
2. How to clear the field (Front end) ?

Thank you
Thank you

This code uploads one file with Ajax, attaching it to an existing node's file field. The content type is file_test, and the field is field_da_files.

(I'm not a professional programmer, so there are no doubt better ways to do this.)

Here's some HTML/JS that talks to a Drupal controller. It sends the node id, and the file to be stored.

In uptest.html.twig:

NID <input type="text" id="nid" name="nid">

<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">

In library JS file:

(function($, Drupal) {
  Drupal.uptestInitialized = false;
  Drupal.behaviors.uptest = {
    attach: function(context, settings) {
      if (Drupal.uptestInitialized) {
        return;
      }
      Drupal.uptestInitialized = true;
      $(document).ready(function() {
        $("#but_upload").click(function() {
          var fd = new FormData();
          var files = $('#file')[0].files[0];
          if (! files) {
            alert("No files");
            return;
          }
          var nid = $("#nid").val();
          if (! nid) {
            alert("No nid");
            return;
          }
          fd.append('nid', nid);
          fd.append('file', files);

          $.ajax({
            url: '/uptest-save',
            type: 'post',
            data: fd,
            contentType: false,
            processData: false,
            success: function(response){
              let result = response.success;
              if (result){
                alert('yay!');
              }
              else {
                let msg = response.message;
                alert('file not uploaded: ' + msg);
              }
            },
          });
        });
      })
}}})(jQuery, Drupal);

Routing file:

uptest.default_controller_hello:
  path: '/uptest'
  defaults:
    _controller: '\Drupal\uptest\Controller\DefaultController::hello'
    _title: 'uptest'
  requirements:
    _permission: 'access content'

uptest.default_controller_upload:
  path: '/uptest-save'
  defaults:
    _controller: '\Drupal\uptest\Controller\DefaultController::saveFile'
    _title: 'Save'
  requirements:
    _permission: 'access content'

In the controller:

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\File\FileSystemInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use \Drupal\Component\Utility\Bytes;

public function hello() {
  $renderable = [
    '#theme' => 'uptest',
    '#cache' => [
      'max-age' => 0,
    ],
    '#attached' => [
      'library' => [
        'uptest/uptest',
      ],
    ],
  ];
  return $renderable;
}

public function saveFile(Request $request) {
  $nid = $request->get('nid');
  if (!$nid || !is_numeric($nid) || $nid < 0) {
    return $this->makeUploadErrorResponse('Bad NID format');
  }
  $node = $this->entityTypeManager->getStorage('node')
    ->load($nid);
  if (!$node) {
    return $this->makeUploadErrorResponse('No node with nid of ' . $nid);
  }
  /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile */
  $uploadedFile = $request->files->get('file');
  if (!$uploadedFile->isValid()) {
    return $this->makeUploadErrorResponse('Invalid file upload.');
  }
  //Get uploaded file metadata.
  $uploadedFileName = $uploadedFile->getClientOriginalName();
  $uploadedFileExtension = $uploadedFile->getClientOriginalExtension();
  $uploadedFileSize = $uploadedFile->getClientSize();
  $uploadedFilePath = $uploadedFile->getPathname();
  //Get node field metadata.
  $nodeFieldMetadata = $this->getFileFieldMetaData('file_test', 'field_da_files');
  if (!$nodeFieldMetadata) {
    return $this->makeUploadErrorResponse('Problem loading file field metadata.');
  }
  //Check uploaded file's extension.
  $allowedExtensions = explode(' ', $nodeFieldMetadata['extensions']);
  if (!in_array($uploadedFileExtension, $allowedExtensions)) {
    return $this->makeUploadErrorResponse('Extension not allowed.');
  }
  //Check the file size.
  $maxSizeAllowed = Bytes::toInt($nodeFieldMetadata['max file size']);
  if ($uploadedFileSize > $maxSizeAllowed) {
    return $this->makeUploadErrorResponse('File too large.');
  }
  //Check cardinality.
  /** @var \Drupal\file\Plugin\Field\FieldType\FileFieldItemList $fieldValueInNode */
  $fieldValueInNode = $node->get('field_da_files');
  $fieldAttachedFileItemList = $fieldValueInNode->getValue();
  $nodeFileFieldNumAttachments = count($fieldAttachedFileItemList);
  $allowedCardinality = $nodeFieldMetadata['cardinality'];
  if ($nodeFileFieldNumAttachments >= $allowedCardinality) {
    return $this->makeUploadErrorResponse('Maximum number of files for this node already reached.');
  }
  //OK. Attach the file.
  //Prepare the directory.
  $directory = 'private://' . $nodeFieldMetadata['directory'];
  $result = file_prepare_directory($directory, FileSystemInterface::CREATE_DIRECTORY);
  if (!$result) {
    return $this->makeUploadErrorResponse('Error preparing directory.');
  }
  //Read the file's contents.
  $fileData = file_get_contents($uploadedFilePath);
  //Save in right dir, creating a file entity instance.
  $savedFile = file_save_data($fileData,
    $directory . '/' . $uploadedFileName,
    FileSystemInterface::EXISTS_RENAME
  );
  if (!$savedFile) {
    return $this->makeUploadErrorResponse('Error saving file.');
  }
  //Attach to the node.
  $node->field_da_files[] = [
    'target_id' => $savedFile->id(),
  ];
  $node->save();
  return new JsonResponse([
    'success' => TRUE,
  ]);
}

/**
 * Make a response for file upload attempt with an error message.
 *
 * @param string $message The error message.
 *
 * @return \Symfony\Component\HttpFoundation\JsonResponse Response to return to client.
 */
protected function makeUploadErrorResponse($message) {
  $result = [
    'success' => FALSE,
    'message' => $message,
  ];
  return new JsonResponse($result);
}

/**
 * Get metadata for a file field.
 *
 * @param string $contentType Content type with the field.
 * @param string $fieldName Name of the field.
 *
 * @return array|bool Metadata, or false if a problem.
 */
public function getFileFieldMetaData($contentType, $fieldName) {
  if ($contentType === '' || $fieldName === '') {
    return FALSE;
  }
  $entityFieldManager = \Drupal::service('entity_field.manager');
  $fields = $entityFieldManager->getFieldDefinitions('node', $contentType);
  if (!$fields || count($fields) === 0) {
    return FALSE;
  }
  //Get file field definition.
  if (!isset($fields[$fieldName])) {
    return FALSE;
  }
  /** @var \Drupal\field\Entity\FieldConfig $fieldDef */
  $fieldDef = $fields[$fieldName];
  //Get settings, doesn't include cardinality.
  $directory = $fieldDef->getSetting('file_directory');
  //Resolve tokens.
  /** @var \Drupal\Core\Utility\Token $tokenService */
  $tokenService = \Drupal::service('token');
  $directory = $tokenService->replace($directory);
  $fileExtensions = $fieldDef->getSetting('file_extensions');
  $maxFileSize = $fieldDef->getSetting('max_filesize');
  //Get cardinality.
  /** @var \Drupal\field\Entity\FieldStorageConfig $fieldStorageDef */
  $fieldStorageDef = $fieldDef->getFieldStorageDefinition();
  $cardinality = $fieldStorageDef->getCardinality();
  //Return results.
  $result = [
    'content type' => $contentType,
    'field' => $fieldName,
    'directory' => $directory,
    'extensions' => $fileExtensions,
    'max file size' => $maxFileSize,
    'cardinality' => $cardinality,
  ];
  return $result;
}

Hope that helps.


How can I create a custom form settings to my custom field formatter? I need to add form settings to my custom display format, can you provide me with an example?

To be clear I just want to add some fields to the format settings form.

Whenever you need to figure out how something works, look at examples that already do what you want. In your case, that's the ImageFormatter plugin.

Specifically, you are looking for the methods defaultSettings(), settingsForm() and settingsSummary(). Implement them, define the form for you settings, specificy default settings and for improved user experience, implement the summary method to give users a short summary of the current settings.

That's all, in viewElements(); you can then access your settings with getSetting().


How to create a Tour on the homepage? I created a Tour with the Tour UI module and I was unable to activate the tour on the homepage.

The homepage of my site is the default view of drupal 8 with the machine name frontpage

How to activate the tour on the homepage ?

Every time a page is rendered, the Tour module load all guided tours for this one. Those tours are added at the end of the DOM (with hook_page_bottom) with a css 'hidden' class. Then the Tour JS script (tour.js) handles those hidden elements by watching a triggering html element targeted by the id toolbar-tab-tour. If any tour is registered for the current page, that toolbar-tab-tourelement will also be hidden by tour.js.
I did this thing for showing a student role tour. I simply created a plugin block within my module:

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'StudentTourBlock' block.
 *
 * @Block(
 *  id = "student_tour_block",
 *  admin_label = @Translation("Student tour block"),
 * )
 */
class StudentTourBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    if (\Drupal::currentUser()->hasPermission('access tour') && !\Drupal::currentUser()->hasPermission('access toolbar')) {

      $build = [
        'tour_button' => [
          '#type' => 'html_tag',
          '#tag' => 'button',
          '#value' => ' ' . $this->t('Help'),
          '#attributes' => [
            'id' => 'toolbar-tab-tour',
            'class' => ['btn btn-success btn-xs hidden-sm hidden-xs']
          ],
          '#cache' => [
            'contexts' => [
              'user.permissions'
            ]
          ],
          '#attached' => [
            'library' => [
              'tour/tour',
            ],
          ],
        ]
      ];
      return $build;
    }
    else
      return [];
  }

}

Don't forget to attach the tour/tour library :)


Field Group Conditional State does not work after upgrade After recent upgrade of fieldgroup module, the conditional state visibility for field group does not work now.

Please find the previous code that used to work:

function ji_custom_field_group_build_pre_render_alter(&$element) {

  //BioChemistry
  if(isset($element['group_tr_biochemistry'])){
    $element['group_tr_biochemistry']['#states'] = array(
      'visible' => array(
        ':input[name="field_tr_test_ref[und]"]' => array('value' => 12),
      ),
    );
  }

  //CBC
  if(isset($element['group_tr_cbc'])){
    $element['group_tr_cbc']['#states'] = array(
      'visible' => array(
        ':input[name="field_tr_test_ref[und]"]' => array('value' => 15),
      ),
    );
  }
}

However this does not work after the upgrade.  I get an PHP notice instead:

  Notice: Undefined index: #id in drupal_process_states() (line 4651 of /srv/www/www.example.com/public_html/includes/common.inc).

Do let me know the workaround possible. Thanks.

Searched for some time. Tried different options. Finally reverted to older version 1.3 and it worked just fine :)

This was the bug which has not been addressed in the dev version as of now: https://www.drupal.org/node/2283245

Thanks.


How to combine two nodes based on common title in Views? I have a Commerce site selling clothing. Some Product Displays have multiple Commerce Products associated with them, and some have only one Product associated with them.

For example...

Shirt - Large - $10
Shirt - Medium - $8
Pants - One Size Fits All - $20

I need to use Views to display the title and price fields, as well as a link to the Product Display. I am using the Taxonomy term (Content) view with the Relationship "Content: Referenced products". I added the Title field, the "Size" field, and the "Commerce Product: Price" field, and enabled the "Distinct" setting in the Query Settings section. The result is as follows (fields are separated by a dash):

Shirt - Large - $10
Shirt - Medium - $8
Pants - One Size Fits All - $20

But I need the two "Shirt" items to be combined into a single line, like this:

Shirt - Large:$10 - Medium:$8
Pants - One Size Fits All - $20

Is it possible to combine products that have the same exact title (in this case, "Shirt")? There is only one Shirt product display page, on which the customer can choose Large or Medium.

Are you using multiple taxonomy terms field to enable the Large, Medium,etc sizes?

On the Views when you click on that taxonomy field, is there a way to show all fields in one line combined instead of separating them? Then use the Rewriting options so that you display with something like this:

[title] - [Sizes]: [Price]

Not sure if it will work, but worth a try. Experiment with separating out the different tokens and combining them in the Rewriting option.

Oh, what Alex said might work too.


Does cache-tag / cache context bubbling up mean core doesn't actually individually cache separate page components? So I read that cache contexts and cache tags bubble up to the entire page they're in. Let's say I have a custom page template with 3 sections that are populated in the page's theme preprocess hook:

[A: The Current Time]
[B: The Logged in User Name / A link to login if not logged in]
[C: Node and Taxonomy data]

A and B are very simple and C is very complex and slow. The node/taxonomy data only changes when new content is added, so it also happens to update the least often and the one we'd want to cache the most. B is different between anonymous users and logged in users, and also unique to every user. A is the same for everyone but changes every minute.

Normally, I would have A with a max-age of 60 seconds, B with a 'user' context, and C with the node:id cache tags relevant to what it needs to show (which we invalidate when new content that affects those nodes is added).

It seems to me that including A and B severely limit the ability to cache C, because if the contexts bubble up then B will force the server to keep a cached copy of the page for every different user. And if the lowest max age bubbles up (not sure if this is a thing) then A will force the entire page to be invalidated every minute.

Does that mean that this specific scenario would force Drupal to clear the cache for C every minute? Does it depend on how the page is implemented?

The bubbling is for the cache_tags and contexts, so it's related to when the cache on the parent item clears.  The parent item will clear based on the children, as the parent has all the child cache tags.  It doesn't mean that the children don't cache.  They do, but they won't refresh at the same rate as the parent.  The parent will potentially clear more often and then rebuild from the cached components.


How to reorganise files location without updating each node manually? In my file system, I have different folders where are stored the files linked to the nodes (either pictures in the body of the node or pictures in a 'Gallery' field I added to custom content type).

I'd like to reorganize all these folders in a more structured way.
How can I do that without editing each of these nodes?

Is there a way to update the database, e.g. change mydomainname/sites/default/files/mypicture.png (or whatever) to mydomainname/sites/default/files/pictures/yyyymmdd/mypicture.png where yyyymmdd is related to an event, for example?

My version of Drupal is 8.5.6.

Yes there is a way to fo this, I have the same situation in my previous project and I have achieved this by using below code:

    $field_name = 'FIELD_MACHINE_NAME';
    $entity_type = 'ENTITY_TYPE'; // Node or user
    $bundle = 'BUNDLE'; // Content Type.
    $table_field = $field_name . '_target_id';
    $table = $entity_type . '__' . $field_name;
    $db_conn = \Drupal::database();
    $query = $db_conn->select($table, 'th');
    $query->leftJoin('file_managed', 'fm', 'fm.fid = th.' . $table_field);
    $query->fields('th', ['entity_id', $table_field]);
    $query->fields('fm', ['filename']);
    $query->condition('bundle', $bundle);
    $entity_results = $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
    foreach ($entity_results as $result) {
      $fid = $result[$table_field];
      $file_load = File::load($fid);
      if ($file_load) {
        $new_directory = 'NEW DIRECTORY PATH';
        $new_uri = "public://" . $new_directory . "/" . $file_load->getFilename();
        $db_conn->update('file_managed')
          ->fields([
            'uri' => $new_uri,
          ])
          ->condition('filename', $file_load->getFilename())
          ->condition('fid', $fid)
          ->execute();
        drupal_set_message('File path changes successfully for for node id ' . $result['entity_id']);
      }
      else {
        drupal_set_message('Unable to load file for node id ' . $result['entity_id'], 'warning');
      }
    }

Here you have to be very careful while moving this to production. Backup DB and files before running this code.

And drush cr or clear cache after running this code for every field.


Making a variable in a certain node type and access that variable in another node type I'm fairly new to Drupal. But I'm trying to learn.

What I'm try to accomplish is have a variable in a certain node type (artist) and I want to access this variable in another node type (news). Is this possible?

Let's say I have two content types, Artists and News. The artist node will have (at some point) related pictures, songs, and news. But at default it does not have any. So I wanted a variable that acts like a flag that if there are any related pictures the flag is changed. In the news node, I have tags that point to an artist if the news is related to him/her, then I'll show the same related songs, pictures of the same tagged artist. I want the flag variable as a checker if there are truly related songs/pictures. In that way I'll just use the flag and before I query the related pictures/songs

What you are looking for is, basically, Entity Reference, as mentioned by Jimajamma and Bala:

  Provides a field type that can reference arbitrary entities

Just add entity reference field to news and allow artists to be selected. For pictures and songs, use either simply fields in Artist content type, or repeat the process - create content types for them, and add entity reference fields to artist content type.

Now, for display consider Views - it can use entity reference field to show all songs by artist in setup like that. I believe that's the easiest way.


auto complete fields from selection I have taxonomy term with 2 fields: a and b. I have two taxonomy terms.

term1: a1 and b1
term2: a2 and b2

I have a content type with 3 fields; the first one is from a selected list from the taxonomy terms (term reference). When I choose the first field, I need that the related taxonomy terms appear on the second and third fields.
For example, if I choose term2, I need that the terms a2 and b2 appear automatically in the other fields.

Is it possible?

Ok, if somebody are interested in it I've found this post that solve my question:

Auto-Fill from on content type to another