Hide fields in Paragraphs conditionally using Form API #states Because the Conditional Fields module doesn't work with paragraphs for Drupal 8, I've followed the instructions in Conditional Fields in Paragraphs Using the Javascript States API for Drupal 8 to hide some paragraphs fields, depending on the value asigned to another field.

But it only works when the dependee field value changes, when the node is edited or when a new paragraph is created, until I change the value in the dependee field manually, the dependent value is always visible.

Does anyone know how can I have those fields hidden when a value is already selected in the dependee field?

I had to do something similar for having localized paragraphs for foreign languages with an option to hide the paragraph (until release date).

The paragraph types I needed this I added a "Display Languages" checkboxes field with the options of All, supported languages, Hide.  For example, you could create a paragraph and tick the DE option and the Hide option. This paragraph was hidden until the Hide tick mark was removed and then it only showed when the language was DE.

Here's an example of the code I used for my announcement_banner paragraph type.  If you need it for more types, just implement the hook code for that type.

/**
 * Implements hook_preprocess_paragraph__announcement_banner().
 *
 * Handles language display for paragraph type.
 *
 * @param array $variables
 */
function MY_MODULE_preprocess_paragraph__announcement_banner(&$variables) {
  $paragraph = $variables['paragraph'];
  if (!MY_MODULE_can_display($paragraph)) {
    $variables['attributes']['style'][] = 'display: none;';
    $variables['content'] = [];
  }
}
/**
 * Checks if a paragraph can be displayed for the current language.
 *
 * @param stdClass $paragraph
 *   The paragraph entity to be tested.
 * @return boolean
 *   True if it can be displayed / False if it can't
 */
function MY_MODULE_can_display( $paragraph ) {
  // Transition check remove once new corporate branding active.
  if (!isset($paragraph->field_display_languages)  || $paragraph->field_display_languages->count() == 0) {
    return TRUE;
  }
  $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $hide = FALSE;
  $allowed = FALSE;
  foreach ($paragraph->field_display_languages as $value ) {
    $langCode = $value->getValue()['value'];
    if ( $langCode == 'hide' ) {
      $hide = TRUE;
    }
    if ( $langCode == 'all'  || $langCode == $lang ) {
      $allowed = TRUE;
    }
  }
  // Hide if hidden option checked.
  if ($hide) {
    return FALSE;
  }
  // Show if nothing is checked or match found.
  return $allowed;
}


Search API cannot search taxonomy terms I have built a search page using Search API, specifically the database version. This search page is a simple view and works exactly how I'd expect it to.

However, now I need to update the index so that it will search taxonomy terms associated with each piece of content. For reference, the field in question is field_author as a piece of content can be associated with several different authors.

From reading online, it seems like I should be able to edit the search index, scroll down to Add Related Fields, add Author, and that makes additional fields show up in the selectable fields to index section.

From there, I check the box beside Author >> Name (field_author:name), click Save Changes, and reindex my field.

However, a search for an author name does not produce any search results and I'm not sure why.

The above steps were correct. Additionally however, you need to add Author >> Name to the Fulltext search filter criteria in the view.


Can Location Modules Geo Code on node save? When I save a node that has a Location associated to it, it does not add the Longitude and Latitude values.  When I run the Autofill empty locations path: admin/config/services/la  it fills in all my nodes that have blank Latitude and Longitude values.

Is this normal?  I wish the Longitude and Latitude values get entered as soon as I save.

I figured out the problem. I have to set a Service for each country I want to use in the Geo Coding Settings: admin/config/content/location/geocoding


Change CSS of grid view (Not just for a field) in Drupal 7 I designed a grid of 3 columns in Drupal 7 using view. Below is the default outcome-

It doesn't look beautiful. Hence I want to change the css for each row and column, something like following-

I already have awards and award-list class defined inside style file. But I don't know how to configure the view, so that it uses these class instead of default classes.

Notice carefully the first image, in which I am able to add the css class awards (in the first line div). Also I am able to add css to each td element. This is perfectly fine. The problem is that td has some more parameters defined such as background, color, text-align, border etc, which I don't need for this view. Also there are few more unwanted attributes defined for table class view-view-grid cols-3. These elements are background and border, which I don't want for this view.

I found out a workaround, in which I redefine all these attributes inside style.css and I changed the border from 1px to 0px etc. See below the css, which I appended in style.css-

.awards table{
  background: #BAF5D9;
  border: 0px;
}

.awards td{
  background: #BAF5D9;
  color: #333;
  text-align: center;
  padding: 0px;
  border: 0px;
}

Here #BAF5D9 is background color of the theme. You can notice that it not a proper way to redefine. as the css is getting bigger.

I want to configure this view, in such a way, so that these attributes don't be generated.

Please have a look. I really appreciate your help.

You can add classes to view
https://www.ostraining.com/blog/drupal/css-views/

Also see:
How to add CSS classes to a Views-generated block? (NOT to its generated content, the block itself!)


How to make existing public files private? Let's say I have a node type "Article" which has a field "File" which is set to handle public files. A lot of articles and files get added.

Now the specs suddenly change and the "Article" will move behind a login and therefore also the attached files must be changed to be not publicly accessible anymore.

I already found out how to change the file system for the file field from public to private pretty easily by reimporting the manually updated field.storage.node.field_file.yml config. But: this only affects new files that will be added after the switch. It doesn't work for existing files. They still are accessible publicly. Many thousand existing files would need to be manually reuploaded to also make them private.

Does anybody of you have solved that in D8 before? If so, then how?

As all I can think of right now is to programmatically query all "Article" nodes, then foreach through all nodes, get the files, temporarily store them somewhere else, empty the field out, then try to reupload the files programmatically (probably my next question) and then resave each node.

Does that sound reasonable? Or can you think of any other approach that might work here (in D8)?

Thanks a lot for the answers! FileField Paths definitely is the way to go.

Update the file field's field storage to handle private files.
Run FileField Paths' Retroactive update on your content type's file field.

Step 1. can be accomplished from within hook_update_N (if you use configuration management do that locally and then export the updated configuration and deploy the resulting *.yml):

$field_type = 'file';
$field_name = 'field_file';

if (!$field_storage_configs = \Drupal::entityManager()
  ->getStorage('field_storage_config')
  ->loadByProperties(['type' => $field_type])) {
  return;
}

foreach ($field_storage_configs as $field_storage) {
  // Note: These settings apply to the field_file field everywhere it is
  // used.
  if ($field_storage->getName() == $field_name) {
    $field_storage->setSetting('uri_scheme', 'private');
    $field_storage->enforceIsNew(FALSE);
    $field_storage->save();
  }
}

Alternatively, follow the manual config update and reimport as suggested in the question.

Step 2. is to go to your file field's edit screen and fire the Retroactive update upon saving the form:


Node title does not update I wanted to add a word in front of the title for certain nodes.
So I run an update sql statement on nodes table. The result can be seen in the attached image.

I empty the cache (flush all) but my new titles still do not appear on the website.
Should I update in a different place in database also? Do I have to do something else to see the new titles?

Thanks in advance for helping me out with this !

I am pretty sure you have to update "node_revision" too.

https://www.drupal.org/node/320614

  Note that the node_revisions table in the database will always have one record associated with each record in the node table, which it keeps track of as the current revision. This will happen even if you do not have revisions enabled.


Set select box options in form_alter I have a select box named field_ee_project . I want to add the select box options dynamically on hook_form_alter .

What i have tried

    function gamodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
       //check whether the form is effort estimation
        if($form_id = 'node_effordestimation_form'){
            $form['field_ee_project']['und']['#options'] = effort_estimation_project_autoload();
        }
     }

    /*
     * Effort estimation project field select box
     */
    function effort_estimation_project_autoload(){
            $matches = array();
            $result = db_query("SELECT ga_id,name FROM ga_projects");
            $row = $result->fetchAll();
            $row = json_decode(json_encode($row), True);
            foreach ($row as $key => $value) {
                $matches[$value['name']] = $value['name'];
             }
            return $matches;
    }

But it is not working . Any idea ?

The Field Type API are more strict in Drupal 8 so that Web Services and Forms  follow the same validation path. This is not always the behavior that we want.

Looking at your question again, I think that using an allowed values callback on the field would work as well.

I provided some alternatives based on the restrictions that core places on list fields below #1 as well in case the following doesn't work as intended. These could be useful for other people doing similar things.

#1: Try to use allowed values callback for the field instead

Set an allowed_values_callback for the list field.

function gamodule_allowed_values_callback(FieldStorageDefinitionInterface $definition, FieldableEntityInterface $entity = NULL, &$cacheable = TRUE) {
  // @todo make this a bit more conditional based on the parameters above.
  $result = db_query("SELECT ga_id,name FROM ga_projects");
  $row = $result->fetchAll();
  $row = json_decode(json_encode($row), True);
  foreach ($row as $key => $value) {
    $matches[$key] = $value['name'];
  }
  return $matches;
}

Note that the documentation for callback_allowed_values_callback mentions using opt groups, but this functionality has a bug and is broken in 8.

#2: Migrate list field to text field

Make a Select list Field Widget for text fields. Migrate your data over.

Risks

A lot of work to re-architect.
May confuse a development team inheriting the site.

#3: Override the AllowedValues constraint plugin

Use hook_validation_constraint_alter to provide your own Constraint plugin (see Symfony 2 Constraint documentation).

Risks

Site is incompatible with a couple of contrib modules doing the same thing (select_or_other, cck_select_other).

#4: Make sure all possible allowed values are in the list field

Don't use a custom table to store allowed values. Set the allowed values in list field configuration. Write a field widget plugin.

Write your own Field Widget that restricts options based on some other parameter like your query.

#5: Override Core handling of list field plugins with your own implementation

Use hook_field_info_alter to not use Core code at all. Write your own List Field Type plugin with a better Options or Allowed Values implementation.

Risks

May confuse a development team inheriting the site.
All list fields now behave this way.


How do I avoid hard coding the links in a custom made navigation bar? I'm creating a custom navigation bar in drupal. I went ahead about this by creating it as a block and gave it all the neceassary CSS, but something that is not quit clear to me is how can I avoid the hard coding for the links?
or any other ways that I can achieve the same result?

You should create a menu for this (drupal menus works with system paths, no need to "hardcode" the links) and display this menu in a block where you want.


Add a form to the list output of a view Assume that I've created a view that outputs a list of cars. For each car, I display the name and the age of the car. This is all done with the Drupal UI. Now I'd like to add a simple button (Set as favorite) at the end of each line that when clicked saves the ID of the chosen car in a user's session variable. So my view table should look like the following:

Name Age Button
car1 23  'set as favorite'
car2 10  'set as favorite'

I am not asking about the session-variable part, but only how I can alter the view output to add a simple button to each row of the list output (I bet it'll be a form in each row).

I've done a lot of reading and I bet this could be done with hook_views_data_alter or some other hook_views_* but I'm not proceeding. I've already tried drop-buttons as suggested on Drupal 8 Add custom action buttons to a view, but that does not solve the things I need. I need the car's ID I want to save in a session variable, so basically I need a form functionality.

You probably can do this with just a Global custom text field and some hidden view fields.

E.g.:

Add car id to the view but exclude from view.
Move this to the top of the list.
Add a global custom text field for your Favorite button using the replacement values.  Could be something like:

Add as Favorite

Notes:

Classes are bootstrap specific.

Href is the code to set the favorite.

Destination string is Drupal way to circle back to view.


How to reduce the time needed to export a view with 50k rows into a CSV file? I am having a view with 50k records I want to export the view as CSV. I tried Views data export module but it takes around 20 min to export the data.

I have configured the view to use Batch export with Segment size 100.
I want to reduce the export time. Is there any way to do it?

As an alternative to using Views (and Views data export), you may want to give it a try using the Forena module (disclosure: I'm a co-mainter). If you do, I doubt it'd take 20 mins to complete such export (my bet is somewhere around 30 to 60 secs, at max ...).

To perform such export using Forena, just create a "report" to select (and sort, etc) the 50K records you want to export using the Forena module. And specify what kind of hyperlinks you want to make available for performing such "export". These hyperlinks correspond to various supported "formats", such as: CSV, PDF, XLS, XML, DOC, HTML ... (the "report designer" selects what the allowed/enabled export formats for a report are).

To get an idea of how that would look like, visit the Customized Simple Table of States. Notice the links in it, such as "CSV" (upper right), which in this case would "export" the results in a CSV file.


Custom node template with related node teasers I have a custom node (article) template file working fine, and I want to show related nodes (events) in their teaser format. I have been doing this in my node--article.tpl.php file like this:

foreach ($field_related_event as $event_node){
    print render(node_view(node_load($event_node['nid']), 'teaser'));
}

I wanted to add a second teaser format for events (teaser_fancy) and downloaded "Entity view modes" thinking I would be able to do something like this:

foreach ($field_related_event as $event_node){
    print render(node_view(node_load($event_node['nid']), 'teaser_fancy'));
}

But now I read that node_view can only use teaser and full, and it's probably not a good idea to render relationships in my template this way. What's the recommended way to go about this? Should I create an Events Fancy view and use views_embed_view instead?

A valid "view_mode" should work with node_view and that approach looks reasonable.

However, if it's proving problematic, you can also use Views with views_embed_view

e.g

print views_embed_view('viewname', 'display_id', $node->nid); // node id contextual filter


How do you use Drush to import a bunch of users via a csv file from the command line terminal? I have a csv file of users and I would like to use the "drush user-create" command to create an account with these users and have them blocked by default with no password.

I noticed that there is a --pipe option, but I'm unsure how to use this with drush user-create to consume a csv file.

My csv file is just an email and the state:

peter@yahoo.com,ny
sally@gmail.com,nj
howard@bl.com,oh
billy@yes.com,wy

It works with this:

awk -F "," '{cmd="drush -y ucrt " $1 ">> output"; system(cmd)}' users.csv

But it wouldn't work if you have thousands of users as it takes at least a second to create one. And also I can't seem to see the output when the user account is created. Not sure why "output" isn't working. But overall it works if you need to do it like that.

-F stands for field separator
The single quote starts the awk language
cmd is the command variable u designate
system is where you run the variable cmd
users.csv is the file.


Virtual Directory for "sites" folder in IIS 7 I am running Drupal 7 on a Windows using IIS 7.5. This is not something I can change and is required by my company. Everything has been running great which is awesome.

I would like to setup the environment so that the "sites" folder is outside of Drupal Core so upgrading core will only require changing the application's Physical Path and not require copying the "sites" folder between versions. I have been doing some reading and this seems like a very easy thing to do using a Symlink for any Linux Machine.

So I have been trying a couple different configurations and have had no luck. I tried moving the "sites" folder out of the Drupal Folder and creating a Virtual Directory for the "sites" folder in IIS. This did not work, Drupal does not seem to respect the virtual directory and when Browsing the site I am asked to install. This should not be the case since I have sites that are running and working when the "sites" folder is placed inside the folder.

The second method was to use Windows and not the Web Server. I kept the "sites" folder outside of core where I had moved it and created a Shortcut. The same way you would create any shortcut on Windows OS. I took the shortcut which was named "sites" and put it in the Drupal Core folder. This will not work either and returns the same results by asking me to install.

If anyone has experience working with Drupal and IIS and has an answer it would be greatly appreciated.

After some research and some help from a co-worker the answer has been discovered. It looks like Windows actually lets you create Symlinks, it is just not obvious.

http://technet.microsoft.com/en-us/library/cc753194(WS.10).aspx


How do I use variables from config.ini.php? I have a config.ini.php file as follows :

;<?php
;die(); // For further security
; // These php lines are used to hide the data from the browser
; // They are both valid php and valid ini files
;/*
; Don't forget to disable and reenable module, after adjusting the values
[folders]
var_1= "value1"
var_2 = "value2"

And in module_name.install file, I am using it as follows.

/**
 * Implementation of hook_enable().
 */
function module_name_enable() {
  $config_file = 'config.ini.php';
  $parameters = parse_ini_file($config_file);
  foreach ($parameters as $key => $value) {
    \Drupal::state()->set($key, $value);
    \Drupal::config('module_name.settings')
      ->set($key, $value)
      ->save();
  }
}

I then try to use a variable with the following code.

$getvar = \Drupal::config('module_name.settings')
      ->get('var_1');
\Drupal::state()->get('var_1', '');

I am not getting the value. What am I doing wrong?

As far as I know, you shouldn't be using a "config.ini.php" file for configs in your custom module.

You should have a /examplemodule/config/install/examplemodule.settings.yml file like this:

var_1: "value1"
var_2: "value2"

Then when you reinstall your module, it adds the values.  There's no need to run code in hook_install.

To access the values, use:

\Drupal::config('examplemodule.settings')->get('var_1');

and to edit:

\Drupal::configFactory()
  ->getEditable('examplemodule.settings')
  ->set('var_1', $value)
  ->save();

You're using state correctly, I tested this out:

\Drupal::state()->set('var_1', $value);

$var_1 = \Drupal::state()->get('var_1');


Add css to nodes of certain content type I've been trying to add css to a content type for a while, but I can't seem to find any help on this for drupal 8.

How do you add a library to only the nodes of a content type?

Thanks in advance!

The generic answer:

if (some condition) {
  $something['#attached']['library'][] = 'yourmodule/yourlibrary';
}

If you're in a module, do it in hook_node_view() and add it to $build. If you're in a theme, do it in hook_preprocess_node() and add it to $variables.

some_condition for your case would be $node->getType() == 'your_type', in case of preprocess, the node object is in $variables['node']

You can even do it directly within a template with attach_library(), see https://www.drupal.org/node/2456753.


Weekly Gym schedule / irregular recurring Events / D7 I've been searching and trying for weeks now, but could not find a way to properly display a gym's schedule. Here is the setup:

atm there are 3 gym branches with their own unique schedule (but using one pool of classes)
each gym got its own node showing a schedule table/calendar
classes recur irregular e.g. Gym-1: "Zumba" each Mo 8-9am and Fr 6-7pm (but Gym-2 with different times)
tables only need to be editable by admins; no user interaction
table granularity should be 15 or 30 minutes (but only showing rows with at least one item)
also, on the front page there will be a block, showing the next class for each gym (day and time)

So I created one node for each class (e.g. "Bodypump", "Zumba",..) and added all kind of fields but can not work out how to show them in 3 independent schedules. I think it has to be 3 views but unsuccesfully tried TableField, multi-value date Fields with FullCalendar, Taxonomy,...  Is it actually possible to do this with existing modules? Pushing me in the right direction would be highly appreciated!

Note: I am not capable of programming my own modules, but at least i would know how things stand when this is becoming necessary. Also I am not a Drupal pro and might have missed the obvious.. Thank you!

Try this:

Create content types gym1, gym2, gym3... > add suitable fields to them eg. Title and time(name the time field to field_gym1_calendar, reason for this -- see part five).
Create content: EXAMPLE: "content type: gym 3 --> Title: bodypump, Time: 10/10/2013 14:00-14:30".
You can also add a taxonomy "bodypump, zumba, etc..." and add a 'Term Reference'-field to your content type (This way admin doesn't have to type 'bodypump' or 'zumba' every time he's adding stuff to calendar, just select the right one from dropdown-box)
Install "Date Tools" and "Date"- modules
Go to Views > look for button "+ Add view from template" On top of the page.
Search for the NAME of the TIME field you added to CONTENT TYPE gym1.
Should look something like this: "A calendar view of the 'field_gym1_calendar' field in the 'node' base table."
Name this view to 'Gym 1 calendar'- for example.
If you have content in "gym1/......." It should be listed in "Preview" Below

Play around with "+ Add view from template" button, it creates a calendar view of any node type with -date / time- field in it (I think)

All this works in a commerce_kickstart install I'm currently f*cking with.. All the modules you need are listed in my comment... don't know. Have fun :)


E Newsletter sign up form I would like to create a sign up form for visitors to my site to receive an e newsletter. One of the stakeholders in the project has specified some additional functionality in that he wants an email to fire to the user after they have completed to form that asks them to validate their details and confirm they wish to receive the email prior to said details being stored on Drupal.

Is there an off the shelf solution anywhere in the community, or will I have to create something from scratch?

I have done a (very) quick search, which yielded no results - if someone has seen something/ heard of something that will give this functionality I would appreciate hearing about it.

Many thanks.

There is Simplenews module

  Simplenews publishes and sends newsletters to lists of subscribers.
  Both anonymous and authenticated users can opt-in to different mailing
  lists. HTML email can be sent by adding Mime Mail module.

Read documentation


How to configure gmap in template file I override node display for content type Match Fixtures by creating node--match-fixtures.tpl.php file and put code below:

<?php
$location = $content['field_stadium'][0]['#locations'];
$stadium_map = array('id' => 'stadium_map',
             'latitude' => $location['latitude'],
             'longitude'=> $location['longitude'],
             'zoom'     => 13,
             'width'    => '100%',
             'height'   => '400px',
             'type'     => 'Satellite',
);

echo theme('gmap', array('#settings' => $stadium_map))
?>

But it show wrong map and also not 100% width. I use gmap and location module. What is the correct way?

If its showing the wrong map, you might be displaying the wrong view mode. Make sure you have set the gmap display for view mode full.


Allow different users to upload pdf to nodes privately I am trying to build a question answer site in drupal 7. User with teacher role will create a question node, after that users with student role can upload answers in PDF. Different students can upload/attach their respective answers pdf for that question node.

Teacher after evaluating uploaded answer pdf will upload evaluated/corrected pdf for each student. Students can not view other students answers pdf or corrected pdf.

I am thinking to create a question content type and answer content type. Each answer will be linked to specific question node. Answer content type will have two file fields, one to upload answer pdf and another for corrected pdf.

Is my approach correct? Is there any better approach or any module which can help?

Creating two content types "Question" and "Answer" seems to be the right approach per me. These two could be related via entity reference fields. And the storage of the file fields should be "private" for the implementing the access control. I have recently written about private files in my answer you might check out.


How do I conditionally add a class to my page title within page-title.html.twig? I have a boolean field within my Page content type called Hide Title.

I need to conditionally add a class to h1's to visually hide them if this field is checked.

I have the following within page-title.html.twig

{% set hide_title = content.field_hide_title.0 %}

{% if 'On' in hide_title %}

{{ title }}

{% else %}

{{ title }}

{% endif %}

This is is not adding the class while the boolean is set on or off.

In page-title.html.twig you don't have access to content variable.
according to page-title.html.twig comment section:

Available variables are:

title_attributes
title_prefix
title
title_suffix

So you should implement hook_preprocess_HOOK to passe hide_title to your twig like the following:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['hide_title'] = $node->field_hide_title->value;
  }
}

Now you can do the following in your twig:

{% if hide_title == "1" %}

{{ title }}

  {% else %}

{{ title }}

{% endif %}


Term not being migrated into taxonomy reference field I've got two migrations set up, pulling from two separate JSON feeds.

The first is a feed of taxonomy terms with a tid, vid, and name. I'm able to run migration on this fine and generate the relevant terms on my Drupal 8 test build.

The second JSON feed is one of node articles, that includes a taxonomy reference field, with a name value that matches up with the terms migrated in the previous migration described.

When I run the second migration for nodes, the taxonomy reference field is blank.

I've tried both entity_generate and migrate_lookup plugins to no success

field_taxonomy_term:
  plugin: migrate_lookup
  migration: migrate_taxonomy_terms_en
  source: tid

The JSON file for the taxonomy terms looks like the following:

[{
"name":"Term one",
"tid":"1",
"vid":"Vocabulary"
},
{
"name":"Term two",
"tid":"2",
"vid":"Vocabulary","}]

The JSON feed for the node migration looks like:

   {"title":"Page title","field_taxonomy_term":"Term one"}

Does anyone have ideas on what I'm missing?

Thanks!

I'm sorry that in 8 months no one has answered this question.
I was stuck on this as well and finally got it to work by using the following format nested under the process key of your migration that will look up the previously migrated taxonomy:
field_taxonomy_term:
  plugin: migrate_lookup
  migration: migrate_taxonomy_terms_en
  source: field_taxonomy_term

The field_taxonomy_term from your node source should be the entity id of the taxonomy term.
Also it should be noted that I migrated the taxonomy vocabulary and the node that will reference the taxonomy as a group.  I'm not sure if that matters or not.  The order the migrations are executed in is determined by setting the dependency on the taxonomy migration in the node migration.


Working with a subtheme I am customizing my sub-theme and looking to see where to place styling rules. My web inspector is not showing me the specific files where the base theme rules are, it just show that all the rules are in foundation_subtheme.css.  I don't believe that I have any aggregation turned on, what do I need to do to see the specific files that the styling rules are inside of?

For example, how do I fine this rule?

.top-bar input, .top-bar select, .top-bar .button, .top-bar #contact-btn, .top-bar .button-ghost, .top-bar button {
    font-size: 0.875rem;
    height: 1.75rem;
    position: relative;
    top: 0.53125rem;
}

Even when I add a rule to _header.scss the web inspector doesn't show me that its there it only shows the main css file.

scss isn't parsed by the browser- it needs to be compiled to css... ,Assuming you have already installed ruby and sass, open a terminal window and navigate to your theme's root directory. Then sass --update to compile the styles once or sass --watch to continue compiling as you work.


Invalid argument supplied for foreach() error in a custom view I wanted to display a table vertically and I found some code to do so, but I'm getting the following error:

warning: Invalid argument supplied for foreach() in site/modules/views/theme/views-view-table.tpl.php on line 35.

Line 35 contains the following code: <?php foreach($row['title'] as $title): ?>.

If I comment out that line, the table stops to be displayed vertically. I read on drupal.org forums that modifying the user's view permissions was a way to resolve, but I granted all permissions to views and I am still getting the same error.

How can I avoid the error appears?

I fixed it..anyone using views hacks will need to nest the above statement in an php if statement to ensure there is data in the array.


How do I properly render a private file URI with l()? If given a private file with a uri of private://Screenshot from 2015-12-07 15-52-42_0.png. How might I use l() to properly render the link?

When rendered as follows I see https://server/drupal-private-file-system/Screenshot%20from%202015-12-07%2015-52-42_0.png instead of system/.... in the URL.

The function file_create_url() is what I was after. I'm able to find what I was after with that.

dpm(file_create_url($file_obj['uri']));


What makes a maintenance mode message display, when a site is not in maintenance mode? What makes a maintenance mode message display, when a site is not in maintenance mode? In this instance, it appears that it was because a contrib module was throwing a recoverable fatal error. So there was no WSOD/ general crash but because there was an error, the maintenance mode message was being displayed. Is this possible? I suppose it's too localised to really be sure.

This question is for Drupal 6 (it can't connect to the database) is the same true for Drupal 7?

Maintenance mode is not turned on, yet I'm getting a maintenance mode message. What's more it's being displayed as a second HTML page rendered fully marked up, beneath the target page which is also rendered fully marked up: Maintenance page being rendered as an entire page load after the main page load

If not in Maintenance it could also be an uncaught PHP exception as suggested here: "The website encountered an unexpected error. Please try again later." so check your Drupal logs (Reports > Recent log messages), or a problem with your database service.

You can test whether it's a database offline situation by using a special theme template based off of maintenance-page.tpl.php called maintenance-page--offline.tpl.php where you put your own HTML and text instead of printing the $content variable:

Connection to database lost!

[Suggestions about what to do...]

You can test what the page looks like (on your local dev environment) by disabling the mysqld temporarily and visiting your local site. Don't forget to clear the cache to get the new template to register before trying to test it.


Storing taxonomy terms count in DB In drupal 6 , Term Node Count were the module which was developed to store number of nodes containing each taxonomy term in DB , but it is not developed for Drupal 7 . Now my question is : "Is there any module like Term Node Count in Drupal 7 ? if not what solution do you present for this problem "

Note : In a project with thousands of taxonomy term I want to know which terms are used most and on the fly calculation will become too time consuming.

You should be able to do this with Views, I am pretty sure that is why the D7 port did not happen for Term Node Count (see: https://www.drupal.org/node/603868). A view can be cached so it will essentially store the value as that module did but it will update more frequently (or less if you want to set the cache up like that) and give more flexibility to where you can display the information. You can setup a view pretty easily for this:

This is just one way to get the information but the view will really depend on your use case for what you need the count for:

In Fields: add Taxonomy term: Name
In Relationships, add a Taxonomy term: Content with term
Add a contextual filter for Taxonomy term: Name
Choose 'Display a summary'
Choose 'Display Record count with link'.

Views is a very flexible module and chances are you are probably already using it, it will work for most all needs. You can also do this yourself in code pretty easily by doing the count and storing it statically then writing a update function that will update the term count every once and a while but it will cut down on flexibility but I tend to go for code if it makes sense.


Custom template for a specific page within module for Drupal 7 I'm writing a module for Drupal 7 that gives every user with the right permissions a new page in his profile. I want this page to only display the Drupal header and a div with a specific ID, for a JS web app to attach itself to. AFAIK, the easiest way to do this would be by using a template file that only prints those two things.

From what I read in Create a template for a custom page in Drupal 7?, I just need to create a page--user--%--POD.tpl.php file, which I have
 (the new page resides at the path user/%/POD). I have als added this file to my .info file.

name = Module with some template problems

...

files[] = page--user--7--POD.tpl.php

As a way of minimizing factors, I've started by creating a page for user 7 only, but this will have to work for any user eventually. I have uninstalled the module, cleared all caches and reinstalled it again, but it still doesn't get used when I browse to user/7/POD.

Any help would be greatly appreciated.

According to https://drupal.org/node/1089656, the correct hook suggestion that I need to implement would be page--user--POD.tpl.php. I've renamed my template file accordingly. No success yet.

I believe the original template name you had with the percent symbol was correct. The problem is you are doing it in a module, not in a theme.

By default, you have to put the template in your theme for it to be picked up automatically.

Also, in module info files, the use of files[] = something.ext is only for files that contain classes, so Drupal can autoload them. Files like template files, module files, installation files, etc. don't go in there.


How to export GMap configurations? I have a View block which renders a map through GMap formatter and includes two fields - Company Name and Address. When I export it through features and try to render it on another system, the map doesn't show up.
I've given custom height and width and some other configurations in GMap under Configurations > Web Services > GMap. I think the problem is that the configuration settings for GMap are not being exported with the feature. Is it possible? If so, how to export them?

Here's an image of the View

I found from my seniors that these configurations (in this case GMap configurations) are stored in variables and Strongarm module can be utilised to export them. After enabling Strongarm module, these variables will be available for exporting under Strongarm Feature Component in Features UI. The other system/environment on which these variables need to be imported will also need to have Strongarm module enabled.
Though these configurations were exported from my system and imported on the other system properly, the map still didn't show up on the other system, the reason being that the devel generate module which we were using to generate content of Contact content-type was unable to generate dummy latitude and longitude for the Location field (enabled through Location module). I entered those latitude and longitude values manually, saved the changes and vola! the map was rendered.
Note: In my case, I wasn't using a Google Maps API key so that wasn't a problem.


How to add condition for 1st Iteration in views-view-fields.html.twig file I am trying to implement a carousel , inside my views-view-fields--block_1.html.twig , I want to add  active class inside the div for the first Iteration . I have added the code in twig file but every time it is adding active class for all the iteration.

code snippet:

{% if fields.counter.content == 1 %}
{% set tag = "active" %}
{% else %}
{% set tag = "" %}
{% endif %}

In my view title,body,image and result counter fields are there . From result counter i am getting the value and comparing inside the above twig file. Can anyone give suggestion, how to achieve this.

Thanks,

If your code snippet is within a for loop, you could use either loop.first or loop.index in your if statement to target the first iteration.
 Refer to https://twig.symfony.com/doc/2.x/tags/for.html#the-loop-variable

Thus your twig template would probably resemble:

{% for item in items %}
  {% if loop.first 1 %}
    {% set tag = "active" %}
  {% else %}
    {% set tag = "" %}
  {% endif %}

... render row/field with class in template ...
{% endfor %}


Imagecache custom action: scale image to width defined by other field I would like to define a custom image style with imagecache_actions module, where the image is scaled to a width (in pixels) given by a interger field in the same node. How is this accomplished?

You would need to create a custom module to do this. Something like this... Create two files in a folder, for example, we'll call this User Defined Width.

user_defined_width.info

name = User Defined Width
description = A module that allows a user to define an image width.
core = 7.x

user_defined_width.module

<?php

function user_defined_width_image_effect_info(){
  $effects=array();
  $effects['advance_resize']=array(
    'label'=>t('User Defined Width'),
    'help'=>t('Resize to a size defined by the user.'),
    'effect callback'=>'user_defined_width_effect',
    'dimensions callback' => 'image_resize_dimensions',
    'form callback' => 'image_resize_form',
    'summary theme' => 'image_resize_summary',
  );
  return $effects;
}

function user_defined_width_effect(stdClass $image, $width, $height) {
      // Your logic here.

  $image->resource = YOUR_IMAGE;
  $image->info['width'] = YOUR_WIDTH_FIELD;
  $image->info['height'] = YOUR_HEIGHT_FIELD;
  return TRUE;
}

This should get you started, but the more I think about it, the more I think you are going to run into all sorts of problems with image caching, as image styles are stored in sites/default/files. You will need to override this some how and make sure the file regenerate on every page load. This wont be good for performance, but could probably be achieved with something like Image Style Flush


how to show html content when select box item selected i have a select box called Delivery method and it has two options Drop off and pick up..,i want to load few extra html fields like size ,pick up address to the page when user select pick up method,what is the best way of doing it drupal..

In custom form you can use ajax API for this. You can find the sample code from here

When you are using node form then use conditional_fields module for this purpose.


how to subtract 2 months from current month? I have used this :

  $date = date("Y-m", strtotime("-2 months"));

and it is gives "2016-12" but what i needed is "2016-11".

If you try to change format to dmY for example:
echo date("dmY", strtotime("-2 months"));
You will see that result is 01122016.

You can check comments from this question also:
https://stackoverflow.com/questions/10586615/current-date-2-months

And you can check solution here: https://stackoverflow.com/questions/9058523/php-date-and-strtotime-return-wrong-months-on-31st

Pass second parameter.


Attach Fields to Entity during install? How can I automatically attach/create fields to an entity when I enable a module that provides entities?

For example, I want my Entity to have an Image field, and a handful of text, date, and number fields ready to roll.

I see field_create_field and field_create_instance, do I need to define them or can I use whats already defined as fields in Drupal and just give them labels and default values?

This is a just a follow up to @googletorp's answer, you can use the following code to export an existing field instance definition to PHP code which you can then alter as you need to for your new instance:

$entity_type = 'node';
$field_name = 'field_name';
$bundle_name = 'node_type';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');

That will give you both the field_create_field and field_create_instance code for the field.


Drag & drop files into drupal site? Does anyone know of a module that allows to drag files from users computer into a target area in site (like in gmail or wordpress)?
ideally this would work with Image and other modules to insert the file "correctly" into drupal, save uploader info and allow adding meta data for file (like in the wordpress media area).

I've tried several solutions using the Media module with Plupload with drag and drop capability, but I have never gotten them to work the way I want. I don't like the way Media handles files and even though I can bulk upload them into the Media area, when I want to connect them to an individual node, I still have to select them individually with an awkward media browser. Not a fan.

However, I have been VERY pleased with Multiupload Imagefield Widget (requires: Multiupload Filefield Widget). It works with a standard Image field, no need to change your content structure or do anything weird. All you need to do is edit the Widget Type on your Image field and change it from Image to Multiupload.

It will let you use the standard Image field upload, but you'll be able to select multiple images at once and upload them all with one click.


Create a node programmatically? I found this code to create a node programmatically. It creates the node but the "title" field is not populated.

    $body_text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.';

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

  $node->title    = 'Node Created on ' . date('c');
  $node->language = 'en';

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $path = 'content/my-lipsum-' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);

The machine name of my Title is "title_field", but using this neither works:

  $node->title_field    = 'Node Created on ' . date('c');

Are you using https://www.drupal.org/project/title ? If that's the case you must treat it like a field:

$node->title_field[$node->language][0]['value'] = 'Node Created on ' . date('c');


How to set a multi-value image field's default value from author's profile field on a node create form? On /admin/config/people/accounts/fields page, there is an optional multi-value image field field_proof_images. There is a content type Proof, I reuse the field_proof_images in Proof.
Then on /node/add/proof page, I want the field_proof_images to be automatically filled with the images from field_proof_images in the user accounts.

How to make this in Drupal 7?

You can prepopulate from other content through Tokens and Entityreference field. Here's a tutorial: Automatically Populate Drupal Fields From Other Content.

I don't know if it works with images but I don't see why it wouldn't. Not sure about the multi-value fields, you can try and see.

For a custom module solution you can lean on Prepopulate.

In Drupal 8 you can create a custom Media Entity browser that would show only the current user images from that field, then you might be able to choose them, or maybe even set as default.

Saving the images into the Content types ensures that if the user changes their user images it won't affect the Proof content. But if you want to always have them the same then you shouldn't add that to the Proof content at all. Simply create a contextual Views Block that would always display the content author's proof images and display it on the Proof nodes.


How to select sub-terms in taxonomy when creating content? In creating a document management system I've created a taxonomy vocabulary with this structure:

Accounting
  Client 1
  Client 2
Client 1
  Contacts
Client 2
  Contacts
  Correspondance
Leasing
  Client 1
  Client 2

Then, in my Document content type I've created a term reference field called Tags which uses autocomplete. The autocomplete part works great, but I don't know how to differentiate Accounting:Client 1 from Leasing:Client 1 from Client 1 (parent level). When loading a new document, is there a way to reference these terms properly?

Simple Hierarchical Select is the module for the job.

  Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.

Just change the widget-type of field Tags to "Simple hierarchical select" after you install the module. This guide might come handy if you're running 7.


Why do I get a backup file that has three different sizes? I am using Drupal 7 site on a remote server (bluehost). I cleared the cache before the backup.

When I am using the backup and migrate module, and use admin -> config -> back up - the size of the file is 456 kb.
When I am using the my php admin interface, and Export the specific database - the size of the file is over 22 MB.
When I am looking at the database interface of bluehost, it's written that the same database is over 176 MB.

I know that I am missing something, but I can't figure out the answer.

What is the difference between the databases? Which one should I save?

456kb does sound very small, maybe you don't have much content/field data? Backup and migrate will exclude data from core cache tables, and the sessions and watchdog tables (though not cache tables installed by contrib modules) by default; so that might account for it. It's also probably gzipped.
An export through phpmyadmin will include all those tables (and perhaps isn't gzipped), so it should be larger than the backup and migrate version
The size of the database on disk, on the server, isn't and can't be proportional to the size of an SQL dump file. There are indexes and other meta data which take up space, so it will almost always have a larger footprint.

You don't need the cache table data, so as soon as you've confirmed that the dump from backup and migrate has the content you need in it (always a good idea to check), you should use that one going forward.


Custom token [node:customtoken] not available in rules action 'set a data value' I've created module with hook_token_info() and hook_tokens(). Now i can see my token in list of all availble tokens:

$ drush token | grep customtoken
 node        customtoken         Node related token

But this token is not available in rules action 'Set a data value'. What is the problem with custom token?

My rule looks like:

Events: 'After saving new content', 'After updating existing content'
Conditions: 'Content is of type'
Action: 'Set a data value'

1) The easy, but dirty way:
You can nest your tokens in an existing type (see http://drupal.org/node/1714418#comment-6468184). Eg, in hook_token_info() do:
  return array(
    'types' => $types,
    'tokens' => array(
      'site' => $my_tokens,
    ),
  );

Your tokens will appear under "Site information"
2) The harder, but cleaner way:
Define your own rules data type with hook_rules_data_info()
function mymodule_data_info() {
  return array(
    'vub_events_data' => array(
      'label' => t('My Module Data'),
      'group' => t('My Module'),
      'token type' => 'my_module',
      'property info' => array(),
    ),
  );
}

and use this in your hook_token_info() implementation.


How to find if file was successfully uploaded to webform I am using the file field in webform, I would like to check if the file was successfully uploaded. I was using

  .onChange

But that only means that a file was attempted to be uploaded. How can I be sure if the file was correctly uploaded. Would like to do this via javascript/jquery to trigger some next steps.

Thanks.

I wouldn't recommend doing this with javascript, you should use a PHP function to inform the client-side of success.

However, if you insist on doing it,  you could (in theory) just create a new AJAX call to the location wehre you expect the new file to be.   If it errors,  it means it wasn't uploaded.

$.ajax({
    url:'http://www.example.com/yourfile.jpg'
    error: function()
    {
        //file not there.
    },
    success: function()
    {
        //file is there
    }
});


update variable from 7.1 to 7.2 : got error message "The form has become outdated" Got D7 multilingual configuration with many modules, from which i18n...

Trying to update variable from 7.1 to 7.2 version, following http://drupal.org/node/1660798 #1 tutorial (I also tried other methods explained in other nodes like http://drupal.org/node/1670274 ).

After clearing cache (twice !), replacing old i18n and variable folders with the new ones, I try to run update.php. Nothing happens, I mean reloading same page... I try then to put website into maintenance mode.

After submitting maintenance mode form, got error message "The form has become outdated. Copy any unsaved work in the form below and then reload this page."
So I tried to put first into maintenance mode, before replacing folders. But then back to the same story : update.php reloads its page so I have to check again if I'm still into maintenance mode : BUT I'm not anymore...!

I guess what may happen is that changing variable folder generates the following mistake : Drupal doesn't read correctly its database variables, so doesn't see any more it is into maintenance mode ?

So who from the egg or hen comes first ? How could I manage that and stop eating aspirin ? Thanks a lot for sharing experience

So to answer the question :

for people who don't manage to update simultaneously variable and i18n to get variable 2.1 & i18n 1.7 :

even if unusual, you have to update first from your current version (i.e i18n 1.4  and variable 1.1 ) to i18n 1.5 and variable 1.2, only after that you'll be able to update to variable 2.1 and i18n 1.7 versions.

Always following same steps :

clear cache
replace modules folders with the new version
run update.php


How to mass-unpublish nodes? I have a site with a tremendous number of nodes of various content types. I want to set them all to unpublished, and I don't see a way to do that easily without going through page after page after page of content pieces.

I was thinking of doing a query directly on the database: UPDATE node SET published = 0; -- but will this correctly unpublish all content?

Edit: We're dealing with several thousand nodes, and as I understand, there's a hard-coded limit of 50 nodes displayed on the bulk edit page. So I am trying to avoid flipping through dozens of pages.

If you want unpublish all nodes, quick and dirty method is simple sql query UPDATE node SET status = 0; Then clear cache and its done. But if you use Views, they could still show unpublish content depends on settings.


How can I add something after the day/hour/time in a date select list? On Drupal 8, the select list provided by the Date module looks like this:

The site I am building in Japanese, and in Japanese, it's common to add a character to indicate what the number means, like this:

2018 2 5 15 00　-> 2018年 2月 5日 15時 00分

How can I add these labels?  I attempted to do it through the string translation UI screen, but since the year, day, hour, and minutes are just numbers, there is no way to "translate" them.  The month shows up correctly because it is translated from Jan/Feb/etc.

I am thinking the solution involves hook_form_alter() but I don't know how to modify the way the values are displayed in the select widget without actually changing the values input and causing the form to fail.

You can't use hook_form_alter() or hook_field_widget_form_alter() in this case. Try with hook_element_info_alter()

function MY_MODULE_element_info_alter(array &$types) {
  if (isset($types['datelist'])) {
     $types['datelist']['#process'][] = '_mymodule_add_suffix_value';
  }
}

function _mymodule_add_suffix_value(&$element) {
  // process logic option $element['day']
  // process $element['month']
  // process $element['hour']
  return $element;
}


How to verify a token in the url of a drupal 7 site against an external web service and skip the login form all together? Context

We have this JSON web service GET https://api.my-domain.com/accounts/me (and a bunch of other endpoints). It takes a token in the header. When that token is valid it will return

{
  "email": "me@my-domain.com"
}

That JSON web service is used by a web application. That web application links their users to a Drupal forum. We don't want them to log in again.

The simplest solution we could think of is to link the users to:

https://drupal.my-domain.com?token=123456789

The Challenge

Our challenge is for our Drupal instance to:

Read that token from the URL https://drupal.my-domain.com?token=123456789
Call our web service GET https://api.my-domain.com/accounts/me with header Authorization: token 123456789
If it responds with a status 200 response and {"email": "me@my-domain.com"}, have Drupal pick up the email value.
Drupal matches it against the drupal users.
When the user doesn't exist in Drupal, it has to be created.
And the user is logged (SSO) into the Drupal forum.
No login form was ever shown. The token was either correct (status 200 from the web service) or incorrect (status 403 or whatever) and some drupal node/page should show that an invalid token was used accessing the forum.

I have done some investigation but none of the solutions that I found quite matched this use case. Most show how to build a module and have the login form check against an external system. We don't need the form. Just a token in the url validated without a form. I don't want to build a fully fletched CAS-Server, OpenID or OAuth2 provider at the web service. We'd like to keep it simple and just verify one token in the URL against our web service.

Can we use a module for this? And how would the simplest version of this module look like?

So, I don't have a working solution for this (yet!) but I'm working on a similar use case. From what I've read, you can't really have an authenticated user do anything on a Drupal site without passing them through the user module, creating a user, and storing info about them in the database.

I believe you need to write a module that passes a user object based of the email in your json response to user_external_login_register passing in some sort of programmatically populated dummy text for the extra fields you need, and then programmatically create the user and log them in in the background. In theory, all you need to do is pass the user object based off of your 200 response, and proceed to create and log the user in.


How to limit the products available to choose from, in the inline entity form of a product display Drupal Commerce, when adding/editing a product display, allows for the creation of new products and the selection of existing products, using the inline entity form.

I have created a marketplace website in which multiple sellers can create their products and product displays.

Question: how to limit the available products to those created by the logged in user? When a seller creates or edits a products, he should be able to only select his own products in he 'add existing product' field.

I would have expected that the field would allow for the selection of an entityreference view, but that seems not implemented in the module.

Alternatives to accomplish the same are welcome! Thanks

When you are adding an existing product to a product display there is an autocomplete field that you can use to search existing products.

This field is called entity_id. If you use hook_form_alter() and inspect the form you'll see this field has a property called #autocomplete_path.

e.g.

$form['product_display_variations'][LANGUAGE_NONE]['form']['entity_id']['#autocomplete_path'] = 'inline_entity_form/autocomplete/node/product_display_variations/product_type';

You can visit that URL and see it just returns a set of json formatted results.

You can create your own path with hook_menu() and then use your path instead of the default one (make this change in hook_form_alter).

In your custom menu callback you can apply any additional logic (e.g. filtering by uid) to just return a sub-set of products. Then use drupal_json_output() to return your dataset.


Query remaining field names from a database table There's a database table. I know only one field name on the database table: username. How do I view  remaining field names on the table?
namespace Drupal\fixx_helper\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class AutocompleteController extends ControllerBase
{
   public function handleAutocomplete(Request $request)
   {
      $results = [];

      $input = $request->query->get('q');
      $database = \Drupal::database();
      $my_query = $database->query("select distinct username from banner_exports.ws_students where username like '$input%'");

      while($result = $my_query->fetchAssoc()){
         $matches[] = array('value' => $result['username'], 'label' => $result['username']);
       }
       return new JsonResponse($matches);

}}

There are multiple table locations for Drupal field data: the base User entity
table users_field_data & the user__$FIELD tables that contain the custom fields defined by site builder / developer. If you need field data from a DB query, then you're going to need to build a query with a few joins to put it all together.
If you're only looking for the field names then it's much earlier to use the entity field manager to pull the base & custom fields:
\Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user')


Drupal 7 Views Exposed Filter - How to Select all Taxonomy terms Upon adding new terms? Whenever I add new taxonomy terms I have to manually go into my exposed view filter to have them show up in the dropdown box when filtering. Is there a way to just select all terms with what im filtering by?

You have the answer in the attached image itself.

Just Un-select the Limit list to selected items then save the configuration. Now the all the terms for that selected vocabulary will be listed automatically.

When you selected Limit list to selected items options, only the selected terms alone will be exposed to the user.


How to print field type image in views-view-fields--xyz--block.tpl.php How to print field type image in this page?

I'm using this code:

print $fields['field_xyz']->content;"

Is it wrong?

Use field_view_field.

E.g.

$node = node_load($node_id);
print drupal_render(field_view_field('node', $node, 'field_your_field_name'));

Or if you don't want the label with the field then:

print drupal_render(field_view_field('node', $node, 'field_your_field_name', array('label' => 'hidden')))


request new password link does not work if not logged in When anonymous user comes to the site, the login block offers a link to "Request new password".  This returns the user to the home page with no action happening.  If a user is logged in, using the same link brings one to the reset password by email link.

What I want is a form taking username and returning email address with a link to the one time password change.

Drupal 7's core handling of password reset can seem a bit cumbersome, since it uses a one-time link to a one-time login reset page which can be confusing to users. I recommend using the Simple Password Reset module which streamlines the process and makes it very easy for users. It works great right out of the box.


template to add a h2 tag around a field group title I have a field group in my content type. I want to wrap an h2 tag around the title of the field group. I have tried looking at the node.tpl.php and field.tpl.php for a way to wrap just the title, and have not succeeded.

Where can I target this?

The way I dealt with this was to change the wrapper in the Manage Display section from a fieldset to a div. Then, options for the label element could be changed from inside the UI.


How can I set default value (prepopulate) for field in views exposed filter? I've tried to use solution from Can I prepopulate an exposed filter text field? but failed. Cache clearing does not help.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-test-populate-page" ) {
    $form['title']['#default_value'] = 'test title';
    dpm($form);
  }
}

Dimetry. Since it is a drupal view you can add the default value in views itself. Please open your view and in the Filter Criteria section select the field you want to add the default value. It opens up a popup in that you can able to see "Value" field. Please give your default value there.

Please see the below picture for your reference.


Revision tab not appearing I have just starting using Drupal today and am going through a tutorial for Drupal 7 (I am using Drupal 8). I have made several revisions; however, the Revision tab does not appear when in the Edit area. I am logged in as Admin and have permissions for everything. After several revisions I got fed up and decided to delete the node (content) by clicking the Delete tab - to my surprise, the Revisions tab then appeared to the right of the Delete tab. I cannot find any documentation on the Revisions tab only appearing once the delete button has been clicked. Is this standard behaviour or is there something that I am missing?

This is a known bug, and is being fixed: https://www.drupal.org/node/2592325. The fix is already present, it just needs test coverage now.


Password reset link gives access denied Password reset link is not working in drupal 8.6. The email with the one-time login link is sent just fine, but when the user clicks on the Login button, they get "You are not authorized to access this page" message. Even I tried to open user/reset/{id} with login as admin still same error. When I figuring out the issue I found one line in user.module line no 556
\Drupal::moduleHandler()->invokeAll('user_login', [$account]); is causing the issue. If I remove this line then I can reset my password successfully. whats this line is doing? Does it load all active modules in website? than there must be issue in any module. Could I remove this line? Any alter solution?

I tried by clearing cache,cookie, browser history, session table, also $cookie_domain = $_SERVER['HTTP_HOST']; this line is not in my settings.php

Had similar outcome but issue was purely that the User record was still set to Blocked rather than Active.


Perform a query with an entity field condition with multiple values I have a content type that has a entity reference field that allows users to add multiple taxonomy terms in that field. I'm attempting to perform queries that grab nodes that have a specific set of taxonomy terms within that field.

Using one value in that field works fine, like so.

    $query = \Drupal::entityQuery('node')
        ->condition('status', NODE_PUBLISHED)
        ->condition('type', 'custom_type')
        ->condition('custom_taxonomy', 2)
        ->sort('field_last_name', DESC);

Where 2 is the id of the term I'm searching for. However when I attempt to search for nodes that contain two specific terms like so,

    $query = \Drupal::entityQuery('node')
        ->condition('status', NODE_PUBLISHED)
        ->condition('type', 'custom_type')
        ->condition('custom_taxonomy', [2,8])
        ->sort('field_last_name', DESC);

I receive the error

  Invalid parameter number: number of bound variables does not match
  number of tokens:

I've also attempted

    $query = \Drupal::entityQuery('node')
        ->condition('status', NODE_PUBLISHED)
        ->condition('type', 'custom_type')
        ->condition('custom_taxonomy', [2,8], 'IN')
        ->sort('field_last_name', DESC);

Which doesn't fail, but doesn't provide the intended results. It displays every node that has either term 2 OR term 8. Instead of term 2 AND term 8 as intended.
How would I perform a query that checks if a node has multiple specific values in an entity reference field?

Use two separate andConditionGroup():

$query = \Drupal::entityQuery('node')
  ->condition('status', NODE_PUBLISHED)
  ->condition('type', 'custom_type');
$and = $query->andConditionGroup();
$and->condition('custom_taxonomy', 2);
$query->condition($and);
$and = $query->andConditionGroup();
$and->condition('custom_taxonomy', 8);
$query->condition($and);
$result = $query->execute();

This works no matter how many terms are in the field or in which delta they are.

Edit

This results in this SQL:

SELECT base_table.vid AS vid, base_table.nid AS nid
FROM
{node} base_table
INNER JOIN {node_field_data} node_field_data ON node_field_data.nid = base_table.nid
INNER JOIN {node__custom_taxonomy} node__custom_taxonomy ON node__custom_taxonomy.entity_id = base_table.nid
INNER JOIN {node__custom_taxonomy} node__custom_taxonomy_2 ON node__custom_taxonomy_2.entity_id = base_table.nid
WHERE  (node_field_data.status = '1') AND (node_field_data.type = 'custom_type') AND( (node__custom_taxonomy.custom_taxonomy_target_id = '2') )AND( (node__custom_taxonomy_2.custom_taxonomy_target_id = '8') )


Rules: How to modify an existing condition programmatically I've been able to add a condition to an existing rule, but I can't find any documentation on how to modify an existing condition on a rule. The following code works for adding but I need to modify the one that already exists. Any ideas?:

$hk_delivery_rule = rules_config_load('commerce_shipping_service_hong_kong_delivery');

$hk_delivery_settings = array(
    'first_price:select' => 'commerce-order:commerce-order-total',
    'operator' => '<',
    'second_price' => array(
      'amount' => $hk_threshold,
      'currency_code' => 'HKD'
    )

  );

$hk_delivery_rule->condition(rules_condition('commerce_price_compare_price', $hk_delivery_settings));
$hk_delivery_rule->save();

So turned out it was quite easy:

  $hk_delivery_rule = rules_config_load('commerce_shipping_service_hong_kong_delivery');

  foreach ($hk_delivery_rule->conditions() as $condition) {

    if (isset($condition->settings['second_price'])) {

      $condition->settings['second_price']['amount'] = $hk_threshold;

    }

  }

  $hk_delivery_rule->save();


Alter all images styles to add a particular effect before all others? I just downloaded the manual crop module: https://www.drupal.org/project/manualcrop

It must be added as an image style effect before it is applied.

I would like to apply it to all image styles before others are executed.

Is there any hook_preprocess_image_style that can add an effect to the stack before others are processed?

Or anybody have any other good ideas about how to do this programmatically other than manually adding the style?

Thanks!

Yes,  you can do this with hook_image_styles_alter.

I'm not so sure it's a great idea since you'll be enforcing adding your effect no matter what the user might try to configure via the interface, but it will definitely let you do what you want to do.


Can't find file to patch at input line 11, File to patch:? I got an error message on module installation simpletest

  SimpleTest could not be installed. Must apply core patch, please see INSTALL.txt. (Currently using SimpleTest code addition Not-found)

Then by the instruction provided by INSTALL.txt I run the command

  ioss@ioss-System-Product-Name:~$ patch -p0 < /var/www/Drupal/beeone/sites/all/modules/simpletest/D6-core-simpletest.patch

Then I got error below

can't find file to patch at input line 11
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|? sites/all/modules
|? sites/default/files
|? sites/default/settings.php
|Index: install.php
|===================================================================
|RCS file: /cvs/drupal/drupal/install.php,v
|retrieving revision 1.113.2.12
|diff -u -p -r1.113.2.12 install.php
|--- install.php    9 May 2010 14:13:31 -0000   1.113.2.12
|+++ install.php    7 Oct 2010 21:55:51 -0000
--------------------------
File to patch:

The patch is trying to alter the install.php file that comes with Drupal, but it doesn't find it. That file is normally removed, once Drupal has been installed.

What the command line is prompting for is the name of the file to patch, in the case has been renamed, or moved in a different directory.

Keep in mind that the SimpleTest module should not be installed in a production server, but in a development site.


How can I override the container.html.twig template for one submit button only? How can I override  container.html.twig for one submit button only?

It showing no template suggestions.

Based somewhat on kiemi's answer, you could go for something to this degree:

<?php

/**
 * Implements hook_theme_suggestions_container_alter().
 */
function yourtheme_theme_suggestions_container_alter(array &$suggestions, array $variables) {
  $pieces = [
    $variables['element']['#type'],
    $variables['element']['#name'],
    $variables['element']['#display_id'],
  ];
  $suggestions[] = 'container__' . implode('_', $pieces);
}

This will produce a suggestion, for example, of container--view-articles-featured.html.twig

Of course, if you want it to follow true Drupal template suggestion standards, you'll want to add several suggestions with varying levels of specificity.


How to rewrite the output of $content inside a pane template? I am trying to reformat / rewrite the output of pane content inside my panel template.

Here is what I have:

panels-pane--panels-mini--some-name.tpl

Inside this file I have:

print render($content)

I need to break apart the items inside of content. What is the best way to go about doing this?

Look in your panels module the function template_preprocess_panels_pane() you can use this.

http://www.drupalcontrib.org/api/drupal/contributions%21panels%21panels.module/function/template_preprocess_panels_pane/7

http://www.drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/template_preprocess_panels_pane/8


Register an anonymous user when entity form is submitted with rules I have created an entityform called "Order Request". This form has fields for the user to enter their first name, last name, email address, and their order contents. I would like to register this anonymous user when they submit this form. I have this working, configured with the Email Registration module and Rules to use these fields to create the new user.

However, the problem is this:
Both anonymous and registered users (with the role: customer) need to be able to use the form. I need to prevent an error if there is already an account created using the email address submitted in the form. I would like to check that and not fire the rule to create a new account. How can I create this conditional in my rule?
Hope that's clear. Thanks

I thought the field validation module should have been able to do this but I couldn't make it validate against the user mail field. Maybe you could try that and have better luck.

The other option which definitely works and requires no coding is to use the Views Bulk Operations (VBO) module and use rules conditions to check the number of results for that email address.

a. VBO Mail Check View

Create a new view page to display users.
Add the "Bulk operations: User" field (no changes needed).
Add the contextual filter, "User: Email" and provide the default, "Raw value from Url, path component 2".
Test with the preview using a valid email address and make sure one result shows before proceeding.

b. New rule condition in your main rule for when the entity form is saved.

"Check number of results returned by a VBO View"
Choose the view and page display you created above.
Send the text field from the entity form as an argument. (This will be path component 2 in the VBO view above)
Set the minimum value to 1.
Negate the condition.

This will make the rule fire if the VBO view returns zero results ie. no email.

c. Create a new rule to show an error if the mail exists.

Same condition as above.
I don't really know why this works but anyways. Add an AND above the condition, negate it and indent the condition which is also negated. (move it to the right like it's a child). It will look like

Entity has field

NOT AND

      NOT Check number of results returned by a VBO View

Action: Display site message and tell the user that the email is already in use.

It looks a bit convoluted but should only take a few minutes to get working. Good luck!


Link webform to a specific node Use-case-scenario:
There are multiple content types.
There is the webform module.
Context and Views are used.

Requirement:
Display specific webform below specific node.
The content editor should be able to choose specific form for specific node.

My first idea is:
->start with adding a node/entity reference field (lets call it "webform_node_url")in the webform, so that a webform is related with a specific node.
->create a view that renders all webforms that have "webform_node_url"
->Embedding this view in the context.

But the problem I have is, I cant find entity/reference functionality for the webform.
Do you have any ideas and/or suggestions.

I think you should be able to do this fairly easily, without even involving views or contexts!

Here's how you can do it:

Just like you said, you can create a new Entity Reference field that will point to the relevant webform.  I'd make this field an Autocomplete (Tags style) field:

When you're setting up your field, make sure to select that it should only pull from your Webform content type:

When you've created the new field, make sure you hit the 'Manage Display' settings on the content type that includes this webform reference.  Here's where the real magic is going to happen: you can have this new referenced entity (which is your webform) be displayed not as a link, but as a rendered entity.  Which means you can just automatically display the webform under or above your node, or whereever you choose to output it.  In my case, I made it the very last field (so it displays under my node), and here are the exact settings:

Now test:
If you go to create a new content type, you should be able to just start typing in the title of the webform you want to attach (such as "Contact Us"), and all the matching webforms will pop up - just choose the right one, save, and it should appear under your node.

Voila!

Let us know if it works for you.


Easiest way to hack Drupal 6.22 installation for security audit I am doing a security audit for a client.  Their installation is Drupal 6.22.  I need to show them it's unsafe.  What is the easiest way to hack it as an example?

I would need to directly show them the steps, so it must be quite detailed instructions.  They have the following modules installed:

Administration menu
Color
Comment
Database logging
Help
PHP filter
Taxonomy
Update status
Masquerade
CKEditor
AES

Here are some common settings:

Server      Apache/2.2.3
MySQL database  5.0.77
PHP     5.2.17
update.php  Protected
File system Writable
register_globals    Disabled

The question you're asking is pretty impossible to answer. If you know Drupal and/or web security then you'll know the answer already. If you don't then the answer is too long to put into a Stack Exchange comment.

Here are some articles about how I have gained knowledge of web application security and how I perform a security audit of a Drupal site:

How to become a Drupal security expert
Steps to a Drupal Security Review

I agree with Ivan Alfaro that the security_review module is a good start. Many of the elements that the security_review module audits can be audited from outside a site, so you could look at what it does and see if you can do similar things.


Contextual filter : Override Title The content architecture of the site which I am working on is something like:-

Song - Content type
Genre - Vocabulory

Song has an entity reference field which points to the terms in "Genre" vocabulary.

Genre field is added in the view which lists Songs content.
The field result has been rewritten as link which points to the URL pattern : songs/<genre-name> ([field-genre] was used).

The path songs/% is a separate view page, which is supposed to take the "genre name" as contextual filter, and show songs of that particular genre.

Here the url gets the taxonomy term name but the title gives %2 instead of the name

Override title is %2

The view is working fine but I am not able to replace the title.

I tried %1 in the override title and it worked.


Commerce rule for total of product lines only (not shipping as well) I have a requirement to add an amount to the total of all Commerce product lines items in a users cart and then add that amount to the shipping amount.

The rule I currently have uses the "calculating a shipping rate" event. The element on the rule uses "Calculate a value" with the input value as commerce-line-item:order:commerce-order-total:amount. However, this value also takes into account the shipping. I only want to apply the calculation to the ordered items in the cart - not shipping as well.

Does anyone know how I can access just the subtotal for the cart?

Thanks!

Using [site:current-cart-order:commerce-order-total:amount] seems to do the trick.


drupal remove individual paragraph tags of the tokens of my replacement patterns in a View I want to rewrite results in a View and use replacement patterns to do this. The problem is that when I do this the 2 tokens are displayed in a separate paragraph.

--> [views_conditional][field_blg_inhoud]

What I have now:
Views_conditional text

Field_blg_inhoud text

What I want:
Views_conditional text Field_blg_inhoud text

I think I have to change a lot in my standaard CSS etc. but isn't there an easier way? Can I somehow ignore the   somehow?

You could uncheck the standard style settings for "add default classes" for each field.

This should place both tokens in one paragraph if you rewrite them in another field (e.g. global custom text).


Unable to perform update when adding new menu field I'm attempting to add a custom image field to my menu from a custom module like so

function my_module_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = array();
      if ($entity_type->id() === 'menu_link_content') {
          $fields['menu_link_secondary_image'] = BaseFieldDefinition::create('image')
              ->setLabel(t('Menu link secondary image'))
              ->setDescription(t('Upload a secondary image related to this menu item'))
              ->setDisplayOptions('form',array('type' => 'image','weight' => 1))
              ->setDisplayConfigurable('form',TRUE)
          ->setSettings([
              'file_directory' => 'public://',
              'alt_field_required' => 'FALSE',
              'file_extensions' => 'png jpg jpeg',
          ]);

      return $fields;
    }
}

Then in my update function I have

function my_module_update_8001(){
    $entity_manager = \Drupal::entityManager();
    $definitions = $entity_manager->getLastInstallFieldStorageDefinitions('menu_link_content');
    if(!isset($definitions['menu_link_secondary_image']) || empty($definitions['menu_link_secondary_image'])){
        $definition = $entity_manager->getFieldStorageDefinitions('menu_link_content')['menu_link_secondary_image'];
        $entity_manager->onFieldStorageDefinitionCreate($definition);
    }
}

But when I attempt to run update.php it hangs and I get errors like

  Notice: Undefined index: menu_link_secondary_image__alt in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->loadFromSharedTables()

Strangely enough I added a menu link afterwards and my field was actually there. I couldn't tell if my update actually worked and just didn't act as if it did, or if it already worked before hand and the update was unnecessary. Did I do something wrong?

UPDATE: I see that although my field appeared I'm unable to save it due to this error

  Column not found: 1054 Unknown column
  'menu_link_secondary_image__target_id' i

Just update entities it will work: run the command drush entity-updates.
No need for hook_update_N.
You can add hook_install to update entities automatically when you install your module don't need to do it by command each time or get the error on every installation .

/**
 * Implements hook_install().
 */
function my_module_install() {
  \Drupal::service('entity.definition_update_manager')->applyUpdates();
}


Use a block in a panel Like the title says, is there a way I can use a block inside my panel? It looks like it can't be done...

As you can see here, there is no option to add a block to my panel...

Most of the blocks are under the "Miscellaneous" category.

I'm not sure exactly what the distinction is, but a few of them, such as user login, end up under "Widgets" instead.


Porting a multi-site setup to local (MAMP) server There seems to be plenty of tutorials about setting up a local multi-site installation, however, I cannot seem to find any information about porting a live multi-site to a local environment.

Specifically I want to work on just one of the sites from the live setup. I am using Drupal 6. Here are the steps I have taken:

I have setup a database on my local MAMP server with the same name as one of the live sites that I want to work on.
I have imported the mysql dump of just the database I want (removing the others multisite sites from the dump).
All site files transfered to a folder in my MAMP>htdocs>new-folder-name
In new-folder-name>sites>desired-site-folder>settings.php I've set the db_url variable to mysql://root:root@localhost/dbname

What further steps do I need to take? When I navigate to the local site I get the  'It works!' message. I presume I maybe need to set up a htaccess file to redirect, but if so, how should it be formed?

Unless you've got MAMP pro, or have set it up as such (which you haven't mentioned) vhosts probably won't be enabled; Apache will be looking at MAMP > htdocs for the web root, not any folder underneath it.

Try moving the Drupal web root up one folder (i.e. directly under MAMP > htdocs) and try again


Can't add block in a region I'm using a Drupal 7 version website and I'm trying to add a block to a region, when I go in blocks and try to add the block to the region and I do save it reply me that it has been saved but no block is been placed in that region. I'm using omega 4 theme module.
 Anyone knows on how I can solve this issue ?

Many thanks to all.

I had a similar issue. But I had Bean and Bean-all module installed, so only in the blocks ticked in admin/config/system/bean-all the move/edit actions were "real" or commited, although success message was showed in the non-ticked ones.


Theme preprocess for module's template variables using dynamic path I am doing templating for a module that adds a block in the module's folder so that the template can be there, and it may be overridden in the theme if desired. I want the module to support different "sources" (but only one will be active/used at a time), which may each have a separate template and variable preprocessing. I have hook_theme() working, and the template works. But the .vars.php file I have contains the preprocess function, and it doesn't get called.

Here is a basic example of what I have:

/MODULE.module

function MODULE_theme($existing, $type, $theme, $path) {
  $source = '';
  switch ($source) {
    case 'SRC_A':
      $path .= '/sources/SRC_A/theme';
    default:
      $source = 'default';
      $path .= '/theme';
  }

  return array(
    'MODULE_block' => array(
      'path' => $path,
      'variables' => array('data' => array(), 'source' => $source),
      'template' => 'MODULE-block',
    )
  );
}

/MODULE/sources/SRC_A/theme/MODULE-block.tpl.php

(contains template HTML with references to PHP variables)

/MODULE/sources/SRC_A/theme/MODULE-block.vars.php

/**
 * Implements template_preprocess_HOOK() for theme_MODULE_block().
 */
function template_preprocess_MODULE_block(&$vars) {
  // Add variables before they get to the template file.
  $vars['some_key'] = 'some_value';
}

I originally was trying to modify the $template value in hook_theme() to MODULE-block--SRC-A, but I decided that didn't matter, and if only one template is active at once I should just call them all MODULE-block.tpl.php regardless of the source, since they are all in different folders.

The template works, and adding a template in my theme will correctly override it. But the .vars.php file with the preprocess function does not seem to do anything unless it is in my actual theme and is THEME_preprocess_MODULE_block instead.

I'm still pretty new to this, but I looked at a lot of pages online, and there aren't any similar examples in my code base that have a module-specific .vars.php file that is located in the module's folder rather than in the theme.

I do not know what I am doing wrong. Any ideas?

I figured it out. There was already a preprocess function with the name template_preprocess_MODULE_block in the module file. Declaring the same function a second time has no effect.


Render quicktabs in view template file I am using quicktabs module for grouping three view blocks as a single block.
Everthing is working fine with quicktabs . But according to my design , i Have to render tabs created by quicktabs in my views template file .

How can i achieve that.

Please Help !

You can reder quick tabs using quicktabs_build_quicktabs function..

  Constructs a Quicktabs instance.

  This function can be called by other modules to programmatically build
  a quicktabs instance.

<?php
   $quicktabs = quicktabs_build_quicktabs('recruitment_quicktabs'); // use your qt name here
   print render($quicktabs);
?>


Node Type in Views Template I made a custom template for my view to print fields into a custom html syntax.  The problem  I have is that in the view I am calling all content types.  Now, in my template file I want to display certain information depending on what content type the content is coming from.

For instance, I want something like this:

If (node->type['animals']{
    print 'this is the animal node';
}
else{
    print 'this is not the animal node';
}

My fields inside the view are printed as follows, but this works:

<?php print $fields['title']->content; ?>

The only problem I am having is calling the node type.

I tried adding content type to my views in drupal, then tried it that way:

<?php if ($fields['type']->content = 'animals'){} ?>

but the view looks through the document and see that there is a content type with that name, and prints the data anyway.

I believe you are using the wrong template in order to access the relevant information. As your comment states your view template is for the entire View, and as you say it looks through the entire document and will always find the content type if any content of that type is present.

Since you are trying to affect a single field, you should look at other template suggestions for fields only in order to process the fields individually instead of trying to do it at the whole View stage.


how can I manipulate functionality or the structure of an existing form? How can I manipulate functionality or the element's structure of an existing form in a different way and create my own template?

For example, I can use below code to display a user login form page, but this code doesn't have any flexibility and doesn't allow me to edit or customize each part of this form element separately and I can't change the look and order of this form straightforwardly.
Imagine that I want to add show password checkbox and other visual effect and style to that's form element.

Page--user.html.twig

{{ page.content }}

You should separate functional and visual changes.

All the functional changes should done by hook_form_alter and the rest with preprocess functions (if needed) but rather with twig.

If you use devel module, you can use the kint() function in twig, so you will see you can also filter page.content. But if that's not enough you can make an own template to this particular form, you will need twig debug enabled, which will show you HOW TO change a part of the dom (once again preprocess function and template naming convention suggestions).


How node_access tag works with query? I'm not able to understand the use and role of the node_access tag. I used the Node View permission module to restrict the access to the article content type for anonymous users.

Now I have created an auto-complete search box that searches node titles. This is the query I used.

$query = \Drupal::entityquery('node');
$query->condition('title', trim($search));
$query->condition('status', 1);
$query->addTag('node_access');
$nids = $query->execute();
$nodes = Node::loadMultiple($nids);

I don't want this search box to search titles that belong to the article content type, and I used the node_access tag.

Will this tag serves my purpose here or is there any other approach to achieve the same?

No, it will not serve for the purpose you have in mind. It checks the currently logged-in user has view access to the node, which means that if the currently logged-in user is the user #1, it will see every node, including the ones that aren't published, and independently from the content type.

As @Neograph734 says, you should not use that tag to filter out nodes basing on their content type. If you want to filter the result by content type, you should use a line like $query->condition('type', 'article'); to built the query.


Revert back to the previous dev version of a module using composer Current last dev release of the Field Group module for drupal 8 was out on (29 Mar 2019).
However, I need to download the previous dev version before the dev version release mentioned above.

The last dev release was out on (29 Mar 2019)

but I need the previous dev version which was out on (10 May 2017)

It is important for me to record this specific dev version in composer.json file so the same dev version of the module will be used on all environments.

How can I do that ?

Note: i can use any of Composer, Git or Drush commands.

You have to refer to the dev branch and reference the SHA of the version of dev you want in Composer.

Example:

composer require drupal/field_group:3.x-dev#COMMITSHA

This will fetch the dev branch of version 8.x-3.x at this specific commit. To get that commit itself, you’ll have to find it on the git page for the project ( which now goes to GitLab).

I can’t find the exact one you are looking for (I’m on mobile) but here is an example.

https://git.drupalcode.org/project/field_group/commit/a4bd38698187c30184d5c76fd884be86e2091fe7

So you’d do:

composer require drupal/field_group:3.x-dev#a4bd3869


How to trigger a Rule when content is viewed with Panels activated? Easy problem: when users visit a node page on my website, one of the node's integer fields should be changed. Answer: Rules. Now comes the tricky part...

I installed Panels and enabled the node template node_view via the Pages UI. I added the Pane "Node being viewed" content (build mode: Full content), but none of my Rules with an event Content is viewed is triggered anymore on the node pages. After searching around a whole day on the internet, I think my problem is a classic, but I didn't find a clear answer anywhere. Hopefully, we can get over it here once and for all.

Here are some things that I tried so far:

This comment suggested to disable the No extras option in the Pane's settings (which works), but that also renders the comments, comment form, etc.; which is not what I want, since I add those as separate Panes.
Combining the power of Conditional Rules and Rules URL Argument. The general idea is to check on Drupal is initializing whether the path starts with node, save the nid arg(1) as a variable, load the node and make the necessary changes afterwards. Unfortunately, I couldn't find a way to use the nid in the path without using custom PHP (I want to avoid that).
Forgetting about Rules and trying to code is also fine for me, but I haven't found the correct hook yet. Using hook_node_view doesn't work, because it doesn't get called (that's precisely why the Rules aren't triggered). I also tried to use

function hook_init() {
  if (arg(0) == 'node') {
    $node = node_load(arg(1));
  }
}

in my custom module, but that results in some theme related errors, so I'm afraid that my node templates are getting messed up by this. Lastly, different sources referred to hook_ctools_render_alter, so that seemed promising. Though, after some debugging, I quickly gave up trying to understand how this hook works. If this is the correct way to go, I would like to have some more information about the hook or some example code.

Do you have any suggestions to fix this frustrating problem?

Note: I'm using the currently latest versions of all modules, i.e. CTools 1.11, Panels 3.8 and Rules 2.9.

You should use Rules Bonus Pack which allows to create a new event when a panel variation is loaded.

Detailed instructions:

Download Rules Bonus Pack and enable "Rules Bonus: Miscellaneous" sub module.
From the panel settings page you will see a new "Reactions" tab. On this tab you will select the new option "Create a Rules event for this variant".
Now open the rule and add a new event. You will find a new section "Rules Bonus: Miscellaneous" with the selected panel variation. Use this event instead the "Content is viewed" one.

It should work as you expect.

Alternative solution

An alternative solution is to write a custom module. You should take a look to the Rules Bonus Pack source code. You can find some inspiration to solve the problem.

Instead using hook_node_view() you can implement hook_ctools_render_alter().

First you should check the handler (node_view) and after load the node data from the ctools/panels context.

Example:

function yourcustommodule_ctools_render_alter(&$info, &$page, &$context){
  // Verify if the page/node is the one you want to interact with
  // and set the field value as you wish.

  // First check if the handler is node_view:
  if($context['handler']->task == "node_view"){

    // Then verify the node content from the context sub array
    // The $context variable contains the node data but you
    // have to dig in.
    $node = $context['contexts'][key($context['contexts'])]->data;

    // [... your code ...]

}

Happy coding :-)


Execute code before cache is cleared I want to execute code before cache is cleared, for example for the menu cache:

// Clear menu cache
$cache = \Drupal::cache('menu');
$cache->deleteAll();

I want to intervene when the cache clear is called, right before it is deleted. I've read the documentation on Drupal::cache and the Cache API but didn't find a solution. Do note that I want to do this using core code only, no contributed modules.

It isn't clean but I'm able to do this with hook_cache_flush. It's called when a cache clear has been called, before the cache has been cleared.