Clean up Unused Tables I have installed some analytics module for my drupal sites. Because it's on company's internal network, I couldn't use it. Now I have the tables created by the module sitting in my database (after I just forcefully removed the module folder from drupal installation).

Is there a way to clean unused tables in Drupal 7?

Note: I tried Schema, but it doesn't seem doing anything but displaying tables are in use and not used

Most Drupal modules that installed their own database tables also remove them upon uninstall. I have bolded uninstall due to the fact that modules can have two states when they are turned off namely disabled and uninstalled.

Disabled implies that you have simply turned the module off, but have chosen to keep the module's settings and database tables intact in the event that you turn it back on again at some point. Disabling is done by simply unchecking the module on the module administration page and clicking on "Save configuration".

Uninstalled on the other hand indicates that you have decided that a previously disabled module will never be used again. Consequently, you are happy to remove all the settings and database tables created. This is done by clicking on the "Uninstall" tab on the module administration page, checking the module that you want to uninstall and then clicking on "Uninstall".

If for some reason the module does not have an uninstallation script in its .install file, then you will need to remove the tables manually. You can also try creating an issue in the module's issue queue asking for this oversight to be remedied.

If you have removed the module's files from the server, then you will (obviously) be unable to run the uninstallation script (as the module will no longer be listed under the uninstall tab). To fix this, simply download/restore the module again to the file system (you do not need to install it). This should list it again under the uninstall tab and you can proceed to run its uninstallation script as above.


Alter the "My Account" link in installation profile Well i've tried the following code to insert an attribute to the user-account link on installation profile.It works for all other menu items (Home[]), except the user-account link, probably due to the reason it is rebuilt again.

<?php
   $path = 'user';
   // Check for user (My account) menu item.
   $existing_item = db_select('menu_links')
    ->fields('menu_links')
    ->condition('link_path', $path)
    //->condition('module', 'system')
    ->execute()->fetchAssoc();

  $item = array(
   'mlid' => $existing['mlid'],
   'link_path' => $existing['link_path'],
   'link_title' => $existing['link_title'],
 //'menu_name' => $existing['menu_name'],
   'router_path' => $existing['router_path'],
 //'module' => $existing['module'],
 //'plid' => $existing['plid'],
   'options' => array(
    'attributes' => array(
    'target' => '_blank',
    ),
   ),
 );
 // $item['options'] = serialize($item['options']);
 // $item = _menu_link_build($item);

 // $link['options'] = serialize($link['options']);
 if (menu_link_save($item, $existing) == $existing['mlid']) {

   drupal_set_message(t('User menu target attribute updated'));
 }

The above code :

selects form the database the {menu_links} record for 'user' menu item.
Alter the options in the $item['options'] array
Performs menu_link_save() on the existing item since we have given an existing $mlid

Well, i've tried menu_cache_clear, rebuilds, straight altering the database values.. everything! but the "My account" link is rebuilded after my profile installation routines, even though is the last one.

How this will work?
How can i achieve this kind of alteration in installation profile?

In general, is it possible to override module-defined menu items options/properties in profile, or hook_menu() will run always after my code and revoke all my changes?

Perhaps you could use:

hook_menu_alter

Not sure if it'll work with option attributes, but worth a try.

e.g

/**
 * Implements hook_menu_alter
 */
PROFILE_menu_alter(&$items){
  $items['user']['options'] = array('attributes' => array('target' => '_blank'));
}

Alternatively, it would be easy enough to add the _blank attr with jQuery.

e.g:

$('body.some-class #user-menu-link a').attr('target', '_blank');

Update: added example PROFILE_ option for menu_alter hook


Redirect after login for specific role on specific day using Rule I want to create a rule for specific user to redirect to his profile page on specific day like Monday and Thursday. For this, I used the Rules module, together with the Rules Once per Day module. If you're not familiar with this last module (which is pretty new), here are some quotes from its project page:

... to easily enable Rules to be fired once per day at, or soon after, a specific hour.
The module also provides a "Day of the week is a" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.

But that didn't work so far.
I have also tried with PHP code, but that's not working either.

There is an interesting comment in issue 2495775, related to the "Rules Once per Day" module, from the module owner. It says:

  You specify a trigger hour on the administration settings page for this module. The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

The way I understand/Read this (haven't experimented with it yet though) is like so:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

Obviously, by using the "Day of the week is a"-option, an extra condition might be that the day has to match also.

With that in mind, it appears to me that this module can not help you to implement what you're trying to do. You want something to happen "when some user performs login", not "when some cron job is run".

But, maybe there is a way to reach your goal by cutting your problem / question in 2 parts:

Create a 1st rule that takes care of "Redirect after login for specific role to "some URL".
Create a 2nd rule that, using the "Rules Once per Day" module, sets the path for that "some URL". To actually set the path, their might be multiple options / modules to consider. I'm think of things like 'global redirect', using some 'token', maybe using the Variable module, etc (more investigation / research needed to find the best fit).

Yes the Rules module is one of those amazing Drupal modules. However it does have some challenges with processing dates ... (= open issues in its issue queue).

If the above doesn't help, then consider using an approach as detailed in the (great) answer to the question about Rule to check if a date value is a specific day of the week ...

Curious to hear if you can get it to work somehow.


How do I delete files the correct way? I have added a file attachment field to my basic pages.

Now for instance I want to delete a certain file from a page, how should I approach this?

I know deleting it from the file system isn't the correct way to go as it would still keep a database record of it.

However, if I remove it on the basic page 'Edit' page, it will also keep a record in the database.

How do I clean-up the database for files that don't exist or aren't used anymore?

I am using Drupal 8, the Media and File entity browser modules.

However if I remove it on the basic page 'Edit' page, it will also
  still keep a record in the database.

Correct, however after editing, the status of the file should be set to 0. (Unless the same file is in use elsewhere.) Drupal has a built in system that should automatically clean up these stale files both from the filesystem and the database, which you can configure on example.com/admin/config/media/file-system. The default time is set to 6 hours (depending on when cron runs this could take up to the next cron run).

Be aware though that there are known issues with this automated deletion. See the File usage tracking causes unexpected file deletion section in the release notes.


Style views exposed filters options I'm using views exposed filter, so the users can select a categories from taxonomy.

This is an example of the structure:

Category 1

-sub category 1

-- sub-sub category 1

-- sub-sub category 2

-sub category 2

Category 2

-sub category 1

-sub category 2

The problem is some of the sub categories has a same name, so for the user it's hardly to recognize which sub category belongs to specific category. I'm trying to style with CSS the main categories in one color and sub categories in other, but with firebug I don't see a way how to do that.
Is there any option or feature for Views exposed filters? So far I've tried with better exposed filters module, but it does not have any option for that.

You need each subcategory in a separate opt-group.

There is a thread about adding support for that here: Support optgroups for taxonomy selection list.

The thread includes a patch that can be applied to give this functionality.

There is also a module called Taxonomy container that looks like it also does what you want (image from module page):

I would also recommend the chosen module to further improve the select and allow additional styling changes (it converts the select to a UL).


Change the layout order of webform Normally, a webform places the body content first and then the form after. I want to reverse it. I want the form to appear first and the body content to appear afterward. Is this possible?

In Drupal the content of a page view is created by a template file and $variables. The variables are typically a simple PHP string or Drupal7 render arrays when the content is more complex than just a string, and the system composes all the render arrays into page output.

A render array for instance can be a Webform, or a Node of a Page (content type). When you place Node ID 1 which contains a Webform reference the system is really composing these 2 items into your 1 page.

A single key per render array may be a #weight value this integer value denotes where this content appears from top to bottom among the many render arrays composed by the system within a given Region of the page.

Yes, it is possible to flip or change the ordering of the Body field and the Webform presentation to the visitor. Typically you would do this in the theme layer of drupal by implementing a Drupal hook to change the weight value in a render array.

If you don't want to code alot there are numerous modules that can let you change the display of items on the page with little or not coding. One example is Display Suite (otherwise known as DS). It allows you to override or customize view_modes of content on your site.

For example I have on a website the default Drupal content type of Page, and I've configured Webform to allow webforms to be placed on Page Nodes. Using DS I could change all webforms to appear before the Body of the Page Node in a simple administrative UI:

I leave it to you to do additional research to find the tool(s) you are comfortable with to complete your task. I've outlined at least 2 here (DS and core APIs).

EDIT

To be clear, if you're using Webform as a content type directly (and not attaching it other content types) DS may not show you "Body" and "webform" fields on the Webform content type -- but the webform Node is still just a render array and its fields still have #weight values. I find it more useful to attach webforms onto content, then to use Webforms by themselves.


How to identify permissions which current user lacks to access node create page? I have a user with custom role. This role has permission custom-type: create new content.

When I try to access node/add/custom-type I am getting 403. Site is quite complex.
What is the quickest way to find which permissions I need to add to this user role to access that page?

Devel Node Access (DNA) provides detailed information on permissions that take effect.

  View the node access entries for the node(s) that are shown on a page. Essential for developers of node access modules and useful for site admins in debugging problems with those modules.

Unless some modules abuse access system with dirty hacks, it should pretty reliably identify which module refused access to given user.


How do I create a rule to run during every cron run? I'm creating rules for posting to twitter. However I need these rules to run every time cron runs. What is the best way to structure these rules so they send the appropriate post at the appropriate time?

Rules has a specific "React on event" under system -> "cron maintenance tasks performed". If your using the rules modules, that will trigger your rule on every cron run.

Also, if your building a custom module, and you need to call a function on every cron run, you can use hook_cron to add a function to the cron tasks as well.


Make GMAP api aware that the gmap has been resized I'm using jquery and css to toggle my gmap between full screen and normal size. However, since the original height is 200px, when I press the full screen button, it only draws 200px of the map and the rest is covered with a gray color. Is there a way to "let the GMap api know" that the map is resized so that it will draw the rest of the map and center the location selected to the new size?

With regular GMaps API, you would need to reinitialize the map or trigger the resize event to start recalculation/replotting the map.

However, this seems to be a common problem for several users of GMap module and there were no direct answers 1 2 3 4.

This is one of the workarounds:

Go to admin/config/services/gmap and check collapsehack. This feature is supposed to be used when the map is in Drupal's collapsible fieldsets, but what it does is that it triggers map resizing on hash change. You can see this in the source code of gmap/gmap.js.
In your trigger add any hashchange - such as #open-map and #close-map.

Here's an example node content. JS/CSS are injected there just to give you an idea:

[gmap markers=blue::41.902277040963696,-87.6708984375 |zoom=5 |center=42.94033923363183,-88.857421875 |width=300px |height=200px |control=Small |type=Map]

Toggle gmap size

I tested this and it worked perfectly.


What is the equivalent of domain_get_domain()? I need the equivalent of domain_get_domain() in the Domain Access module for Drupal 8, but I can't find it.

I need to find the domain for the current request.

Finally worked out the following ...

$domainNegotiator = \Drupal::service('domain.negotiator');
$current = $domainNegotiator->negotiateActiveHostname();

There are other methods on the DomainNegotiator service that I thought should work, particularly getActiveDomain() and getActiveId(), but they didn't return the domain I was actually on like I thought they would.

It's still a bit confusing to me, but I made it work.

EDIT:
@berramou 's answer below helped as well. Originally, I was looking for the Domain object (from the Domain Access module), but it turns out the host was enough to match a Domain reference on my entity.


Why does not the preview of the loaded image appear? When I load an image into a Drupal 8 form, JS errors appear in the console and the file link is not displayed. I have a limit of 10 MB per file in Drupal. If I load an image of 1 MB or less, it works. If I load an image of more than 1MB, it does not load and there are errors in the consoles :

I load an image of less than 1 MB, it works:

I load an image of more than 1 MB, it is a failure (errors in the console and no warning) :

The form fields and my server are correctly configured :

The server and Drupal seem to me correctly set. How can I fix this ?

do you have access to the nginx configuration for this website? If so, you can add the following to the configuration and see what happens. It might set already to 1m:

http {
    #...
    client_max_body_size 10m;
    #...
}


Why do I get 'access denied' when viewing nodes? I'm testing my website and I have to cope with a strange problem. Although every role has the permission "View published content", only the administrator can access nodes: anonymous users and authenticated users can't. The same problem occurs with adding content. I've tried clearing caches, saving the permissions again and rebuilding the permissions, but nothing helps. I'm not using any modules that control node access either...

How can I solve this?

Things to try when you get inexplicable "Access denied" when non-admins try to view nodes and you're sure every role has the permission "View published content":

Clear all caches. Note that you need to both clear your browser's cache and the Drupal cache on the server. To clear your browser's cache, hold down Shift and reload the page. To clear the server cache, navigate to Administration → Configuration → Development → Performance → Clear all caches. If you use Views, clear Views' cache: Administration → Structure → Views → Settings Advanced → Clear Views' cache. If you've got drush installed (always a good thing to have around), a quick way to clean all caches on the server is drush cc all.
Rebuild permissions: append the path: admin/reports/status/rebuild to your site's base URL, or navigate to Administration → Reports → Status report and look for the link "Rebuild permissions".
Repair the Sessions table: Use phpMyAdmin or a similar tool, choose your Drupal database, check the box next to the {sessions} table, and find the "With selected" drop-down near the bottom of the page. Choose "Repair table".
If you've just installed a new module, make sure that you've executed a database update. To execute a database update, append the path update.php to you site's base URL.  (There will be a link to this page on the Status reports page if Drupal thinks you need to do it.)
Use the DNA module (part of Devel) to debug node access problems. DNA will display a block telling you exactly what permissions are enforced and where they come from.  Remember to give give the anonymous and authenticated user roles permission to "Access developer information" to use DNA to debug access problems for these roles. Report your findings here by editing your question if you don't understand the output of DNA.
If none of the above works, start disabling modules to see if one of those causes the problem.  Remember to clear caches after disabling a module.  You may also want to rebuild permissions (see pt. 2 above) after disabling a module, even if the module don't tell you to do it.


Change output of a field with PHP field? I'm constructing a view in Drupal 7 with a field called "Content: Fruit". If the value of that field is "lemon", I want to change the output to "citrus". How can I accomplish this?

Here's what I tried:

First, I excluded the "Content: Fruit" field from the display. Then I added a "Global: PHP" field after it where, in the "Value code" section, I added:

return $row->field_fruit;

Then in the "Output code" section I added:

<?php
    if ($value == 'lemon') {
        print 'citrus';
    }
?>

This doesn't work. The value of $value seems to be the node ID ("nid").

Thought this would be straightforward... what am I doing wrong here? Is there a better way to accomplish this?

it looks like you have the logic a little backwards:

Value Code:

if($row->field_fruit == 'lemon') return 'citrus';

Output Code:

<?php print $value; ?>


How to add rel=author when you have "multiple authors" in one site? I would like to use Google rel=author meta tag, but I do have several authors writing in one site. I have a Drupal 7 site. Should I add a different authorship for each author?
How should I manage in that case?

I was planning to use meta tags module, (as explained here) but the only way it seems to modify all urls in order to affect different url with different meta tags.
ie: /authorname/title that way, with different urls I could create different meta tags.

Could that be a normal procedure? Or there´s another way to add the author´s context?
Or maybe you just should use one single author and avoid multiplying authorship altogether?

Ps. I don´t think this is a duplicated post, because this one refers about multiple authors, instead of just asking how to implement rel=author in D7.

This is simple.

Add a text field to the user profile at /admin/config/people/accounts/fields and call it Google Profile (or similar).
Go to the Metatag configuration page and look up the token for Google Profile.
Add this token to the Author Metatag for the relevent content type(s). The token for my setup is: [node:author:field_google_profile]
Have every author load their Google+ profile to this field in their user profile.

[EDIT] It's worth noting that Google no longer uses rel=author as a ranking factor, so this discussion is now purely academic.

Regards

David


Can contextual drop-down menu replace menu tabs? When I am viewing stuff I have admin rights to the tabbed menu with stuff like 'View | Edit | Outline | etc ' takes up too much space.

Is there a way to switch drop down menus similar to those used for blocks?

Contextual tabs module used in Open Atrium distribution seems to be exactly for that:

  Moves the normal Drupal primary tabs into a drop-down "contextual links" menu to the right of the node title.

Screenshot:


Webform image select element is dispalying another image while used in webform handler In drupal 8,

I have created a custom webform handler to create a new article node and copy the data and images from the webform element
to the created article node.

In both artcle node and contact webform, i have created the required fields/elements.

Article node fields:

Contact webform element:

Now, after submitting the contact webform:

everything goes as expected and a new Article node is created with all fields filled in with data/images.

However, only the Webform element image select is displaying another image instead of the one selected
while submitting the webform.

Below is the created article:

As you can see, the webform element image has been properly populated  but the problem is within the webform element image select !!!

I am sure that my custom code is fine as all other fields are populated correctly.

Any idea/help why the picture is being replaced by another one ??!!

Below is my custom handler code:

<?php

namespace Drupal\my_module_name\Plugin\WebformHandler;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Form\FormStateInterface;

use Drupal\node\Entity\Node;

use Drupal\webform\WebformInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\webformSubmissionInterface;
use Drupal\webform\Entity\WebformSubmission;

/**
 * Create a new node entity from a webform submission.
 *
 * @WebformHandler(
 *   id = "Create a node",
 *   label = @Translation("Create a node"),
 *   category = @Translation("Entity Creation"),
 *   description = @Translation("Creates a new node from Webform Submissions."),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class ExampleWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */

  // Create node object from webform-submission.

  // Function to be fired while submitting the Webform.
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // Before you actually save the node, make sure you get what you
    // want. So at first comment the line further down with
    // $node->save(), run the debug code, check the output and then
    // uncomment the $node->save() and delete the debug foreach loop.
    // You can use whatever debug method you prefer, this is just a
    // simple one-time example.
     foreach($values as $key=>$value) {
       drupal_set_message($key . ' -> ' . $value);
     }

    // This is the node creating/saving part.
      $node = Node::create([
     'type'        => 'article',
    // Use this format: 'node_machine_name_field' => $values('webform_machine_name_field') for below fields.
      'title' => $values['subject'],
      'body' => $values['message'],
      'field_image' => $values['picture'],
      'field_picture_select' => $values['picture_select'],
    // etc...
     ]);

    // Before you un-comment this line, make sure you get all the
    // values you need from the webform data (in the foreach loop).
    $node->save();
  }
}

Finally, I am decided to go with "Business rules" module which will allow to create any content type and transfer all data from webform submission to the created node by setting up a few actions to be triggered on the rule event: entity insert of type webform submission.

See video tutorials here: https://www.youtube.com/channel/UC3jgO5Yt-5y__VVT74qRgSg


Can't get module configuration form into modal I'm writing my first Drupal 7 module. I've successfully created the block's html and integrated that with the home page. I've also succeeded in creating a configuration form fo the block.

However, you can only access the configuration form by going to mysite.com/admin/config/content/mymodule and I would much rather have the user be able to access it in the modal that appears when they click the upper-right gear and click "Configure block."

Is there a good way to add my module configuration form to the block configuration?

You need to add your configuration form using the hook_block_configure instead of making it a page. Add your information to the form as you would any normal drupal form api along with your validate and submit functions. You will also need to hook into hook_block_save for save functionality.


How to import/sync comments from Disqus into my drupal database? After reading the module´s homepage, I understand that there´s an easy way to get disquss comments easily imported/exported from your Drupal database in D7.

  To import/sync: You can do a one-time import at Comments->Disqus
  Import. Specify the timestamp you want to import from. You can have
  comments automatically import from Disqus on an interval basis. Turn
  this on in the import settings at Site Config -> Disqus -> Import.
  Turning on syncing will query Disqus for any comments that came in
  since the last import.

But how do I actually do that?

I don´t have any "Disquss import" tab or link under "admin/content/comment"

And under "/admin/config/services/disqus" I don´t have any "Import" link or tab.
Maybe I´m missing something?

Thanks for your help!!
Rosamunda

here is some sandbox project for drupal 7, that import comments from disqus to drupal core comments


Pre-populate field in content from user profile I'm trying to pre-populate a field in a new piece of content with a country field from a users profile. These are two different Drupal fields, but they are both using the location module so country codes should easily transferred between the two.

I have managed to verify the data from $field_country_you_co_ordinate_fo['und'][0]['country']), this prints the country code 'gb' as expected.

I can't pull the value into $form['field_location']. Tried several different chains of array keys based on the previous ticket linked at the bottom. I'm clearly misunderstanding the combinations of keys needed to pull from one variable to another, so any help would be greatly appreciated.

Thanks in advance

function perma_boot_form_organisation_node_form_alter(&$form, &$form_state, $form_id) {
  // Only run against newly created node

  if (empty($form['nid']['#value']) && (!isset($form['#node']->op))) {
    global $user;
    $user_fields = user_load($user->uid);

    if (isset($user_fields->field_country_you_co_ordinate_fo['und'][0]['country'])) {
        //print_r ($user_fields->field_country_you_co_ordinate_fo['und'][0]['country']);
        $form['field_location']['und'][0]['country'] = $user_fields->field_country_you_co_ordinate_fo['und'][0]['country'];
    }
  }
}

Have been working from the previous example:
How to pre-populate fields on a node creation form based on fields from Profile2 module?

Firstly, thanks to all for the help. I followed your advice and configured devel to print $page. Followed the structure of the page and came up with the amended the code:

$form['field_location']['und'][0]['country']['#value']

Leaving Devel enabled, I can see the value has been set correctly to gb. However, this breaks the google map functionality.

On to the next problem :)


Domain access - prevent redirecting to default domain on account creation Drupal 7.36 & Domain access 7.x-3.x

I have 2x domains running curtesy of domain access. Each domain has been set up for 2 specific groups of users. The idea is that each group can create accounts, log-in and access content on their respective domain. Setting up the default domain worked fine. But, when users attempt to register on the second domain, they are redirected to the default domain instead, causing confusion.

I have Domain Strict enabled – plus I have tried Domain bonus, but the solution does not seem to be straight forward.

How you I prevent this from happening?

Apologies - it turned out that the default domain had been set as the base URL in the settings.php file. When a user requested an account, they were being returned to the default domain homepage


How to get a list of fields that are used in entities? I want to retrieve all fields that entities are using (including locked fields).

How can I get a list of fields that are used in entities?

Like we get in admin/reports/fields.

I would recommend EntityFieldManager::getFieldMap. The EntityManager is only a service to provide functions from other classes.
From documentation:

Return value
array An array keyed by entity type. Each value is an array which keys are field names and value is an array with two entries:

type: The field type.
bundles: An associative array of the bundles in which the field appears, where the keys and values are both the bundle's machine name.


When using &drupal_static to cache variables how do I store an empty return result of null or false? I'm making an expensive soap call and would like to cache it even if it is empty through the duration of the script and page load. It's entirely possible that in the third party database the object is empty and null. I don't want to make five soap calls if the object is empty. I feel like using PHP empty() and isset() this way is hackish. It works but there is a lot of funky logic involved. Is there a better way?

I need the drupal_static so if the $third_party_info_object is change anywhere else all the caches can get cleaned.

function my_module_get_information($user) {

  third_party_soap_initialize();

  $third_party_info = &drupal_static(__FUNCTION__);

  if (!isset($third_party_info) && is_null($third_party_info)) {
    // work some magic here
    $account_object = new thirdPartyAccounObject();
    $account_object->setThirdParyAccountId($user->uid);

    $third_party_info_object = new ThirdPartyInfo();
    $response = $third_party_info_object->getByAccount($account_object, false);

    $returnCode = {get the $returnCode here}

    if ($returnCode == 200) {
      $third_party_info = $response->getThirdPartyInfo();
    }
  }

  if (!isset($third_party_info)) {
    $third_party_info = false;
  }

  return $third_party_info;
}

drupal_static()'s default value is null. So instead of doing this

<?php
$third_party_info = &drupal_static(__FUNCTION__);
if (!isset($third_party_info) && is_null($third_party_info)) {
?>

Try this

<?php
$third_party_info = &drupal_static(__FUNCTION__);
if (is_null($third_party_info)) {
?>


Custom VBO action to print selected nodes I would like to use views bulk operations to select and then print a large amount of nodes at once. I only want the print dialog box to open one time for the whole batch. Any ideas on how to approach this process?

In your hook_action_info() implementation, you should set 'aggregate' to TRUE. For example:

function YOURMODULE_action_info() {
  return array(
    'YOURMODULE_your_custom_print_action' => array(
      'type' => 'node',
      'label' => t('Print nodes'),
      'aggregate' => TRUE,
    ),
  );
}


How can I generate a Report from database table? and how can I show it in page I want to generate a report from values of a database table. I tried table wizard and views to generate reports. It shows it. But how I show this to a perticular Page/form.

Create a page view, and see your report in that page.


Print element title in email Given the following element in my webform, how do I print Name: Fred in my email?

Title   Key   Value
Name    name  Fred

I understand how to print the raw value. How do I print the title?

[?]: [webform_submission:values:name:raw]

An admin may change the element's title, so I can't have Name: [webform_submission:values:name:raw].

Accessing a webform's element properties including #title, #description via tokens is not currently supported. I am not sure the core Webform module should provide these tokens, but a third-party module can easily make these tokens available.


Drupal 8 Blog Autoposting To Facebook, Twitter, LinkedIn etc I'm deciding what technology to use to build a social website. One of the features I'd like is autoposting to Facebook, Twitter, Linkedin, Youtube etc from a blog.

Joomla has a component called easyblog - http://stackideas.com/easyblog. I was wondering if there is anything similar for Drupal?

Normally I build basic websites with Joomla and more complicated things with Drupal 7 but with 8 out would ideally like to have used that.

Kind regards and many thanks for your time it is appreciated.

There's a framework of modules under development as part of a 'Social initiative'. See https://www.drupal.org/project/social_post


WYSIWYG editor on Paragraphs text field? How do I enable the WYSIWYG editor on a paragraphs text field in Drupal 8?

Currently, adding a text field (of any type) displays a single line input box.  I'd like this field to be at least a multi line textarea, with preferably, a WYSIWYG editor.  Is there a setting or module I can use to change this ?

EDIT: I should add that the editor works fine in a field on a content type or block.  It does not load for any text type in a paragraphs field.

If you want to have a multi line textarea with an WYSIWYG editor, you'll have to create, for your paragraph type, a field of type "Text (formatted, long)" and while editing your field, you should choose "Full HTML" as "Text format". Hope this works for you.


How to combine two menu's in Drupal I'm building a site with 2 menu's. One is the main menu, the other one is similar to the user menu.

The user menu is only displayed in a panel on the frontpage, the main menu is always visible. To keep the user-menu options available I'd like to add them to the main menu as well so they are always accessible too.

I thought of appending the user-menu to the main-menu in my custom template.php like below, but that gave me just the main-menu.

function THEME_preprocess_page(&$variables) {
  $variables['main_menu'] = array_merge(menu_main_menu(), menu_navigation_links('menu-myoptions'));
}

I was using the main-menu-block, so I thought that could be the reason the altered menu is not showing up. (The block might load the menu directly).
But when I user render($main_menu) in my page.tpl.php it doesn't work eighter.

Am I missing something?

Instead you can try this Advanced Menu module, Menus can now be merged into other menus. This allows users with the appropriate permission to add links to other menus which are then displayed as if there were a single menu.

  Example:

  Create new role "News Manager"

  Create new user "News Editor"

  Create new menu "News Releases", Set "News Manager" as an editor for
  the menu.


How can I disable a troublesome module? I've been playing around with D8 and have managed to break a few things I can't figure out how to fix. Most recently, after installing (via manually adding the module code to the modules folder) the Name Field module and subsequently enabling it in the Admin panel, my Drupal 8 instance started throwing fatal PHP errors. No problem, I thought, apparently the module has a bug and I'll just remove it for now. Not so easy. I removed the module folder from my instance, but the errors are persisting.

Not that the specific error matters as this question is not about troubleshooting the module, but here's an example of something I get after removing the module code:

  Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginException: "Plugin (name) instance class "Drupal\name\Element\Name" does not exist." at /srv/http/drupal.protestan.org/core/lib/Drupal/Component/Plugin/Factory/DefaultFactory.php line 87

Is there a way to disable a malfunctioning module without being able to load the control panel? I've looked around but all the hacks for D6/D7 including tweaking the database manually don't seem to apply any more. At the very least the layout has changed and I was unable to find the corresponding bit to toggle. Likewise  the current version of drush does not seem to be able to cope with D8 yet.

Is my whole database borked? Is there a secret URL or other way to load the Admin panel with no modules enabled (i.e. some sort of safe mode)?

You seem to be having two issues: this module (i.e. PHP Fatal Errors resulting from something that's broken in the module) and Drush.

Let's start by the easiest fix, Drush.

Make sure you have Drush 8 (or 9-dev), which is the only version compatible with Drupal 8. Run $ drush --version to know for sure. If you're not running Drush 8, then, read the documentation and install it via Composer.

As to your module issue, my best bet at this point would be to put the module back in place where it was so that Drupal can see it, else, it'll never be in a position to trigger the uninstall process if the module isn't there. Once it's back (under the /modules directory at the root of your Drupal install), run the $ drush pm-uninstall -y command which will not disable the module (this has been removed completely from D8) but uninstall it completely. If it doesn't fail during the process, then, chances are that everything will be fine. If you do have issues during the uninstall phase, try to visit the /admin/modules/uninstall page to uninstall the module from the UI (assuming something didn't work well with Drush).

If nothing works, try to rebuild the cache (/admin/config/development/performance or $ drush cr) and repeat the above operation. Finally, if you're still stuck, I'd advise you report your bug (at the very least the PHP error message) in the module's issue queue. Note that it should not be the error you mentioned earlier since you got it after you removed the module from its original location.


How to print barcode labels on standard printer drupal? I am using barcode creation module to create barcode labels on standard printer.while giving print option it is not showing any barcode labels on print preview.

How can i able to see my labels?

  The directory /var/www/html/transgenic/sites/default/files/barcodes is not writable or not exist or something else wrong. You can not print barcodes without correct settings.
  An error occured while generating the barcode.
  The directory /var/www/html/transgenic/sites/default/files/barcodes is not writable or not exist or something else wrong. You can not print barcodes without correct settings.

It is showing this error..

You have to set the permissions right. try 'chmod 755 -R /var/www/html/transgenic/sites/default/files/barcodes' Do this with the same account as the webserver uses.


CKEditor custom configuration (implemented using WYSIWYG module) How can I set some custom configurations for the CKeditor module? I want to set spell check SCAYT on by default, and a few other things like that. Ideally, I would like to create my own custom config file somewhere sensible that won't be overwritten.

Look at hook_wysiwyg_settings_alter

  Act on editor profile settings.

  This hook is invoked from wysiwyg_get_editor_config() after the
  JavaScript settings have been generated for an editor profile and
  before the settings are added to the page. The settings may be
  customized or enhanced; typically with options that cannot be
  controlled through Wysiwyg module's administrative UI currently.

  Modules implementing this hook to enforce settings that can also be
  controlled through the UI should also implement
  hook_form_wysiwyg_profile_form_alter() to adjust or at least indicate
  on the editor profile configuration form that certain/affected
  settings cannot be changed.

Additionally this blog post by Fuse Interactive: WYSIWYG MODULE + CKEDITOR: TAMING THE BEAST goes into great depths on how to make use of this hook. From the blog post ...

/**
 * Implements hook_wysiwyg_editor_settings_alter()
 */
function ckeditor_custom_wysiwyg_editor_settings_alter(&$settings, $context) {

  // The $context variable contains information about the wysiwyg profile we're using
  // In this case we just need to check that the editor being used is ckeditor

  if ($context['profile']->editor == 'ckeditor') {

    // The $settings variable contains all the config options ckeditor uses.
    // The array keys correspond directly with any setting that can be applied
    // to CKEditor - as outlined in the CKEditor docs:
    // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
    // Another way to override configuration is to use your own configuration javascript
    // file. In this case, we're going to add our own configuration file that will
    // Hold our stylesSet customizations...
    $settings['customConfig'] = base_path() . drupal_get_path('module', 'ckeditor_custom') .
                                '/ckeditor_custom_config.js';

    // We are also going to specify a custom body id and class
    $settings['bodyId'] = 'ckeditor_custom_id';
    $settings['bodyClass'] = 'ckeditor_custom_class';

    // To see what's in $settings and $context, install the devel module
    // And run the variables through the dpm() function.
  }
}


Show a menu block only on nodes that belongs to this menu I am trying to accomplish something similar to the book navigation module.

Say I create a block containing a menu. I want this block to become visible for nodes that belong to this menu.

So if NodeA belongs to the menu "My SubMenu 1", which is included in a block called "My Submenu 1 Block", I want this block to appear everytime NodeA comes up.

This could be accomplished with some pathauto tricks, or assigning a certain taxonomy term to all nodes of "My Submenu 1". But I realise this is redundunt, there is no need to force the user to create content with specific terms--the information is all there in menu-->node connection.

Take a peek at http://drupal.org/project/menu_block. I think it might do what you want, or, if not, at least maybe its code might give you an idea on how to do so yourself.


Add ability to add bundles to an entity that does not currently have bundles? If you have a custom entity that does not create bundles, is it possible to modify it to allow new bundles to be created?

Possible yes, although not trivial. Not having a bundle means internally, Drupal exposes a default bundle that has the same name as the entity type. So the by far easiest approach would be to create a bundle entity type, create a default bundle with the same id (possibly only in the update path for existing sites) and then allow to create additional ones.

What's hard is changing the bundle of an entity type, that's not officially supported. file_entity does it for the file entity type, you can have a look at its entity class and the methods it overrides the detect the file type and based on that, sets the bundle.


How to add anchor link through Link field? We have a link field (field_link) on the Basic page content type. We wanted to add the link as an anchor link by putting current-page#section1 into the Link field, but it is not current.

What can we do to populate a link field such that it take the current URL and add #section1?

This is how the link field is used in the twig template

{% set cta = content.field_link.0 %}

 {{ content.field_name }}

 {{ cta['#title'] }}

Current output

 Professionally facilitate standardized vortals whereas high-payoff e-business. Distinctively productize high.

 Download

Expected output

 Completely brand cross-platform "outside the box" thinking through visionary supply.

 Download

Drupal will automatically do that if you only enter #section1 into the Link URL.


Emails sent via a Rules action contain arbitrary line breaks I have an email sent by Rules. Here is the text of the email in the Rules action:

  Welcome to x! As a professional user, you can now showcase your
  business on x by creating a Professional Profile and uploading photos
  of your best x.

Here is what the user gets (note line breaks):

Welcome to x! As a professional user, you can now showcase your
business
on x by creating a Professional Profile and uploading photos of your
best x.

I'm not sure why there are arbitrary line breaks being inserted in the text when sent via email. I've excluded the RTE on email field in the rule, and included only plain text.

You are most likely up against the hard limit of line length (77) for plain text emails, defined in a Drupal core function _drupal_wrap_mail_line. It quotes RFC 3676 as the reason for this.

If you want the one line of text you might be able to do it using a HTML formatted email rather than plain text. Alternatively you may want to reformat your email so it suits the available width. The third option of altering core or making a plugin to let you make long lined emails is probably a little overboard.


Programmatically loading Custom block in page/node preprocessor I've followed some previous solutions on DA to programmatically load a Custom block in my page preprocessor hook but nothing I try seems to be working.

Currently, my custom block is within Structure > Block Layout > Custom block Library under the name 'SGT Pricing Header' (Machine name: sgt_pricing_header, ID 12).

I have attempted loading it in the page preprocessor as well as the node preprocessor hooks.

Currently I have:

function THEME_preprocess_node(&$variables) {
    $block_entity = Drupal\block_content\Entity\BlockContent::load(12);// BLOCK_ID
    $block_view = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block_entity, 'sgt_pricing_header');
    $variables['block_pricing_header'] = $block_view;
}

I have also used 'sgt_pricing_header' in place of the ID 2 with no success.

In the TWIG template, which is a paragraph template by the way, if that is relevant, I am simply trying to display the block with

{{ block_pricing_header }}

I referenced Programatically render a block in a twig template when trying to get this to work.

I also tried using Twig Tweak to display the block, without success.

{{ drupal_block('sgt_pricing_header') }}

Simply does nothing.

PHP Version: 5.6.32-1+ubuntu17.10.1+deb.sury.org+1
Drupal version: Lightning (lightning-8.x-2.17)

Not entirely certain what to try next other than simply hard code the block content into the template which I would prefer to avoid.

I think the problem here is that Drupal 8 has both block definitions (a.k.a. plugins) and block instances.  Both of which tend to be called blocks.  What is listed in the custom block library is a block definition. This is like what is done when a block is created with code.  It define the block but not the configuration.

An instance is the configuration data for a block.  It has the settings for a specific block.  E.g., title override, display title, region, and the like.

So, you are trying to render the block definition with code that requires an instance block.

How do you get an instance of a block to render?  The simplest way is to create a hidden region in your theme by adding a region line in the info file.  Something like "Hidden Blocks".

Add your custom (or code based) blocks to this region in the block placement screen.  I also tend to set the rules for where this can be displayed just to help keep these from being generated when not needed.

Once you do this, you should be able to render using the block id from the placement screen.  Note this can be different from the plug-in id on the custom block page if you have placed it more than one.


How to displaying translate tab in the node I have Multilingual and internalization Module installed on a Drupal installation. I need to have the translate link option on every node as the following screenshot:

Also I need if the content (node) in some language has no translated version in other language, when clicking to the language choose bar, it go to the default home page in the other language or Page Not found.

This tab does show when:

You have more than one language installed. Locale module needs to be enabled.
You have Content Translation or Entity Translation modules enabled (not i18n)
You have set up the content to be translatable, in the the content type settings page (if it's a node). When using Entity Translation, prior to that, you should define the entity type (e.g. node) to be translatable.
Your user has permissions to translate content.


How to access cookies in Views PHP Code filter? I have a view that will display nearby locations.

The center coordinates would come from a cookie (lat,lng).

I am trying to get the cookie with $_COOKIE, but I get an error saying that it is not set.

How would i access that cookie and return in for a proximity filter i Views (Using the Location module)?

Checked with the views php module.

Then i get the cookies stored.


Parent-child-grandchild relationship for content or comments Background

I am creating online courses, where groups of students work together giving answers to questions and commenting on each others answer.

I'm using Drupal 8, probably with Panels.

Challenge

I will have a content type called “Question”, created by the course creator.

The page for each Question should have:

the content of the Question, followed by
a list of (some of) the “Answers” from other students, showing the students name, the text of their Answer, a count of how many comments from other students the answer got, and a "show comments" link that shows the comments and offers a form for a new comment

a “new Answer” form where students can post their own Answer to the Question

Possible routes

I can see 2 ways to achieve this:

A: Treat top-level comments as "Answers"

AFAIK comments can be threaded, so I could treat the top-level comments as "Answers" and lower-level comments as "Comments". I could use a custom view block to only show the top-level comments on the “Question” page.

In this case, how would I enable the full text of the Answer and its child comments (the comments on the “Answer”) to show up (by AJAX or on a different page) when the reader clicked “show comments” on an answer?

B: Have “Answers” be a content type

The Answers content type would have an entity reference field “Question” that holds a reference to the parent Question.

This works well, but how would I insert a “new Answer” form which automatically and invisibly prepopulated the "Question" entity reference field with the id of the current Question?

Possible solutions seem to include

using the module formblock, which has a D8 port
porting the module entityreference_current to D8.
Creating a view that returns only the current Question id (by using Views contextual filters), having that view as the source for the entity reference field on an entityform, and finding some way to hide the field. This approach I found here: Reference to parent node on entity form type. This looks good and simple - any drawbacks?

Am I understanding the options right? Is there a better/different way to achieve this?  My impression is that Option B  - a second content type - is more robust and flexible?

I would go with option B, as having answers as content types allows you to add other features like the Flag module for up-votes.
The automatic and invisible reference linking can be done with the Entityreference prepopulate module, once there is a Drupal 8 version. You could also port it yourself or make an equivalent custom module. The older Node Reference URL Widget module would even add a link to your Question node on the Create Answer page with the appropriate URL adjustment for the reference.


How to bulk delete selected content/nodes? I want to bulk delete data and along with it I need check-box where I should able to "select all" data to delete. I tried the Delete all module, which is helpful to delete all the content, but it's all or nothing.

Sometimes I may not want to delete all the content/nodes. Therefore, I would also like to be able to select which specific content/nodes gets deleted only.

Can anyone help me on this?

Using the VBO module as suggested in the prior answer is indeed the way to go, BUT ... if you add the Rules module to that also the possibilities for what you can do are virtually only limited by your own imagination. Read on for more details on that ...

Step 1: Create a Rules Component

Have a look at this example of a Rules Component (in Rules export format):

{ "rules_delete_nodes_containing_a_specific_value_in_a_text_field" : {
    "LABEL" : "Delete nodes containing a specific value in a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "text_field_value" : { "label" : "Text Field Value", "type" : "text" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "data_is" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[text-field-value:value]"
        }
      }
    ],
    "DO" : [
      { "entity_delete" : { "data" : [ "node" ] } },
      { "drupal_message" : { "message" : "Deleted node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022 (which contained the string \u0022[text-field-value:value]\u0022 in field \u0022field_free_format_text\u0022)." } }
    ]
  }
}

Some more details to further explain the above above example:

This Rules Component will be used in the subsequent step.
In my case I have a text field with machine name field_free_format_text.

Note that I also added the Rules Condition Entity has field to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the Entity has field condition should be sufficient already.

If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of that field to match the machine name of your field, and then you can simply import this Rules Component in your own environment.

After you did this, you can navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node identifier and hit the Execute mode. Depending on the node id you selected (if it has that field, and if the Rules Condition is satisfied), your node will be updated.

After you're confident your rule works perfect for all variations of your nodes, move on to the next step below.

Here is an example of the (2) Drupal messages I got when executing this Rules component for a node with ID = 48, in which I used the string "GetRidOfThisNode":

  Deleted node with id "48" and title "Demo field_free_format_text replacement" (which contained the string "GetRidOfThisNode" in field "field_free_format_text").
  Component rule: Delete nodes containing a specific value in a text field has been executed.

Variation of the display of that message could be that you use Rules to create a (similar) log record ...

Attention: you always get the 2nd message. But the first one only shows up if you have an actual match ... and hence the update gets performed also.

Step 2: Let VBO do the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.

Attention: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


Display Vocabulary (VID) From Selected Field I'm trying to print out the selected vocabulary from a content type on a page.  As the previous user did not use views for this layout, I need to find a way to add it.

Here is my code so far.

foreach ( (array)$node->taxonomy as $term ) {
        echo $term->name;
    }?>

Right now, it shows all of the terms that are listed in my taxonomy. Is there a way to narrow this down? to only show selected vid?

Regards,

Answering my own question for future purposes:

<?php

$vocabularies = taxonomy_get_vocabularies();
if ($vocabularies) {
  foreach($vocabularies as $vocabulary) {
    if ($vocabulary->vid == 1) {
      $terms = taxonomy_node_get_terms_by_vocabulary($node, $vocabulary->vid);
      if ($terms) {
        foreach ($terms as $term) {
          print $term->name;
        }
      }
    }
  }
}
?>

Did the trick.


How to  redirect the user to a  page and show a message on the admin overlay (using drupal_set_message and drupal_goto) I need to redirect the user to a destination and show a confirmation/error message. How can I do that? This is my code:

watchdog('webform', 'The user @user has been successfully created', array('@user'=> $mail));
drupal_set_message(t('Settings saved.', array()));
drupal_goto(drupal_get_destination());

This code redirects, but the message is not shown. Do i need some special action in the destination page?

EDIT - the problem is that i'm redirecting to an administrative page and the message is showing in the main theme, i want it to display on the overlay theme. I'll  explain a little bit more in depth what i'm doing (this could be totally wrong).

I added a link that the user can click when he is viewing a submission entered through a webform (webform module). i defined a menu voice for that link in this way (i'ts only a callback, no page is shown):

$items ['createuser/%'] = array (
                                    'title' => 'Create users',
                                    'access callback' => TRUE,
                                    'page callback' => 'provintegra_createuser',
                                    'page arguments' => array (
                                                            1 ),
                                    'type' => MENU_CALLBACK );

Then i defined provintegra_createuser

function provintegra_createuser($sid) {
        //save user
    watchdog ( 'webform', 'L\'utente @utente è stato creato cons successo', array (
                                                                                '@utente' => $mail ) );
    drupal_set_message(t('Settings saved.', array()));
    drupal_goto(drupal_get_destination());//This redirects you to the page of the webform submission in the overlay
}

I se the message "Setting saved" but it's in the main theme, not in the theme (seven) i'm using for the administrative overlay. Do i need to set some special parameter so that the message is shown in the overlay?

I don't think this is possible with the current message system, it would require some crazy workaround do make it work anyways.

The problem is that when you use drupal_set_message(), the message is stored in the session variable and displayed whenever possible. When you redirect to a page with an overlay two things happens.

The main page is rendered and displayed.
The overlay page is rendered and displayed (with an iframe).

This means that whatever message you set, would always be displayed on the main page.

What you could do, is when the messages has been extracted to set them again and remove them. This could happen in your theme somewhere. The problem is that it is probably very hard to determine when you should do this, as you effectively would hide all messages if you always did this. Another side effect would be that you would constantly get more and more messages, possibly leading to a fatal memory error at worse.


Drupal-Bootstrap CSS-oriented question Background

I've installed the Bootstrap theme, created a sub-theme, edited it's INFO file, and the theme itself seem to appear fine while surfing at the site.

The problem

I went to this themes' Style.CSS file and added some CSS, but for some reason, Most (if not all) of the CSS I add requires the !important declaration at the end of each property... Any idea why all of these !important's needed? It is surly not the natural behavior of any theme...

Further details

The site is RTL.
I'm not sure if there is a connection but this problem might do with the fact that my new sub-theme is running online only to me, via the ThemeKey module which let's you associate a specific theme with a specific something (like users).

As mentioned by @clive in the comments, the issue is certainly specificity or style precedence, which basically means that some CSS rules will have more importance than others. I'll give you the 2 most basic things you need to know:

Order. The latest in the code a CSS rule is, the more power it has. So, your custom CSS stylesheet should be loaded after other stylesheets.

Selector specificity. By rule, the more specific a selector is, the more power it has. An ID selector takes precedence over a class selector, and a class selector over an element selector. For instance, let's say you want to style a div:

...

In your CSS, you could reference this div in, basically, three ways:

div { color: red; }

.col-md-1 { color: green; }

#login { color: orange; }

In this case #login rules will have precedence because of two reasons: Order (it is below the other two selectors) and Selector specificity (an ID selector is more specific because it's unique). Therefore, the text color will be orange.

The only exception to these rules is when you use the !important keyword, which adds superpowers to your rule, forcing it to take precedence over any other selector. That's why in your code, it only works when you do this, as you mention.

So, instead of adding !important, try to understand your selectors and you'll do just fine.

EDIT: As mentioned in the comments, a syntax error (in this case, a missing bracket) in your CSS file could cause all following code not being read (Tip: If you use SASS or Scss, they will alert you of these type of errors).


Exportable options for views_plugin_display_extender I have trouble implementing exportable options (using standard views export) for a views_display_extender. The corresponding issue is here: https://drupal.org/node/2128119

From looking at views_object::export_options(), it seems to me, that the declaration of option_definition should be sufficient. But then again looking at view::export() I have the impression that only display handlers are called. But I don't really understand what else might get called.

Full code of the sandbox module in question is here: http://drupalcode.org/sandbox/berliner/2087181.git/tree

I would be glad about any solutions, ressources, docs or even smallest hints about this problem. I did an extensive research before posting the issue and as far as I can see from the docs, I did everything needed to make the modules options exportable.

There is a working implementation of a views display extender in Authcache. The only difference I see between your code and mine is that I'm using options_definition_alter while you've implemented option_definition.


Drupal 7 as an Oauth 2.0 and/or 1.0a provider I am trying to make my Drupal 7 site a Oauth provider. I have found the Drupal modules for Oauth 1, yet I am having trouble with finding Oauth 2.0 provider modules and I am not sure that Drupal supports Oauth 1.0a.

I found this project at Drupalcode: http://drupalcode.org/project/oauth2.git it supports Oauth 2.0 for Drupal 6. While browsing to the repository I saw the tags: "7.x-1.x-dev" and "7.x-1.x-Rj" (don't know what this Rj stands for..) which made me very happy. So I checked out the code and put that, together with the latest http://code.google.com/p/oauth2-php/ in my Drupal installation. However when I wanted to enable the module in Drupal 7 and it says: "This version is not compatible with Drupal 7.x and should be replaced."

Furthermore, while implementing a OAuth-PHP client for my OAuth 1 setup, I found that Drupal does not return a "verified token". I read somewhere that this is implemented since OAuth 1.0a to fix a security bug. Does Drupal support OAuth 1.0a? If so what am I missing if I don't recieve a Verified token?

Has anyone got any idea if this module should work in Drupal 7? (the tags confuse me) and if not is there another module for Oauth 2.0 for Drupal?

Thank you in advance

I think you should try http://drupal.org/sandbox/sadashiv/1857254 for google_oauth2  This module is yet is sandbox but you can give it a try.


Drupal 6 Ahah With FileField Problem i'm creating a form which uses ahah in Drupal 6.

I have 2 select fields. The first uses ahah in order to populate the second and it works well.

But the problem is when I add a file field to the form because the ahah call doesn't work (it doesn't appear in firebug and the page is refreshed instead of the normal behavior). If I remove the file field it works again.

Any idea please? I'm getting frustrated thinking about the solution.

Thanks

It's a common issue that is reported here and even in the drupal documentation, the issue is reported so I think it's not yet solved at all so you need to find another solution that AHAH for the file upload filed.


Entity wrapper save using db_transaction()? I am using a db_transaction() for some data updates. I am using some EntityMetadataWrappers, modify some data, then save.

The thing is, the wrapper ->save() function doesn't have a parameter for $transaction like the entity controller does: entity_get_controller($entity_type)->save($entity, $transaction).

If I don't pass in a transaction, it will call db_transaction() when one already exists.

What will happen in this case during commit or rollback of the outer transaction?
If a new transaction is created, does this commit the one that already existed?
If a rollback of the outer one won't rollback the inner one, or if it messes up stuff when a new one is created, then is there a way to do it all in one transaction?

Note: I'm using MariaDB.

I finally found an explanation of what happens in this case in the Transactions documentation.

While we cannot declare functions "transactional" in PHP, we can emulate Java's nesting logic by using objects with constructors and destructors. A function simply calls "$transaction = db_transaction();" as its first (or nearly first) operation to make itself transactional. If one transactional function calls another, our transaction abstraction layer nests them by performing no transactional operations (as far as the database sees) within the inner nesting layers.
To start a new transaction, simply call $transaction = db_transaction(); in your own code. The transaction will remain open for as long as the variable $transaction remains in scope. When $transaction is destroyed, the transaction will be committed. If your transaction is nested inside of another then Drupal will track each transaction and only commit the outer-most transaction when the last transaction object goes out out of scope, that is, all relevant queries completed successfully.


sending mail for select list field I have created a content type in which I have a field as field_result of type select list with options as;

pass
fail
hold
postpone

When user selects the pass from select list and update or create a content, email should be sent to all admin users and other users stating that result is pass. Following same thing to other select list options ie for fail,hold and postpone. So what exactly I need to do using rules?

Here event can be both like; user can save the new content also can update using this select list field. Whenever user selects, it should send an email according to corresponding select list option.

Can anyone help me please? I will be thankful to you. My problem is similar to sending mail after checking a selected list in field but it didn't work for me.

Following rule should help you

{ "rules_send_email" : {
    "LABEL" : "Send Email After Save",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--send_email" : { "bundle" : "send_email" } },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "3" : "3" } },
          "subject" : "Subject Test",
          "message" : "submittted value for Result field is [node:field-result]"
        }
      }
    ]
  }
}

The above rule will trigger email when a new content will be added For update also clone this rule and change the event to "After updating existing content"


Drupal 7 Views url translated alias with contextual filter I want to translate the url of my view. So I've made a translated alias for it. But when I add a contextual filter I get a 404 error.

For example: I've a view with the url example.com/overview with alias example.com/overzicht this works. This works also example.com/overview/[category], but this doesn't work: example.com/overzicht/[category]

How can I fix this?

I've finally found the solution for my problem, after a couple of hours :).

It was solved after installing the Extended Path Aliases module.


Form generated from form cache displays, but missing name and value attributes I'm having a problem displaying a cached multi-step form in a custom module which generates custom entities.

After two steps, the form posts to an external URL (action changed with hook_form_form_id_alter).
If the external URL returns errors, the form is pulled from cache with form_get_cache() and displayed using drupal_render().
Form displays okay, but field elements are missing name and value attributes.
Printing the form object retrieved from cache shows expected values (#entity, fields, and user input associated with fields).

  $form_state = array(
    'submitted' => FALSE,
    'rebuild' => FALSE,
    'cache' => TRUE,
  );

  $form = form_get_cache($form_build_id, $form_state);

  $output = drupal_render($form);

I suspect that I need to rebuild $form_state input/values or am missing a form rebuild step.

Figured it out. Use form_get_cache() to get the cached entity, throw that into $form_state, and then use drupal_build_form() to put it together again.

    $form_state = array(
        'submitted' => FALSE,
        'rebuild' => FALSE,
        'cache' => TRUE,
    );

    // Pull the entity object from cache.
    $cached_form = form_get_cache($form_build_id, $form_state);
    $myentity = $cached_form['#entity'];

    $form_state['myentity'] = $myentity;
    $output = drupal_build_form('myentity_form', $form_state);


Pager extention not working in dynamic database query I am trying to create a page which shows all the nodes created by the currently logged in user.  To do this I am using a dynamic query to fetch the relevant nodes.  However, for some reason the pager is not working.  Instead it lists all of the nodes.  I have not been able to work out why this is occurring as I have successfully used pagination previously with other less complex queries.  The following is from the page callback function:

function playground_page() {
  $build = array();

  $build['intro'] = array(
    '#markup' => 'This is a testing ground for Drupal concepts.',
  );

  // Example of table join. Display content created by current user.

  // Construct base query.
  global $user;
  $query = db_select('users', 'u');
  $node_table_alias = $query->join('node', 'n', 'n.uid = u.uid');
  $query
    ->fields($node_table_alias, array('nid'))
    ->condition('u.uid', $user->uid);

  // Add pager and node_access options.
  $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    $key = 'node_' . $node->nid;
    $build[$key] = node_view($node, 'teaser');
  }

  $pager_args = array('tags' => array('<<', '<', NULL, '>', '>>'));
  $build['pager'] = array(
    '#markup' => theme('pager', $pager_args),
  );

  return $build;
}

This issue is related to the use of extenders.  When using an extender it is important to note that $query is not altered in place. A new query object is returned from extend(), and if it is not saved to a variable it will be lost.  See Extenders documentation for more info.

To achieve this with the OP code, one would need to modify the following section:

  // Add pager and node_access options.
  $query = $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

Full working code is as follows:

function playground_page() {
  $build = array();

  $build['intro'] = array(
    '#markup' => 'This is a testing ground for Drupal concepts.',
  );

  // Example of table join. Display content created by current user.

  // Construct base query.
  global $user;
  $query = db_select('users', 'u');
  $node_table_alias = $query->join('node', 'n', 'n.uid = u.uid');
  $query
    ->fields($node_table_alias, array('nid'))
    ->condition('u.uid', $user->uid);

  // Add pager and node_access options.
  $query = $query
    ->addTag('node_access')
    ->extend('PagerDefault')
    ->limit(5);

  $nids = $query->execute()->fetchCol();
  $nodes = node_load_multiple($nids);

  foreach ($nodes as $node) {
    $key = 'node_' . $node->nid;
    $build[$key] = node_view($node, 'teaser');
  }

  $pager_args = array('tags' => array('<<', '<', NULL, '>', '>>'));
  $build['pager'] = array(
    '#markup' => theme('pager', $pager_args),
  );

  return $build;
}


How do I clear cache using an SQL query? After a module update, my site has become unusable, and only shows a php error message.
I tried circumventing the problem with drush cc, but that didn't help.

Also tried with a custom php script but that has issues finding my DRUPAL_ROOT

I just want to clear the cache tables from Drupal 7 directly on the mysql server, but I'm unsure which tables should be cleared for that and especially which I should not clear.

Do I just need to clear all the [SITE-PREFIX_]cache* tables?

Yes, you can simply clear (TRUNCATE) all cache* tables.

This worked well for me:

TRUNCATE TABLE cache;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_filter;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_token;
TRUNCATE TABLE cache_update;

If you use drush, run drush sql-cli and paste the above in there.

These commands might not clear all cache tables of your specific site but it can help fix some errors. Afterwards you can try drush cc all to clear the rest.


View to display 2 posts from 1 content type 1 and 2 posts from content type 2 I want to display 4 featured posts on home page. 2 from the content type 1 and 2 from the content type 2. For this the straight forward way is to create two different views blocks. What I want to know if it is possible to display all 4 posts through a single view ??

I have a multipart part answer to this question:

No, there's no way to do show exactly two nodes of one content type and two of another type using only 1 view if you want them grouped in a specific order.
If you don't care about that nodes of different content types are mixed up together, you can change your content-type filter to include multiple content types. This only uses one view but may not be exactly what you want.
If you give up on using only 1 view, Kojo's comment lays out an excellent and quick way to embed views inside of another view to create the desired effect. Just to recap: create one view for each content type, and put one of the views in the header of the other view. This gives the desired effect, but gives up on using only 1 view.
You could use a SQL query like this to create a custom theme hook that would have the intended effect without using Views at all. It would require SQL knowledge to maintain it, but it would also have a lot less overhead. Here's what you'd need to do:

Inside template.php in your theme:

<?php
/**
 * Implements hook_theme().
 *
 * This registers a custom function for use with the theme() function.
 * To make your featured nodes show up in a template, add this code:
 *
 *   print theme('featured_nodes');
 *
 * Whenever theme() is called with that argument, a certain preprocess function
 * will be called. I like to write SQL in those preprocess functions to
 * find raw data from the database. Then a template will be used to display
 * the information looked up in the preprocess function. Finally, the template
 * is returned as a string wherever theme() was originally called.
 *
 * Look up hook_theme in the API docs at http://api.drupal.org/ for more info.
 */
function mytheme_theme() {
    return array(
        'features_nodes'] = array(
            // Here I define which template should be used.
            // In this case, the template will be called featured-nodes.tpl.php
            'template' => 'featured-nodes',
        )
    );
}

/**
 * Implements hook_preprocess_hook().
 *
 * This function is triggered before the template is rendered. You can
 * pass variables into the template simply by adding them to $vars.
 */
function mytheme_preprocess_features_nodes(&$vars) {
    // This is a really simple query that looks up all the fields
    // on the node table for the 2 most recent nodes of type 1,
    // then it adds all the fields of the 2 most recent nodes of type 2.
    // Learning SQL is bigger than the scope of this question.
    $results = db_query('
        SELECT *
          FROM {node}
         WHERE type = "machine_name_of_content_type_1"
         LIMIT 2
      ORDER BY created DESC
         UNION
        SELECT *
          FROM {node}
         WHERE type = "machine_name_of_content_type_2"
      ORDER BY created DESC
         LIMIT 2
    ');
    $featured_nodes = array();

    // We use db_fetch_object() repeatedly to read out each result row.
    while ($row = db_fetch_object($result)) {
        $featured_nodes[] = $row;
    }

    // Anything in $vars will be added to the templates when they are rendered.
    $vars['featured_nodes'] = $featured_nodes;
}

Then, inside featured-nodes.tpl you'll have access the $featured_nodes variable and you can display some very basic information about the nodes that you want (nid, title, author, and created date).

Here's an example of what should go inside featured-nodes.tpl.php:

    <?php foreach ($featured_nodes as $node) : ?>

<?php print l($node->title, "node/{$node->nid}"); ?>

    <?php endforeach; ?>

NOTE: None of the above code is tested and it may require some tweaking.

Here's an in-depth blog post I wrote with more information on how and why to do version 4.


Change the format of 'Authored on' date in views filter In Drupal 8, I want to remove the timestamp on 'Authored on' date in views filter. Any Idea how to do this?

As @prkos said enable better_exposed_filters and in Exposed form style change it as Better Exposed Filters. Open setting and under Authored On select jQuery UI Datepicker. It will enable to give only date format.

BEF Settings:


WYSIWYG not appearing for custom content type I am working on a re-work of Drupalerp (D6), as I found so many problems with it...but have run into an odd issue. As drupalerp creates it's extra content types programatically, I am unsure if it is doing it correctly. For content types created in the GUI, the Drupal way, I can get the Wysiwyg to appear.

In the node_type table the drupal nodes that work have 'node' in the module column, and has_body = 1. The erp ones have their individual module names instead of 'node'. If I switch the module to node for those ones, I get wysiwyg, but of course lose the custom programmed handling of those types.

So my question is, does that have to be 'node' in the module column of node_type in order to get wysiwyg, or is there another element missing from the programming of those custom types?

I know that wysiwyg is related to input filters, are these available on the body (if there is one) of the custom nodes?


Image path all 404 after move my remote site to localhost I just moved everything from my remote Drupal site to localhost (C:\xampp\htdocs\folder). All links (content images, menu links) are shown like http://localhost/sites/default/files/inline-images/magento.png when it should be http://localhost/foldername/sites/default/files/inline-images/magento.png.

Is there any quick method I can use to fix this problem like using mod_rewrite?

If the RewriteBase Method is not working and every other page works, try to set the $base_url variable in your settings.php file to your folder.


Contextual Links not appearing for blocks I have contextual links enabled. I've added

print render($action_links);

to both my page template and every block template I have but it's always blank. Out of desperation, I set permissions to allow even anonymous users. Still nothing.

I read that Devel might mess with contextual links but I don't have it enabled.

EDIT:

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

<?php echo $block->title; ?>

<?php
   echo preg_replace("/(<)[\/]?[p](>)/is", "", $content);
   ?>

Contextual links are printed with:

print render($title_suffix);

I Have checked it on block.tpl.php

See: Working with contextual links

I would suggest not to put inline css in your template.
Here working code:

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?> clearfix" <?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <?php if ($title): ?>
    <div <?php print $title_attributes; ?> style="background: #044faa; color: #fff; padding: 5px 15px; font-size: 16px">
     <?php print $title; ?>

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

      <?php print preg_replace("/(<)[\/]?[p](>)/is", "", $content); ?>


How can I programmatically change the parse mode? We have a view that works with Search API and Solr search. The multiple search terms work with single quotes and with no quotes. I want to make the search terms work with double quotes as well. The issue is also listed here without a fix:
https://www.drupal.org/project/search_api/issues/2141575
I found that I can change the parse mode in the View > Query > Settings to direct method and the term with double quotes work just fine. I want to make this change using hooks. I have tried hook_search_api_views_query_alter and it does not work. Does anyone know how to change the parse mode in the query settings using hooks?

On Drupal 7, I've achieved this by using hook_views_pre_build() since this hook is executed before hook_views_pre_execute() and hook_search_api_views_query_alter(). Using code similar to the following will do the job.
$options = $view->display_handler->get_option('query');
$options['options']['parse_mode'] = 'TYPE_OF_PARSE_MODE';
$view->display_handler->set_option('query', $options);

Note that TYPE_OF_PARSE_MODE can be:

Direct query - direct
Single term - single
Multiple terms - terms


Export my block configuration I have used configuration management to export and import my drupal configurations.However,when i add a new block,the configuration management can't track the change of block and i can't export the configuration.I want to know whether the configuration management can track the block and export block configuration.

Configuration Management module  does not support exporting blocks. See https://www.drupal.org/node/2125089 for more info.

There are several other modules than can help you with this:

Features and Features Extra
Blockexport


Changing video content type (mime type) in CDN I am using media module to save media in CDN. To play videos, we are using jwplayer in Drupal 7. Jwplayer throws error in IE, If video is not of content type [mime type] video/mp4.
I have changed the existing CDN videos mime type from application/octet-stream to video/mp4.

Now whatever mp4 videos are being uploaded/saved to cdn should only be of video/mp4 mime type but when I upload mp4 videos in media module it is saved in CDN with mime type application/octet-stream, How do I change the uploaded mime type [content type] to video/mp4.

How do I change mime type[content type] to video/mp4 in media module, Drupal 7, when mp4 video are being uploaded.

Found the Answer :

1)  "A MIME-TYPE is a server side setting. You can ask your hosting provider to add the MP4 MIME-TYPE for you.

Or, you can add a .htaccess file to the directory where you uploads are stored".

A sample .htaccess file that adds the MP4 MIME-TYPE is:

<IfModule mod_rewrite.c>
  AddType video/mp4 .mp4
</IfModule>"

Source : Need to Change Video Content Type to video/mp4 so it plays in IE

But this did not work for me for some reason

2) I did the change in my core class file which i was using in drupal module for CDN upload
I had made a change in my class.s3.php file -> in mime_type[] array and also, cross checked with putObject() function.

**

  Setting of mime type is always done in coding side and not in AWS S3
  bucket, We need to use AWS PHP Class file or sdk to do the
  manipulation in mime type or make the necessary changes in core class
  file (eg. class.s3.php )

**
 For details check here find-mime-type-of-file-or-url-using-php-for-all-file-format

Second Answer has worked for me :)


CSV Feeds import troubles with CiviCRM entity reference field I'm stumped with this particular Feed import problem.

I've got a content type (node) that has an entity reference field that relates it to an number of CiviCRM organization contacts. When you manually create a node, the entity reference field auto-completes the field and if you look at it in the editing view, you see the name of the contact along with their CiviCRM unique contact id. It would look like the following:

Contact Name [cid:8]

In the regular view, you just see the Contact Name.

I figured I could use Drupal Feeds and Feeds Tamper and then create a CSV import but I can't seem to format the entity reference field correctly so that the data is accepted. I've tried setting it to "Organization Name" as well as "id" and "user_unique_id". I've fed it straight integers for id and the unique id and I've tried "Contact Name [cid:8]" as well as just the contact name or just the "[cid:8]" part and nothing seems to stick. The content is created but the entity reference field remains empty. I can of course manually enter the values but that defeats the point of the import.

Any ideas?

These are the pertinent parts of the site:

Drupal 7.x
CiviCRM 4.4.x
Feeds
Feeds Tamper
Entity
CiviCRM entities
Entity Reference
CiviCRM Contact Reference Field

Thanks,
Andrew

Not sure if https://www.drupal.org/project/civicrm_user_reference will work for you, but I wrote that when having issues with CiviCRM Contact Reference Field in another use case.


Where is the the full tokens list for a site? In the Metatag module UI it uses tokens but only shows a small list of tokens that are relative to the site information rather than the full content tokens which it can use, in D7 there was an admin token page so you can check values.

Where is this in Drupal 8?

I see its one of those things that you once you know.

Enable modules:

Token
Help (core)

Navigate to the page: /admin/help/token.


How do I access a custom field from an action? I want to access a custom field names field_heat in a Rules action in D8 and it does not accept it. This is my condition:

And this is my action which cannot be accepted:

If I use a build field like node.title.value it works OK so the problem must be with custom fields. I am using Rules 8.x-3.0-alpha1.

Preface

Be aware of what's written in comment nr 7 of issue nr 2574691:

  rules 8.x-3.0-alpha1 ... is a preview release and is not intended for production sites. Use at your own risk.

With that in mind, read on for more details to do a similar experiment with rules 8.x-3.0-alfa1.

Verify setup of content type and field

I'll use content type "Article", which already has a field with machine name "field_image" (out of the D8-box).
Navigate to /admin/structure/types/manage/article/fields to verify this.

Create a rule

Enable the Rules module.
Navigate to /admin/config/workflow/rules and create a new rule, with these details:

Use Rules Event "Before saving content"
Add a Rules Condition like "Entity has field" (for the field_image field). To do so, click on "Value" (within the "Entity" box), and select node. And also click on "Value" (within the "Field" box), and select field_image. Then click the Save button (to save the Rules Condition).
Add a Rules Action "Set a data value",and continue like so: click on "Value" (within the "Data" box), and select node:field_image:value (note that for this Data Selector I'm using : (twice), instead of . (twice) as in your screenprint). And also enter some "Value" (within the "Value" box), eg myNiceImage. Then click the Save button (to save the Rules Action).
You are then returned to the "edit rules reaction" screen (for the rule you are editing. And it shows a message like "You have unsaved changes.". Click the Save button (to save the rule). Then a message will be shown like "Reaction rule ABC has been updated." (ABC = the label you gave to your rule).

Verify if the rule got saved

Navigate to /admin/config/workflow/rules to ensure the rule was really saved (that it does show up there).
Navigate to admin/config/development/configuration/single/export and as "Configuration type" select "Reaction Rule". Then select the label of your rule as the "Configuration name".
You should then see the exported rule, which should look similar to mine, i.e.:

uuid: ab289332-0b45-484f-a1ae-38842620b7e4
langcode: en
status: true
dependencies: {  }
id: check_a_field_before_saving_a_node
label: 'Check a field before saving a node'
events:
  -
    event_name: 'rules_entity_presave:node'
description: ''
tags:
  - ''
config_version: '3'
expression:
  id: rules_rule
  uuid: 354332c5-8307-4097-b33c-0e77307a5e0e
  conditions:
    id: rules_and
    uuid: e82407a4-05c6-45d3-8195-1c1b5f34a07d
    conditions:
      -
        id: rules_condition
        uuid: 3c9094ed-95ec-4202-8398-5a6ca000604a
        context_values:
          entity: node
          field: field_image
        context_mapping: {  }
        context_processors: {  }
        provides_mapping: {  }
        condition_id: rules_entity_has_field
        negate: false
  actions:
    id: rules_action_set
    uuid: 3313095c-f75a-46f2-8d11-f845d12a90f2
    actions:
      -
        id: rules_action
        uuid: 23a3a68e-893e-48c4-a7ee-102201af5a25
        context_values:
          data: 'node:field_image:value'
          value: myNiceImage
        context_mapping: {  }
        context_processors: {  }
        provides_mapping: {  }
        action_id: rules_data_set

The above export should illustrate that I could perfectly save this ... because otherwise I could not have exported it, right?

Pushing the limits

So far so good, but next I wanted to update the value to be assigned in my Rules Action, let's say myNiceImage should be updated to myNewestNiceImage. So I returned to my Rules Action, and started to edit it. But, that resulted in an error message like so:

  The context Data may only be configured using a selector.

By clicking on the Switch to data selection button (so that the button label changed to Swith to direct input mode), and trying again, I got another error message like so:

  Data selector node:field_image for context Data is invalid. Unable to get variable node:field_image, it is not defined.

There has to be a way to do it ...

So it seems like updating a Rules Action is not what you should try to do (at least not in the current D8 release of the Rules module).

However, here are the steps I performed to actually get the value updated (from myNiceImage to myNewestNiceImage) anyhow:

delete the Rules Action (with the old value myNiceImage).
create a new Rules Action (with the new value myNewestNiceImage).

Voilà!

PS: did you notice I'm using "Entity has field", and not "Entity is of type"?


How do I remove the page title only from the front page? I have created a basic page and assigned it to the front page. Now I would like to remove the title shown in the front page.

How can I achieve this?

The Title is a Block now in Drupal 8. You can edit the Page Title Block and set it to show on all paths except for <front> to hide it from the front page.


Allowing users to use the same email I am working on a system that will be used at least partially by students some of which will likely be grade schoolers.  The old system that we are replacing with a Drupal site would allow mass creation of user accounts all with the same email address.  They did this so that the teacher could just use her email for all of the students and if they needed a password reset the info would just get sent to the teacher.  Also, many very young students do not have their own email accounts.

I need import these accounts into my Drupal site but I am going to have trouble because Drupal 7 does not allow different accounts with the same email.  After a quick Google search I did not find much that was to promising, I found a dirty hack for Drupal 5 but nothing that seemed like it might work with Drupal 7.  Is there any way around this?

You could use the Shared Email module.

The shared email module allows multiple users to use the same email address for different accounts. The module works for both registration and account updates.

Users using that module could also be interested in the Shared Email Password Reset module.

This module will have users reset their password based on both email and user name, there are some cases where this module can help when using the Shared Email module or when there is a requirement that passwords should be reset only if email and username matches.

Both the modules have a Drupal 8 version, and they are declared compatible with Drupal 9.


Access current node in an existing block I am using Drupal Lightning and a bootstrap subtheme. I have a requirement to place a section of the node page template in another block region. So I need to access the nodes fields in that block, fields like the taxonomy, block, breadcrumbs. Example my node--page.html.twig template prints these fields:

{{ node.title.value }}
{{ content.field_text }}
{{ drupal_view('mysection', 'block_1') }}
{{ drupal_block('mytheme_breadcrumbs') }}

It also has an includes template

{% include '@mytheme/includes/section.html.twig' %}

I can print these fields fine in a node template

node--page.html.twig

But I need to print these fields outside of the node template and into a block. I tried to create a View block and set a contextual filter "Content ID from URL" Then placed the View block in a region and then in the region template I tried to access the node fields from my region template but could not. I can access the title and body fields. This is the template.

region--myregion.html.twig

I then tried Entity blocks. I created a new block of type Entity view (Content). I tried to access the node fields from my region template but could not.

block--entityviewcontent.html.twig

Enable debug
by going in sites/default/ and copying the file default.services.yml to services.yml  and modifying the following lines
cache: false
debug: true

Turn browser comments on
make sure your browser has Comments enabled (some browsers have them disabled by default for example in chrome in inspector on the 3 dot menu click settings and preferences find Show HTML comments
Find out which twig template is used
after that inspect the code in near the block that you want to override and you should see something similar to this

you can get the twig block template from the location in comment BEGIN OUTPUT
Use and modify template
Copy this twig file into your theme templates folder and rename to any name above.  Modify the code and add something similar to the twig block template you just created
{% if nid %}
    nid:{{nid}}

    title:{{node_title}}

    body:{{body}}

    text:{{field_text}}

{% endif %}

Expose node variable to block templates
Add into your THEMENAME.theme the following code or similar
function THEMENAME_preprocess_block(&$vars){
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      // You can get nid and anything else you need from the node object.
      $vars["nid"] = $node->id();
      $vars["node_title"] = $node->getTitle();
      $vars["body"] = $node->body->value;
      $vars["field_text"] = $node->field_text->value;

      //following did not work ?!
      //$vars["field_text"] = $node->get('field_text')->getValue();
      //$vars["field_text"] = $node->field_text->getValue();
    }
}

Clear cache
with the above you are making the node fields available to block templates